file_name large_stringlengths 4 140 | prefix large_stringlengths 0 12.1k | suffix large_stringlengths 0 12k | middle large_stringlengths 0 7.51k | fim_type large_stringclasses 4
values |
|---|---|---|---|---|
analytic_account_open.py | # -*- coding: utf-8 -*-
# Copyright 2015 Eficent - Jordi Ballester Alomar
# License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl.html).
from odoo import api, fields, models
class AnalyticAccountOpen(models.TransientModel):
_name = 'analytic.account.open'
_description = 'Open single analytic account'
... | (self, curr_id):
result = {}
result[curr_id] = True
# Now add the children
self.env.cr.execute('''
WITH RECURSIVE children AS (
SELECT parent_id, id
FROM account_analytic_account
WHERE parent_id = %s
UNION ALL
SELECT a.parent_id, a.id
... | _get_child_analytic_accounts | identifier_name |
analytic_account_open.py | # -*- coding: utf-8 -*-
# Copyright 2015 Eficent - Jordi Ballester Alomar
# License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl.html).
from odoo import api, fields, models
class AnalyticAccountOpen(models.TransientModel):
_name = 'analytic.account.open'
_description = 'Open single analytic account'
... |
return result
@api.multi
def analytic_account_open_window(self):
self.ensure_one()
act_window_id = self.env.ref(
'analytic.action_account_analytic_account_form')
result = act_window_id.read()[0]
acc_id = self.analytic_account_id.id
acc_ids = []
... | result[y] = True | conditional_block |
analytic_account_open.py | # -*- coding: utf-8 -*-
# Copyright 2015 Eficent - Jordi Ballester Alomar
# License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl.html).
from odoo import api, fields, models
class AnalyticAccountOpen(models.TransientModel):
_name = 'analytic.account.open'
_description = 'Open single analytic account'
... |
@api.multi
def analytic_account_open_window(self):
self.ensure_one()
act_window_id = self.env.ref(
'analytic.action_account_analytic_account_form')
result = act_window_id.read()[0]
acc_id = self.analytic_account_id.id
acc_ids = []
if self.include_chi... | result = {}
result[curr_id] = True
# Now add the children
self.env.cr.execute('''
WITH RECURSIVE children AS (
SELECT parent_id, id
FROM account_analytic_account
WHERE parent_id = %s
UNION ALL
SELECT a.parent_id, a.id
FROM account_analytic_... | identifier_body |
server.js | const express = require('express')
const app = express()
const formidable = require('formidable')
const path = require('path')
const rimraf = require('rimraf')
const fs = require('fs')
const throttle = require('express-throttle-bandwidth')
const
port = process.env.PORT || 4444,
folder = path.join(__dirname, 'files... |
process.on('exit', () => {
rimraf.sync(path.join(folder))
})
app.set('port', port)
app.use(throttle(1024 * 128))
app.use((_, res, next) => {
res.header('Access-Control-Allow-Origin', '*')
res.header('Access-Control-Allow-Headers', 'Origin, X-Requested-With, Content-Type, Accept')
next()
})
app.post('/uploa... | {
rimraf.sync(path.join(folder, '*'))
} | conditional_block |
server.js | const express = require('express')
const app = express()
const formidable = require('formidable')
const path = require('path')
const rimraf = require('rimraf')
const fs = require('fs')
const throttle = require('express-throttle-bandwidth')
const
port = process.env.PORT || 4444,
folder = path.join(__dirname, 'files... | })
app.set('port', port)
app.use(throttle(1024 * 128))
app.use((_, res, next) => {
res.header('Access-Control-Allow-Origin', '*')
res.header('Access-Control-Allow-Headers', 'Origin, X-Requested-With, Content-Type, Accept')
next()
})
app.post('/upload', (req, res) => {
rimraf.sync(path.join(folder, '*'))
co... |
process.on('exit', () => {
rimraf.sync(path.join(folder)) | random_line_split |
karma.conf.js | // Karma configuration
// http://karma-runner.github.io/0.12/config/configuration-file.html
// Generated on 2015-11-25 using
// generator-karma 1.0.0
module.exports = function(config) {
'use strict';
config.set({
// enable / disable watching file and executing tests whenever any file changes
autoWatch: tr... | 'bower_components/angular-sanitize/angular-sanitize.js',
'bower_components/angular-touch/angular-touch.js',
'bower_components/angular-mocks/angular-mocks.js',
// endbower
"app/scripts/**/*.js",
"test/mock/**/*.js",
"test/spec/**/*.js"
],
// list of files / patterns to ... | 'bower_components/angular-cookies/angular-cookies.js',
'bower_components/angular-resource/angular-resource.js',
'bower_components/angular-route/angular-route.js', | random_line_split |
service.py | import attr
from navmazing import NavigateToAttribute
from navmazing import NavigateToSibling
from cfme.common import Taggable
from cfme.common import TagPageView
from cfme.containers.provider import ContainerObjectAllBaseView
from cfme.containers.provider import ContainerObjectDetailsBaseView
from cfme.containers.pro... |
return services
@navigator.register(ServiceCollection, 'All')
class All(CFMENavigateStep):
prerequisite = NavigateToAttribute('appliance.server', 'LoggedIn')
VIEW = ServiceAllView
def step(self, *args, **kwargs):
self.prerequisite_view.navigation.select('Compute', 'Containers', 'Contain... | services.append(self.instantiate(name=name, project_name=project_name,
provider=provider or get_crud_by_name(ems_name))) | conditional_block |
service.py | from cfme.common import TagPageView
from cfme.containers.provider import ContainerObjectAllBaseView
from cfme.containers.provider import ContainerObjectDetailsBaseView
from cfme.containers.provider import GetRandomInstancesMixin
from cfme.containers.provider import Labelable
from cfme.containers.provider import Logging... | import attr
from navmazing import NavigateToAttribute
from navmazing import NavigateToSibling
from cfme.common import Taggable | random_line_split | |
service.py | import attr
from navmazing import NavigateToAttribute
from navmazing import NavigateToSibling
from cfme.common import Taggable
from cfme.common import TagPageView
from cfme.containers.provider import ContainerObjectAllBaseView
from cfme.containers.provider import ContainerObjectDetailsBaseView
from cfme.containers.pro... | (CFMENavigateStep):
prerequisite = NavigateToAttribute('parent', 'All')
VIEW = ServiceDetailsView
def step(self, *args, **kwargs):
search_visible = self.prerequisite_view.entities.search.is_displayed
self.prerequisite_view.entities.get_entity(name=self.obj.name,
... | Details | identifier_name |
service.py | import attr
from navmazing import NavigateToAttribute
from navmazing import NavigateToSibling
from cfme.common import Taggable
from cfme.common import TagPageView
from cfme.containers.provider import ContainerObjectAllBaseView
from cfme.containers.provider import ContainerObjectDetailsBaseView
from cfme.containers.pro... |
@navigator.register(Service, 'Details')
class Details(CFMENavigateStep):
prerequisite = NavigateToAttribute('parent', 'All')
VIEW = ServiceDetailsView
def step(self, *args, **kwargs):
search_visible = self.prerequisite_view.entities.search.is_displayed
self.prerequisite_view.entities.get... | prerequisite = NavigateToAttribute('appliance.server', 'LoggedIn')
VIEW = ServiceAllView
def step(self, *args, **kwargs):
self.prerequisite_view.navigation.select('Compute', 'Containers', 'Container Services')
def resetter(self, *args, **kwargs):
# Reset view and selection
self.vie... | identifier_body |
binary_manager.py |
import os
import py_utils
from py_utils import binary_manager
from py_utils import cloud_storage
from py_utils import dependency_util
import dependency_manager
from dependency_manager import base_config
from devil import devil_env
from telemetry.core import exceptions
from telemetry.core import util
TELEMETRY_PR... |
if fetch_reference_chrome_binary:
_FetchReferenceBrowserBinary(platform)
# For now, handle client config separately because the BUILD.gn & .isolate of
# telemetry tests in chromium src failed to include the files specified in its
# client config.
# (https://github.com/catapult-project/catapult/issues/2... | if host_platform == 'linux_x86_64':
fetch_devil_deps = True
else:
logging.error('Devil only supports 64 bit linux as a host platform. '
'Android tests may fail.') | conditional_block |
binary_manager.py |
import os
import py_utils
from py_utils import binary_manager
from py_utils import cloud_storage
from py_utils import dependency_util
import dependency_manager
from dependency_manager import base_config
from devil import devil_env
from telemetry.core import exceptions
from telemetry.core import util
TELEMETRY_PR... | # we do with android below.
if _IsChromeOSLocalMode(os_name):
os_name = 'linux'
target_platform = '%s_%s' % (os_name, platform.GetArchName())
dep_manager.PrefetchPaths(target_platform)
host_platform = None
fetch_devil_deps = False
if os_name in ('android', 'chromeos'):
host_platform = '%s_%s' % (... | """ Fetch all binary dependenencies for the given |platform|.
Note: we don't fetch browser binaries by default because the size of the
binary is about 2Gb, and it requires cloud storage permission to
chrome-telemetry bucket.
Args:
platform: an instance of telemetry.core.platform
client_configs: A list... | identifier_body |
binary_manager.py |
import os
import py_utils
from py_utils import binary_manager
from py_utils import cloud_storage
from py_utils import dependency_util
import dependency_manager
from dependency_manager import base_config
from devil import devil_env
from telemetry.core import exceptions
from telemetry.core import util
TELEMETRY_PR... | (dependency, dep_local_path, version,
os_name=None, arch_name=None):
config = os.path.join(
util.GetTelemetryDir(), 'telemetry', 'binary_dependencies.json')
if not os_name:
assert not arch_name, 'arch_name is specified but not os_name'
os_name = py_utils.GetHostOsName()
arch_... | UpdateDependency | identifier_name |
binary_manager.py | .path.join(
util.GetTelemetryDir(), 'telemetry', 'binary_dependencies.json')
CHROME_BINARY_CONFIG = os.path.join(util.GetCatapultDir(), 'common', 'py_utils',
'py_utils', 'chrome_binaries.json')
SUPPORTED_DEP_PLATFORMS = (
'linux_aarch64', 'linux_x86_64', 'linux_armv7l', '... | c = base_config.BaseConfig(config, writable=True)
try:
old_version = c.GetVersion(dependency, dep_platform)
print('Updating from version: {}'.format(old_version)) | random_line_split | |
index.tsx | import {XCircleIcon, CheckCircleIcon} from '@heroicons/react/solid'
import dayjs from 'dayjs'
import {Badge, Accordion, Spinner} from '@/components'
import {dateFromNow, statusColors, formatFullDate} from '@/utils'
import {useRequests} from '@/lib/data'
import type {MouseEventHandler} from 'react'
import type {Request,... | <button onClick={handleAccept}>
<CheckCircleIcon className="w-8 h-8 hover:text-green-600" />
</button>
<button onClick={handleDeny}>
<XCircleIcon className="w-8 h-8 hover:text-red-600" />
</button>
</div>
)
}
function PermissionRequestInfo({userName, date, id}: Pick<Reque... | {
const {update} = useRequests()
const mutation = update(id)
const handleAccept: MouseEventHandler<HTMLButtonElement> = e => {
e.stopPropagation()
mutation.mutate({status: 'accepted'})
}
const handleDeny: MouseEventHandler<HTMLButtonElement> = e => {
e.stopPropagation()
mutation.mutate({stat... | identifier_body |
index.tsx | import {XCircleIcon, CheckCircleIcon} from '@heroicons/react/solid'
import dayjs from 'dayjs'
import {Badge, Accordion, Spinner} from '@/components'
import {dateFromNow, statusColors, formatFullDate} from '@/utils'
import {useRequests} from '@/lib/data'
import type {MouseEventHandler} from 'react'
import type {Request,... | ({userName, date, id}: Pick<Request, 'userName' | 'date' | 'id'>) {
return (
<div className="space-y-1">
<h3 className="mb-1 text-base font-medium">Permission request</h3>
<p>
Requested by {userName} on {formatFullDate(date)}
</p>
<p className="text-sm text-gray-500">Request id #{i... | PermissionRequestInfo | identifier_name |
index.tsx | import {XCircleIcon, CheckCircleIcon} from '@heroicons/react/solid'
import dayjs from 'dayjs'
import {Badge, Accordion, Spinner} from '@/components'
import {dateFromNow, statusColors, formatFullDate} from '@/utils'
import {useRequests} from '@/lib/data'
import type {MouseEventHandler} from 'react'
import type {Request,... |
return (
<div className="flex items-center space-x-2 text-gray-300">
<button onClick={handleAccept}>
<CheckCircleIcon className="w-8 h-8 hover:text-green-600" />
</button>
<button onClick={handleDeny}>
<XCircleIcon className="w-8 h-8 hover:text-red-600" />
</button>
<... | {
return <Spinner className="w-6 h-6 text-gray-400" />
} | conditional_block |
index.tsx | import {XCircleIcon, CheckCircleIcon} from '@heroicons/react/solid'
import dayjs from 'dayjs'
import {Badge, Accordion, Spinner} from '@/components'
import {dateFromNow, statusColors, formatFullDate} from '@/utils'
import {useRequests} from '@/lib/data'
import type {MouseEventHandler} from 'react'
import type {Request,... | <p>Object id </p>
<div className="px-2 py-1 text-sm bg-gray-50">{objectId}</div>
<p>Object type</p>
<div className="px-2 py-1 text-sm bg-gray-50">{objectType}</div>
</div>
</div>
)
}
function PermissionReason({reason}: Pick<Request, 'reason'>) {
return (
<div className... | <div className="space-y-2"> | random_line_split |
Legend.tsx | import React, { PureComponent, SyntheticEvent } from 'react';
import SeriesName from './SeriesName';
import { GraphSeries } from './Graph';
interface LegendProps {
chartData: GraphSeries[];
shouldReset: boolean;
onLegendMouseOut: (ev: SyntheticEvent<HTMLDivElement>) => void;
onSeriesToggle: (selected: number[]... | ? onHover(index) : undefined}
key={index}
className="legend-item"
>
<span className="legend-swatch" style={{ backgroundColor: color }}></span>
<SeriesName labels={labels} format />
</div>
))}
{chartData.length > 1 && (
<div c... | canUseHover | identifier_name |
Legend.tsx | import React, { PureComponent, SyntheticEvent } from 'react';
import SeriesName from './SeriesName';
import { GraphSeries } from './Graph';
interface LegendProps {
chartData: GraphSeries[];
shouldReset: boolean;
onLegendMouseOut: (ev: SyntheticEvent<HTMLDivElement>) => void;
onSeriesToggle: (selected: number[]... |
className="legend-item"
>
<span className="legend-swatch" style={{ backgroundColor: color }}></span>
<SeriesName labels={labels} format />
</div>
))}
{chartData.length > 1 && (
<div className="pl-1 mt-1 text-muted" style={{ fontSize: 13 ... | {index} | identifier_body |
Legend.tsx | import React, { PureComponent, SyntheticEvent } from 'react';
import SeriesName from './SeriesName';
import { GraphSeries } from './Graph';
interface LegendProps {
chartData: GraphSeries[];
shouldReset: boolean;
onLegendMouseOut: (ev: SyntheticEvent<HTMLDivElement>) => void;
onSeriesToggle: (selected: number[]... | {chartData.length > 1 && (
<div className="pl-1 mt-1 text-muted" style={{ fontSize: 13 }}>
Click: select series, {navigator.platform.includes('Mac') ? 'CMD' : 'CTRL'} + click: toggle multiple series
</div>
)}
</div>
);
}
} | ))} | random_line_split |
Legend.tsx | import React, { PureComponent, SyntheticEvent } from 'react';
import SeriesName from './SeriesName';
import { GraphSeries } from './Graph';
interface LegendProps {
chartData: GraphSeries[];
shouldReset: boolean;
onLegendMouseOut: (ev: SyntheticEvent<HTMLDivElement>) => void;
onSeriesToggle: (selected: number[]... |
}
handleSeriesSelect = (index: number) => (ev: React.MouseEvent<HTMLDivElement, MouseEvent>) => {
// TODO: add proper event type
const { selectedIndexes } = this.state;
let selected = [index];
if (ev.ctrlKey || ev.metaKey) {
const { chartData } = this.props;
if (selectedIndexes.include... | {
this.setState({ selectedIndexes: [] });
} | conditional_block |
help.js | var express = require('express')
var router = express.Router()
var path = require('path')
var debug = require('debug')('app:' + path.basename(__filename).replace('.js', ''))
var request = require('request')
var entu = require('./entu')
// GET requests/offers listing
router.get('/:type', function(req, res, ... | var help_group = 650
var help_type = 'request'
} else if(req.params.type === 'offers') {
var page_id = 655
var help_group = 651
var help_type = 'offer'
} else {
res.redirect('/help/requests')
return
}
entu.get_entities(help_group, 'request', null,... | random_line_split | |
domparser.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use dom::bindings::codegen::Bindings::DocumentBinding::DocumentReadyState;
use dom::bindings::codegen::Bindings::D... | Ok(DOMParser::new(global.as_window()))
}
}
impl<'a> DOMParserMethods for JSRef<'a, DOMParser> {
// http://domparsing.spec.whatwg.org/#the-domparser-interface
fn ParseFromString(self,
s: DOMString,
ty: DOMParserBinding::SupportedType)
... | random_line_split | |
domparser.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use dom::bindings::codegen::Bindings::DocumentBinding::DocumentReadyState;
use dom::bindings::codegen::Bindings::D... | (self,
s: DOMString,
ty: DOMParserBinding::SupportedType)
-> Fallible<Temporary<Document>> {
let window = self.window.root();
let url = window.r().get_url();
let content_type = DOMParserBinding::SupportedTypeValues::strings[ty ... | ParseFromString | identifier_name |
domparser.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use dom::bindings::codegen::Bindings::DocumentBinding::DocumentReadyState;
use dom::bindings::codegen::Bindings::D... |
}
}
}
| {
//FIXME: this should probably be FromParser when we actually parse the string (#3756).
Ok(Document::new(window.r(), Some(url.clone()),
IsHTMLDocument::NonHTMLDocument,
Some(content_type),
... | conditional_block |
domparser.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use dom::bindings::codegen::Bindings::DocumentBinding::DocumentReadyState;
use dom::bindings::codegen::Bindings::D... | None,
DocumentSource::NotFromParser))
}
}
}
}
| {
let window = self.window.root();
let url = window.r().get_url();
let content_type = DOMParserBinding::SupportedTypeValues::strings[ty as usize].to_owned();
match ty {
Text_html => {
let document = Document::new(window.r(), Some(url.clone()),
... | identifier_body |
client_config_update.py | #!/usr/bin/python -u
#
# Copyright (c) 2008--2010 Red Hat, Inc.
#
# This software is licensed to you under the GNU General Public License,
# version 2 (GPLv2). There is NO WARRANTY for this software, express or
# implied, including the implied warranties of MERCHANTABILITY or FITNESS
# FOR A PARTICULAR PURPOSE. You sho... | (line):
"""parse a line from a config file. Format can be either "key=value\n"
or "whatever text\n"
return either:
(key, value)
or
None
The '\n' is always stripped from the value.
"""
kv = string.split(line, '=')
if len(kv) < 2:
# not a setting
return... | _parseConfigLine | identifier_name |
client_config_update.py | #!/usr/bin/python -u
#
# Copyright (c) 2008--2010 Red Hat, Inc.
#
# This software is licensed to you under the GNU General Public License,
# version 2 (GPLv2). There is NO WARRANTY for this software, express or
# implied, including the implied warranties of MERCHANTABILITY or FITNESS
# FOR A PARTICULAR PURPOSE. You sho... |
if len(kv) > 2:
# '=' is part of the value, need to rejoin it.
kv = kv[0], string.join(kv[1:], '=')
if string.find(kv[0], '[comment]') > 0:
# comment; not a setting
return None
# it's a setting, trim the '\n' and return the (key, value) pair.
kv[0] = string.strip(kv[0... | return None | conditional_block |
client_config_update.py | #!/usr/bin/python -u
#
# Copyright (c) 2008--2010 Red Hat, Inc.
#
# This software is licensed to you under the GNU General Public License,
# version 2 (GPLv2). There is NO WARRANTY for this software, express or
# implied, including the implied warranties of MERCHANTABILITY or FITNESS
# FOR A PARTICULAR PURPOSE. You sho... |
def dumpConfigFile(configFile):
"print out dictionary of key/value pairs from configFile"
import pprint
pprint.pprint(readConfigFile(configFile))
def mapNewSettings(configFile, dnew):
fo = tempfile.TemporaryFile(prefix = '/tmp/client-config-overrides-', mode = 'r+b')
fin = open(configFile, 'rb... | "read in config file, return dictionary of key/value pairs"
fin = open(configFile, 'rb')
d = {}
for line in fin.readlines():
kv = _parseConfigLine(line)
if kv:
d[kv[0]] = kv[1]
return d | identifier_body |
client_config_update.py | #!/usr/bin/python -u
#
# Copyright (c) 2008--2010 Red Hat, Inc.
#
# This software is licensed to you under the GNU General Public License,
# version 2 (GPLv2). There is NO WARRANTY for this software, express or
# implied, including the implied warranties of MERCHANTABILITY or FITNESS
# FOR A PARTICULAR PURPOSE. You sho... | # Specifically engineered with the RHN Update Agent configuration files
# in mind though it is relatively generic in nature.
#
# Author: Todd Warner <taw@redhat.com>
#
# $Id$
"""
Client configuration mapping script that writes to an RHN Update Agent-type
config file(s)
I.e., maps a file with RHN Update Agent-like key... | #
# NOT TO BE USED DIRECTLY
# This is called by a script generated by the rhn-bootstrap utility.
# | random_line_split |
Sidebar.Geometry.TetrahedronGeometry.js | import * as THREE from 'three';
import { UIRow, UIText, UIInteger, UINumber } from './libs/ui.js';
import { SetGeometryCommand } from './commands/SetGeometryCommand.js';
function GeometryParametersPanel( editor, object ) {
const strings = editor.strings;
const signals = editor.signals;
const container = new UI... |
return container;
}
export { GeometryParametersPanel };
| {
editor.execute( new SetGeometryCommand( editor, object, new THREE.TetrahedronGeometry(
radius.getValue(),
detail.getValue()
) ) );
signals.objectChanged.dispatch( object );
} | identifier_body |
Sidebar.Geometry.TetrahedronGeometry.js | import * as THREE from 'three';
import { UIRow, UIText, UIInteger, UINumber } from './libs/ui.js';
import { SetGeometryCommand } from './commands/SetGeometryCommand.js';
function | ( editor, object ) {
const strings = editor.strings;
const signals = editor.signals;
const container = new UIRow();
const geometry = object.geometry;
const parameters = geometry.parameters;
// radius
const radiusRow = new UIRow();
const radius = new UINumber( parameters.radius ).onChange( update );
radi... | GeometryParametersPanel | identifier_name |
Sidebar.Geometry.TetrahedronGeometry.js | import * as THREE from 'three';
import { UIRow, UIText, UIInteger, UINumber } from './libs/ui.js';
import { SetGeometryCommand } from './commands/SetGeometryCommand.js';
function GeometryParametersPanel( editor, object ) {
const strings = editor.strings;
const signals = editor.signals;
const container = new UI... | const detailRow = new UIRow();
const detail = new UIInteger( parameters.detail ).setRange( 0, Infinity ).onChange( update );
detailRow.add( new UIText( strings.getKey( 'sidebar/geometry/tetrahedron_geometry/detail' ) ).setWidth( '90px' ) );
detailRow.add( detail );
container.add( detailRow );
//
function up... | container.add( radiusRow );
// detail
| random_line_split |
output2csv.py | import os, re, csv
# regular expressions for capturing the interesting quantities
noise_pattern = 'noise: \[(.+)\]'
res_pattern = '^([0-9.]+$)'
search_dir = "output"
results_file = '../results.csv'
os.chdir( search_dir )
files = filter( os.path.isfile, os.listdir( '.' ))
#files = [ os.path.join( search_dir, f ) for ... | writer.writerow( result ) | conditional_block | |
output2csv.py | import os, re, csv
# regular expressions for capturing the interesting quantities
noise_pattern = 'noise: \[(.+)\]'
res_pattern = '^([0-9.]+$)'
search_dir = "output"
results_file = '../results.csv'
os.chdir( search_dir )
files = filter( os.path.isfile, os.listdir( '.' ))
#files = [ os.path.join( search_dir, f ) for ... | continue
# rmse
matches = re.search( res_pattern, contents, re.M )
try:
res = matches.group( 1 )
except AttributeError:
print "matches error 2: %s" % ( contents )
continue
results.append( [ res ] + noise )
writer = csv.writer( open( results_file, 'wb' ))
for result in results:
writer.writerow( re... | print "noise error 1: %s" % ( contents ) | random_line_split |
helpers.py | #!/usr/bin/python
import numpy, os, time, math
from sklearn.preprocessing import MinMaxScaler, StandardScaler, normalize
import ConfigParser
import os.path
from sklearn.metrics import mean_squared_error
from keras.preprocessing import sequence
import json, time
def ConfigSectionMap(settings_file, section):
Confi... |
elif (command == 'ping'):
return 23
elif (command == 'open'):
return 24
else:
return 0
| return 22 | conditional_block |
helpers.py | #!/usr/bin/python
import numpy, os, time, math
from sklearn.preprocessing import MinMaxScaler, StandardScaler, normalize
import ConfigParser
import os.path
from sklearn.metrics import mean_squared_error
from keras.preprocessing import sequence
import json, time
def ConfigSectionMap(settings_file, section):
Confi... | (dataset, length):
# Padding (from left, otherwise results are affected in Keras)
return sequence.pad_sequences(dataset, maxlen=length, padding='pre') # shape (n, length)
def extract_hour(unixtime):
hour = time.strftime("%H", time.gmtime(float(unixtime)))
return hour
def normalize(dataset):
# No... | padding | identifier_name |
helpers.py | #!/usr/bin/python
import numpy, os, time, math
from sklearn.preprocessing import MinMaxScaler, StandardScaler, normalize
import ConfigParser
import os.path
from sklearn.metrics import mean_squared_error
from keras.preprocessing import sequence
import json, time
def ConfigSectionMap(settings_file, section):
Confi... |
"""
Convert an array of values into a dataset matrix
"""
def convert_to_timeseries(dataset, look_back=3):
dataX, dataY = [], []
for i in range(len(dataset) - look_back - 1):
a = dataset[i:(i + look_back)]
b = dataset[i + look_back]
dataX.append(a)
dataY.append(b)
data... | rmse_totals = []
for i in range(len(dataset)):
rmse = math.sqrt(mean_squared_error(dataset[i][0], predictions[i]))
rmse_totals.append(rmse)
return rmse_totals | identifier_body |
helpers.py | #!/usr/bin/python
import numpy, os, time, math
from sklearn.preprocessing import MinMaxScaler, StandardScaler, normalize
import ConfigParser
import os.path
from sklearn.metrics import mean_squared_error
from keras.preprocessing import sequence
import json, time
def ConfigSectionMap(settings_file, section):
Confi... |
command = columns[0]
if (command == 'wget'):
return 1
elif (command == 'rm'):
return 2
elif (command.startswith('./')):
return 3
elif (command == 'ls'):
return 4
elif (command == 'cat'):
return 5
elif (command == 'cp'):
return 6
elif (com... | columns = columns.split(" ")
if (len(columns) == 1 and type(columns[0]) == int):
# New osquery case shell_history query
return columns | random_line_split |
htmlappletelement.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use dom::attr::AttrValue;
use dom::bindings::codegen::Bindings::HTMLAppletElementBinding;
use dom::bindings::codeg... |
#[allow(unrooted_must_root)]
pub fn new(localName: Atom,
prefix: Option<DOMString>,
document: &Document) -> Root<HTMLAppletElement> {
let element = HTMLAppletElement::new_inherited(localName, prefix, document);
Node::reflect_node(box element, document, HTMLAppletE... | {
HTMLAppletElement {
htmlelement:
HTMLElement::new_inherited(localName, prefix, document)
}
} | identifier_body |
htmlappletelement.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use dom::attr::AttrValue;
use dom::bindings::codegen::Bindings::HTMLAppletElementBinding;
use dom::bindings::codeg... | (localName: Atom,
prefix: Option<DOMString>,
document: &Document) -> Root<HTMLAppletElement> {
let element = HTMLAppletElement::new_inherited(localName, prefix, document);
Node::reflect_node(box element, document, HTMLAppletElementBinding::Wrap)
}
}
impl HTMLAppletElem... | new | identifier_name |
htmlappletelement.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use dom::attr::AttrValue;
use dom::bindings::codegen::Bindings::HTMLAppletElementBinding;
use dom::bindings::codeg... | impl VirtualMethods for HTMLAppletElement {
fn super_type(&self) -> Option<&VirtualMethods> {
Some(self.upcast::<HTMLElement>() as &VirtualMethods)
}
fn parse_plain_attribute(&self, name: &Atom, value: DOMString) -> AttrValue {
match name {
&atom!("name") => AttrValue::from_atom... | make_atomic_setter!(SetName, "name");
}
| random_line_split |
keyboard-navigable-list-test.js | import { moduleForComponent, test } from 'ember-qunit';
import hbs from 'htmlbars-inline-precompile';
moduleForComponent('keyboard-navigable-list', 'Integration | Component | keyboard navigable list', {
integration: true
});
test('if passed in an array it renders the items in a list.', function(assert) {
//this.... | assert.equal(this.$('li.active').length, 0, 'by default no one is active');
});
test('if linkDirection is set, hasLink is true and a link is present', function(assert) {
this.set('theArray', [{ name: 'hello'}, {name: 'second item'}, {name: 'third item'}]);
this.render(hbs`{{keyboard-navigable-list contentArray=... |
this.render(hbs`{{keyboard-navigable-list contentArray=theArray objectKey="name"}}`);
| random_line_split |
ClientDS.js |
// ClientDS (Client Data Storage) works with Local/Session Storage, Cached Data, etc.
// Note that __SERVER__ side will crash when accessing Local/Session Storage => do a check for __CLIENT__
// Usage: ClientDS.Local.setItem('myKey', 'value')
let isClient = false
if (typeof __CLIENT__ === 'undefined') {
isClient = ... |
},
setJson: (key, val) => {
if (val) {
ClientDS.Session.setItem(key, JSON.stringify(val))
} else {
ClientDS.Session.setItem(key, JSON.stringify({}))
}
},
getItem: (key) => {
if (isClient) {
return sessionStorage.getItem(key)
}
return null
... | {
sessionStorage.setItem(key, val)
} | conditional_block |
ClientDS.js |
// ClientDS (Client Data Storage) works with Local/Session Storage, Cached Data, etc.
// Note that __SERVER__ side will crash when accessing Local/Session Storage => do a check for __CLIENT__
// Usage: ClientDS.Local.setItem('myKey', 'value')
let isClient = false
if (typeof __CLIENT__ === 'undefined') {
isClient = ... | (ss) {
ClientDS.Session.setJson('sessionData', ss)
}
}
| setLoginSession | identifier_name |
ClientDS.js | // ClientDS (Client Data Storage) works with Local/Session Storage, Cached Data, etc.
// Note that __SERVER__ side will crash when accessing Local/Session Storage => do a check for __CLIENT__
// Usage: ClientDS.Local.setItem('myKey', 'value')
let isClient = false
if (typeof __CLIENT__ === 'undefined') {
isClient = t... | },
setJson: (key, val) => {
if (val) {
ClientDS.Session.setItem(key, JSON.stringify(val))
} else {
ClientDS.Session.setItem(key, JSON.stringify({}))
}
},
getItem: (key) => {
if (isClient) {
return sessionStorage.getItem(key)
}
return null
}... | static Session = {
setItem: (key, val) => {
if (isClient) {
sessionStorage.setItem(key, val)
} | random_line_split |
managers.py | import collections
from .settings import preferences_settings
from .exceptions import CachedValueNotFound, DoesNotExist
class PreferencesManager(collections.Mapping):
"""Handle retrieving / caching of preferences"""
def __init__(self, model, registry, **kwargs):
self.model = model
self.re... | (self, key):
return self.get(key)
def __setitem__(self, key, value):
section, name = self.parse_lookup(key)
self.update_db_pref(section=section, name=name, value=value)
def __repr__(self):
return repr(self.all())
def __iter__(self):
return self.all().__iter__()
... | __getitem__ | identifier_name |
managers.py | import collections
from .settings import preferences_settings
from .exceptions import CachedValueNotFound, DoesNotExist
class PreferencesManager(collections.Mapping):
"""Handle retrieving / caching of preferences"""
def __init__(self, model, registry, **kwargs):
self.model = model
self.re... |
def parse_lookup(self, lookup):
try:
section, name = lookup.split(
preferences_settings.SECTION_KEY_SEPARATOR)
except ValueError:
name = lookup
section = None
return section, name
def get(self, key, model=False):
"""Return th... | return self.registry.get(section=section, name=name) | identifier_body |
managers.py | import collections
from .settings import preferences_settings
from .exceptions import CachedValueNotFound, DoesNotExist
class PreferencesManager(collections.Mapping):
"""Handle retrieving / caching of preferences""" |
def __init__(self, model, registry, **kwargs):
self.model = model
self.registry = registry
self.queryset = self.model.objects.all()
self.instance = kwargs.get('instance')
if self.instance:
self.queryset = self.queryset.filter(instance=self.instance)
@prope... | random_line_split | |
managers.py | import collections
from .settings import preferences_settings
from .exceptions import CachedValueNotFound, DoesNotExist
class PreferencesManager(collections.Mapping):
"""Handle retrieving / caching of preferences"""
def __init__(self, model, registry, **kwargs):
self.model = model
self.re... |
@property
def cache(self):
from django.core.cache import caches
return caches['default']
def __getitem__(self, key):
return self.get(key)
def __setitem__(self, key, value):
section, name = self.parse_lookup(key)
self.update_db_pref(section=section, name=name, ... | self.queryset = self.queryset.filter(instance=self.instance) | conditional_block |
test_client.rs | BlockNumber) {
let hash = self.block_hash(BlockId::Number(n)).unwrap();
let mut header: BlockHeader = self.block_header(BlockId::Number(n)).unwrap().decode();
header.set_extra_data(b"This extra data is way too long to be considered valid".to_vec());
let mut rlp = RlpStream::new_list(3);
rlp.append(&header);
... | random_line_split | ||
test_client.rs | let blocks_read = self.numbers.read();
let index = blocks_read.len() - delta;
blocks_read[&index].clone()
}
fn block_hash(&self, id: BlockId) -> Option<H256> {
match id {
BlockId::Hash(hash) => Some(hash),
BlockId::Number(n) => self.numbers.read().get(&(n as usize)).cloned(),
BlockId::Earliest => sel... | block | identifier_name | |
test_client.rs | 5".from_hex().unwrap(),
gas: U256::from(100_000),
gas_price: U256::from(20_000_000_000u64),
nonce: U256::zero()
};
let signed_tx = tx.sign(keypair.secret(), None);
self.set_balance(signed_tx.sender(), U256::from(10_000_000_000_000_000_000u64));
let res = self.miner.import_external_transactions(self, ve... | {
match id {
BlockId::Number(number) if (number as usize) < self.blocks.read().len() => BlockStatus::InChain,
BlockId::Hash(ref hash) if self.blocks.read().get(hash).is_some() => BlockStatus::InChain,
BlockId::Latest | BlockId::Pending | BlockId::Earliest => BlockStatus::InChain,
_ => BlockStatus::Unknown... | identifier_body | |
test_client.rs | 1);
let mut uncle_header = BlockHeader::new();
uncle_header.set_difficulty(From::from(n));
uncle_header.set_parent_hash(self.last_hash.read().clone());
uncle_header.set_number(n as BlockNumber);
uncles.append(&uncle_header);
header.set_uncles_hash(uncles.as_raw().sha3());
uncles
}... | {
Some(self.balances.read().get(address).cloned().unwrap_or_else(U256::zero))
} | conditional_block | |
index.d.ts | /*
* @license Apache-2.0
*
* Copyright (c) 2019 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 ap... | */
readonly byteLength: number | null;
}
/**
* Interface defining a returned iterable iterator.
*/
interface ExtendedIterableIterator extends ExtendedIter {
/**
* Returns a new iterable iterator.
*
* @returns iterable iterator
*/
[Symbol.iterator](): IterableIterator;
}
// Define a union type representing bot... | * PRNG state size (in bytes). | random_line_split |
ObjectNode.ts | import { IElement } from '../Element';
import { DomElementParent } from '../DomElementParent';
export default class | extends DomElementParent implements IElement {
public data?: string;
public form?: string;
public height?: string;
public name?: string;
public type?: string;
public usemap?: string;
public width?: string;
generate() : HTMLElement{
var element = document.createElement(... | ObjectNode | identifier_name |
ObjectNode.ts | import { IElement } from '../Element';
import { DomElementParent } from '../DomElementParent';
export default class ObjectNode extends DomElementParent implements IElement {
public data?: string;
public form?: string;
public height?: string;
public name?: string;
public type?: string;
public use... |
if (this.className) {
element.className = this.className;
}
if (this.data) {
element.data = this.data;
}
if (this.height) {
element.height = this.height;
}
if (this.name) {
element.name = this.name;
}
... | {
element.setAttribute('style', styleString);
} | conditional_block |
ObjectNode.ts | import { IElement } from '../Element';
import { DomElementParent } from '../DomElementParent';
export default class ObjectNode extends DomElementParent implements IElement {
public data?: string;
public form?: string;
public height?: string;
public name?: string;
public type?: string;
public use... | if (this.className) {
element.className = this.className;
}
if (this.data) {
element.data = this.data;
}
if (this.height) {
element.height = this.height;
}
if (this.name) {
element.name = this.name;
}
... | } | random_line_split |
views.py | import requests
from allauth.socialaccount import app_settings
from allauth.socialaccount.providers.jupyterhub.provider import (
JupyterHubProvider,
)
from allauth.socialaccount.providers.oauth2.views import (
OAuth2Adapter,
OAuth2CallbackView,
OAuth2LoginView,
)
class JupyterHubAdapter(OAuth2Adapter... |
oauth2_login = OAuth2LoginView.adapter_view(JupyterHubAdapter)
oauth2_callback = OAuth2CallbackView.adapter_view(JupyterHubAdapter)
| headers = {
'Authorization': 'Bearer {0}'.format(access_token)
}
extra_data = requests.get(self.profile_url, headers=headers)
user_profile = extra_data.json()
return self.get_provider().sociallogin_from_response(
request,
user_profile
) | identifier_body |
views.py | import requests
from allauth.socialaccount import app_settings
from allauth.socialaccount.providers.jupyterhub.provider import (
JupyterHubProvider,
)
from allauth.socialaccount.providers.oauth2.views import (
OAuth2Adapter,
OAuth2CallbackView,
OAuth2LoginView,
)
class JupyterHubAdapter(OAuth2Adapter... | 'Authorization': 'Bearer {0}'.format(access_token)
}
extra_data = requests.get(self.profile_url, headers=headers)
user_profile = extra_data.json()
return self.get_provider().sociallogin_from_response(
request,
user_profile
)
oauth2_login =... | headers = { | random_line_split |
views.py | import requests
from allauth.socialaccount import app_settings
from allauth.socialaccount.providers.jupyterhub.provider import (
JupyterHubProvider,
)
from allauth.socialaccount.providers.oauth2.views import (
OAuth2Adapter,
OAuth2CallbackView,
OAuth2LoginView,
)
class | (OAuth2Adapter):
provider_id = JupyterHubProvider.id
settings = app_settings.PROVIDERS.get(provider_id, {})
provider_base_url = settings.get("API_URL", '')
access_token_url = '{0}/hub/api/oauth2/token'.format(provider_base_url)
authorize_url = '{0}/hub/api/oauth2/authorize'.format(provider_base_ur... | JupyterHubAdapter | identifier_name |
cleanup-rvalue-scopes-cf.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 ... | let _x = AddFlags(1).get(); //~ ERROR value does not live long enough
let _x = &*arg(&AddFlags(1)); //~ ERROR value does not live long enough
let ref _x = *arg(&AddFlags(1)); //~ ERROR value does not live long enough
let &ref _x = arg(&AddFlags(1)); //~ ERROR value does not live long enough
let _x =... | random_line_split | |
cleanup-rvalue-scopes-cf.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 ... | { bits: u64 }
fn AddFlags(bits: u64) -> AddFlags {
AddFlags { bits: bits }
}
fn arg<'a>(x: &'a AddFlags) -> &'a AddFlags {
x
}
impl AddFlags {
fn get<'a>(&'a self) -> &'a AddFlags {
self
}
}
pub fn main() {
let _x = arg(&AddFlags(1)); //~ ERROR value does not live long enough
let _x... | AddFlags | identifier_name |
mod.rs | pub mod semantic;
#[derive(Debug)]
pub struct Program(pub Vec<Function>);
#[derive(Debug)]
pub struct Function {
pub name: String,
pub returns: Type,
pub statements: Vec<Statement>
}
#[derive(Debug)]
pub enum Statement {
Block(Vec<Statement>),
Declare(Type, String, Expression),
Assign(String,... | {
Neg
}
#[derive(Debug, Clone)]
pub enum BinaryOp {
Add,
Sub,
Mul,
Div,
Mod
}
#[derive(Debug, Clone)]
pub enum Type {
Unknown,
Error,
Any,
Void,
Int,
Char,
Bool,
Str,
Array(Box<Type>),
Pair(Box<Type>, Box<Type>)
}
impl PartialEq for Type {
fn eq(&s... | UnaryOp | identifier_name |
mod.rs | pub mod semantic;
#[derive(Debug)]
pub struct Program(pub Vec<Function>);
#[derive(Debug)]
pub struct Function {
pub name: String,
pub returns: Type,
pub statements: Vec<Statement>
}
#[derive(Debug)]
pub enum Statement {
Block(Vec<Statement>),
Declare(Type, String, Expression),
Assign(String,... | }
#[derive(Debug, Clone)]
pub enum Type {
Unknown,
Error,
Any,
Void,
Int,
Char,
Bool,
Str,
Array(Box<Type>),
Pair(Box<Type>, Box<Type>)
}
impl PartialEq for Type {
fn eq(&self, other: &Type) -> bool {
match *self {
Type::Unknown => false,
... | Div,
Mod | random_line_split |
UserFormModal.tsx | import { Trans } from "@lingui/macro";
import { i18nMark, withI18n } from "@lingui/react";
import mixin from "reactjs-mixin";
import { Hooks } from "PluginSDK";
import * as React from "react";
import StoreMixin from "#SRC/js/mixins/StoreMixin";
import AuthStore from "../../stores/AuthStore";
import FormModal from "..... | () {
return (
<div>
{Hooks.applyFilter("userAddPolicy", null)}
{Hooks.applyFilter(
"userFormModalFooter",
<Trans
render="p"
className="form-group-without-top-label flush-bottom text-align-center"
>
<strong>Important:</strong> Be... | getFooter | identifier_name |
UserFormModal.tsx | import { Trans } from "@lingui/macro";
import { i18nMark, withI18n } from "@lingui/react";
import mixin from "reactjs-mixin";
import { Hooks } from "PluginSDK";
import * as React from "react";
import StoreMixin from "#SRC/js/mixins/StoreMixin";
import AuthStore from "../../stores/AuthStore";
import FormModal from "..... | ,
value: "",
},
],
props,
state
);
}
getHeader() {
return Hooks.applyFilter(
"userFormModalHeader",
<ModalHeading>
<Trans render="span">Add User to Cluster</Trans>
</ModalHeading>
);
}
getFooter() {
return (
<div>
{Hoo... | {
return true;
} | identifier_body |
UserFormModal.tsx | import { Trans } from "@lingui/macro";
import { i18nMark, withI18n } from "@lingui/react";
import mixin from "reactjs-mixin";
import { Hooks } from "PluginSDK";
import * as React from "react";
import StoreMixin from "#SRC/js/mixins/StoreMixin";
import AuthStore from "../../stores/AuthStore";
import FormModal from "..... |
delete model.confirmPassword; // We don't need to send this to the backend.
this.setState({ disableNewUser: true });
const userModelObject = Hooks.applyFilter("userModelObject", {
...model,
creator_uid: AuthStore.getUser().uid,
cluster_url: `${window.location.protocol}//${window.location... | {
// Check if passwords match.
return this.setState({
errorMsg: i18n._(passwordsMessage),
});
} | conditional_block |
UserFormModal.tsx | import { Trans } from "@lingui/macro";
import { i18nMark, withI18n } from "@lingui/react";
import mixin from "reactjs-mixin";
import { Hooks } from "PluginSDK";
import * as React from "react";
import StoreMixin from "#SRC/js/mixins/StoreMixin";
import AuthStore from "../../stores/AuthStore";
import FormModal from "..... | };
onUserStoreCreateError(errorMsg, userID, xhr) {
this.setState({
disableNewUser: false,
errorMsg,
errorCode: xhr.status,
});
}
handleClose = () => {
this.setState({
disableNewUser: false,
errorMsg: false,
errorCode: null,
});
this.props.onClose();
};
... | errorCode: null,
});
this.props.onClose(); | random_line_split |
index.d.ts | import * as React from 'react';
import { StyledComponentProps } from './styles'
export { StyledComponentProps }
/**
* All standard components exposed by `material-ui` are `StyledComponents` with
* certain `classes`, on which one can also set a top-level `className` and inline
* `style`.
*/
export type StandardProp... | // From index.js
export { default as AppBar } from './AppBar';
export { default as Avatar } from './Avatar';
export { default as Badge } from './Badge';
export { default as BottomNavigation, BottomNavigationButton } from './BottomNavigation';
export { default as Button } from './Button';
export { default as ButtonBase ... | random_line_split | |
remove-system-libs.py | #!/usr/bin/env python
# @author: Martin Siggel <martin.siggel@dlr.de>
#
# This script fixes the cmake exports file by
# removing explicit linking to system libraries
import sys, re
def | (line):
"""
Removes libraries from the line that are found under /usr
"""
if sys.platform == 'win32':
return line
elif sys.platform == 'darwin':
return re.sub('/Applications/[-_a-zA-Z0-9/.]+.framework[;]?', '', line)
else:
return re.sub('/usr/[-_a-zA-Z0-9/]+.so[;]?', '',... | remove_absolute_paths | identifier_name |
remove-system-libs.py | #!/usr/bin/env python
# @author: Martin Siggel <martin.siggel@dlr.de>
#
# This script fixes the cmake exports file by
# removing explicit linking to system libraries
import sys, re
def remove_absolute_paths(line):
"""
Removes libraries from the line that are found under /usr
"""
if sys.platform == '... |
if __name__ == "__main__":
assert(len(sys.argv) == 2)
filename = sys.argv[1]
fix_paths(filename)
| with open(filename) as f:
lines = f.readlines()
# just select lines containing string IMPORTED_LINK_INTERFACE_LIBRARIES
for i, line in enumerate(lines):
if "IMPORTED_LINK_INTERFACE_LIBRARIES" in line or "INTERFACE_LINK_LIBRARIES" in line:
lines[i] = remove_absolute_p... | identifier_body |
remove-system-libs.py | #!/usr/bin/env python
# @author: Martin Siggel <martin.siggel@dlr.de>
#
# This script fixes the cmake exports file by
# removing explicit linking to system libraries
import sys, re
def remove_absolute_paths(line):
"""
Removes libraries from the line that are found under /usr
"""
if sys.platform == '... |
def fix_paths(filename):
with open(filename) as f:
lines = f.readlines()
# just select lines containing string IMPORTED_LINK_INTERFACE_LIBRARIES
for i, line in enumerate(lines):
if "IMPORTED_LINK_INTERFACE_LIBRARIES" in line or "INTERFACE_LINK_LIBRARIES" in line:
... | return re.sub('/usr/[-_a-zA-Z0-9/]+.so[;]?', '', line) | conditional_block |
remove-system-libs.py | #!/usr/bin/env python
# @author: Martin Siggel <martin.siggel@dlr.de>
#
# This script fixes the cmake exports file by
# removing explicit linking to system libraries
import sys, re
def remove_absolute_paths(line):
"""
Removes libraries from the line that are found under /usr
"""
if sys.platform == '... | # just select lines containing string IMPORTED_LINK_INTERFACE_LIBRARIES
for i, line in enumerate(lines):
if "IMPORTED_LINK_INTERFACE_LIBRARIES" in line or "INTERFACE_LINK_LIBRARIES" in line:
lines[i] = remove_absolute_paths(line)
fout = open(filename,'w')
fout.write(... | with open(filename) as f:
lines = f.readlines()
| random_line_split |
drugstore.py | import re
import os
from scrapy.spider import BaseSpider
from scrapy.selector import HtmlXPathSelector
from scrapy.http import Request, HtmlResponse
from scrapy.utils.response import get_base_url
from scrapy.utils.url import urljoin_rfc
from urllib import urlencode
import csv
from product_spiders.items import Produc... | if next_page:
next_page = urljoin_rfc(get_base_url(response), next_page[0])
yield Request(next_page, callback=self.parse_product)
products = hxs.select(u'//div[contains(@class,"itemGrid")]')
for product in products:
product_loader = ProductLoader(item=Produc... | next_page = hxs.select(u'//div[@style="float:left;padding-right:8px;"]/a[child::img]/@href').extract() | random_line_split |
drugstore.py | import re
import os
from scrapy.spider import BaseSpider
from scrapy.selector import HtmlXPathSelector
from scrapy.http import Request, HtmlResponse
from scrapy.utils.response import get_base_url
from scrapy.utils.url import urljoin_rfc
from urllib import urlencode
import csv
from product_spiders.items import Produc... | (self, response):
if not isinstance(response, HtmlResponse):
return
hxs = HtmlXPathSelector(response)
# categories
categories = hxs.select(u'//div[@id="MenuCntr"]//ul/li/a/@href').extract()
for url in categories:
url = urljoin_rfc(get_base_url(res... | parse | identifier_name |
drugstore.py | import re
import os
from scrapy.spider import BaseSpider
from scrapy.selector import HtmlXPathSelector
from scrapy.http import Request, HtmlResponse
from scrapy.utils.response import get_base_url
from scrapy.utils.url import urljoin_rfc
from urllib import urlencode
import csv
from product_spiders.items import Produc... |
# price range
price_range = hxs.select(u'//div[@class="srchRefine"]//a[preceding-sibling::div[@class="dimension" and text()="price range"]]/@href').extract()
for price in price_range:
price = urljoin_rfc(get_base_url(response), price)
yield Request(price, callback=self.... | see_all = urljoin_rfc(get_base_url(response), see_all[0])
yield Request(see_all) | conditional_block |
drugstore.py | import re
import os
from scrapy.spider import BaseSpider
from scrapy.selector import HtmlXPathSelector
from scrapy.http import Request, HtmlResponse
from scrapy.utils.response import get_base_url
from scrapy.utils.url import urljoin_rfc
from urllib import urlencode
import csv
from product_spiders.items import Produc... | yield Request(price, callback=self.parse_product)
def parse_product(self, response):
if not isinstance(response, HtmlResponse):
return
hxs = HtmlXPathSelector(response)
# pages
next_page = hxs.select(u'//div[@style="float:left;padding-right:8px;"]/a[ch... | if not isinstance(response, HtmlResponse):
return
hxs = HtmlXPathSelector(response)
# categories
categories = hxs.select(u'//div[@id="MenuCntr"]//ul/li/a/@href').extract()
for url in categories:
url = urljoin_rfc(get_base_url(response), url)
y... | identifier_body |
vacuum2.py | import agents as ag
def HW2Agent() -> object:
"An agent that keeps track of what locations are clean or dirty."
oldPercepts = [('None', 'Clean')]
oldActions = ['NoOp']
actionScores = [{
'Right': 0,
'Left': 0,
'Up': -1,
'Down': -1,
'NoOp': -100,
}]
level ... | })
highest = -80
for actionType, score in actionScores[level].items():
if score > highest:
highest = score
action = actionType
print(actionScores)
oldPercepts.append(percept)
oldActions.append... | "Same as ReflexVacuumAgent, except if everything is clean, do NoOp."
level = len(actionScores) - 1
bump, status = percept
lastBump, lastStatus = oldPercepts[-1]
lastAction = oldActions[-1]
if status == 'Dirty':
action = 'Suck'
actionScores[level][lastActi... | identifier_body |
vacuum2.py | import agents as ag
def HW2Agent() -> object:
"An agent that keeps track of what locations are clean or dirty."
oldPercepts = [('None', 'Clean')]
oldActions = ['NoOp']
actionScores = [{
'Right': 0,
'Left': 0,
'Up': -1,
'Down': -1,
'NoOp': -100,
}]
level ... |
else:
if bump == 'Bump':
actionScores[level][lastAction] -= 10
else:
if lastAction == 'Up' or lastAction == 'Down':
actionScores.append({
'Right': 0,
'Left': 0,
'... | action = 'Suck'
actionScores[level][lastAction] += 2 | conditional_block |
vacuum2.py | import agents as ag
def HW2Agent() -> object:
"An agent that keeps track of what locations are clean or dirty."
oldPercepts = [('None', 'Clean')]
oldActions = ['NoOp']
actionScores = [{
'Right': 0,
'Left': 0,
'Up': -1,
'Down': -1,
'NoOp': -100,
}]
level ... | (percept):
"Same as ReflexVacuumAgent, except if everything is clean, do NoOp."
level = len(actionScores) - 1
bump, status = percept
lastBump, lastStatus = oldPercepts[-1]
lastAction = oldActions[-1]
if status == 'Dirty':
action = 'Suck'
actionSco... | program | identifier_name |
vacuum2.py | import agents as ag
def HW2Agent() -> object:
"An agent that keeps track of what locations are clean or dirty."
oldPercepts = [('None', 'Clean')]
oldActions = ['NoOp']
actionScores = [{
'Right': 0,
'Left': 0,
'Up': -1,
'Down': -1,
'NoOp': -100,
}]
level ... | oldActions.append(action)
return action
return ag.Agent(program) |
print(actionScores)
oldPercepts.append(percept) | random_line_split |
canvasgradient.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use cssparser::RGBA;
use canvas_traits::{CanvasGradientStop, FillOrStrokeStyle, LinearGradientStyle, RadialGradien... |
}
| {
let gradient_stops = self.stops.borrow().clone();
match self.style {
CanvasGradientStyle::Linear(ref gradient) => {
FillOrStrokeStyle::LinearGradient(
LinearGradientStyle::new(gradient.x0, gradient.y0,
gradie... | identifier_body |
canvasgradient.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use cssparser::RGBA;
use canvas_traits::{CanvasGradientStop, FillOrStrokeStyle, LinearGradientStyle, RadialGradien... | FillOrStrokeStyle::LinearGradient(
LinearGradientStyle::new(gradient.x0, gradient.y0,
gradient.x1, gradient.y1,
gradient_stops))
},
CanvasGradientStyle::Radial(ref gradie... | fn to_fill_or_stroke_style(&self) -> FillOrStrokeStyle {
let gradient_stops = self.stops.borrow().clone();
match self.style {
CanvasGradientStyle::Linear(ref gradient) => { | random_line_split |
canvasgradient.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use cssparser::RGBA;
use canvas_traits::{CanvasGradientStop, FillOrStrokeStyle, LinearGradientStyle, RadialGradien... | {
Linear(LinearGradientStyle),
Radial(RadialGradientStyle),
}
impl CanvasGradient {
fn new_inherited(style: CanvasGradientStyle) -> CanvasGradient {
CanvasGradient {
reflector_: Reflector::new(),
style: style,
stops: DOMRefCell::new(Vec::new()),
}
}
... | CanvasGradientStyle | identifier_name |
canvasgradient.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use cssparser::RGBA;
use canvas_traits::{CanvasGradientStop, FillOrStrokeStyle, LinearGradientStyle, RadialGradien... |
}
}
}
| {
FillOrStrokeStyle::RadialGradient(
RadialGradientStyle::new(gradient.x0, gradient.y0, gradient.r0,
gradient.x1, gradient.y1, gradient.r1,
gradient_stops))
} | conditional_block |
companies.js | $(function(){
$("#addCompanyForm").validate({
rules: {
name : {
required : true
},
email: {
required: true,
email: true
},
url : {
required : true,
url : true
}
},
messages: {
name : {
required : "Please enter your company name"
},
url : {
required : "P... | }
});
$('#addCompanyDialog').on('hide.bs.modal', function (e) {
refresh();
});
$('#addCompanyDialog').on('shown.bs.modal', function (e) {
$('#name').focus();
$('#id').val('');
var id = $(e.relatedTarget).attr('id');
var isEdit = $(e.relatedTarget).hasClass('fa-edit');
console.... | email: {
required: "Enter your Company email address",
email: "Please enter a valid email address",
} | random_line_split |
sidebar-status.service.spec.ts | // Copyright 2018 The Oppia Authors. All Rights Reserved.
//
// 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 ap... |
// This approach was choosen because spyOn() doesn't work on properties
// that doesn't have a get access type.
// Without this approach the test will fail because it'll throw
// 'Property innerWidth does not have access type get' error.
// eslint-disable-next-line max-len
// ref: https://devel... |
beforeEach(() => {
$window = TestBed.get(WindowRef);
sss = TestBed.get(SidebarStatusService); | random_line_split |
async-test.ts | /**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
class | implements ZoneSpec {
_finishCallback: Function;
_failCallback: Function;
_pendingMicroTasks: boolean = false;
_pendingMacroTasks: boolean = false;
_alreadyErrored: boolean = false;
runZone = Zone.current;
constructor(finishCallback: Function, failCallback: Function, namePrefix: string) {
this._fini... | AsyncTestZoneSpec | identifier_name |
async-test.ts | /**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
class AsyncTestZoneSpec implements ZoneSpec {
_finishCallback: Function;
_failCallback: Function;
_pendingMicr... |
return false;
}
onHasTask(delegate: ZoneDelegate, current: Zone, target: Zone, hasTaskState: HasTaskState) {
delegate.hasTask(target, hasTaskState);
if (hasTaskState.change == 'microTask') {
this._pendingMicroTasks = hasTaskState.microTask;
this._finishCallbackIfDone();
} else if (hasT... | {
this._failCallback(error);
this._alreadyErrored = true;
} | conditional_block |
async-test.ts | /**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
class AsyncTestZoneSpec implements ZoneSpec {
_finishCallback: Function;
_failCallback: Function;
_pendingMicr... | // Let the parent try to handle the error.
const result = parentZoneDelegate.handleError(targetZone, error);
if (result) {
this._failCallback(error);
this._alreadyErrored = true;
}
return false;
}
onHasTask(delegate: ZoneDelegate, current: Zone, target: Zone, hasTaskState: HasTaskSt... | random_line_split | |
async-test.ts | /**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
class AsyncTestZoneSpec implements ZoneSpec {
_finishCallback: Function;
_failCallback: Function;
_pendingMicr... |
_finishCallbackIfDone() {
if (!(this._pendingMicroTasks || this._pendingMacroTasks)) {
// We do this because we would like to catch unhandled rejected promises.
this.runZone.run(() => {
setTimeout(() => {
if (!this._alreadyErrored && !(this._pendingMicroTasks || this._pendingMacroT... | {
this._finishCallback = finishCallback;
this._failCallback = failCallback;
this.name = 'asyncTestZone for ' + namePrefix;
} | identifier_body |
track.rs | use chill::DocumentId;
use id3::Tag;
use Uri;
#[derive(Serialize, Deserialize, Debug)]
pub struct Track {
#[serde(rename="type")]
_type: String,
pub name: String,
pub number: u32,
pub artist: DocumentId,
pub album: DocumentId,
pub uris: Vec<Uri>,
}
impl Track {
pub fn new(name: &str,
... | {
pub name: String,
pub number: u32,
pub artist: String,
pub album: String,
pub uri: Uri,
}
impl DecodedTrack {
pub fn from_tag(tag: Tag, uri: Uri) -> Option<DecodedTrack> {
let artist = match tag.artist() {
Some(artist) => artist,
None => return None,
... | DecodedTrack | identifier_name |
track.rs | use chill::DocumentId;
use id3::Tag;
use Uri;
#[derive(Serialize, Deserialize, Debug)]
pub struct Track {
#[serde(rename="type")]
_type: String,
pub name: String,
pub number: u32,
pub artist: DocumentId,
pub album: DocumentId,
pub uris: Vec<Uri>,
}
impl Track {
pub fn new(name: &str,
... | #[derive(Serialize, Deserialize, Debug)]
pub struct DecodedTrack {
pub name: String,
pub number: u32,
pub artist: String,
pub album: String,
pub uri: Uri,
}
impl DecodedTrack {
pub fn from_tag(tag: Tag, uri: Uri) -> Option<DecodedTrack> {
let artist = match tag.artist() {
S... | }
| random_line_split |
IPv4.js | /**
* Filter type for {@link Ext.grid.column.Number number columns}.
*
* Based on Ext.grid.filters.filter.Number.
*/
Ext.define('NetProfile.grid.filters.filter.IPv4', {
extend: 'NetProfile.grid.filters.filter.TriFilter',
alias: 'grid.filter.ipv4',
uses: ['NetProfile.form.field.IPv4'],
type: 'ipv4',
config: {
... |
else
me.menu.add(key);
}
},
getValue: function(field)
{
var value = {};
value[field.filterKey] = field.getValue();
return value;
},
onIPValueChange: function(field, newval)
{
var me = this,
updateBuffer = me.updateBuffer;
if(updateBuffer)
me.task.delay(updateBuffer, null, null, [me.getV... | {
field = fields[key];
cfg = {
value: (me.filter && me.filter[key] ? me.filter[key].getValue() : null),
labelClsExtra: Ext.baseCSSPrefix + 'grid-filters-icon ' + field.iconCls
};
if(itemDefaults)
Ext.merge(cfg, itemDefaults);
Ext.merge(cfg, field);
delete cfg.iconCls;
me.f... | conditional_block |
IPv4.js | /**
* Filter type for {@link Ext.grid.column.Number number columns}.
*
* Based on Ext.grid.filters.filter.Number.
*/
Ext.define('NetProfile.grid.filters.filter.IPv4', {
extend: 'NetProfile.grid.filters.filter.TriFilter',
alias: 'grid.filter.ipv4',
uses: ['NetProfile.form.field.IPv4'],
type: 'ipv4',
config: {
... | var value = {};
value[field.filterKey] = field.getValue();
return value;
},
onIPValueChange: function(field, newval)
{
var me = this,
updateBuffer = me.updateBuffer;
if(updateBuffer)
me.task.delay(updateBuffer, null, null, [me.getValue(field)]);
else
me.setValue(me.getValue(field));
}
}); | { | random_line_split |
CommandLoader.ts | import * as Glob from 'glob';
import * as Path from 'path';
import { Logger, logger } from '../util/logger/Logger';
import { BaseCommandName } from '../types/BaseCommandName';
import { Client } from '../client/Client';
import { Command } from './Command';
import { CommandRegistry } from './CommandRegistry';
import { Ut... | (client: Client)
{
this._client = client;
this._commands = client.commands;
}
/**
* Load commands from the given directory
* @param {string} dir Directory to load from
* @param {boolean} [base=false] Whether or not the commands being loaded are base commands
* @returns {number} The number of Commands lo... | constructor | identifier_name |
CommandLoader.ts | import * as Glob from 'glob';
import * as Path from 'path';
import { Logger, logger } from '../util/logger/Logger';
import { BaseCommandName } from '../types/BaseCommandName';
import { Client } from '../client/Client';
import { Command } from './Command';
import { CommandRegistry } from './CommandRegistry';
import { Ut... |
private readonly _client: Client;
private readonly _commands: CommandRegistry<any>;
public constructor(client: Client)
{
this._client = client;
this._commands = client.commands;
}
/**
* Load commands from the given directory
* @param {string} dir Directory to load from
* @param {boolean} [base=false]... | export class CommandLoader
{
@logger('CommandLoader')
private readonly _logger!: Logger; | random_line_split |
CommandLoader.ts | import * as Glob from 'glob';
import * as Path from 'path';
import { Logger, logger } from '../util/logger/Logger';
import { BaseCommandName } from '../types/BaseCommandName';
import { Client } from '../client/Client';
import { Command } from './Command';
import { CommandRegistry } from './CommandRegistry';
import { Ut... |
/**
* Load commands from the given directory
* @param {string} dir Directory to load from
* @param {boolean} [base=false] Whether or not the commands being loaded are base commands
* @returns {number} The number of Commands loaded from the directory
*/
public loadCommandsFrom(dir: string, base: boolean = ... | {
this._client = client;
this._commands = client.commands;
} | identifier_body |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.