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
lc804-unique-morse-code-words.py
# coding=utf-8 import unittest """804. Unique Morse Code Words https://leetcode.com/problems/unique-morse-code-words/description/ International Morse Code defines a standard encoding where each letter is mapped to a series of dots and dashes, as follows: `"a"` maps to `".-"`, `"b"` maps to `"-..."`, `"c"` maps to `"-...
if __name__ == "__main__": unittest.main()
def test(self): s = Solution() self.assertEqual(s.uniqueMorseRepresentations(["gin", "zen", "gig", "msg"]), 2)
identifier_body
lc804-unique-morse-code-words.py
# coding=utf-8 import unittest """804. Unique Morse Code Words https://leetcode.com/problems/unique-morse-code-words/description/ International Morse Code defines a standard encoding where each letter is mapped to a series of dots and dashes, as follows: `"a"` maps to `".-"`, `"b"` maps to `"-..."`, `"c"` maps to `"-...
(self, words): """ :type words: List[str] :rtype: int """ self.CODE = [ ".-", "-...", "-.-.", "-..", ".", "..-.", "--.", "....", "..", ".---", "-.-", ".-..", "--", "-.", "---", ".--.", "--.-", ".-.", "...", "-", "..-", "...
uniqueMorseRepresentations
identifier_name
lc804-unique-morse-code-words.py
# coding=utf-8 import unittest """804. Unique Morse Code Words https://leetcode.com/problems/unique-morse-code-words/description/ International Morse Code defines a standard encoding where each letter is mapped to a series of dots and dashes, as follows: `"a"` maps to `".-"`, `"b"` maps to `"-..."`, `"c"` maps to `"-...
unittest.main()
conditional_block
SourcePositionTest.py
import unittest from os.path import relpath from coalib.results.SourcePosition import SourcePosition from coala_utils.ContextManagers import prepare_file class SourcePositionTest(unittest.TestCase): def test_initialization(self): with self.assertRaises(TypeError): SourcePosition(None, 0) ...
def test_json(self): with prepare_file([''], None) as (_, filename): uut = SourcePosition(filename, 1) self.assertEqual(uut.__json__(use_relpath=True) ['file'], relpath(filename)) def assert_equal(self, first, second): self.assertGreaterEqu...
uut = SourcePosition('filename', 1) self.assertRegex( repr(uut), "<SourcePosition object\\(file='.*filename', line=1, " 'column=None\\) at 0x[0-9a-fA-F]+>') self.assertEqual(str(uut), 'filename:1') uut = SourcePosition('None', None) self.assertRegex( ...
identifier_body
SourcePositionTest.py
import unittest from os.path import relpath from coalib.results.SourcePosition import SourcePosition from coala_utils.ContextManagers import prepare_file class SourcePositionTest(unittest.TestCase): def test_initialization(self): with self.assertRaises(TypeError): SourcePosition(None, 0) ...
(self, greater, lesser): self.assertGreater(greater, lesser) self.assertGreaterEqual(greater, lesser) self.assertNotEqual(greater, lesser) self.assertLessEqual(lesser, greater) self.assertLess(lesser, greater)
assert_ordering
identifier_name
SourcePositionTest.py
import unittest from os.path import relpath from coalib.results.SourcePosition import SourcePosition from coala_utils.ContextManagers import prepare_file class SourcePositionTest(unittest.TestCase): def test_initialization(self): with self.assertRaises(TypeError):
SourcePosition(None, 0) with self.assertRaises(ValueError): SourcePosition('file', None, 1) # However these should work: SourcePosition('file', None, None) SourcePosition('file', 4, None) SourcePosition('file', 4, 5) def test_string_conversion(self)...
random_line_split
uk.js
(function($) { $.Redactor.opts.langs['uk'] = { html: 'Код', video: 'Відео', image: 'Зображення', table: 'Таблиця', link: 'Посилання', link_insert: 'Вставити посилання ...', link_edit: 'Edit link', unlink: 'Видалити посилання', formatting: 'Стил...
alignment: 'Alignment', filename: 'Name (optional)', edit: 'Edit', center: 'Center' }; })(jQuery);
deleted: 'Закреслений', anchor: 'Anchor', link_new_tab: 'Open link in new tab', underline: 'Underline',
random_line_split
test_jenkins.py
# stdlib from collections import defaultdict import datetime import logging import os import shutil import tempfile # 3p import xml.etree.ElementTree as ET # project from tests.checks.common import AgentCheckTest logger = logging.getLogger(__file__) DATETIME_FORMAT = '%Y-%m-%d_%H-%M-%S' LOG_DATA = 'Finished: SUCCE...
(self): """ Test that an unsuccessful build will create the correct metrics. """ metadata = dict_to_xml(UNSUCCESSFUL_BUILD) self._populate_build_dir(metadata) self._create_check() # Set the high_water mark so that the next check will create events self.c...
testCheckUnsuccessfulEvent
identifier_name
test_jenkins.py
# stdlib from collections import defaultdict import datetime import logging import os import shutil import tempfile # 3p import xml.etree.ElementTree as ET # project from tests.checks.common import AgentCheckTest logger = logging.getLogger(__file__) DATETIME_FORMAT = '%Y-%m-%d_%H-%M-%S' LOG_DATA = 'Finished: SUCCE...
def write_file(file_name, log_data): with open(file_name, 'w') as log_file: log_file.write(log_data) class TestJenkins(AgentCheckTest): CHECK_NAME = 'jenkins' def setUp(self): super(TestJenkins, self).setUp() self.tmp_dir = tempfile.mkdtemp() self.config = { ...
""" Convert a dict to xml for use in a build.xml file """ build = ET.Element('build') for k, v in metadata_dict.iteritems(): node = ET.SubElement(build, k) node.text = v return ET.tostring(build)
identifier_body
test_jenkins.py
# stdlib from collections import defaultdict import datetime import logging import os import shutil import tempfile # 3p import xml.etree.ElementTree as ET # project from tests.checks.common import AgentCheckTest logger = logging.getLogger(__file__) DATETIME_FORMAT = '%Y-%m-%d_%H-%M-%S' LOG_DATA = 'Finished: SUCCE...
def testCheckWithRunningBuild(self): """ Test under the conditions of a jenkins build still running. The build.xml file will exist but it will not yet have a result. """ metadata = dict_to_xml(NO_RESULTS_YET) self._populate_build_dir(metadata) self._create_...
assert 'job_name:foo' in tag.get('tags') assert 'result:ABORTED' in tag.get('tags') assert 'build_number:99' in tag.get('tags')
conditional_block
test_jenkins.py
# stdlib from collections import defaultdict import datetime import logging import os import shutil import tempfile # 3p import xml.etree.ElementTree as ET # project from tests.checks.common import AgentCheckTest logger = logging.getLogger(__file__) DATETIME_FORMAT = '%Y-%m-%d_%H-%M-%S' LOG_DATA = 'Finished: SUCCE...
build_metadata = metadata write_file(metadata_file, build_metadata) def testParseBuildLog(self): """ Test doing a jenkins check. This will parse the logs but since there was no previous high watermark no event will be created. """ metadata = dict_to_xml(SUCCE...
write_file(log_file, log_data) metadata_file = os.path.join(build_dir, 'build.xml')
random_line_split
block_metadata.rs
// Copyright (c) The Diem Core Contributors // SPDX-License-Identifier: Apache-2.0 use crate::{config::global::Config as GlobalConfig, errors::*}; use diem_crypto::HashValue; use diem_types::{account_address::AccountAddress, block_metadata::BlockMetadata}; use std::str::FromStr; #[derive(Debug)] pub enum
{ Account(String), Address(AccountAddress), } #[derive(Debug)] pub enum Entry { Proposer(Proposer), Timestamp(u64), } impl FromStr for Entry { type Err = Error; fn from_str(s: &str) -> Result<Self> { let s = s.split_whitespace().collect::<String>(); let s = &s .st...
Proposer
identifier_name
block_metadata.rs
// Copyright (c) The Diem Core Contributors // SPDX-License-Identifier: Apache-2.0 use crate::{config::global::Config as GlobalConfig, errors::*}; use diem_crypto::HashValue; use diem_types::{account_address::AccountAddress, block_metadata::BlockMetadata}; use std::str::FromStr; #[derive(Debug)] pub enum Proposer { ...
} pub fn build_block_metadata(config: &GlobalConfig, entries: &[Entry]) -> Result<BlockMetadata> { let mut timestamp = None; let mut proposer = None; for entry in entries { match entry { Entry::Proposer(s) => { proposer = match s { Proposer::Account(...
{ if s.starts_with("//!") { Ok(Some(s.parse::<Entry>()?)) } else { Ok(None) } }
identifier_body
block_metadata.rs
// Copyright (c) The Diem Core Contributors // SPDX-License-Identifier: Apache-2.0 use crate::{config::global::Config as GlobalConfig, errors::*}; use diem_crypto::HashValue; use diem_types::{account_address::AccountAddress, block_metadata::BlockMetadata}; use std::str::FromStr; #[derive(Debug)] pub enum Proposer { ...
}
{ Err(ErrorKind::Other("Cannot generate block metadata".to_string()).into()) }
conditional_block
block_metadata.rs
// Copyright (c) The Diem Core Contributors // SPDX-License-Identifier: Apache-2.0 use crate::{config::global::Config as GlobalConfig, errors::*}; use diem_crypto::HashValue; use diem_types::{account_address::AccountAddress, block_metadata::BlockMetadata}; use std::str::FromStr; #[derive(Debug)] pub enum Proposer { ...
return Ok(Entry::Proposer(Proposer::Address( AccountAddress::from_hex_literal(s)?, ))); } if let Some(s) = s.strip_prefix("block-time:") { return Ok(Entry::Timestamp(s.parse::<u64>()?)); } Err(ErrorKind::Other(format!( "fai...
random_line_split
cast.py
""" Provide functionality to interact with Cast devices on the network. For more details about this platform, please refer to the documentation at https://home-assistant.io/components/media_player.cast/ """ # pylint: disable=import-error import logging import voluptuous as vol from homeassistant.components.media_pla...
else: return STATE_UNKNOWN @property def volume_level(self): """Volume level of the media player (0..1).""" return self.cast_status.volume_level if self.cast_status else None @property def is_volume_muted(self): """Boolean if volume is currently muted.""" ...
return STATE_OFF
conditional_block
cast.py
""" Provide functionality to interact with Cast devices on the network. For more details about this platform, please refer to the documentation at https://home-assistant.io/components/media_player.cast/ """ # pylint: disable=import-error import logging import voluptuous as vol from homeassistant.components.media_pla...
@property def media_content_type(self): """Content type of current playing media.""" if self.media_status is None: return None elif self.media_status.media_is_tvshow: return MEDIA_TYPE_TVSHOW elif self.media_status.media_is_movie: return MEDIA_...
random_line_split
cast.py
""" Provide functionality to interact with Cast devices on the network. For more details about this platform, please refer to the documentation at https://home-assistant.io/components/media_player.cast/ """ # pylint: disable=import-error import logging import voluptuous as vol from homeassistant.components.media_pla...
def media_pause(self): """Send pause command.""" self.cast.media_controller.pause() def media_stop(self): """Send stop command.""" self.cast.media_controller.stop() def media_previous_track(self): """Send previous track command.""" self.cast.media_controll...
"""Send play commmand.""" self.cast.media_controller.play()
identifier_body
cast.py
""" Provide functionality to interact with Cast devices on the network. For more details about this platform, please refer to the documentation at https://home-assistant.io/components/media_player.cast/ """ # pylint: disable=import-error import logging import voluptuous as vol from homeassistant.components.media_pla...
(self): """Flag of media commands that are supported.""" return SUPPORT_CAST def turn_on(self): """Turn on the ChromeCast.""" # The only way we can turn the Chromecast is on is by launching an app if not self.cast.status or not self.cast.status.is_active_input: i...
supported_media_commands
identifier_name
parser.py
import json from datetime import datetime from dojo.models import Finding class MeterianParser(object): def get_scan_types(self): return ["Meterian Scan"] def get_label_for_scan_types(self, scan_type): return scan_type def get_description_for_scan_types(self, scan_type): return...
severity = "High" else: severity = "Critical" else: if advisory["severity"] == "SUGGEST" or advisory["severity"] == "NA" or advisory["severity"] == "NONE": severity = "Info" else: severity = advisory["severity"]....
if advisory['cvss'] <= 3.9: severity = "Low" elif advisory['cvss'] >= 4.0 and advisory['cvss'] <= 6.9: severity = "Medium" elif advisory['cvss'] >= 7.0 and advisory['cvss'] <= 8.9:
random_line_split
parser.py
import json from datetime import datetime from dojo.models import Finding class MeterianParser(object): def get_scan_types(self): return ["Meterian Scan"] def get_label_for_scan_types(self, scan_type): return scan_type def get_description_for_scan_types(self, scan_type): return...
else: severity = advisory["severity"].title() return severity def get_reference_url(self, link_obj): url = link_obj["url"] if link_obj["type"] == "CVE": url = "https://cve.mitre.org/cgi-bin/cvename.cgi?name=" + link_obj["url"] elif link_obj[...
severity = "Info"
conditional_block
parser.py
import json from datetime import datetime from dojo.models import Finding class MeterianParser(object): def get_scan_types(self): return ["Meterian Scan"] def get_label_for_scan_types(self, scan_type): return scan_type def get_description_for_scan_types(self, scan_type): return...
(self, link_obj): url = link_obj["url"] if link_obj["type"] == "CVE": url = "https://cve.mitre.org/cgi-bin/cvename.cgi?name=" + link_obj["url"] elif link_obj["type"] == "NVD": url = "https://nvd.nist.gov/vuln/detail/" + link_obj["url"] return url
get_reference_url
identifier_name
parser.py
import json from datetime import datetime from dojo.models import Finding class MeterianParser(object): def get_scan_types(self): return ["Meterian Scan"] def get_label_for_scan_types(self, scan_type): return scan_type def get_description_for_scan_types(self, scan_type):
def get_findings(self, report, test): findings = [] report_json = json.load(report) security_reports = self.get_security_reports(report_json) scan_date = str(datetime.fromisoformat(report_json["timestamp"]).date()) for single_security_report in security_reports: ...
return "Meterian JSON report output file can be imported."
identifier_body
urls.py
from django.conf.urls import patterns, url from django.views.generic import RedirectView from django.conf import settings from . import views products = r'/products/(?P<product>\w+)' versions = r'/versions/(?P<versions>[;\w\.()]+)' version = r'/versions/(?P<version>[;\w\.()]+)' perm_legacy_redirect = settings.PERMA...
)), # Redirect old independant pages to the unified Profile page. url(r'^your-crashes/$', RedirectView.as_view( url='/profile/', permanent=perm_legacy_redirect )), url(r'^permissions/$', RedirectView.as_view( url='/profile/', p...
permanent=True
random_line_split
position.rs
* 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/. */ //! Generic types for CSS handling of specified and computed values of //! [`position`](https://drafts.csswg.org/css-backgrounds-3/#position) #[derive(Clone, Copy, Debug, HasViewportPe...
/* This Source Code Form is subject to the terms of the Mozilla Public
random_line_split
position.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/. */ //! Generic types for CSS handling of specified and computed values of //! [`position`](https://drafts.csswg.org/c...
<H, V> { /// The horizontal component of position. pub horizontal: H, /// The vertical component of position. pub vertical: V, } impl<H, V> Position<H, V> { /// Returns a new position. pub fn new(horizontal: H, vertical: V) -> Self { Self { horizontal: horizontal, ...
Position
identifier_name
queue.ts
import { QueueAction } from './QueueAction'; import { QueueScheduler } from './QueueScheduler'; /** * * 队列调度器 * * <span class="informal">将每个任务都放到队列里,而不是立刻执行它们</span> * * `queue` 调度器, 当和延时一起使用的时候, 和 {@link async} 调度器行为一样。 * * 当和延时一起使用, 它同步地调用当前任务,即调度的时候执行。然而当递归调用的时候,即在调度的任务内, * 另一个任务由调度队列调度,而不是立即执行,该任务将被放在队列中,...
* // "after", 2 * // "after", 3 * * // 但实际使用队列的输入: * // "before", 3 * // "after", 3 * // "before", 2 * // "after", 2 * // "before", 1 * // "after", 1 * * * @static true * @name queue * @owner Scheduler */ export const queue = new QueueScheduler(QueueAction);
* // "before", 2 * // "before", 1 * // "after", 1
random_line_split
NagiosConnector.ts
///ts:ref=jquery.d.ts /// <reference path="../../vendor/jquery.d.ts"/> ///ts:ref:generated ///ts:ref=NagiosResponse.d.ts /// <reference path="../../jsonInterfaces/NagiosResponse.d.ts"/> ///ts:ref:generated ///ts:import=Connector import Connector = require('../../connector/Connector'); ///ts:import:generated ///ts:impor...
}); //reload data periodically. setTimeout(() => this.getRemoteData(model), ConnectorBase.getRandomTimeout()); } public static updateModel(json: NagiosJsonResponse.NagiosServices, model: NagiosMonitorModel): void { model.setData(json); } public getApiUrl(model: Nagios...
{ console.log(jqXHR, textStatus, errorThrown, this.getApiUrl(model)); }
conditional_block
NagiosConnector.ts
///ts:ref=jquery.d.ts /// <reference path="../../vendor/jquery.d.ts"/> ///ts:ref:generated ///ts:ref=NagiosResponse.d.ts /// <reference path="../../jsonInterfaces/NagiosResponse.d.ts"/> ///ts:ref:generated ///ts:import=Connector import Connector = require('../../connector/Connector'); ///ts:import:generated ///ts:impor...
import NagiosMonitorModel = require('../model/NagiosMonitorModel'); ///ts:import:generated import jQuery = require('jquery'); import NagiosJsonResponse = require('NagiosJsonResponse'); /** * Get data from Nagios {@link http://www.nagios.org/} */ class NagiosConnector extends ConnectorBase implements Connector { ...
import ConnectorBase = require('../../connector/ConnectorBase'); ///ts:import:generated ///ts:import=NagiosMonitorModel
random_line_split
NagiosConnector.ts
///ts:ref=jquery.d.ts /// <reference path="../../vendor/jquery.d.ts"/> ///ts:ref:generated ///ts:ref=NagiosResponse.d.ts /// <reference path="../../jsonInterfaces/NagiosResponse.d.ts"/> ///ts:ref:generated ///ts:import=Connector import Connector = require('../../connector/Connector'); ///ts:import:generated ///ts:impor...
(json: NagiosJsonResponse.NagiosServices, model: NagiosMonitorModel): void { model.setData(json); } public getApiUrl(model: NagiosMonitorModel): string { return this.getUrl(model.getHostname(), NagiosConnector.NAGIOS_PREFIX + NagiosConnector.NAGIOS_HOST_SUFFIX + ...
updateModel
identifier_name
NagiosConnector.ts
///ts:ref=jquery.d.ts /// <reference path="../../vendor/jquery.d.ts"/> ///ts:ref:generated ///ts:ref=NagiosResponse.d.ts /// <reference path="../../jsonInterfaces/NagiosResponse.d.ts"/> ///ts:ref:generated ///ts:import=Connector import Connector = require('../../connector/Connector'); ///ts:import:generated ///ts:impor...
public getHostInfoUrl(nagiosHostname: string, hostname: string): string { return this.getUrl(nagiosHostname, NagiosConnector.NAGIOS_HOSTINFO_PREFIX + hostname); } } export = NagiosConnector;
{ return this.getUrl(model.getHostname(), NagiosConnector.NAGIOS_PREFIX + NagiosConnector.NAGIOS_HOST_SUFFIX + NagiosConnector.DISPLAY_ALL_HOSTS + NagiosConnector.NAGIOS_JSONP_SUFFIX); }
identifier_body
run.py
import sys import linecache import time import socket import traceback import thread import threading import Queue from idlelib import CallTips from idlelib import AutoComplete from idlelib import RemoteDebugger from idlelib import RemoteObjectBrowser from idlelib import StackViewer from idlelib import...
(self, flist_oid=None): if self.usr_exc_info: typ, val, tb = self.usr_exc_info else: return None flist = None if flist_oid is not None: flist = self.rpchandler.get_remote_proxy(flist_oid) while tb and tb.tb_frame.f_globals["__name__"] i...
stackviewer
identifier_name
run.py
import sys import linecache import time import socket import traceback import thread import threading import Queue from idlelib import CallTips from idlelib import AutoComplete from idlelib import RemoteDebugger from idlelib import RemoteObjectBrowser from idlelib import StackViewer from idlelib import...
def stop_the_debugger(self, idb_adap_oid): "Unregister the Idb Adapter. Link objects and Idb then subject to GC" self.rpchandler.unregister(idb_adap_oid) def get_the_calltip(self, name): return self.calltip.fetch_tip(name) def get_the_completion_list(self, what, mode): ...
return RemoteDebugger.start_debugger(self.rpchandler, gui_adap_oid)
identifier_body
run.py
import sys import linecache import time import socket import traceback import thread import threading import Queue from idlelib import CallTips from idlelib import AutoComplete from idlelib import RemoteDebugger from idlelib import RemoteObjectBrowser from idlelib import StackViewer from idlelib import...
print_exception() jit = self.rpchandler.console.getvar("<<toggle-jit-stack-viewer>>") if jit: self.rpchandler.interp.open_remote_stack_viewer() else: flush_stdout() def interrupt_the_server(self): if interruptable: ...
exit()
conditional_block
run.py
import socket import traceback import thread import threading import Queue from idlelib import CallTips from idlelib import AutoComplete from idlelib import RemoteDebugger from idlelib import RemoteObjectBrowser from idlelib import StackViewer from idlelib import rpc from idlelib import PyShell from idl...
import sys import linecache import time
random_line_split
bdgbroadcall_cmd.py
# Time-stamp: <2019-09-25 10:04:48 taoliu> """Description: Fine-tuning script to call broad peaks from a single bedGraph track for scores. This code is free software; you can redistribute it and/or modify it under the terms of the BSD License (see the file LICENSE included with the distribution). """ # ------------...
( options ): info("Read and build bedGraph...") bio = BedGraphIO.bedGraphIO(options.ifile) btrack = bio.build_bdgtrack(baseline_value=0) info("Call peaks from bedGraph...") bpeaks = btrack.call_broadpeaks (lvl1_cutoff=options.cutoffpeak, lvl2_cutoff=options.cutofflink, min_length=options.minlen, l...
run
identifier_name
bdgbroadcall_cmd.py
# Time-stamp: <2019-09-25 10:04:48 taoliu> """Description: Fine-tuning script to call broad peaks from a single bedGraph track for scores. This code is free software; you can redistribute it and/or modify it under the terms of the BSD License (see the file LICENSE included with the distribution). """ # ------------...
def run( options ): info("Read and build bedGraph...") bio = BedGraphIO.bedGraphIO(options.ifile) btrack = bio.build_bdgtrack(baseline_value=0) info("Call peaks from bedGraph...") bpeaks = btrack.call_broadpeaks (lvl1_cutoff=options.cutoffpeak, lvl2_cutoff=options.cutofflink, min_length=options.mi...
# Main function # ------------------------------------
random_line_split
bdgbroadcall_cmd.py
# Time-stamp: <2019-09-25 10:04:48 taoliu> """Description: Fine-tuning script to call broad peaks from a single bedGraph track for scores. This code is free software; you can redistribute it and/or modify it under the terms of the BSD License (see the file LICENSE included with the distribution). """ # ------------...
info("Read and build bedGraph...") bio = BedGraphIO.bedGraphIO(options.ifile) btrack = bio.build_bdgtrack(baseline_value=0) info("Call peaks from bedGraph...") bpeaks = btrack.call_broadpeaks (lvl1_cutoff=options.cutoffpeak, lvl2_cutoff=options.cutofflink, min_length=options.minlen, lvl1_max_gap=optio...
identifier_body
bdgbroadcall_cmd.py
# Time-stamp: <2019-09-25 10:04:48 taoliu> """Description: Fine-tuning script to call broad peaks from a single bedGraph track for scores. This code is free software; you can redistribute it and/or modify it under the terms of the BSD License (see the file LICENSE included with the distribution). """ # ------------...
bpeaks.write_to_gappedPeak(bf, name_prefix=(options.oprefix+"_broadRegion").encode(), score_column="score", trackline=options.trackline) info("Done")
bf = open ( os.path.join( options.outdir, "%s_c%.1f_C%.2f_l%d_g%d_G%d_broad.bed12" % (options.oprefix,options.cutoffpeak,options.cutofflink,options.minlen,options.lvl1maxgap,options.lvl2maxgap)), "w" )
conditional_block
ticker.ts
import { State } from './core/enum/state' import { ITicker } from './core/interfaces/ITicker' /** * Main Fatina Ticker * Parent of all the normal tween and sequence * * @export * @class Ticker * @extends {EventList} * @implements {ITicker} */ export class Ticker implements ITicker { public state = State.Idle...
} /** * Method used to tick all the child (tick listeners) * * @param {number} dt * @returns */ public tick(dt: number) { if (this.state !== State.Run) { return } this.dt = dt * this.timescale if (this.newTicks.size > 0) { this.newTicks.forEach((tick) => this.ticks.ad...
{ this.newTicks.delete(cb) }
conditional_block
ticker.ts
import { State } from './core/enum/state' import { ITicker } from './core/interfaces/ITicker' /** * Main Fatina Ticker * Parent of all the normal tween and sequence * * @export * @class Ticker * @extends {EventList} * @implements {ITicker} */ export class Ticker implements ITicker { public state = State.Idle...
} public start(): void { if (this.state === State.Idle) { this.state = State.Run } } public pause(): void { if (this.state === State.Run) { this.state = State.Pause } } public resume(): void { if (this.state === State.Pause) { this.state = State.Run } } publ...
random_line_split
ticker.ts
import { State } from './core/enum/state' import { ITicker } from './core/interfaces/ITicker' /** * Main Fatina Ticker * Parent of all the normal tween and sequence * * @export * @class Ticker * @extends {EventList} * @implements {ITicker} */ export class Ticker implements ITicker { public state = State.Idle...
(): boolean { return this.state === State.Pause } }
isPaused
identifier_name
driver.ts
import { createDecorator } from 'vs/platform/instantiation/common/instantiation'; // !! Do not remove the following START and END markers, they are parsed by the smoketest build //*START export interface IElement { tagName: string; className: string; textContent: string; attributes: { [name: string]: string; }; ...
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *---------------------------------------------------------------...
random_line_split
wss.js
if ( typeof Promise == 'undefined' ) { var _P = require('../lib/promise.min.js').Promise; } else { var _P = Promise; } var Excp = require('excp.js'); var Session = require('session.js'); var Table = require('table.js'); function
( option ) { this.isOpen = false; this.events = {}; this.conn_events = {}; this.host = option['wss'] || option['host']; this.ss = new Session( option ); this.ss.start(); this.cid = option.app || ''; this.prefix= option['table.prefix'] || ''; this.table_name = option['ws.table'] || 'message'; this.user_tab...
Wss
identifier_name
wss.js
if ( typeof Promise == 'undefined' ) { var _P = require('../lib/promise.min.js').Promise; } else { var _P = Promise; } var Excp = require('excp.js'); var Session = require('session.js'); var Table = require('table.js'); function Wss( option )
{ this.isOpen = false; this.events = {}; this.conn_events = {}; this.host = option['wss'] || option['host']; this.ss = new Session( option ); this.ss.start(); this.cid = option.app || ''; this.prefix= option['table.prefix'] || ''; this.table_name = option['ws.table'] || 'message'; this.user_table = option...
identifier_body
wss.js
if ( typeof Promise == 'undefined' ) { var _P = require('../lib/promise.min.js').Promise; } else { var _P = Promise; } var Excp = require('excp.js'); var Session = require('session.js'); var Table = require('table.js'); function Wss( option ) { this.isOpen = false; this.events = {}; this.conn_events = {}; this....
ss;
鉴权 ( 需要管理员权限 ) * @return Promise */ this._acl = function() { } } module.exports = W
conditional_block
wss.js
if ( typeof Promise == 'undefined' ) { var _P = require('../lib/promise.min.js').Promise; } else { var _P = Promise; } var Excp = require('excp.js'); var Session = require('session.js'); var Table = require('table.js'); function Wss( option ) { this.isOpen = false; this.events = {}; this.conn_events = {}; this....
return; } var resp = JSON.parse( res.data ); resp['data'] = resp['data'] || {}; var code = resp['code']; var req = resp['data']['request'] || {}; var res = resp['data']['response'] || {}; var error = resp['data']['error'] || null; var cmd = req['c'] || null; if ( code !==...
that.conn_events['message']( res ); } catch(e){} } if ( typeof res.data !== 'string' ) {
random_line_split
hateoas.py
# -*- coding: utf8 -*- # This file is part of PyBossa. # # Copyright (C) 2013 SF Isle of Man Limited # # PyBossa is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at...
def remove_links(self, item): """Remove HATEOAS link and links from item""" if item.get('link'): item.pop('link') if item.get('links'): item.pop('links') return item
cls = item.__class__.__name__.lower() if cls == 'taskrun': link = self.create_link(item) links = [] if item.app_id is not None: links.append(self.create_link(item.app, rel='parent')) if item.task_id is not None: links.append(self.cr...
identifier_body
hateoas.py
# -*- coding: utf8 -*- # This file is part of PyBossa. # # Copyright (C) 2013 SF Isle of Man Limited # # PyBossa is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at...
elif cls == 'task': link = self.create_link(item) links = [] if item.app_id is not None: links = [self.create_link(item.app, rel='parent')] return links, link elif cls == 'category': return None, self.create_link(item) ...
link = self.create_link(item) links = [] if item.app_id is not None: links.append(self.create_link(item.app, rel='parent')) if item.task_id is not None: links.append(self.create_link(item.task, rel='parent')) return links, link
conditional_block
hateoas.py
# -*- coding: utf8 -*- # This file is part of PyBossa. # # Copyright (C) 2013 SF Isle of Man Limited # # PyBossa is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at...
class Hateoas(object): def link(self, rel, title, href): return "<link rel='%s' title='%s' href='%s'/>" % (rel, title, href) def create_link(self, item, rel='self'): title = item.__class__.__name__.lower() method = ".api_%s" % title href = url_for(method, id=item.id, _external=...
from flask import url_for
random_line_split
hateoas.py
# -*- coding: utf8 -*- # This file is part of PyBossa. # # Copyright (C) 2013 SF Isle of Man Limited # # PyBossa is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at...
(self, rel, title, href): return "<link rel='%s' title='%s' href='%s'/>" % (rel, title, href) def create_link(self, item, rel='self'): title = item.__class__.__name__.lower() method = ".api_%s" % title href = url_for(method, id=item.id, _external=True) return self.link(rel, ...
link
identifier_name
socialnetwork.py
# -*- coding: utf-8 -*- from canaimagnulinux.wizard.interfaces import IChat from canaimagnulinux.wizard.interfaces import ISocialNetwork from canaimagnulinux.wizard.utils import CanaimaGnuLinuxWizardMF as _ from collective.beaker.interfaces import ISession from collective.z3cform.wizard import wizard from plone impor...
(self, context, request, wizard): # Use collective.beaker for session managment session = ISession(request, None) self.sessionmanager = session super(SocialNetworkStep, self).__init__(context, request, wizard) def load(self, context): member = api.user.get_current() ...
__init__
identifier_name
socialnetwork.py
# -*- coding: utf-8 -*- from canaimagnulinux.wizard.interfaces import IChat from canaimagnulinux.wizard.interfaces import ISocialNetwork from canaimagnulinux.wizard.utils import CanaimaGnuLinuxWizardMF as _ from collective.beaker.interfaces import ISession from collective.z3cform.wizard import wizard from plone impor...
# Plone < 4.1 from zope.app.pagetemplate import viewpagetemplatefile import logging logger = logging.getLogger(__name__) class ChatGroup(group.Group): prefix = 'chats' label = _(u'Chats Information') fields = field.Fields(IChat) class SocialNetworkGroup(group.Group): prefix = 'socialnetwork...
random_line_split
socialnetwork.py
# -*- coding: utf-8 -*- from canaimagnulinux.wizard.interfaces import IChat from canaimagnulinux.wizard.interfaces import ISocialNetwork from canaimagnulinux.wizard.utils import CanaimaGnuLinuxWizardMF as _ from collective.beaker.interfaces import ISession from collective.z3cform.wizard import wizard from plone impor...
if not data.get('skype', None): skype = member.getProperty('skype') if type(skype).__name__ == 'object': skype = None data['skype'] = skype # Social Network group if not data.get('twitter', None): twitter = member.getProperty('tw...
telegram = member.getProperty('telegram') if type(telegram).__name__ == 'object': telegram = None data['telegram'] = telegram
conditional_block
socialnetwork.py
# -*- coding: utf-8 -*- from canaimagnulinux.wizard.interfaces import IChat from canaimagnulinux.wizard.interfaces import ISocialNetwork from canaimagnulinux.wizard.utils import CanaimaGnuLinuxWizardMF as _ from collective.beaker.interfaces import ISession from collective.z3cform.wizard import wizard from plone impor...
prefix = 'Social' label = _(u'Social Network accounts') description = _(u'Input your social networks details') template = viewpagetemplatefile.ViewPageTemplateFile('templates/socialnetwork.pt') fields = field.Fields() groups = [ChatGroup, SocialNetworkGroup] def __init__(self, context, request...
identifier_body
index.js
'use strict'; module.exports = geojsonvt; var convert = require('./convert'), // GeoJSON conversion and preprocessing transform = require('./transform'), // coordinate transformation clip = require('./clip'), // stripe clipping algorithm wrap = require('./wrap'), // date line proce...
var stack = [features, z, x, y], options = this.options, debug = options.debug; // avoid recursion by using a processing queue while (stack.length) { y = stack.pop(); x = stack.pop(); z = stack.pop(); features = stack.pop(); var z2 = 1 << z, ...
GeoJSONVT.prototype.splitTile = function (features, z, x, y, cz, cx, cy) {
random_line_split
index.js
'use strict'; module.exports = geojsonvt; var convert = require('./convert'), // GeoJSON conversion and preprocessing transform = require('./transform'), // coordinate transformation clip = require('./clip'), // stripe clipping algorithm wrap = require('./wrap'), // date line proce...
(a, b, y) { return [(y - a[1]) * (b[0] - a[0]) / (b[1] - a[1]) + a[0], y, 1]; } function extend(dest, src) { for (var i in src) dest[i] = src[i]; return dest; } // checks whether a tile is a whole-area fill after clipping; if it is, there's no sense slicing it further function isClippedSquare(tile, extent...
intersectY
identifier_name
index.js
'use strict'; module.exports = geojsonvt; var convert = require('./convert'), // GeoJSON conversion and preprocessing transform = require('./transform'), // coordinate transformation clip = require('./clip'), // stripe clipping algorithm wrap = require('./wrap'), // date line proce...
// checks whether a tile is a whole-area fill after clipping; if it is, there's no sense slicing it further function isClippedSquare(tile, extent, buffer) { var features = tile.source; if (features.length !== 1) return false; var feature = features[0]; if (feature.type !== 3 || feature.geometry.leng...
{ for (var i in src) dest[i] = src[i]; return dest; }
identifier_body
IncTemplate.js
'use strict'; var util = require('util'); var GtReq = require('../GtReq'); var BaseTemplate = require('./BaseTemplate'); function
(options) { BaseTemplate.call(this, options); options = util._extend({ transmissionContent: '', incAppId: '' }, options); util._extend(this, options); } util.inherits(IncTemplate, BaseTemplate); IncTemplate.prototype.getActionChain = function() { var actionChain1 = new Gt...
IncTemplate
identifier_name
IncTemplate.js
'use strict'; var util = require('util'); var GtReq = require('../GtReq'); var BaseTemplate = require('./BaseTemplate'); function IncTemplate(options) { BaseTemplate.call(this, options); options = util._extend({ transmissionContent: '', incAppId: '' }, options); util._extend(th...
// 启动app // Start the app var actionChain2 = new GtReq.ActionChain({ actionId: 10030, type: GtReq.ActionChain.Type.startapp, appid: this.incAppId, autostart: 1 === this.transmissionType, appstartupid: appStartUp, failedAction: 100, next: 100 ...
android: '', symbia: '', ios: '' });
random_line_split
IncTemplate.js
'use strict'; var util = require('util'); var GtReq = require('../GtReq'); var BaseTemplate = require('./BaseTemplate'); function IncTemplate(options)
util.inherits(IncTemplate, BaseTemplate); IncTemplate.prototype.getActionChain = function() { var actionChain1 = new GtReq.ActionChain({ actionId: 1, type: GtReq.ActionChain.Type.Goto, next: 10030 }); var appStartUp = new GtReq.AppStartUp({ android: '', s...
{ BaseTemplate.call(this, options); options = util._extend({ transmissionContent: '', incAppId: '' }, options); util._extend(this, options); }
identifier_body
applayerframetype.rs
/* Copyright (C) 2021 Open Information Security Foundation * * You can copy, redistribute or modify this Program under the terms of * the GNU General Public License version 2 as published by the Free * Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARR...
(input: TokenStream) -> TokenStream { let input = parse_macro_input!(input as DeriveInput); let name = input.ident; let mut fields = Vec::new(); let mut vals = Vec::new(); let mut cstrings = Vec::new(); let mut names = Vec::new(); match input.data { syn::Data::Enum(ref data) => { ...
derive_app_layer_frame_type
identifier_name
applayerframetype.rs
/* Copyright (C) 2021 Open Information Security Foundation * * You can copy, redistribute or modify this Program under the terms of * the GNU General Public License version 2 as published by the Free * Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARR...
xname.push_str(&chars[i].to_lowercase().to_string()); } xname } #[cfg(test)] mod test { use super::*; #[test] fn test_transform_name() { assert_eq!(transform_name("One"), "one"); assert_eq!(transform_name("OneTwo"), "one.two"); assert_eq!(transform_name("OneTwoThre...
{ xname.push('.'); }
conditional_block
applayerframetype.rs
/* Copyright (C) 2021 Open Information Security Foundation * * You can copy, redistribute or modify this Program under the terms of * the GNU General Public License version 2 as published by the Free * Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARR...
}
{ assert_eq!(transform_name("One"), "one"); assert_eq!(transform_name("OneTwo"), "one.two"); assert_eq!(transform_name("OneTwoThree"), "one.two.three"); assert_eq!(transform_name("NBSS"), "nbss"); assert_eq!(transform_name("NBSSHdr"), "nbss.hdr"); assert_eq!(transform_nam...
identifier_body
applayerframetype.rs
/* Copyright (C) 2021 Open Information Security Foundation * * You can copy, redistribute or modify this Program under the terms of * the GNU General Public License version 2 as published by the Free * Software Foundation. *
* You should have received a copy of the GNU General Public License * version 2 along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA * 02110-1301, USA. */ extern crate proc_macro; use proc_macro::TokenStream; use quote::quote; use syn::{self, ...
* This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. *
random_line_split
appointment_tags.py
# # Newfies-Dialer License # http://www.newfies-dialer.org # # 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/. # # Copyright (C) 2011-2014 Star2Billing S.L. # # The Initia...
METHOD = dict(ALARM_METHOD) try: return METHOD[value].encode('utf-8') except: return ''
return ''
conditional_block
appointment_tags.py
# # Newfies-Dialer License # http://www.newfies-dialer.org # # 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/. # # Copyright (C) 2011-2014 Star2Billing S.L. # # The Initia...
return ''
random_line_split
appointment_tags.py
# # Newfies-Dialer License # http://www.newfies-dialer.org # # 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/. # # Copyright (C) 2011-2014 Star2Billing S.L. # # The Initia...
(value): """Event Status Templatetag""" if not value: return '' STATUS = dict(EVENT_STATUS) try: return STATUS[value].encode('utf-8') except: return '' @register.filter(name='alarm_status') def alarm_status(value): """Alarm Status Templatetag""" if not value: ...
event_status
identifier_name
appointment_tags.py
# # Newfies-Dialer License # http://www.newfies-dialer.org # # 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/. # # Copyright (C) 2011-2014 Star2Billing S.L. # # The Initia...
"""Alarm Method Templatetag""" if not value: return '' METHOD = dict(ALARM_METHOD) try: return METHOD[value].encode('utf-8') except: return ''
identifier_body
fetch.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::RequestBinding::RequestInfo; use dom::bindings::codegen::Bindings::RequestBi...
(&mut self, fetch_metadata: Result<FetchMetadata, NetworkError>) { let promise = self.fetch_promise.take().expect("fetch promise is missing").root(); // JSAutoCompartment needs to be manually made. // Otherwise, Servo will crash. let promise_cx = promise.global().get_cx(); let _...
process_response
identifier_name
fetch.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::RequestBinding::RequestInfo; use dom::bindings::codegen::Bindings::RequestBi...
fn process_response_chunk(&mut self, mut chunk: Vec<u8>) { self.body.append(&mut chunk); } fn process_response_eof(&mut self, _response: Result<(), NetworkError>) { let response = self.response_object.root(); let global = response.global(); let cx = global.get_cx(); ...
{ let promise = self.fetch_promise.take().expect("fetch promise is missing").root(); // JSAutoCompartment needs to be manually made. // Otherwise, Servo will crash. let promise_cx = promise.global().get_cx(); let _ac = JSAutoCompartment::new(promise_cx, promise.reflector().get_j...
identifier_body
fetch.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::RequestBinding::RequestInfo; use dom::bindings::codegen::Bindings::RequestBi...
mode: request.mode.clone(), use_cors_preflight: request.use_cors_preflight, credentials_mode: request.credentials_mode, use_url_credentials: request.use_url_credentials, origin: GlobalScope::current().expect("No current global object").origin().immutable().clone(), referr...
headers: request.headers.clone(), unsafe_request: request.unsafe_request, body: request.body.clone(), destination: request.destination, synchronous: request.synchronous,
random_line_split
fetch.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::RequestBinding::RequestInfo; use dom::bindings::codegen::Bindings::RequestBi...
} /// Use this if you don't want it to send a cancellation request /// on drop (e.g. if the fetch completes) pub fn ignore(&mut self) { let _ = self.cancel_chan.take(); } } impl Drop for FetchCanceller { fn drop(&mut self) { self.cancel() } } fn from_referrer_to_referrer_...
{ // stop trying to make fetch happen // it's not going to happen // The receiver will be destroyed if the request has already completed; // so we throw away the error. Cancellation is a courtesy call, // we don't actually care if the other side heard. ...
conditional_block
nb.js
/*! Select2 4.0.0 | https://github.com/select2/select2/blob/master/LICENSE.md */ (function () { if (jQuery && jQuery.fn && jQuery.fn.select2 && jQuery.fn.select2.amd)var e = jQuery.fn.select2.amd; return e.define("select2/i18n/nb", [], function () { return { inputTooLong: function (e) { var t = e...
}), {define: e.define, require: e.require} })();
random_line_split
path.ts
import { each } from '@antv/util'; import MaskBase from './base'; /** * @ignore * 多个点构成的 Path 辅助框 Action */ class PathMask extends MaskBase { // 生成 mask 的路径 protected getMaskPath() { const points = this.points; const path = []; if (points.length) { each(points, (point, index) => { if (...
'L', points[0].x, points[0].y]); } return path; } protected getMaskAttrs() { return { path: this.getMaskPath(), }; } /** * 添加一个点 */ public addPoint() { this.resize(); } } export default PathMask;
point.x, point.y]); } }); path.push([
conditional_block
path.ts
import { each } from '@antv/util'; import MaskBase from './base';
class PathMask extends MaskBase { // 生成 mask 的路径 protected getMaskPath() { const points = this.points; const path = []; if (points.length) { each(points, (point, index) => { if (index === 0) { path.push(['M', point.x, point.y]); } else { path.push(['L', point.x,...
/** * @ignore * 多个点构成的 Path 辅助框 Action */
random_line_split
path.ts
import { each } from '@antv/util'; import MaskBase from './base'; /** * @ignore * 多个点构成的 Path 辅助框 Action */ class PathMask extends MaskBase { // 生成 mask 的路径 protected getMaskPath() { const points = this.po
{ return { path: this.getMaskPath(), }; } /** * 添加一个点 */ public addPoint() { this.resize(); } } export default PathMask;
ints; const path = []; if (points.length) { each(points, (point, index) => { if (index === 0) { path.push(['M', point.x, point.y]); } else { path.push(['L', point.x, point.y]); } }); path.push(['L', points[0].x, points[0].y]); } return path; ...
identifier_body
path.ts
import { each } from '@antv/util'; import MaskBase from './base'; /** * @ignore * 多个点构成的 Path 辅助框 Action */ class PathMask extends MaskBase { // 生成 mask 的路径 protected getMaskPath() { const points = this.points; const path = []; if (points.length) { each(points, (point, index) => { if (...
: this.getMaskPath(), }; } /** * 添加一个点 */ public addPoint() { this.resize(); } } export default PathMask;
{ path
identifier_name
passport-local-mongoose-tests.ts
/// <reference types="express" /> /** * Created by Linus Brolin <https://github.com/linusbrolin/>. */ import { Schema, model, Document, PassportLocalDocument, PassportLocalSchema, PassportLocalModel, PassportLocalOptions,
import * as passport from 'passport'; import { Strategy as LocalStrategy } from 'passport-local'; //#region Test Models interface User extends PassportLocalDocument { _id: string; username: string; hash: string; salt: string; attempts: number; last: Date; } const UserSchema = new Schema({ ...
PassportLocalErrorMessages } from 'mongoose'; import * as passportLocalMongoose from 'passport-local-mongoose'; import { Router, Request, Response } from 'express';
random_line_split
passport-local-mongoose-tests.ts
/// <reference types="express" /> /** * Created by Linus Brolin <https://github.com/linusbrolin/>. */ import { Schema, model, Document, PassportLocalDocument, PassportLocalSchema, PassportLocalModel, PassportLocalOptions, PassportLocalErrorMessages } from 'mongoose'; import * as pass...
return done(null, authuser); }); }); }); }) ); passport.serializeUser(UserModel.serializeUser()); passport.deserializeUser(UserModel.deserializeUser()); let router: Router = Router(); router.post('/login', passport.authenticate('local'), function(req: Req...
{ console.log(errorMessages.IncorrectPasswordError); return done(null, false, errorMessages.IncorrectPasswordError); }
conditional_block
autoregressive_layers.py
import numpy as np import six import tensorflow as tf from tensorflow_probability.python.bijectors.masked_autoregressive import ( AutoregressiveNetwork, _create_degrees, _create_input_order, _make_dense_autoregressive_masks, _make_masked_constraint, _make_masked_initializer) from tensorflow_probability.pyth...
if k + 1 < len(self._masks): outputs.append( tf.keras.layers.Activation(self._activation)(outputs[-1])) self._network = tf.keras.models.Model(inputs=inputs, outputs=outputs[-1]) # Allow network to be called with inputs of shapes that don't match # the specs of the network's input l...
random_line_split
autoregressive_layers.py
import numpy as np import six import tensorflow as tf from tensorflow_probability.python.bijectors.masked_autoregressive import ( AutoregressiveNetwork, _create_degrees, _create_input_order, _make_dense_autoregressive_masks, _make_masked_constraint, _make_masked_initializer) from tensorflow_probability.pyth...
else: output_shape = ps.concat([input_shape[:-1], (self._event_size,)], axis=0) return tf.reshape(self._network(x), tf.concat([output_shape, [self._params]], axis=0))
if conditional_input is None: raise ValueError('`conditional_input` must be passed as a named ' 'argument') conditional_input = tf.convert_to_tensor(conditional_input, dtype=self.dtype, ...
conditional_block
autoregressive_layers.py
import numpy as np import six import tensorflow as tf from tensorflow_probability.python.bijectors.masked_autoregressive import ( AutoregressiveNetwork, _create_degrees, _create_input_order, _make_dense_autoregressive_masks, _make_masked_constraint, _make_masked_initializer) from tensorflow_probability.pyth...
(AutoregressiveNetwork): """ Masked autoregressive network - a generalized version of MADE. MADE is autoencoder which require equality in the number of dimensions between input and output. MAN enables these numbers to be different. """ def build(self, input_shape): """See tfkl.Layer.build.""" ass...
AutoregressiveDense
identifier_name
autoregressive_layers.py
import numpy as np import six import tensorflow as tf from tensorflow_probability.python.bijectors.masked_autoregressive import ( AutoregressiveNetwork, _create_degrees, _create_input_order, _make_dense_autoregressive_masks, _make_masked_constraint, _make_masked_initializer) from tensorflow_probability.pyth...
def call(self, x, conditional_input=None): """Transforms the inputs and returns the outputs. Suppose `x` has shape `batch_shape + event_shape` and `conditional_input` has shape `conditional_batch_shape + conditional_event_shape`. Then, the output shape is: `broadcast(batch_shape, conditional_ba...
"""See tfkl.Layer.build.""" assert self._event_shape is not None, \ 'Unlike MADE, MAN require specified event_shape at __init__' # `event_shape` wasn't specied at __init__, so infer from `input_shape`. self._input_size = input_shape[-1] # Construct the masks. self._input_order = _create_input_...
identifier_body
zippy.component.ts
import {Component, Input} from '@angular/core'; @Component({ selector: 'zippy', //templateUrl:'../app/html/zippyComponent.html', template: ` <div class="zippy"> <div class="zippyHeader" (click)="chevronClick()"> {{title}} <i class="pull-right glyphicon" [...
}) /** * */ export class ZippyComponent{ constructor(){ console.log(this.title + '..........' + this.isSelected); } ngOnInit(){ this.isSelected = true ? this.priority == 1 : this.isSelected; console.log(this.title + '..........' + this.isSelected + '....' + this.priority); } isSelected= false; ...
, providers: []
random_line_split
zippy.component.ts
import {Component, Input} from '@angular/core'; @Component({ selector: 'zippy', //templateUrl:'../app/html/zippyComponent.html', template: ` <div class="zippy"> <div class="zippyHeader" (click)="chevronClick()"> {{title}} <i class="pull-right glyphicon" [...
(){ console.log(this.title + '..........' + this.isSelected); } ngOnInit(){ this.isSelected = true ? this.priority == 1 : this.isSelected; console.log(this.title + '..........' + this.isSelected + '....' + this.priority); } isSelected= false; @Input() title: string; @Input() priority: Number...
constructor
identifier_name
zippy.component.ts
import {Component, Input} from '@angular/core'; @Component({ selector: 'zippy', //templateUrl:'../app/html/zippyComponent.html', template: ` <div class="zippy"> <div class="zippyHeader" (click)="chevronClick()"> {{title}} <i class="pull-right glyphicon" [...
ngOnInit(){ this.isSelected = true ? this.priority == 1 : this.isSelected; console.log(this.title + '..........' + this.isSelected + '....' + this.priority); } isSelected= false; @Input() title: string; @Input() priority: Number; chevronClick(){ this.isSelected = !this.isSelected; ...
{ console.log(this.title + '..........' + this.isSelected); }
identifier_body
query-language.ts
import {customElement, bindable} from 'aurelia-templating'; import {inject} from 'aurelia-dependency-injection'; import {Utils, DomUtils} from 'marvelous-aurelia-core/utils'; import {AureliaUtils} from 'marvelous-aurelia-core/aureliaUtils'; @customElement('m-query-language') @inject(Element, AureliaUtils) export class...
() { this.validateOptions(); this.createOptions(); this.registerInputHandlers(); } detached() { this._subs.forEach(x => x()); this._subs = []; } submit() { if (this._lastSubmittedQuery === this.query) { // submits only if query has some changes return; } let promi...
attached
identifier_name
query-language.ts
import {customElement, bindable} from 'aurelia-templating'; import {inject} from 'aurelia-dependency-injection'; import {Utils, DomUtils} from 'marvelous-aurelia-core/utils'; import {AureliaUtils} from 'marvelous-aurelia-core/aureliaUtils'; @customElement('m-query-language') @inject(Element, AureliaUtils) export class...
select(completion: IAutoCompletionRow) { this.selectedCompletionIndex = this.autoCompletionResult.Completions.indexOf(completion); } selectNext() { if (this.selectedCompletionIndex == this.autoCompletionResult.Completions.length - 1) { this.selectedCompletionIndex = 0; return; } thi...
{ this.selectedCompletionIndex = 0; if (this.autoCompletionResult) this.autoCompletionResult.Completions = []; }
identifier_body
query-language.ts
import {customElement, bindable} from 'aurelia-templating'; import {inject} from 'aurelia-dependency-injection'; import {Utils, DomUtils} from 'marvelous-aurelia-core/utils'; import {AureliaUtils} from 'marvelous-aurelia-core/aureliaUtils'; @customElement('m-query-language') @inject(Element, AureliaUtils) export class...
this._loading = true; promise.then((x) => { this._loading = false; if (!x) { return; } // if wrapped with DataSourceResult<T> // then uses `queryLanguage` // otherwise result is assumed to be QueryLanguageFilterResult<T> let result = x.queryLanguage || ...
this._lastSubmittedQuery = this.query;
random_line_split
query-language.ts
import {customElement, bindable} from 'aurelia-templating'; import {inject} from 'aurelia-dependency-injection'; import {Utils, DomUtils} from 'marvelous-aurelia-core/utils'; import {AureliaUtils} from 'marvelous-aurelia-core/aureliaUtils'; @customElement('m-query-language') @inject(Element, AureliaUtils) export class...
this.selectedCompletionIndex++; } selectPrevious() { if (this.selectedCompletionIndex == 0) { this.selectedCompletionIndex = this.autoCompletionResult.Completions.length - 1; return; } this.selectedCompletionIndex--; } refreshCompletions(caretPosition = DomUtils.getCaretPosition(t...
{ this.selectedCompletionIndex = 0; return; }
conditional_block
helper.py
from __future__ import division from __future__ import unicode_literals from builtins import range from past.utils import old_div import hashlib import os import random import string import tempfile import re import time import urllib from datetime import datetime from datetime import timedelta from elodie.compatabil...
final_name, headers = urllib.request.urlretrieve(url_to_file) return final_name except Exception as e: return False def get_file(name): file_path = get_file_path(name) if not os.path.isfile(file_path): return False return file_path def get_file_path(name): ...
final_name ) else:
random_line_split
helper.py
from __future__ import division from __future__ import unicode_literals from builtins import range from past.utils import old_div import hashlib import os import random import string import tempfile import re import time import urllib from datetime import datetime from datetime import timedelta from elodie.compatabil...
else: return file_name # time_convert(s_time) # Change s_time (struct_time) by the offset # between UTC and local time # (Windows only) def time_convert(s_time): if is_windows(): return time.gmtime((time.mktime(s_time))) else: return s_time # isclose(a,b,rel_tol) # To compare float ...
tz_shift = old_div((datetime.fromtimestamp(0) - datetime.utcfromtimestamp(0)).seconds,3600) # replace timestamp in file_name m = re.search('(\d{4}-\d{2}-\d{2}_\d{2}-\d{2}-\d{2})',file_name) t_date = datetime.fromtimestamp(time.mktime(time.strptime(m.group(0), '%Y-%m-%d_%H-%M-%S'))) ...
conditional_block
helper.py
from __future__ import division from __future__ import unicode_literals from builtins import range from past.utils import old_div import hashlib import os import random import string import tempfile import re import time import urllib from datetime import datetime from datetime import timedelta from elodie.compatabil...
(): return random.random() def random_coordinate(coordinate, precision): # Here we add to the decimal section of the coordinate by a given precision return coordinate + ((old_div(10.0, (10.0**precision))) * random_decimal()) def temp_dir(): return tempfile.gettempdir() def is_windows(): return os...
random_decimal
identifier_name
helper.py
from __future__ import division from __future__ import unicode_literals from builtins import range from past.utils import old_div import hashlib import os import random import string import tempfile import re import time import urllib from datetime import datetime from datetime import timedelta from elodie.compatabil...
# isclose(a,b,rel_tol) # To compare float coordinates a and b # with relative tolerance c def isclose(a, b, rel_tol = 1e-8): if not isinstance(a, (int, float)) or not isinstance(b, (int, float)): return False diff = abs(a - b) return (diff <= abs(rel_tol * a) and diff <= abs(rel_tol...
if is_windows(): return time.gmtime((time.mktime(s_time))) else: return s_time
identifier_body
main.py
#!/usr/bin/python # MinerLite - A client side miner controller. # This will launch cgminer with a few delay seconds and # retrieve the local data and post it into somewhere! # # Author: Yanxiang Wu # Release Under GPL 3 # Used code from cgminer python API example import socket import json import sys import subproc...
def retrieve_cgminer_info(command, parameter): """retrieve status of devices from cgminer """ api_ip = '127.0.0.1' api_port = 4028 s = socket.socket(socket.AF_INET,socket.SOCK_STREAM) s.connect((api_ip,int(api_port))) if not parameter: s.send(...
return buffer
conditional_block
main.py
#!/usr/bin/python # MinerLite - A client side miner controller. # This will launch cgminer with a few delay seconds and # retrieve the local data and post it into somewhere! # # Author: Yanxiang Wu # Release Under GPL 3 # Used code from cgminer python API example import socket import json import sys import subproc...
except socket.error: pass
logfile.write( retrieve_cgminer_info("devs", None) )
random_line_split
main.py
#!/usr/bin/python # MinerLite - A client side miner controller. # This will launch cgminer with a few delay seconds and # retrieve the local data and post it into somewhere! # # Author: Yanxiang Wu # Release Under GPL 3 # Used code from cgminer python API example import socket import json import sys import subproc...
(path): subprocess.Popen([path, "--api-listen"]) print "Starting cgminer in 2 seconds" time.sleep(2) print "Running cgminer ..." run_cgminer(path) time.sleep(15) with open(log_file, 'a') as logfile: try: logfile.write( retrieve_cgminer_info("devs", None) ) except socket.erro...
run_cgminer
identifier_name
main.py
#!/usr/bin/python # MinerLite - A client side miner controller. # This will launch cgminer with a few delay seconds and # retrieve the local data and post it into somewhere! # # Author: Yanxiang Wu # Release Under GPL 3 # Used code from cgminer python API example import socket import json import sys import subproc...
def retrieve_cgminer_info(command, parameter): """retrieve status of devices from cgminer """ api_ip = '127.0.0.1' api_port = 4028 s = socket.socket(socket.AF_INET,socket.SOCK_STREAM) s.connect((api_ip,int(api_port))) if not parameter: s.send(...
buffer = socket.recv(4096) done = False while not done: more = socket.recv(4096) if not more: done = True else: buffer = buffer+more if buffer: return buffer
identifier_body
Paginator.test.tsx
import { render, screen } from '@testing-library/react' import userEvent from '@testing-library/user-event' import Paginator from '../Paginator' import type { PaginatorProps } from '../Paginator' const mockPageChange = jest.fn()
[1, 2, 6], [1, 3, 7], [1, 4, 8], [1, 5, 9], [2, 5, 9], [3, 5, 9], [1, 6, 8], [2, 6, 9], [3, 6, 10], [4, 6, 10], [1, 7, 8], [2, 7, 9], [3, 7, 10], [4, 7, 11], [5, 7, 10], [6, 7, 9], [7, 7, 8], [1, 8, 8], [1, 9, 8], [1, 10, 8], [1, 20, 8], [1, 100, 8], [2, 100, 9], [3, 100,...
const testCases = [ // activePage, totalPages, renderedItems, activeItem [3, 10, 10, 4], [1, 1, 5],
random_line_split