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
Add.py
import os import libxml2 from sfatables.command import Command from sfatables.globals import sfatables_config, target_dir, match_dir class Add(Command): def __init__(self): self.options = [('-A','--add')] self.help = 'Add a rule to a chain' self.matches = True self.targets = True ...
def call(self, command_options, match_options, target_options): chain = command_options.args[0] ret = self.call_gen(chain, 'match',match_dir, match_options) if (ret): ret = self.call_gen(chain, 'target',target_dir, target_options) return ret
filename = os.path.join(dir, options.name+".xml") xmldoc = libxml2.parseFile(filename) p = xmldoc.xpathNewContext() supplied_arguments = options.arguments if (hasattr(options,'element') and options.element): element = options.element else: element='*...
identifier_body
Add.py
import os import libxml2 from sfatables.command import Command from sfatables.globals import sfatables_config, target_dir, match_dir class
(Command): def __init__(self): self.options = [('-A','--add')] self.help = 'Add a rule to a chain' self.matches = True self.targets = True return def getnextfilename(self,type,chain): dir = sfatables_config + "/"+chain; last_rule_number = 0 for (...
Add
identifier_name
Add.py
import os import libxml2 from sfatables.command import Command from sfatables.globals import sfatables_config, target_dir, match_dir class Add(Command): def __init__(self): self.options = [('-A','--add')] self.help = 'Add a rule to a chain' self.matches = True self.targets = True ...
for option in supplied_arguments: option_name = option['name'] option_value = getattr(options,option_name) if (hasattr(options,option_name) and getattr(options,option_name)): context = p.xpathEval("//rule[@element='%s' or @element='*']/argument[name='%s']"%(...
if (hasattr(options,'element') and options.element): element = options.element else: element='*'
random_line_split
Add.py
import os import libxml2 from sfatables.command import Command from sfatables.globals import sfatables_config, target_dir, match_dir class Add(Command): def __init__(self): self.options = [('-A','--add')] self.help = 'Add a rule to a chain' self.matches = True self.targets = True ...
filename = self.getnextfilename(type,chain) file_path = os.path.join(sfatables_config, chain, filename) if not os.path.isdir(os.path.dirname(file_path)): os.makedirs(os.path.dirname(file_path)) xmldoc.saveFile(file_path) p.xpathFreeContext() xmldoc.freeDoc()...
context = p.xpathEval("//rule[@element='%s' or @element='*']/argument[name='%s']"%(element, option_name)) if (not context): raise Exception('Unknown option %s for match %s and element %s'%(option,option['name'], element)) else: # Add the value of o...
conditional_block
filesystem.ts
/* * Copyright (C) 2017 TypeFox and others. * * 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 */ import { Disposable } from '@theia/core/lib/commo...
* move the file to trash. */ delete(uri: string, options?: { moveToTrash?: boolean }): Promise<void>; /** * Returns the encoding of the given file resource. */ getEncoding(uri: string): Promise<string>; /** * Return list of available roots. */ getRoots(): Promise<File...
* Deletes the provided file. The optional moveToTrash parameter allows to
random_line_split
limit.js
'use strict'; var ms = require('ms'); var SimpleStrategy = require('./simple.js'); module.exports = LimitStrategy; function LimitStrategy(provider, options) { SimpleStrategy.call(this, provider); this.max = options.max || Infinity; this.min = options.min || 0; for (var i = 0; i < this.min; i++) { this.exp...
} LimitStrategy.prototype = Object.create(SimpleStrategy.prototype); LimitStrategy.prototype.constructor = LimitStrategy; /** * Only allow expanding if the pool size has not hit the maximum */ LimitStrategy.prototype.expand = function () { if (this.poolSize < this.max) { return SimpleStrategy.prototype.expand...
{ var self = this; idleTime = ms(idleTime.toString()); var timeout; var tryShrink = function () { if (self.pool.length) { self.shrink(); } if (self.pool.length) { timeout = setTimeout(tryShrink, idleTime); } } this.on('begin-transaction', function () { ...
conditional_block
limit.js
'use strict'; var ms = require('ms'); var SimpleStrategy = require('./simple.js'); module.exports = LimitStrategy; function
(provider, options) { SimpleStrategy.call(this, provider); this.max = options.max || Infinity; this.min = options.min || 0; for (var i = 0; i < this.min; i++) { this.expand(); } var idleTime = options.idleTime; var lowWaterMark = this.lowWaterMark || 0; if (idleTime && idleTime !== Infinity) { v...
LimitStrategy
identifier_name
limit.js
'use strict'; var ms = require('ms'); var SimpleStrategy = require('./simple.js'); module.exports = LimitStrategy; function LimitStrategy(provider, options) { SimpleStrategy.call(this, provider); this.max = options.max || Infinity; this.min = options.min || 0; for (var i = 0; i < this.min; i++) { this.exp...
/** * Only allow expanding if the pool size has not hit the maximum */ LimitStrategy.prototype.expand = function () { if (this.poolSize < this.max) { return SimpleStrategy.prototype.expand.call(this); } }; /** * Only allow shrinking if the pool size is above the minimum or it is destroyed */ LimitStrategy...
} LimitStrategy.prototype = Object.create(SimpleStrategy.prototype); LimitStrategy.prototype.constructor = LimitStrategy;
random_line_split
limit.js
'use strict'; var ms = require('ms'); var SimpleStrategy = require('./simple.js'); module.exports = LimitStrategy; function LimitStrategy(provider, options)
LimitStrategy.prototype = Object.create(SimpleStrategy.prototype); LimitStrategy.prototype.constructor = LimitStrategy; /** * Only allow expanding if the pool size has not hit the maximum */ LimitStrategy.prototype.expand = function () { if (this.poolSize < this.max) { return SimpleStrategy.prototype.expand.c...
{ SimpleStrategy.call(this, provider); this.max = options.max || Infinity; this.min = options.min || 0; for (var i = 0; i < this.min; i++) { this.expand(); } var idleTime = options.idleTime; var lowWaterMark = this.lowWaterMark || 0; if (idleTime && idleTime !== Infinity) { var self = this; ...
identifier_body
os_release.rs
use std::fs; pub enum OsReleaseId { Amazon, CentOs, Debian, Ubuntu, } const OS_RELEASE_PATH: &str = "/etc/os-release"; impl OsReleaseId { fn from_os_release_str(s: &str) -> Option<Self> { let id_line = s.lines().find(|l| l.starts_with("ID="))?;
let id = id_line.trim_start_matches("ID=").trim_matches('"'); match id { "amzn" => Some(OsReleaseId::Amazon), "centos" => Some(OsReleaseId::CentOs), "debian" => Some(OsReleaseId::Debian), "ubuntu" => Some(OsReleaseId::Ubuntu), _ => None, ...
random_line_split
os_release.rs
use std::fs; pub enum OsReleaseId { Amazon, CentOs, Debian, Ubuntu, } const OS_RELEASE_PATH: &str = "/etc/os-release"; impl OsReleaseId { fn from_os_release_str(s: &str) -> Option<Self> { let id_line = s.lines().find(|l| l.starts_with("ID="))?; let id = id_line.trim_start_matches(...
() -> Option<Self> { fs::read_to_string(OS_RELEASE_PATH) .ok() .as_deref() .and_then(Self::from_os_release_str) } } #[cfg(test)] mod tests { use super::*; #[test] fn test_parse_from_os_release() { let actual = OsReleaseId::from_os_release...
parse_os_release
identifier_name
pending.ts
// Copyright 2019 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License.
// // 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 Licen...
// You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0
random_line_split
moin_migration_cleanup.py
import re from waliki.signals import page_saved from optparse import make_option from django.core.management.base import BaseCommand, CommandError from waliki.models import Page from django.utils.translation import ugettext_lazy as _ from django.utils.text import get_text_list try: from waliki.attachments.models im...
if 'title' in filters and not page.title: title = page._get_part('get_document_title') if raw != page.raw or title: if title: page.title = title if raw != page.raw: page.raw = raw page.save...
if not pandoc: print('The filter "code" need Pandoc installed in your system. Ignoring') else: raw = code(raw)
conditional_block
moin_migration_cleanup.py
import re from waliki.signals import page_saved from optparse import make_option from django.core.management.base import BaseCommand, CommandError from waliki.models import Page from django.utils.translation import ugettext_lazy as _ from django.utils.text import get_text_list try: from waliki.attachments.models im...
(rst_content): # require emojis_map = { ':)': 'smile', ':-)': 'smile', ';)': 'wink', ';-)': 'wink', ':-?': 'smirk', ':?': 'smirk', ':(': 'confused', ':-(': 'confused', ':D': 'laughing', ':-D': 'laughing', ':-P': 'stuck_out_t...
emojis
identifier_name
moin_migration_cleanup.py
import re from waliki.signals import page_saved from optparse import make_option from django.core.management.base import BaseCommand, CommandError from waliki.models import Page from django.utils.translation import ugettext_lazy as _ from django.utils.text import get_text_list try: from waliki.attachments.models im...
pattern = r'^~+$' return re.sub(pattern, dashrepl, rst_content, flags=re.MULTILINE) def code(rst_content): if not pandoc: return rst_content pattern = r'^\:\:\n\s+\.\. raw:: html\n\s+(<span class\=\"line\"\>.*?|\s+?<\/span\>)\n\s*$' def convert(match): source = match.groups()[0] ...
return '-' * len(matchobj.group(0))
identifier_body
moin_migration_cleanup.py
import re from waliki.signals import page_saved from optparse import make_option from django.core.management.base import BaseCommand, CommandError from waliki.models import Page from django.utils.translation import ugettext_lazy as _ from django.utils.text import get_text_list try: from waliki.attachments.models im...
filters = valid_filters else: filters = [f.strip() for f in filters.split(',')] if not set(filters).issubset(valid_filters): valid = get_text_list(valid_filters, 'and') raise CommandError("At least one filter is unknown. Valid filters are:\n ...
filters = options['filters'] if filters == 'all':
random_line_split
SeriesFactory.ts
module n3Charts.Factory.Series { 'use strict'; export class SeriesFactory extends n3Charts.Factory.BaseFactory { public svg: D3.Selection; public type: string;
static seriesClassSuffix: string = '-series'; protected data: Utils.Data; protected options: Options.Options; create() { this.createContainer(this.factoryMgr.get('container').data); // Hard update this.eventMgr.on('data-update.' + this.type, this.update.bind(this)); // Soft u...
static containerClassSuffix: string = '-data';
random_line_split
SeriesFactory.ts
module n3Charts.Factory.Series { 'use strict'; export class SeriesFactory extends n3Charts.Factory.BaseFactory { public svg: D3.Selection; public type: string; static containerClassSuffix: string = '-data'; static seriesClassSuffix: string = '-series'; protected data: Utils.Data; protect...
(parent: D3.Selection) { this.svg = parent .append('g') .attr('class', this.type + SeriesFactory.containerClassSuffix); } updateSeriesContainer(series: Options.ISeriesOptions[]) { // Create a data join var groups = this.svg .selectAll('.' + this.type + SeriesFactory.se...
createContainer
identifier_name
SeriesFactory.ts
module n3Charts.Factory.Series { 'use strict'; export class SeriesFactory extends n3Charts.Factory.BaseFactory { public svg: D3.Selection; public type: string; static containerClassSuffix: string = '-data'; static seriesClassSuffix: string = '-series'; protected data: Utils.Data; protect...
updateSeriesContainer(series: Options.ISeriesOptions[]) { // Create a data join var groups = this.svg .selectAll('.' + this.type + SeriesFactory.seriesClassSuffix) // Use the series id as key for the join .data(series, (d: Options.ISeriesOptions) => d.id); // Create a ne...
{ this.svg = parent .append('g') .attr('class', this.type + SeriesFactory.containerClassSuffix); }
identifier_body
consoleauth.py
# Copyright (c) 2016 Intel, Inc. # Copyright (c) 2013 OpenStack Foundation # 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/li...
(): return {'DEFAULT': CONSOLEAUTH_OPTS}
list_opts
identifier_name
consoleauth.py
# Copyright (c) 2016 Intel, Inc. # Copyright (c) 2013 OpenStack Foundation # 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/li...
console_token_ttl = cfg.IntOpt('console_token_ttl', default=600, help='How many seconds before deleting tokens') CONSOLEAUTH_OPTS = [consoleauth_topic_opt, console_token_ttl] def register_opts(conf): conf.register_opts(CONSOLEAUTH_OPTS) def list_opts(): return {'DEFAULT': CONSOLEAUTH_OPTS}
consoleauth_topic_opt = cfg.StrOpt('consoleauth_topic', default='consoleauth', help='The topic console auth proxy nodes listen on')
random_line_split
consoleauth.py
# Copyright (c) 2016 Intel, Inc. # Copyright (c) 2013 OpenStack Foundation # 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/li...
return {'DEFAULT': CONSOLEAUTH_OPTS}
identifier_body
angular-ui-router.d.ts
// Compiled using typings@0.6.10 // Source: https://raw.githubusercontent.com/DefinitelyTyped/DefinitelyTyped/655f8c1bf3c71b0e1ba415b36309604f79326ac8/angular-ui-router/angular-ui-router.d.ts // Type definitions for Angular JS 1.1.5+ (ui.router module) // Project: https://github.com/angular-ui/ui-router // Definitions ...
when(whenPath: IUrlMatcher, hanlder: Function): IUrlRouterProvider; when(whenPath: IUrlMatcher, handler: any[]): IUrlRouterProvider; when(whenPath: IUrlMatcher, toPath: string): IUrlRouterProvider; when(whenPath: string, handler: Function): IUrlRouterProvider; when(whenPath: stri...
interface IUrlRouterProvider extends angular.IServiceProvider { when(whenPath: RegExp, handler: Function): IUrlRouterProvider; when(whenPath: RegExp, handler: any[]): IUrlRouterProvider; when(whenPath: RegExp, toPath: string): IUrlRouterProvider;
random_line_split
test.py
#!/usr/bin/env finemonkeyrunner # -*- coding:utf8 -*- import sys sys.path.append(r'D:\learning\python\auto\fineMonkeyRunner') from com.fine.android.finemonkeyrunner import fineMonkeyRunner # 导入包路径,否则找不到 ---注意 #sys.path.append(r'C:\Users\wangxu\AppData\Local\Android\sdk\tools\testscript')
finemonkeyrunner = fineMonkeyRunner('emulator-5554') #finemonkeyrunner.assertfocusedwindowmame('com.mdsd.wiicare/com.mdsd.wiicare.function.LoginActivity_') #finemonkeyrunner.assertcurrentactivity('com.mdsd.wiicare/com.mdsd.wiicare.function.LoginActivity_') view = finemonkeyrunner.getviewbyID('id/etAccount') print finem...
#sys.path.append(r'D:\learning\python\auto\fineMonkeyRunner')
random_line_split
index.d.ts
/// <reference types="node" /> /**
* found in the LICENSE file at https://angular.io/license */ import { BuilderContext, BuilderOutput } from '@angular-devkit/architect'; import { WebpackLoggingCallback } from '@angular-devkit/build-webpack'; import { experimental, json, logging, virtualFs } from '@angular-devkit/core'; import * as fs from 'fs'; impor...
* @license * Copyright Google Inc. All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be
random_line_split
test_onyx_config.py
# # (c) 2016 Red Hat Inc. # # This file is part of Ansible # # Ansible is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # Ansible is d...
def test_onyx_config_after(self): set_module_args(dict(lines=['hostname foo'], after=['test1', 'test2'])) commands = ['hostname foo', 'test1', 'test2'] self.execute_module(changed=True, commands=commands, sort=False, is_updates=True) def test_onyx_config_before_after(self): se...
set_module_args(dict(lines=['hostname foo'], before=['test1', 'test2'])) commands = ['test1', 'test2', 'hostname foo'] self.execute_module(changed=True, commands=commands, sort=False, is_updates=True)
identifier_body
test_onyx_config.py
# # (c) 2016 Red Hat Inc. # # This file is part of Ansible # # Ansible is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # Ansible is d...
(self): set_module_args(dict(lines=['hostname foo'])) commands = ['hostname foo'] self.execute_module(changed=True, commands=commands, is_updates=True) def test_onyx_config_before(self): set_module_args(dict(lines=['hostname foo'], before=['test1', 'test2'])) commands = ['te...
test_onyx_config_lines_wo_parents
identifier_name
test_onyx_config.py
#
# (c) 2016 Red Hat Inc. # # This file is part of Ansible # # Ansible is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # Ansible is dis...
random_line_split
mpmc_bounded_queue.rs
/* Copyright (c) 2010-2011 Dmitry Vyukov. All rights reserved. * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, * this list of con...
let q = Queue::with_capacity(nthreads*nmsgs); assert_eq!(None, q.pop()); let (tx, rx) = channel(); for _ in 0..nthreads { let q = q.clone(); let tx = tx.clone(); thread::spawn(move || { let q = q; for i in 0..nmsgs { ...
#[test] fn test() { let nthreads = 8; let nmsgs = 1000;
random_line_split
mpmc_bounded_queue.rs
/* Copyright (c) 2010-2011 Dmitry Vyukov. All rights reserved. * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, * this list of con...
<T> { state: Arc<State<T>>, } impl<T> State<T> { fn with_capacity(capacity: usize) -> State<T> { let capacity = if capacity < 2 || (capacity & (capacity - 1)) != 0 { if capacity < 2 { 2 } else { // use next power of 2 as capacity c...
Queue
identifier_name
mpmc_bounded_queue.rs
/* Copyright (c) 2010-2011 Dmitry Vyukov. All rights reserved. * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, * this list of con...
, Some(_) => { i += 1; if i == nmsgs { break } } } } tx.send(i).unwrap(); }); } for rx in &mut completion_rxs { assert_eq!(...
{}
conditional_block
test_release.py
# Copyright (C) 2015-2019 The Software Heritage developers # See the AUTHORS file at the top-level directory of this distribution # License: GNU Affero General Public License version 3, or any later version # See top-level LICENSE file for more information from datetime import datetime from hypothesis import given ...
) expected_release["target_url"] = target_url assert rv.data == expected_release def test_api_release_not_found(api_client): unknown_release_ = random_sha1() url = reverse("api-1-release", url_args={"sha1_git": unknown_release_}) rv = check_api_get_responses(api_client, url, sta...
target_url = reverse( "api-1-%s" % target_type.value, url_args=url_args, request=rv.wsgi_request
random_line_split
test_release.py
# Copyright (C) 2015-2019 The Software Heritage developers # See the AUTHORS file at the top-level directory of this distribution # License: GNU Affero General Public License version 3, or any later version # See top-level LICENSE file for more information from datetime import datetime from hypothesis import given ...
(api_client, release): url = reverse( "api-1-release-uppercase-checksum", url_args={"sha1_git": release.upper()} ) resp = check_http_get_response(api_client, url, status_code=302) redirect_url = reverse( "api-1-release-uppercase-checksum", url_args={"sha1_git": release} ) asse...
test_api_release_uppercase
identifier_name
test_release.py
# Copyright (C) 2015-2019 The Software Heritage developers # See the AUTHORS file at the top-level directory of this distribution # License: GNU Affero General Public License version 3, or any later version # See top-level LICENSE file for more information from datetime import datetime from hypothesis import given ...
@given(release()) def test_api_release_uppercase(api_client, release): url = reverse( "api-1-release-uppercase-checksum", url_args={"sha1_git": release.upper()} ) resp = check_http_get_response(api_client, url, status_code=302) redirect_url = reverse( "api-1-release-uppercase-checks...
unknown_release_ = random_sha1() url = reverse("api-1-release", url_args={"sha1_git": unknown_release_}) rv = check_api_get_responses(api_client, url, status_code=404) assert rv.data == { "exception": "NotFoundExc", "reason": "Release with sha1_git %s not found." % unknown_release_, }
identifier_body
test_release.py
# Copyright (C) 2015-2019 The Software Heritage developers # See the AUTHORS file at the top-level directory of this distribution # License: GNU Affero General Public License version 3, or any later version # See top-level LICENSE file for more information from datetime import datetime from hypothesis import given ...
sample_release = Release( author=Person( email=b"author@company.org", fullname=b"author <author@company.org>", name=b"author", ), date=TimestampWithTimezone( timestamp=Timestamp( seconds=int...
target = target["sha1_git"]
conditional_block
win_unittest.py
import os import sys # OS Specifics ABS_WORK_DIR = os.path.join(os.getcwd(), "build") BINARY_PATH = os.path.join(ABS_WORK_DIR, "firefox", "firefox.exe") INSTALLER_PATH = os.path.join(ABS_WORK_DIR, "installer.zip") XPCSHELL_NAME = 'xpcshell.exe' EXE_SUFFIX = '.exe' DISABLE_SCREEN_SAVER = False ADJUST_MOUSE_AND_SCREEN =...
"reftest-ipc": ['--setpref=browser.tabs.remote=true', '--setpref=browser.tabs.remote.autostart=true', '--setpref=layers.async-pan-zoom.enabled=true', 'tests/reftest/tests/layout/reftests/reftest-sanity/reftest.list'], "reftest-no-ac...
"crashtest": ["tests/reftest/tests/testing/crashtest/crashtests.list"], "jsreftest": ["--extra-profile-file=tests/jsreftest/tests/user.js", "tests/jsreftest/tests/jstests.list"],
random_line_split
attendances.js
'use strict'; /** * Module dependencies. */ var mongoose = require('mongoose'), CurrentModel = mongoose.model('Attendance'), Schedule = mongoose.model('Schedule'), Group = mongoose.model('Group'), _ = require('lodash'); exports.attendance = function(req, res, next, id) { CurrentModel.load(id, function(err...
if (err) { return res.send('users/signup', { errors: err.errors, object: item }); } else { res.jsonp(item); } }); }; exports.show = function(req, res) { res.jsonp(req.attendance); }; exports.all = function(req, res) { CurrentModel.find({ group: req.group, schedule: ...
random_line_split
test_check.py
"""Tests for distutils.command.check.""" import os import textwrap import unittest from test.support import run_unittest from distutils.command.check import check, HAS_DOCUTILS from distutils.tests import support from distutils.errors import DistutilsSetupError try: import pygments except ImportError: pygment...
@unittest.skipUnless(HAS_DOCUTILS, "won't test without docutils") def test_check_restructuredtext_with_syntax_highlight(self): # Don't fail if there is a `code` or `code-block` directive example_rst_docs = [] example_rst_docs.append(textwrap.dedent("""\ Here's some code: ...
broken_rest = 'title\n===\n\ntest' pkg_info, dist = self.create_dist(long_description=broken_rest) cmd = check(dist) cmd.check_restructuredtext() self.assertEqual(cmd._warnings, 1) # let's see if we have an error with strict=1 metadata = {'url': 'xxx', 'author': 'xxx', ...
identifier_body
test_check.py
"""Tests for distutils.command.check.""" import os import textwrap import unittest from test.support import run_unittest from distutils.command.check import check, HAS_DOCUTILS from distutils.tests import support from distutils.errors import DistutilsSetupError try: import pygments except ImportError: pygment...
(self): # let's run the command with no metadata at all # by default, check is checking the metadata # should have some warnings cmd = self._run() self.assertEqual(cmd._warnings, 2) # now let's add the required fields # and run it again, to make sure we don't get...
test_check_metadata
identifier_name
test_check.py
"""Tests for distutils.command.check.""" import os import textwrap import unittest from test.support import run_unittest from distutils.command.check import check, HAS_DOCUTILS from distutils.tests import support from distutils.errors import DistutilsSetupError try: import pygments except ImportError: pygment...
def test_check_all(self): metadata = {'url': 'xxx', 'author': 'xxx'} self.assertRaises(DistutilsSetupError, self._run, {}, **{'strict': 1, 'restructuredtext': 1}) def test_suite(): return unittest.makeSuite(CheckTestCase) if __name_...
pkg_info, dist = self.create_dist(long_description=rest_with_code) cmd = check(dist) cmd.check_restructuredtext() msgs = cmd._check_rst_data(rest_with_code) if pygments is not None: self.assertEqual(len(msgs), 0) else: self.asse...
conditional_block
test_check.py
"""Tests for distutils.command.check.""" import os import textwrap import unittest from test.support import run_unittest from distutils.command.check import check, HAS_DOCUTILS from distutils.tests import support from distutils.errors import DistutilsSetupError try: import pygments except ImportError: pygment...
str(msgs[0][1]), 'Cannot analyze code. Pygments package not found.' ) def test_check_all(self): metadata = {'url': 'xxx', 'author': 'xxx'} self.assertRaises(DistutilsSetupError, self._run, {}, **{'strict': 1, ...
else: self.assertEqual(len(msgs), 1) self.assertEqual(
random_line_split
serverError.ts
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *---------------------------------------------------------------...
} return undefined; } /** * Drop everything but ".js" and line/column numbers (though retain "tsserver" if that's the filename). */ private static sanitizeStack(message: string | undefined) { if (!message) { return ''; } const regex = /(\btsserver)?(\.(?:ts|tsx|js|jsx)(?::\d+(?::\d+)?)?)\)?$/igm; ...
{ const prefixFreeErrorText = errorText.substr(errorPrefix.length); const newlineIndex = prefixFreeErrorText.indexOf('\n'); if (newlineIndex >= 0) { // Newline expected between message and stack. const stack = prefixFreeErrorText.substring(newlineIndex + 1); return { message: prefixFree...
conditional_block
serverError.ts
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *---------------------------------------------------------------...
private constructor( public readonly serverId: string, public readonly version: TypeScriptVersion, private readonly response: Proto.Response, public readonly serverMessage: string | undefined, public readonly serverStack: string | undefined, private readonly sanitizedStack: string | undefined ) { super...
return new TypeScriptServerError(serverId, version, response, parsedResult?.message, parsedResult?.stack, parsedResult?.sanitizedStack); }
random_line_split
serverError.ts
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *---------------------------------------------------------------...
() { return this.response.message; } public get serverCommand() { return this.response.command; } public get telemetry() { // The "sanitizedstack" has been purged of error messages, paths, and file names (other than tsserver) // and, thus, can be classified as SystemMetaData, rather than CallstackOrException. ...
serverErrorText
identifier_name
serverError.ts
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *---------------------------------------------------------------...
public get serverCommand() { return this.response.command; } public get telemetry() { // The "sanitizedstack" has been purged of error messages, paths, and file names (other than tsserver) // and, thus, can be classified as SystemMetaData, rather than CallstackOrException. /* __GDPR__FRAGMENT__ "TypeScrip...
{ return this.response.message; }
identifier_body
alerts.service.ts
import { Injectable } from '@angular/core'; import { TranslateService } from '@ngx-translate/core'; import { Observable, Subject } from 'rxjs'; import { AlertType, Alert } from './alerts.model'; @Injectable({ providedIn: 'root', }) export class AlertsService { private subject = new Subject<Alert>(); constructo...
getAlert(): Observable<Alert> { return this.subject.asObservable(); } success(translationKey: string, values?: object): void { this.alert(AlertType.SUCCESS, translationKey, values); } warn(translationKey: string, values?: object): void { this.alert(AlertType.WARNING, translationKey, values); ...
{}
identifier_body
alerts.service.ts
import { Injectable } from '@angular/core'; import { TranslateService } from '@ngx-translate/core'; import { Observable, Subject } from 'rxjs'; import { AlertType, Alert } from './alerts.model'; @Injectable({ providedIn: 'root', }) export class AlertsService { private subject = new Subject<Alert>(); constructo...
(translationKey: string, values?: object): void { this.alert(AlertType.INFO, translationKey, values); } private alert(type: string, translationKey: string, values?: object): void { const message = this.translate.instant(translationKey, values); this.subject.next({ type, message } as Alert); } clea...
info
identifier_name
alerts.service.ts
import { Injectable } from '@angular/core'; import { TranslateService } from '@ngx-translate/core'; import { Observable, Subject } from 'rxjs'; import { AlertType, Alert } from './alerts.model'; @Injectable({ providedIn: 'root',
getAlert(): Observable<Alert> { return this.subject.asObservable(); } success(translationKey: string, values?: object): void { this.alert(AlertType.SUCCESS, translationKey, values); } warn(translationKey: string, values?: object): void { this.alert(AlertType.WARNING, translationKey, values); ...
}) export class AlertsService { private subject = new Subject<Alert>(); constructor(private translate: TranslateService) {}
random_line_split
carrera_fecha.controller.ts
import { CarreraFecha } from '../domain/carrera_fecha.model'; import _db from './persistence/db.repository'; import { DateCareerStorageService } from './services/storage/carrera_fecha.storage'; import { DateCareerReadingService } from './services/reading/carrera_fecha.reading'; const createCarreraFecha = async (req, ...
export default { createCarreraFecha, getCarreraFecha, getCarreraFechaMes };
random_line_split
win_pkg.py
# -*- encoding: utf-8 -*- ''' :maintainer: HubbleStack :maturity: 2016.7.0 :platform: Windows :requires: SaltStack ''' from __future__ import absolute_import import copy import fnmatch import logging import salt.utils import salt.utils.platform from salt.exceptions import CommandExecutionError from distutils.version...
if 'more' in value.lower() and LooseVersion(current) >= LooseVersion(evaluator): return True return False
return True
conditional_block
win_pkg.py
# -*- encoding: utf-8 -*- ''' :maintainer: HubbleStack :maturity: 2016.7.0 :platform: Windows :requires: SaltStack ''' from __future__ import absolute_import import copy import fnmatch import logging import salt.utils import salt.utils.platform from salt.exceptions import CommandExecutionError from distutils.version...
if 'equal' in value.lower() and LooseVersion(current) == LooseVersion(evaluator): return True if 'less' in value.lower() and LooseVersion(current) <= LooseVersion(evaluator): return True if 'more' in value.lower() and LooseVersion(current) >= LooseVersion(evaluator): return True retu...
identifier_body
win_pkg.py
# -*- encoding: utf-8 -*- ''' :maintainer: HubbleStack :maturity: 2016.7.0 :platform: Windows :requires: SaltStack ''' from __future__ import absolute_import import copy import fnmatch import logging import salt.utils import salt.utils.platform from salt.exceptions import CommandExecutionError from distutils.version...
(): if not salt.utils.platform.is_windows(): return False, 'This audit module only runs on windows' return True def apply_labels(__data__, labels): ''' Filters out the tests whose label doesn't match the labels given when running audit and returns a new data structure with only labelled tests. ...
__virtual__
identifier_name
win_pkg.py
# -*- encoding: utf-8 -*- ''' :maintainer: HubbleStack :maturity: 2016.7.0 :platform: Windows :requires: SaltStack ''' from __future__ import absolute_import import copy import fnmatch import logging import salt.utils import salt.utils.platform from salt.exceptions import CommandExecutionError from distutils.version...
audit_type = tag_data['type'] match_output = tag_data['match_output'].lower() # Blacklisted audit (do not include) if 'blacklist' in audit_type: if name not in __pkgdata__: ret['Success'].append(tag_data) ...
continue name = tag_data['name']
random_line_split
wrapper.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/. */ #![allow(unsafe_code)] //! Wrapper definitions on top of Gecko types in order to be used in the style //! system....
fn first_child_element(&self) -> Option<Self> { let mut child = self.as_node().first_child(); while let Some(child_node) = child { if let Some(el) = child_node.as_element() { return Some(el) } child = child_node.next_sibling(); } None...
unsafe { bindings::Gecko_GetParentElement(self.0).map(GeckoElement) } }
identifier_body
wrapper.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/. */ #![allow(unsafe_code)] //! Wrapper definitions on top of Gecko types in order to be used in the style //! system....
NonTSPseudoClass::ReadOnly => { !self.get_state().contains(pseudo_class.state_flag()) } NonTSPseudoClass::MozBrowserFrame => unsafe { Gecko_MatchesElement(pseudo_class.to_gecko_pseudoclasstype().unwrap(), self.0) } } } fn ge...
self.get_state().contains(pseudo_class.state_flag()) },
conditional_block
wrapper.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/. */ #![allow(unsafe_code)] //! Wrapper definitions on top of Gecko types in order to be used in the style //! system....
} } } impl<'le> ElementExt for GeckoElement<'le> { #[inline] fn is_link(&self) -> bool { self.match_non_ts_pseudo_class(NonTSPseudoClass::AnyLink) } #[inline] fn matches_user_and_author_rules(&self) -> bool { self.flags() & (NODE_IS_IN_NATIVE_ANONYMOUS_SUBTREE as u32) =...
unsafe { bindings::Gecko_AttrHasSuffix(self.0, attr.ns_or_null(), attr.select_name(self.is_html_element_in_html_document()), value.as_ptr())
random_line_split
wrapper.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/. */ #![allow(unsafe_code)] //! Wrapper definitions on top of Gecko types in order to be used in the style //! system....
lf) { self.unset_flags(NODE_HAS_DIRTY_DESCENDANTS_FOR_SERVO as u32) } fn store_children_to_process(&self, _: isize) { // This is only used for bottom-up traversal, and is thus a no-op for Gecko. } fn did_process_child(&self) -> isize { panic!("Atomic child count not implemented...
t_dirty_descendants(&se
identifier_name
csvl10n.py
#!/usr/bin/env python # -*- coding: utf-8 -*- # # Copyright 2002-2006 Zuza Software Foundation # # This file is part of translate. # # translate is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version...
def parse(self, csvsrc): csvfile = csv.StringIO(csvsrc) reader = SimpleDictReader(csvfile, self.fieldnames) for row in reader: newce = self.UnitClass() newce.fromdict(row) self.addunit(newce) def __str__(self): """convert to a string. double...
base.TranslationStore.__init__(self, unitclass=self.UnitClass) self.units = [] if fieldnames is None: self.fieldnames = ['location', 'source', 'target'] else: if isinstance(fieldnames, basestring): fieldnames = [fieldname.strip() for fieldname in fieldname...
identifier_body
csvl10n.py
#!/usr/bin/env python # -*- coding: utf-8 -*- # # Copyright 2002-2006 Zuza Software Foundation # # This file is part of translate. # # translate is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version...
self.filename = getattr(inputfile, 'name', '') if inputfile is not None: csvsrc = inputfile.read() inputfile.close() self.parse(csvsrc) def parse(self, csvsrc): csvfile = csv.StringIO(csvsrc) reader = SimpleDictReader(csvfile, self.fieldnames) ...
if isinstance(fieldnames, basestring): fieldnames = [fieldname.strip() for fieldname in fieldnames.split(",")] self.fieldnames = fieldnames
conditional_block
csvl10n.py
#!/usr/bin/env python # -*- coding: utf-8 -*- # # Copyright 2002-2006 Zuza Software Foundation # # This file is part of translate. # # translate is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version...
(self, fileobj, fieldnames): self.fieldnames = fieldnames self.contents = fileobj.read() self.parser = sparse.SimpleParser(defaulttokenlist=[",", "\n"], whitespacechars="\r") self.parser.stringescaping = 0 self.parser.quotechars = '"' self.tokens = self.parser.tokenize(se...
__init__
identifier_name
csvl10n.py
#!/usr/bin/env python # -*- coding: utf-8 -*- # # Copyright 2002-2006 Zuza Software Foundation # # This file is part of translate. # # translate is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version...
lentokens = len(self.tokens) while self.tokenpos < lentokens and self.tokens[self.tokenpos] == "\n": self.tokenpos += 1 if self.tokenpos >= lentokens: raise StopIteration() thistokens = [] while self.tokenpos < lentokens and self.tokens[self.tokenpos] != "...
random_line_split
edit-car-row.component.spec.ts
import { async, ComponentFixture, TestBed } from '@angular/core/testing'; import { By } from '@angular/platform-browser'; import { ReactiveFormsModule } from '@angular/forms'; import { EditCarRowComponent } from './edit-car-row.component'; describe('EditCarRowComponent', () => { let component: EditCarRowComponent; ...
TestBed.configureTestingModule({ imports: [ ReactiveFormsModule ], declarations: [ EditCarRowComponent ] }) .compileComponents(); })); beforeEach(() => { fixture = TestBed.createComponent(EditCarRowComponent); component = fixture.componentInstance; component.car = car; fixtu...
random_line_split
place-picker.js
import {inject, customElement, bindable} from 'aurelia-framework'; import mapsapi from 'google-maps-api'; @customElement('place-picker') // Get an API key from https://developers.google.com/maps/documentation/javascript/get-api-key. @inject(Element, mapsapi('AIzaSyA1QmM_IG94DN0kCl7l1dblf4C8vRiuxus', ['places'])) expor...
}); }); } }
{ this.location.name = place.name; this.location.lat = place.geometry.location.lat(); this.location.lng = place.geometry.location.lng(); updateMarker(); }
conditional_block
place-picker.js
import {inject, customElement, bindable} from 'aurelia-framework'; import mapsapi from 'google-maps-api'; @customElement('place-picker') // Get an API key from https://developers.google.com/maps/documentation/javascript/get-api-key. @inject(Element, mapsapi('AIzaSyA1QmM_IG94DN0kCl7l1dblf4C8vRiuxus', ['places'])) expor...
attached() { // This loads the Google Maps API asynchronously. this.mapsApi.then(maps => { // Now that it's loaded, add a map to our HTML. var mapContainer = this.element.querySelector('.place-picker-map'); var map = new maps.Map(mapContainer, { center: {lat: -33.8688, lng: 151.219...
{ this.element = element; this.mapsApi = mapsApi; }
identifier_body
place-picker.js
import {inject, customElement, bindable} from 'aurelia-framework'; import mapsapi from 'google-maps-api'; @customElement('place-picker') // Get an API key from https://developers.google.com/maps/documentation/javascript/get-api-key. @inject(Element, mapsapi('AIzaSyA1QmM_IG94DN0kCl7l1dblf4C8vRiuxus', ['places'])) expor...
(element, mapsApi) { this.element = element; this.mapsApi = mapsApi; } attached() { // This loads the Google Maps API asynchronously. this.mapsApi.then(maps => { // Now that it's loaded, add a map to our HTML. var mapContainer = this.element.querySelector('.place-picker-map'); var...
constructor
identifier_name
place-picker.js
import {inject, customElement, bindable} from 'aurelia-framework'; import mapsapi from 'google-maps-api'; @customElement('place-picker') // Get an API key from https://developers.google.com/maps/documentation/javascript/get-api-key. @inject(Element, mapsapi('AIzaSyA1QmM_IG94DN0kCl7l1dblf4C8vRiuxus', ['places'])) expor...
// This loads the Google Maps API asynchronously. this.mapsApi.then(maps => { // Now that it's loaded, add a map to our HTML. var mapContainer = this.element.querySelector('.place-picker-map'); var map = new maps.Map(mapContainer, { center: {lat: -33.8688, lng: 151.2195}, zoom:...
attached() {
random_line_split
brightness-low.js
'use strict'; var React = require('react'); var PureRenderMixin = require('react-addons-pure-render-mixin'); var SvgIcon = require('../../svg-icon');
displayName: 'DeviceBrightnessLow', mixins: [PureRenderMixin], render: function render() { return React.createElement( SvgIcon, this.props, React.createElement('path', { d: 'M20 15.31L23.31 12 20 8.69V4h-4.69L12 .69 8.69 4H4v4.69L.69 12 4 15.31V20h4.69L12 23.31 15.31 20H20v-4.69zM12 18c-3....
var DeviceBrightnessLow = React.createClass({
random_line_split
application.py
# Copyright © 2013, 2015, 2016, 2017, 2018, 2020, 2022 Tom Most <twm@freecog.net> # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any lat...
self._log.debug( "Content Security Policy violation reported by {userAgent!r}:\n{report}", userAgent=", ".join(request.requestHeaders.getRawHeaders("User-Agent", [])), report=report, ) return b"" # Browser ignores the response. class FallbackResource(Resourc...
turn b""
conditional_block
application.py
# Copyright © 2013, 2015, 2016, 2017, 2018, 2020, 2022 Tom Most <twm@freecog.net> # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any lat...
""" Convert a stdlib logging level into a Twisted :class:`LogLevel`. """ if levelno <= logging.DEBUG: return LogLevel.debug elif levelno <= logging.INFO: return LogLevel.info elif levelno <= logging.WARNING: return LogLevel.warn ...
def _mapLevel(self, levelno):
random_line_split
application.py
# Copyright © 2013, 2015, 2016, 2017, 2018, 2020, 2022 Tom Most <twm@freecog.net> # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any lat...
object): url = attr.ib() referrer = attr.ib() resource = attr.ib() violatedDirective = attr.ib() effectiveDirective = attr.ib() source = attr.ib() sample = attr.ib() status = attr.ib() policy = attr.ib() disposition = attr.ib() def __str__(self): bits = [] fo...
SPReport(
identifier_name
application.py
# Copyright © 2013, 2015, 2016, 2017, 2018, 2020, 2022 Tom Most <twm@freecog.net> # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any lat...
class TwistedLoggerLogHandler(logging.Handler): publisher = globalLogPublisher def _mapLevel(self, levelno): """ Convert a stdlib logging level into a Twisted :class:`LogLevel`. """ if levelno <= logging.DEBUG: return LogLevel.debug elif levelno <= logging.IN...
Suppress the log messages which result from an unhandled error in HTTP/2 connection shutdown. See #282 and Twisted #9462. This log message is relayed from the :mod:`twisted.python.log` so the fields are a little odd: * ``'log_namespace'`` is ``'log_legacy'``, and there is a ``'system'`` ...
identifier_body
utils.py
import numpy as np from pysal.lib.common import requires @requires('matplotlib') def shift_colormap(cmap, start=0, midpoint=0.5, stop=1.0, name='shiftedcmap'): ''' Function to offset the "center" of a colormap. Useful for data with a negative min and positive max and you want the middle of the colormap...
def compare_surfaces(data, var1, var2, gwr_t, gwr_bw, mgwr_t, mgwr_bw, name, kwargs1, kwargs2, savefig=None): ''' Function that creates comparative visualization of GWR and MGWR surfaces. Parameters ---------- data : pandas or geopandas Dataframe gwr/mgwr results var1 :...
return new_cmap @requires('matplotlib') @requires('geopandas')
random_line_split
utils.py
import numpy as np from pysal.lib.common import requires @requires('matplotlib') def shift_colormap(cmap, start=0, midpoint=0.5, stop=1.0, name='shiftedcmap'): ''' Function to offset the "center" of a colormap. Useful for data with a negative min and positive max and you want the middle of the colormap...
#Plot MGWR parameters data.plot(var2, cmap=sm.cmap, ax=ax1, vmin=vmin, vmax=vmax, **kwargs1) if (mgwr_t == 0).any(): data[mgwr_t == 0].plot(color='lightgrey', ax=ax1, **kwargs2) #Set figure options and plot fig.tight_layout() fig.subplots_adjust(right=0.9) cax = fig.add_axes(...
data[gwr_t == 0].plot(color='lightgrey', ax=ax0, **kwargs2)
conditional_block
utils.py
import numpy as np from pysal.lib.common import requires @requires('matplotlib') def shift_colormap(cmap, start=0, midpoint=0.5, stop=1.0, name='shiftedcmap'): ''' Function to offset the "center" of a colormap. Useful for data with a negative min and positive max and you want the middle of the colormap...
''' Function that creates comparative visualization of GWR and MGWR surfaces. Parameters ---------- data : pandas or geopandas Dataframe gwr/mgwr results var1 : string name of gwr parameter estimate column in frame var2 : string name of mgwr paramete...
identifier_body
utils.py
import numpy as np from pysal.lib.common import requires @requires('matplotlib') def shift_colormap(cmap, start=0, midpoint=0.5, stop=1.0, name='shiftedcmap'): ''' Function to offset the "center" of a colormap. Useful for data with a negative min and positive max and you want the middle of the colormap...
(data, var1, var2, gwr_t, gwr_bw, mgwr_t, mgwr_bw, name, kwargs1, kwargs2, savefig=None): ''' Function that creates comparative visualization of GWR and MGWR surfaces. Parameters ---------- data : pandas or geopandas Dataframe gwr/mgwr results var1 : string ...
compare_surfaces
identifier_name
extensions.rs
// Copyright (c) 2020 DDN. All rights reserved. // Use of this source code is governed by a MIT-style // license that can be found in the LICENSE file. use crate::auth::csrf_token; use iml_wire_types::{GroupType, Session}; use seed::{fetch, prelude::*, *}; /// Extension methods for the Session API object. pub(crate) ...
} /// Allows for merging attributes onto an existing item pub(crate) trait MergeAttrs { fn merge_attrs(self, attrs: Attrs) -> Self; } impl MergeAttrs for Attrs { fn merge_attrs(mut self, attrs: Attrs) -> Self { self.merge(attrs); self } } impl<T> MergeAttrs for Node<T> { fn merge_at...
{ match csrf_token() { Some(csrf) => self.header("X-CSRFToken", &csrf), None => self, } }
identifier_body
extensions.rs
// Copyright (c) 2020 DDN. All rights reserved. // Use of this source code is governed by a MIT-style // license that can be found in the LICENSE file. use crate::auth::csrf_token; use iml_wire_types::{GroupType, Session}; use seed::{fetch, prelude::*, *}; /// Extension methods for the Session API object. pub(crate) ...
fn graphql_query<T: serde::Serialize>(x: &T) -> Self; fn with_auth(self: Self) -> Self; } impl RequestExt for fetch::Request { fn api_call(path: impl ToString) -> Self { Self::new(format!("/api/{}/", path.to_string())) } fn api_query(path: impl ToString, args: impl serde::Serialize) -> Resu...
pub(crate) trait RequestExt: Sized { fn api_call(path: impl ToString) -> Self; fn api_query(path: impl ToString, args: impl serde::Serialize) -> Result<Self, serde_urlencoded::ser::Error>; fn api_item(path: impl ToString, item: impl ToString) -> Self;
random_line_split
extensions.rs
// Copyright (c) 2020 DDN. All rights reserved. // Use of this source code is governed by a MIT-style // license that can be found in the LICENSE file. use crate::auth::csrf_token; use iml_wire_types::{GroupType, Session}; use seed::{fetch, prelude::*, *}; /// Extension methods for the Session API object. pub(crate) ...
(mut self, attrs: Attrs) -> Self { self.merge(attrs); self } } impl<T> MergeAttrs for Node<T> { fn merge_attrs(self, attrs: Attrs) -> Self { if let Self::Element(mut el) = self { el.attrs.merge(attrs); Self::Element(el) } else { self ...
merge_attrs
identifier_name
Ol.ts
/* * Copyright (c) 2014 Jose Carlos Lama. www.typedom.org * * Permission is hereby granted, free of charge, to any person * obtaining a copy of this software and associated documentation * files (the \"Software\"), to deal in the Software without restriction, * including without limitation the rights to use, copy, modi...
(idOrAttributesOrElement?: any) { super(idOrAttributesOrElement, Ol.OL); } }
constructor
identifier_name
Ol.ts
/*
* * Permission is hereby granted, free of charge, to any person * obtaining a copy of this software and associated documentation * files (the \"Software\"), to deal in the Software without restriction, * including without limitation the rights to use, copy, modify, merge, * publish, distribute, sublicense, and/or sell ...
* Copyright (c) 2014 Jose Carlos Lama. www.typedom.org
random_line_split
Markers.js
/* Copyright (c) 2006-2010 by OpenLayers Contributors (see authors.txt for * full list of contributors). Published under the Clear BSD license. * See http://svn.openlayers.org/trunk/openlayers/license.txt for the * full text of the license. */ /** * @requires OpenLayers/Layer.js */ /** * Class: O...
else if(marker.icon) { marker.icon.moveTo(px); } } }, /** * APIMethod: getDataExtent * Calculates the max extent which includes all of the markers. * * Returns: * {<OpenLayers.Bounds>} */ getDataExtent: function () { ...
{ var markerImg = marker.draw(px); this.div.appendChild(markerImg); }
conditional_block
Markers.js
/* Copyright (c) 2006-2010 by OpenLayers Contributors (see authors.txt for * full list of contributors). Published under the Clear BSD license. * See http://svn.openlayers.org/trunk/openlayers/license.txt for the * full text of the license. */ /** * @requires OpenLayers/Layer.js */ /** * Class: O...
setOpacity: function(opacity) { if (opacity != this.opacity) { this.opacity = opacity; for (var i=0, len=this.markers.length; i<len; i++) { this.markers[i].setOpacity(this.opacity); } } }, /** * Method: moveTo * ...
* opacity - {Float} */
random_line_split
gen_dist_from_U.py
# encoding: utf8 ''' 随机变量的积分变换 下面的基于U(0,1)实现了几个常用的连续随机变量概率分布的随机数模拟 U(0,1) 在0,1区间的连续均匀分布的随机数模拟 CDF: cumulate distribution function PMF: probility mass function PDF: probility density function 对任意随机变量X, 它有连续的的CDF F(x), 定义随机变量 Y=F(X), 则Y为 [0,1]上的均匀分布,即有 P(Y<=y) = y box-muller方法并没有了解原理 ''' import numpy as np import ...
布图.两种生成方法,对比一下误差 plt.clf() gauss_x2, gauss_y2 = gen_gauss_distribute_pdf_from_dist_table(0, 1) plt.plot(gauss_x, gauss_y, 'g-.') plt.plot(gauss_x2, gauss_y2, 'r--') gauss_x2, gauss_y2 = gen_gauss_distribute_pdf_from_dist_table(0, 2) plt.plot(gauss_x2, gauss_y2, 'b-') gauss_x2, gauss_y2 = gen_gauss_distribute_pdf_from_d...
lot(gauss_x, gauss_y, color='g') plt.savefig('images/norm_distribute_gen_by_U.png', format='png') #绘制正态分
identifier_body
gen_dist_from_U.py
# encoding: utf8 ''' 随机变量的积分变换 下面的基于U(0,1)实现了几个常用的连续随机变量概率分布的随机数模拟 U(0,1) 在0,1区间的连续均匀分布的随机数模拟 CDF: cumulate distribution function PMF: probility mass function PDF: probility density function 对任意随机变量X, 它有连续的的CDF F(x), 定义随机变量 Y=F(X), 则Y为 [0,1]上的均匀分布,即有 P(Y<=y) = y box-muller方法并没有了解原理 ''' import numpy as np import ...
f gen_exp_samples_byU(sample_count, beta): sim_num = np.zeros(sample_count) sim_u = np.zeros(sample_count) for i in range(0, sample_count): u = np.random.uniform(0, 1) if u == 1: x = 0. else: x = -1./beta * np.log(1. - u) sim_u[i] = u si...
.pi * U0) return Z0, Z1 ''' 使用均匀分布随机数,生成符合指数分布的随机数 F(x) = 1 - exp(-1/beta*x) x = -1/beta * 1/log(1 - F) ''' de
conditional_block
gen_dist_from_U.py
# encoding: utf8 '''
下面的基于U(0,1)实现了几个常用的连续随机变量概率分布的随机数模拟 U(0,1) 在0,1区间的连续均匀分布的随机数模拟 CDF: cumulate distribution function PMF: probility mass function PDF: probility density function 对任意随机变量X, 它有连续的的CDF F(x), 定义随机变量 Y=F(X), 则Y为 [0,1]上的均匀分布,即有 P(Y<=y) = y box-muller方法并没有了解原理 ''' import numpy as np import matplotlib.pyplot as plt import ...
随机变量的积分变换
random_line_split
gen_dist_from_U.py
# encoding: utf8 ''' 随机变量的积分变换 下面的基于U(0,1)实现了几个常用的连续随机变量概率分布的随机数模拟 U(0,1) 在0,1区间的连续均匀分布的随机数模拟 CDF: cumulate distribution function PMF: probility mass function PDF: probility density function 对任意随机变量X, 它有连续的的CDF F(x), 定义随机变量 Y=F(X), 则Y为 [0,1]上的均匀分布,即有 P(Y<=y) = y box-muller方法并没有了解原理 ''' import numpy as np import ...
= int(np.sqrt(sample_count) + 0.9999) sim_u, sim_gauss_num = gen_gauss_samples_byU(sample_count) mean_val = np.mean(sim_gauss_num) std_val = np.std(sim_gauss_num) print "mean, std:", mean_val, std_val #绘制高斯采样的直方图 plt_hist(sim_gauss_num, normed=True) #叠加均匀分布采样直方图 plt.hist((sim_u-0.5)*8, bins = group_count, normed=Tr...
= 1000 group_count
identifier_name
location_strategy.ts
/** * `LocationStrategy` is responsible for representing and reading route state * from the the browser's URL. Angular provides two strategies: * {@link HashLocationStrategy} (default) and {@link PathLocationStrategy}. * * This is used under the hood of the {@link Location} service. * * Applications should use t...
{ return (params.length > 0 && params.substring(0, 1) != '?') ? ('?' + params) : params; }
identifier_body
location_strategy.ts
/** * `LocationStrategy` is responsible for representing and reading route state * from the the browser's URL. Angular provides two strategies: * {@link HashLocationStrategy} (default) and {@link PathLocationStrategy}. * * This is used under the hood of the {@link Location} service. * * Applications should use t...
(params: string): string { return (params.length > 0 && params.substring(0, 1) != '?') ? ('?' + params) : params; }
normalizeQueryParams
identifier_name
location_strategy.ts
/** * `LocationStrategy` is responsible for representing and reading route state * from the the browser's URL. Angular provides two strategies: * {@link HashLocationStrategy} (default) and {@link PathLocationStrategy}. * * This is used under the hood of the {@link Location} service. * * Applications should use t...
* interact with application route state. * * For instance, {@link HashLocationStrategy} produces URLs like * `http://example.com#/foo`, and {@link PathLocationStrategy} produces * `http://example.com/foo` as an equivalent URL. * * See these two classes for more. */ export abstract class LocationStrategy { abs...
random_line_split
Update.py
from openflow.optin_manager.sfa.util.method import Method from openflow.optin_manager.sfa.trust.credential import Credential from openflow.optin_manager.sfa.util.parameter import Parameter class Update(Method): """ Update an object in the registry. Currently, this only updates the PLC information associa...
valid_creds = self.api.auth.checkCredentials(creds, "update") # verify permissions hrn = record_dict.get('hrn', '') self.api.auth.verify_object_permission(hrn) # log origin_hrn = Credential(string=valid_creds[0]).get_gid_caller().get_hrn() self.api.logger....
identifier_body
Update.py
from openflow.optin_manager.sfa.util.method import Method from openflow.optin_manager.sfa.trust.credential import Credential from openflow.optin_manager.sfa.util.parameter import Parameter class Update(Method): """ Update an object in the registry. Currently, this only updates the PLC information associa...
(self, record_dict, creds): # validate the cred valid_creds = self.api.auth.checkCredentials(creds, "update") # verify permissions hrn = record_dict.get('hrn', '') self.api.auth.verify_object_permission(hrn) # log origin_hrn = Credential(string=val...
call
identifier_name
Update.py
from openflow.optin_manager.sfa.util.method import Method from openflow.optin_manager.sfa.trust.credential import Credential from openflow.optin_manager.sfa.util.parameter import Parameter class Update(Method): """ Update an object in the registry. Currently, this only updates the PLC information associa...
origin_hrn = Credential(string=valid_creds[0]).get_gid_caller().get_hrn() self.api.logger.info("interface: %s\tcaller-hrn: %s\ttarget-hrn: %s\tmethod-name: %s"%(self.api.interface, origin_hrn, hrn, self.name)) return self.api.manager.Update(self.api, record_dict)
hrn = record_dict.get('hrn', '') self.api.auth.verify_object_permission(hrn) # log
random_line_split
MicrosoftMailServiceReducer.js
import ServiceReducer from './ServiceReducer' class MicrosoftMailServiceReducer extends ServiceReducer { /* **************************************************************************/ // Class /* **************************************************************************/ static get name ()
/* **************************************************************************/ // Reducers /* **************************************************************************/ /** * Sets the basic profile info for this account * @param service: the service to update * @param userId: the users id * @param e...
{ return 'MicrosoftMailServiceReducer' }
identifier_body
MicrosoftMailServiceReducer.js
import ServiceReducer from './ServiceReducer' class MicrosoftMailServiceReducer extends ServiceReducer { /* **************************************************************************/ // Class /* **************************************************************************/ static get name () { return 'Microsoft...
} } export default MicrosoftMailServiceReducer
{ return service.changeData({ unreadMode: unreadMode }) }
conditional_block
MicrosoftMailServiceReducer.js
import ServiceReducer from './ServiceReducer' class MicrosoftMailServiceReducer extends ServiceReducer { /* **************************************************************************/ // Class /* **************************************************************************/ static get name () { return 'Microsoft...
(service, unreadMode) { if (service.unreadMode !== unreadMode) { return service.changeData({ unreadMode: unreadMode }) } } } export default MicrosoftMailServiceReducer
setUnreadMode
identifier_name
MicrosoftMailServiceReducer.js
import ServiceReducer from './ServiceReducer' class MicrosoftMailServiceReducer extends ServiceReducer { /* **************************************************************************/ // Class
/* **************************************************************************/ // Reducers /* **************************************************************************/ /** * Sets the basic profile info for this account * @param service: the service to update * @param userId: the users id * @param em...
/* **************************************************************************/ static get name () { return 'MicrosoftMailServiceReducer' }
random_line_split
input-demo.ts
import {Component} from '@angular/core'; import {FormGroup, FormBuilder, Validators, FormControl} from "@angular/forms"; let max = 5; @Component({ moduleId: module.id, selector: 'input-demo', templateUrl: 'input-demo.html', styleUrls: ['input-demo.css'], }) export class InputDemo { validationForm: FormGrou...
} }
{ this.items.push({ value: ++max }); }
conditional_block
input-demo.ts
import {Component} from '@angular/core'; import {FormGroup, FormBuilder, Validators, FormControl} from "@angular/forms"; let max = 5; @Component({ moduleId: module.id, selector: 'input-demo', templateUrl: 'input-demo.html', styleUrls: ['input-demo.css'], }) export class InputDemo { validationForm: FormGrou...
(n: number) { for (let x = 0; x < n; x++) { this.items.push({ value: ++max }); } } }
addABunch
identifier_name
input-demo.ts
import {Component} from '@angular/core'; import {FormGroup, FormBuilder, Validators, FormControl} from "@angular/forms"; let max = 5; @Component({ moduleId: module.id, selector: 'input-demo', templateUrl: 'input-demo.html', styleUrls: ['input-demo.css'], }) export class InputDemo { validationForm: FormGrou...
{ value: 20 }, { value: 30 }, { value: 40 }, { value: 50 }, ]; rows = 8; constructor(private fb: FormBuilder) { this.validationForm = this.fb.group({ username: new FormControl({value: '', disabled: false}, Validators.minLength(5)), password: new FormControl({value: ''...
name: string; items: any[] = [ { value: 10 },
random_line_split
ast.rs
use std::cell::Cell; use std::fmt; use std::vec::Vec; pub type Var = String; pub type Atom = String; pub enum TopLevel { Fact(Term), Query(Term) } #[derive(Clone, Copy)] pub enum Level { Shallow, Deep } impl fmt::Display for Level { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { mat...
(&self) -> usize { match self { &Reg::ArgAndNorm(_, norm) | &Reg::Norm(norm) => norm } } } pub enum Term { Atom(Cell<usize>, Atom), Clause(Cell<usize>, Atom, Vec<Box<Term>>), Var(Cell<Reg>, Var) } pub enum TermRef<'a> { Atom(Level, &'a Cell<usize>, &'a Atom), Clause...
norm
identifier_name