file_name
large_stringlengths
4
140
prefix
large_stringlengths
0
12.1k
suffix
large_stringlengths
0
12k
middle
large_stringlengths
0
7.51k
fim_type
large_stringclasses
4 values
ViewingRoomAppFixture.ts
import { ViewingRoomApp_Test_QueryRawResponse } from "__generated__/ViewingRoomApp_Test_Query.graphql" export const ViewingRoomAppFixture: ViewingRoomApp_Test_QueryRawResponse = { viewingRoom: {
name: "Subscription Demo GG", id: "UGFydG5lcjo1NTQxMjM3MzcyNjE2OTJiMTk4YzAzMDA=", }, formattedEndAt: "Closes in about 1 month", }, }
title: "Guy Yanai", heroImageURL: "https://d7hftxdivxxvm.cloudfront.net/?resize_to=width&src=https%3A%2F%2Fartsy-media-uploads.s3.amazonaws.com%2F0RnxWDsVmKuALfpmd75YyA%2FCTPHSEPT19_018_JO_Guy_Yanai_TLV_031_20190913.jpg&width=1200&quality=80", partner: {
random_line_split
prod.config.js
require('babel-polyfill'); /* eslint-disable */ // Webpack config for creating the production bundle. var path = require('path'); var webpack = require('webpack'); var CleanPlugin = require('clean-webpack-plugin'); var ExtractTextPlugin = require('extract-text-webpack-plugin'); var strip = require('strip-loader'); va...
}), // ignore dev config new webpack.IgnorePlugin(/\.\/dev/, /\/config$/), // optimizations new webpack.optimize.DedupePlugin(), new webpack.optimize.OccurenceOrderPlugin(), new webpack.optimize.UglifyJsPlugin({ compress: { warnings: false } }), webpackIsomorph...
__SERVER__: false, __DEVELOPMENT__: false, __DEVTOOLS__: false
random_line_split
urwid_tui.py
# # SPDX-FileCopyrightText: 2020 Dmytro Kolomoiets <amerlyq@gmail.com> and contributors. # # SPDX-License-Identifier: GPL-3.0-only # import pickle import urwid import zmq from ..ifc import * def tui_client(src_uri, dst_uri, log_uri): set_current_thread_name() _log = getLogger() ctx = zmq.Context.instan...
dst_sock.send_multipart([b'key', pickle.dumps(key)]) _log.info("Press: " + key) # FIXME: change text only in subscriber body.set_text(repr(key)) loop = urwid.MainLoop(view, unhandled_input=unhandled_input) loop.run() except KeyboardInterrupt: ...
raise urwid.ExitMainLoop()
conditional_block
urwid_tui.py
# # SPDX-FileCopyrightText: 2020 Dmytro Kolomoiets <amerlyq@gmail.com> and contributors. # # SPDX-License-Identifier: GPL-3.0-only # import pickle import urwid import zmq from ..ifc import * def tui_client(src_uri, dst_uri, log_uri): set_current_thread_name() _log = getLogger() ctx = zmq.Context.instan...
def unhandled_input(key): if key in ('esc', ','): raise urwid.ExitMainLoop() dst_sock.send_multipart([b'key', pickle.dumps(key)]) _log.info("Press: " + key) # FIXME: change text only in subscriber body.set_text(repr(key)) loo...
## BET: python-urwid # [Urwid] key capture in different views # http://lists.excess.org/pipermail/urwid/2011-July/001080.html body = urwid.Text("<Press ',' to exit>") view = urwid.Filler(body, 'top')
random_line_split
urwid_tui.py
# # SPDX-FileCopyrightText: 2020 Dmytro Kolomoiets <amerlyq@gmail.com> and contributors. # # SPDX-License-Identifier: GPL-3.0-only # import pickle import urwid import zmq from ..ifc import * def tui_client(src_uri, dst_uri, log_uri): set_current_thread_name() _log = getLogger() ctx = zmq.Context.instan...
(key): if key in ('esc', ','): raise urwid.ExitMainLoop() dst_sock.send_multipart([b'key', pickle.dumps(key)]) _log.info("Press: " + key) # FIXME: change text only in subscriber body.set_text(repr(key)) loop = urwid.MainLoop(view, unh...
unhandled_input
identifier_name
urwid_tui.py
# # SPDX-FileCopyrightText: 2020 Dmytro Kolomoiets <amerlyq@gmail.com> and contributors. # # SPDX-License-Identifier: GPL-3.0-only # import pickle import urwid import zmq from ..ifc import * def tui_client(src_uri, dst_uri, log_uri): set_current_thread_name() _log = getLogger() ctx = zmq.Context.instan...
loop = urwid.MainLoop(view, unhandled_input=unhandled_input) loop.run() except KeyboardInterrupt: pass finally: # _log.info("Fin: " + threading.current_thread().name) # dst_sock.send_multipart([b'*', pickle.dumps('quit')]) dst_sock.close() src_sock.clos...
if key in ('esc', ','): raise urwid.ExitMainLoop() dst_sock.send_multipart([b'key', pickle.dumps(key)]) _log.info("Press: " + key) # FIXME: change text only in subscriber body.set_text(repr(key))
identifier_body
alarm_control_panel.py
"""Support for SimpliSafe alarm control panels.""" import logging import re from simplipy.entity import EntityTypes from simplipy.system import SystemStates from homeassistant.components.alarm_control_panel import ( FORMAT_NUMBER, FORMAT_TEXT, AlarmControlPanel, ) from homeassistant.components.alarm_contr...
(self, code=None): """Send disarm command.""" if not self._validate_code(code, "disarming"): return await self._system.set_off() async def async_alarm_arm_home(self, code=None): """Send arm home command.""" if not self._validate_code(code, "arming home"): ...
async_alarm_disarm
identifier_name
alarm_control_panel.py
"""Support for SimpliSafe alarm control panels.""" import logging import re from simplipy.entity import EntityTypes from simplipy.system import SystemStates from homeassistant.components.alarm_control_panel import ( FORMAT_NUMBER, FORMAT_TEXT, AlarmControlPanel, ) from homeassistant.components.alarm_contr...
@property def changed_by(self): """Return info about who changed the alarm last.""" return self._changed_by @property def code_format(self): """Return one or more digits/characters.""" if not self._code: return None if isinstance(self._code, str) an...
"""Initialize the SimpliSafe alarm.""" super().__init__(system, "Alarm Control Panel") self._changed_by = None self._code = code self._simplisafe = simplisafe self._state = None # Some properties only exist for V2 or V3 systems: for prop in ( ATTR_BAT...
identifier_body
alarm_control_panel.py
"""Support for SimpliSafe alarm control panels.""" import logging import re from simplipy.entity import EntityTypes from simplipy.system import SystemStates from homeassistant.components.alarm_control_panel import ( FORMAT_NUMBER, FORMAT_TEXT, AlarmControlPanel, ) from homeassistant.components.alarm_contr...
return FORMAT_TEXT @property def state(self): """Return the state of the entity.""" return self._state @property def supported_features(self) -> int: """Return the list of supported features.""" return SUPPORT_ALARM_ARM_HOME | SUPPORT_ALARM_ARM_AWAY def _v...
return FORMAT_NUMBER
conditional_block
alarm_control_panel.py
"""Support for SimpliSafe alarm control panels.""" import logging import re from simplipy.entity import EntityTypes from simplipy.system import SystemStates from homeassistant.components.alarm_control_panel import ( FORMAT_NUMBER, FORMAT_TEXT, AlarmControlPanel, ) from homeassistant.components.alarm_contr...
def __init__(self, simplisafe, system, code): """Initialize the SimpliSafe alarm.""" super().__init__(system, "Alarm Control Panel") self._changed_by = None self._code = code self._simplisafe = simplisafe self._state = None # Some properties only exist for V...
class SimpliSafeAlarm(SimpliSafeEntity, AlarmControlPanel): """Representation of a SimpliSafe alarm."""
random_line_split
buf.rs
= buf; buf = &mut tmp[n..]; }, } } } Ok(()) } /// Attemps to fill the buffer with at least `amount` bytes after the offset /// `from`. /// /// If the buffer does not have enough capacity it is replaced with a n...
{ return TestResult::failed(); }
conditional_block
buf.rs
::Result<usize> { unsafe { let count = cmp::min(buf.len(), self.raw.len() - self.offset); ptr::copy_nonoverlapping(buf.as_ptr(), self.raw.buf().offset(self.offset as isize), count); self.offset += count...
/// /// `RawBuf` is not threadsafe, and may not be sent or shared across thread /// boundaries. struct RawBuf { bytes: *mut u8, len: usize, } impl RawBuf { /// Creates a new `RawBuf` instance with approximately the provided /// length. fn new(len: usize) -> RawBuf { unsafe { let...
/// It is left to the user to ensure that data races do not occur and /// unitialized data is not read.
random_line_split
buf.rs
_nonoverlapping(buf.as_ptr(), self.raw.buf().offset(self.offset as isize), count); self.offset += count; Ok(count) } } fn flush(&mut self) -> io::Result<()> { Ok(()) } } impl MutBuf { pub ...
{ fn buf(segments: Vec<Vec<u8>>) -> TestResult { let total_len: usize = segments.iter().fold(0, |acc, segment| acc + segment.len()); let mut buf = MutBuf::with_capacity(total_len + 8); for segment in &segments { buf.write_all(&*segment).unwrap(); ...
identifier_body
buf.rs
Result<usize> { unsafe { let count = cmp::min(buf.len(), self.raw.len() - self.offset); ptr::copy_nonoverlapping(buf.as_ptr(), self.raw.buf().offset(self.offset as isize), count); self.offset += count; ...
(&self, offset: usize, len: usize) -> Buf { unsafe { assert!(offset + len <= self.offset); Buf { raw: self.raw.clone(), ptr: self.raw.buf().offset(offset as isize), len: len, } } } /// Attempts to fill the buffe...
buf
identifier_name
offlineaudiocompletionevent.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 https://mozilla.org/MPL/2.0/. */ use crate::dom::audiobuffer::AudioBuffer; use crate::dom::bindings::codegen::Bindings::EventBinding::EventMethods...
#[allow(non_snake_case)] pub fn Constructor( window: &Window, type_: DOMString, init: &OfflineAudioCompletionEventInit, ) -> Fallible<DomRoot<OfflineAudioCompletionEvent>> { let bubbles = EventBubbles::from(init.parent.bubbles); let cancelable = EventCancelable::fro...
{ let event = Box::new(OfflineAudioCompletionEvent::new_inherited(rendered_buffer)); let ev = reflect_dom_object(event, window, OfflineAudioCompletionEventBinding::Wrap); { let event = ev.upcast::<Event>(); event.init_event(type_, bool::from(bubbles), bool::from(cancelabl...
identifier_body
offlineaudiocompletionevent.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 https://mozilla.org/MPL/2.0/. */ use crate::dom::audiobuffer::AudioBuffer; use crate::dom::bindings::codegen::Bindings::EventBinding::EventMethods...
(&self) -> DomRoot<AudioBuffer> { DomRoot::from_ref(&*self.rendered_buffer) } // https://dom.spec.whatwg.org/#dom-event-istrusted fn IsTrusted(&self) -> bool { self.event.IsTrusted() } }
RenderedBuffer
identifier_name
offlineaudiocompletionevent.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 https://mozilla.org/MPL/2.0/. */ use crate::dom::audiobuffer::AudioBuffer; use crate::dom::bindings::codegen::Bindings::EventBinding::EventMethods...
}
random_line_split
messages.py
from django.utils.encoding import force_text # Levels DEBUG = 10 INFO = 20 WARNING = 30 ERROR = 40 CRITICAL = 50 class CheckMessage: def __init__(self, level, msg, hint=None, obj=None, id=None): assert isinstance(level, int), "The first argument should be level." self.level = level self....
else: obj = force_text(self.obj) id = "(%s) " % self.id if self.id else "" hint = "\n\tHINT: %s" % self.hint if self.hint else '' return "%s: %s%s%s" % (obj, id, self.msg, hint) def __repr__(self): return "<%s: level=%r, msg=%r, hint=%r, obj=%r, id=%r>" % \ ...
obj = self.obj._meta.label
conditional_block
messages.py
from django.utils.encoding import force_text # Levels DEBUG = 10 INFO = 20 WARNING = 30 ERROR = 40 CRITICAL = 50 class CheckMessage: def __init__(self, level, msg, hint=None, obj=None, id=None): assert isinstance(level, int), "The first argument should be level." self.level = level self....
class Warning(CheckMessage): def __init__(self, *args, **kwargs): super().__init__(WARNING, *args, **kwargs) class Error(CheckMessage): def __init__(self, *args, **kwargs): super().__init__(ERROR, *args, **kwargs) class Critical(CheckMessage): def __init__(self, *args, **kwargs): ...
def __init__(self, *args, **kwargs): super().__init__(INFO, *args, **kwargs)
identifier_body
messages.py
from django.utils.encoding import force_text # Levels DEBUG = 10 INFO = 20 WARNING = 30 ERROR = 40 CRITICAL = 50 class CheckMessage: def __init__(self, level, msg, hint=None, obj=None, id=None): assert isinstance(level, int), "The first argument should be level." self.level = level self....
(CheckMessage): def __init__(self, *args, **kwargs): super().__init__(CRITICAL, *args, **kwargs)
Critical
identifier_name
messages.py
from django.utils.encoding import force_text # Levels DEBUG = 10 INFO = 20 WARNING = 30 ERROR = 40 CRITICAL = 50 class CheckMessage: def __init__(self, level, msg, hint=None, obj=None, id=None): assert isinstance(level, int), "The first argument should be level." self.level = level self....
class Critical(CheckMessage): def __init__(self, *args, **kwargs): super().__init__(CRITICAL, *args, **kwargs)
random_line_split
once.rs
use core; use Poll; use stream; use stream::Stream; /// A stream which emits single element and then EOF. /// /// This stream will never block and is always ready. #[must_use = "streams do nothing unless polled"] pub struct Once<T, E>(stream::IterStream<core::iter::Once<Result<T, E>>>); /// Creates a stream of singl...
<T, E>(item: Result<T, E>) -> Once<T, E> { Once(stream::iter(core::iter::once(item))) } impl<T, E> Stream for Once<T, E> { type Item = T; type Error = E; fn poll(&mut self) -> Poll<Option<T>, E> { self.0.poll() } }
once
identifier_name
once.rs
use core; use Poll; use stream; use stream::Stream; /// A stream which emits single element and then EOF. /// /// This stream will never block and is always ready. #[must_use = "streams do nothing unless polled"] pub struct Once<T, E>(stream::IterStream<core::iter::Once<Result<T, E>>>); /// Creates a stream of singl...
fn poll(&mut self) -> Poll<Option<T>, E> { self.0.poll() } }
type Error = E;
random_line_split
utils_lib.py
# Copyright 2017 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applica...
remove_undocumented(__name__, allowed_exception_list=_allowed_symbols)
random_line_split
png_unittest.py
# Copyright (C) 2012 Balazs Ankes (bank@inf.u-szeged.hu) University of Szeged # # 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 lis...
class PNGCheckerTest(unittest.TestCase): """Tests PNGChecker class.""" def test_init(self): """Test __init__() method.""" def mock_handle_style_error(self): pass checker = PNGChecker("test/config", mock_handle_style_error, MockSystemHost()) self.assertEqual(checke...
from webkitpy.common.system.filesystem_mock import MockFileSystem from webkitpy.common.system.systemhost_mock import MockSystemHost
random_line_split
png_unittest.py
# Copyright (C) 2012 Balazs Ankes (bank@inf.u-szeged.hu) University of Szeged # # 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 lis...
def test_check(self): errors = [] def mock_handle_style_error(line_number, category, confidence, message): error = (line_number, category, confidence, message) errors.append(error) fs = MockFileSystem() file_path = "foo.png" fs.write_binary_file(f...
"""Test __init__() method.""" def mock_handle_style_error(self): pass checker = PNGChecker("test/config", mock_handle_style_error, MockSystemHost()) self.assertEqual(checker._file_path, "test/config") self.assertEqual(checker._handle_style_error, mock_handle_style_error)
identifier_body
png_unittest.py
# Copyright (C) 2012 Balazs Ankes (bank@inf.u-szeged.hu) University of Szeged # # 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 lis...
(unittest.TestCase): """Tests PNGChecker class.""" def test_init(self): """Test __init__() method.""" def mock_handle_style_error(self): pass checker = PNGChecker("test/config", mock_handle_style_error, MockSystemHost()) self.assertEqual(checker._file_path, "test/c...
PNGCheckerTest
identifier_name
TextField.tsx
import * as React from 'react'; import clsx from 'clsx'; import { withStyles, WithStyles } from '@mui/styles'; import MuiTextField, { FilledTextFieldProps, StandardTextFieldProps, } from '@mui/material/TextField'; const inputStyleMapping = { small: 'inputSizeSmall', medium: 'inputSizeMedium', large: 'inputSi...
} = InputProps; return ( <MuiTextField InputProps={{ classes: { root: classes.root, input: clsx( classes.input, classes[inputStyleMapping[size]], { [classes.inputBorder]: !noBorder, }, InputPropsClassesI...
const { classes: { input: InputPropsClassesInput, ...InputPropsClassesOther } = {}, ...InputPropsOther
random_line_split
pypf.py
def neighbors(node, all_nodes): dirs = [[0, 1], [1, 0], [-1, 0], [0, -1]] ddirs = [[1, 1], [1, -1], [-1, 1], [-1, -1]] result = set() # cdef bool x for dir in dirs: nx, ny = node[0] + dir[0], node[1] + dir[1] try: all_nodes[nx][ny] except IndexError: ...
closed = True for co in open_list: if co.node == c.node: closed = True if not closed: c.count = count count += 1 c.score = get_score(c, current.node, goal, heightmap) open_li...
open_list = [] closed_list = [] path_list = [] final_list = [] start = Candidate(node, None) current = Candidate(node, start) count, current.count = 0, 0 while current.node != goal: candidates = [] for n in neighbors(current.node, all_nodes): c = Candidate(n, cu...
identifier_body
pypf.py
def neighbors(node, all_nodes): dirs = [[0, 1], [1, 0], [-1, 0], [0, -1]] ddirs = [[1, 1], [1, -1], [-1, 1], [-1, -1]] result = set() # cdef bool x for dir in dirs: nx, ny = node[0] + dir[0], node[1] + dir[1] try: all_nodes[nx][ny] except IndexError: ...
for c in reversed(path_list): final_list.append(c) if len(final_list) > 0: print("Pathfinding successful!") print("Steps: {0}".format(len(final_list))) return final_list, True else: print("ERROR: Pathfinding went wrong, returning to start.") final_list = [s...
nextnode = nextnode.lastnode path_list.append(nextnode.node)
conditional_block
pypf.py
def neighbors(node, all_nodes): dirs = [[0, 1], [1, 0], [-1, 0], [0, -1]] ddirs = [[1, 1], [1, -1], [-1, 1], [-1, -1]] result = set() # cdef bool x for dir in dirs: nx, ny = node[0] + dir[0], node[1] + dir[1] try: all_nodes[nx][ny] except IndexError: ...
(self, node, lastnode=None): self.node = node self.score = 0 self.visited = False self.lastnode = lastnode def get_path(all_nodes, node, goal, heightmap): open_list = [] closed_list = [] path_list = [] final_list = [] start = Candidate(node, None) current = Cand...
__init__
identifier_name
pypf.py
def neighbors(node, all_nodes): dirs = [[0, 1], [1, 0], [-1, 0], [0, -1]] ddirs = [[1, 1], [1, -1], [-1, 1], [-1, -1]] result = set() # cdef bool x for dir in dirs: nx, ny = node[0] + dir[0], node[1] + dir[1] try: all_nodes[nx][ny] except IndexError: p...
score += (gx + gy) * 5 penalty = heightmap[c.node[0]][c.node[1]] * 1 # print(score, "penalty:", penalty) score -= penalty return score class Candidate: def __init__(self, node, lastnode=None): self.node = node self.score = 0 self.visited = False self.lastnode =...
score += 10 gx = abs(goal[0] - c.node[0]) gy = abs(goal[1] - c.node[1])
random_line_split
beer.node.js
) or invalid, using defaults"); TIME_START = DEFAULT_TIME_START; TIME_CRASH = DEFAULT_TIME_CRASH; } } } // Enable verbose console logging else if (argv[i] === "-v" || argv[i] === "--verbose") { // Set verbose mode true VERBOSE = true; } else { // Else, invalid argument console...
{ console.log("[console] panic mode enabled, all screens blacked out"); }
conditional_block
beer.node.js
if (VERBOSE) { console.log(string); } } // Parse and set command line arguments function parse_argv() { if (DEBUG) { console.log("parse_argv()"); } // Retrieve "argv" arguments from node.js var argv = process.argv.splice(2); // Iterate command line arguments for (var i = 0; i < argv.length; i++) { /...
{ // Split into array var chunk = chunk.toString(); var input = chunk.substring(0, chunk.length -1).split(' '); var i = 0; // Clear console if (input[i] === "clear") { // Linux trick to clear console console.log('\033[2J'); } // Toggle forced crash else if (input[i] === "crash") { // Toggle crash sta...
identifier_body
beer.node.js
Set verbose mode true VERBOSE = true; } else { // Else, invalid argument console.log("[beer.node.js] - error: invalid argument '" + argv[i] + "'"); process.exit(-1); } } } // Send POST request to target, put result into cache key function post_handler(handler, cache_key, data) { if (DEBUG) { ...
} // Display current program status else if (input[i] === "stat") { console.log("[beer.node.js] - Matt Layher, 2012-2013");
random_line_split
beer.node.js
http.createServer(function(req, res) { res.writeHead(200, { 'Content-Type': 'text/plain' }); res.end(auth_key); }).listen(8081); logger("[init] HTTP key server started"); // Generate default POST data var POST_DATA = { key: auth_key, crash: FORCE_CRASH } // Update prices using randomization algorithm post_handle...
socket_handler
identifier_name
setup.py
#!/usr/bin/python3 # -*- Coding : UTF-8 -*- from os import path import github_update_checker from setuptools import setup, find_packages file_path = path.abspath(path.dirname(__file__)) with open(path.join(file_path, "README.md"), encoding="UTF-8") as f: long_description = f.read() setup( name="github_upda...
keywords="update", packages=find_packages() )
random_line_split
header.tsx
import React from "react"; import ccLogoSrc from "../../../img/cc-logo.png"; import { HeaderMenuContainer } from "./header-menu"; import { AccountOwnerDiv } from "./account-owner"; import { CustomSelect, SelectItem } from "./custom-select"; import AssignmentIcon from "../../../img/svg-icons/assignment-icon.svg"; impor...
{ value: "FeedbackReport", label: "Feedback Report", icon: FeedbackIcon, onSelect: this.changeViewMode("FeedbackReport") }]; const customSelectColorTheme = colorTheme === "progress" ? "progressNavigation" : colorTheme === "response" ? ...
const { trackEvent, viewMode, colorTheme } = this.props; const items: SelectItem[] = [{ value: "ProgressDashboard", label: "Progress Dashboard", icon: DashboardIcon, onSelect: this.changeViewMode("ProgressDashboard") }, { value: "ResponseDetail...
random_line_split
header.tsx
import React from "react"; import ccLogoSrc from "../../../img/cc-logo.png"; import { HeaderMenuContainer } from "./header-menu"; import { AccountOwnerDiv } from "./account-owner"; import { CustomSelect, SelectItem } from "./custom-select"; import AssignmentIcon from "../../../img/svg-icons/assignment-icon.svg"; impor...
extends React.PureComponent<IProps> { render() { const { colorTheme, userName, setCompact, setHideFeedbackBadges, trackEvent } = this.props; const colorClass = colorTheme ? css[colorTheme] : ""; return ( <div className={`${css.dashboardHeader} ${colorClass}`} data-cy="dashboard-header"> <di...
Header
identifier_name
header.tsx
import React from "react"; import ccLogoSrc from "../../../img/cc-logo.png"; import { HeaderMenuContainer } from "./header-menu"; import { AccountOwnerDiv } from "./account-owner"; import { CustomSelect, SelectItem } from "./custom-select"; import AssignmentIcon from "../../../img/svg-icons/assignment-icon.svg"; impor...
colorTheme={colorTheme} trackEvent={trackEvent} /> </div> </div> ); } private changeViewMode = (mode: DashboardViewMode) => () => { this.props.setDashboardViewMode(mode); } private renderNavigationSelect = () => { const { trackEvent, viewMode, color...
{ const { colorTheme, userName, setCompact, setHideFeedbackBadges, trackEvent } = this.props; const colorClass = colorTheme ? css[colorTheme] : ""; return ( <div className={`${css.dashboardHeader} ${colorClass}`} data-cy="dashboard-header"> <div className={css.appInfo}> <img src={ccL...
identifier_body
testsetXML2intermediateConverter.py
#!/usr/bin/python #=============================================================================== # # conversion script to create a mbstestlib readable file containing test specifications # out of an testset file in XML format # #=============================================================================== # Input c...
else: print("The xml file could not be processed properly. It most likely contains errors.") sys.exit(_state.error_occured_while_processing_xml)
print("Conversion successful.")
conditional_block
testsetXML2intermediateConverter.py
#!/usr/bin/python #=============================================================================== # # conversion script to create a mbstestlib readable file containing test specifications # out of an testset file in XML format # #=============================================================================== # Input c...
#=============================================================================== # process command line arguments (i.e. file i/o) #=============================================================================== script_name = sys.argv[0][sys.argv[0].rfind("\\")+1:] if len(sys.argv) == 1: _state.input_file = _config....
random_line_split
testsetXML2intermediateConverter.py
#!/usr/bin/python #=============================================================================== # # conversion script to create a mbstestlib readable file containing test specifications # out of an testset file in XML format # #=============================================================================== # Input c...
'tcp_v': zero_vec, 'tcp_omega': zero_vec, 'tcp_vdot': zero_vec, 'tcp_omegadot': zero_vec, 'f_ext': zero_vec, 'n_ext': zero_vec } case_output_order = [ ...
default_input_file = 'testset-example.xml' output_file_ext = '.txt' empty_vecn = "" zero_vec = "0 0 0" unity_mat = "1 0 0 0 1 0 0 0 1" case_defaults = { 'delta': "0.001", 'base_r': zero_vec, 'base_R': unity_mat, 'base_v': zero_ve...
identifier_body
testsetXML2intermediateConverter.py
#!/usr/bin/python #=============================================================================== # # conversion script to create a mbstestlib readable file containing test specifications # out of an testset file in XML format # #=============================================================================== # Input c...
(nodename, valuetype, current_case, current_case_value_dict): # if the node does not exist use the default value nodelist = current_case.getElementsByTagName(nodename) if nodelist.length == 0: current_case_value_dict.update({nodename : _config.case_defaults.get(nodename)}) elif nodelist.length >...
parse_opt
identifier_name
Todo.js
import React from 'react'; import PropTypes from 'prop-types'; import './Todo.css'; const ARCHIVE_SHORTCUT_KEY_CODE = 65; // 'a' const onArchiveShortcutPress = (handler, event) => { if(event.keyCode === ARCHIVE_SHORTCUT_KEY_CODE) handler(event); }; const Todo = ({text, completed, onClick, onDeleteClick}) => ( <...
c-3.052,0-4.364-1.303-4.364-4.363V230.32h424.431V721.922z M644.715,182.339H129.551v-38.387c0-3.053,1.312-4.802,4.364-4.802 H640.35c3.053,0,4.365,1.749,4.365,4.802V182.339z"/> <rect x="475.031" y="286.593" width="48.418" height="396.942"/> <rect x="363.361" y="286.593" width="...
c29.667,0,52.782-22.678,52.782-52.346v-491.6h45.366v-47.981v-38.387C693.133,114.286,670.008,91.169,640.35,91.169z M285.713,47.981h202.84v43.188h-202.84V47.981z M599.349,721.922c0,3.061-1.312,4.363-4.364,4.363H179.282
random_line_split
hash-table.js
const LinkedList = require('./linked-list'); /** * A hashtable is a data structure that allows Insert, Delete and Search operations in O(1) time. * This hashtable implimentation uses chaining and a trivial hash function for brevity. * Insert - O(1) * Delete - O(1) * Search - O(1) */ class HashTable { constru...
} } /** * Hash the passed key to an index in the array. * @param {any} key - The key to be hashed * @returns {number} - The hashed value of the key corresponding to an array index. */ _hash(key) { let value; switch(typeof(key)){ case 'string': ...
{ let node = oldTable[i].head; while(node) { this.insert(node.key, node.value); node = node.next; } }
conditional_block
hash-table.js
const LinkedList = require('./linked-list'); /** * A hashtable is a data structure that allows Insert, Delete and Search operations in O(1) time. * This hashtable implimentation uses chaining and a trivial hash function for brevity. * Insert - O(1) * Delete - O(1) * Search - O(1) */ class HashTable { constru...
() { return this.table.length; } /** * Inserts the value into the table indexed by the passed key * @param {any} key * @param {any} value */ insert(key, value) { const hashedKey = this._hash(key); // Insert a new linked list if the index is empty otherwise app...
getLength
identifier_name
hash-table.js
const LinkedList = require('./linked-list'); /** * A hashtable is a data structure that allows Insert, Delete and Search operations in O(1) time. * This hashtable implimentation uses chaining and a trivial hash function for brevity. * Insert - O(1) * Delete - O(1) * Search - O(1) */ class HashTable { constru...
if(linkedList) { const node = linkedList.search(key); if (node) { linkedList.delete(node); this.itemCount--; } } this._shrinkTable(); } toString(){ return this.table; } } module.exports = HashTable;
*/ delete(key) { const hashedKey = this._hash(key); const linkedList = this.table[hashedKey];
random_line_split
hash-table.js
const LinkedList = require('./linked-list'); /** * A hashtable is a data structure that allows Insert, Delete and Search operations in O(1) time. * This hashtable implimentation uses chaining and a trivial hash function for brevity. * Insert - O(1) * Delete - O(1) * Search - O(1) */ class HashTable { constru...
} module.exports = HashTable;
{ return this.table; }
identifier_body
photos.js
import React, { PropTypes } from 'react'; import { connect } from 'react-redux'; import * as P from '../../../actions/fb-photos'; import Photo from './partials/photo'; import EmbeddedPhoto from './partials/embedded-photo'; import Masonry from 'react-masonry-component'; import Upload from './upload'; class Photos exten...
return <Photo photo={photo} key={photo.id} />; }); // return photos.map((photo) => { // return <EmbeddedPhoto photo={photo} key={photo.id} />; // }); } render() { return ( <div> <h1>Photos</h1> <hr/> ...
} return photos.map((photo) => {
random_line_split
photos.js
import React, { PropTypes } from 'react'; import { connect } from 'react-redux'; import * as P from '../../../actions/fb-photos'; import Photo from './partials/photo'; import EmbeddedPhoto from './partials/embedded-photo'; import Masonry from 'react-masonry-component'; import Upload from './upload'; class Photos exten...
return photos.map((photo) => { return <Photo photo={photo} key={photo.id} />; }); // return photos.map((photo) => { // return <EmbeddedPhoto photo={photo} key={photo.id} />; // }); } render() { return ( <div> <h1>Photo...
{ return (<div className="col-xs-12">No photos</div>); }
conditional_block
photos.js
import React, { PropTypes } from 'react'; import { connect } from 'react-redux'; import * as P from '../../../actions/fb-photos'; import Photo from './partials/photo'; import EmbeddedPhoto from './partials/embedded-photo'; import Masonry from 'react-masonry-component'; import Upload from './upload'; class Photos exten...
(state) { return { photos: state.fb.photos.photos, uploadShow: state.fb.photos.uploadShow, }; } export default connect(mapStateToProps)(Photos);
mapStateToProps
identifier_name
photos.js
import React, { PropTypes } from 'react'; import { connect } from 'react-redux'; import * as P from '../../../actions/fb-photos'; import Photo from './partials/photo'; import EmbeddedPhoto from './partials/embedded-photo'; import Masonry from 'react-masonry-component'; import Upload from './upload'; class Photos exten...
renderPhotos() { const photos = this.props.photos.filter((photo) => { return !this.state.filterText || (photo.name && photo.name.toLowerCase().indexOf(this.state.filterText.toLowerCase()) !== -1); }); if (!photos.length) { return (<div className="co...
{ // FB.XFBML.parse(); }
identifier_body
about_triangle_project.py
#!/usr/bin/env python # -*- coding: utf-8 -*- from runner.koan import * # You need to write the triangle method in the file 'triangle.py' from triangle import * class AboutTriangleProject(Koan): def test_equilateral_triangles_have_equal_sides(self): self.assertEqual('equilateral', triangle(2, 2, 2)) ...
self.assertEqual('scalene', triangle(3, 4, 5)) self.assertEqual('scalene', triangle(10, 11, 12)) self.assertEqual('scalene', triangle(5, 4, 2))
identifier_body
about_triangle_project.py
#!/usr/bin/env python # -*- coding: utf-8 -*- from runner.koan import * # You need to write the triangle method in the file 'triangle.py' from triangle import * class AboutTriangleProject(Koan): def test_equilateral_triangles_have_equal_sides(self): self.assertEqual('equilateral', triangle(2, 2, 2)) ...
(self): self.assertEqual('isosceles', triangle(3, 4, 4)) self.assertEqual('isosceles', triangle(4, 3, 4)) self.assertEqual('isosceles', triangle(4, 4, 3)) self.assertEqual('isosceles', triangle(10, 10, 2)) def test_scalene_triangles_have_no_equal_sides(self): self.assertEq...
test_isosceles_triangles_have_exactly_two_sides_equal
identifier_name
about_triangle_project.py
#!/usr/bin/env python # -*- coding: utf-8 -*- from runner.koan import * # You need to write the triangle method in the file 'triangle.py' from triangle import * class AboutTriangleProject(Koan): def test_equilateral_triangles_have_equal_sides(self): self.assertEqual('equilateral', triangle(2, 2, 2))
self.assertEqual('equilateral', triangle(10, 10, 10)) def test_isosceles_triangles_have_exactly_two_sides_equal(self): self.assertEqual('isosceles', triangle(3, 4, 4)) self.assertEqual('isosceles', triangle(4, 3, 4)) self.assertEqual('isosceles', triangle(4, 4, 3)) self.as...
random_line_split
must_use-in-stdlib-traits.rs
#![deny(unused_must_use)] #![feature(futures_api, pin, arbitrary_self_types)] use std::iter::Iterator; use std::future::Future; use std::task::{Poll, LocalWaker}; use std::pin::Pin; use std::unimplemented; struct MyFuture; impl Future for MyFuture { type Output = u32; fn poll(self: Pin<&mut Self>, lw: &Local...
() { iterator(); //~ ERROR unused implementer of `std::iter::Iterator` that must be used future(); //~ ERROR unused implementer of `std::future::Future` that must be used square_fn_once(); //~ ERROR unused implementer of `std::ops::FnOnce` that must be used square_fn_mut(); //~ ERROR unused implementer of `...
main
identifier_name
must_use-in-stdlib-traits.rs
#![deny(unused_must_use)] #![feature(futures_api, pin, arbitrary_self_types)] use std::iter::Iterator; use std::future::Future; use std::task::{Poll, LocalWaker}; use std::pin::Pin; use std::unimplemented; struct MyFuture; impl Future for MyFuture { type Output = u32; fn poll(self: Pin<&mut Self>, lw: &Local...
fn square_fn_once() -> impl FnOnce(u32) -> u32 { |x| x * x } fn square_fn_mut() -> impl FnMut(u32) -> u32 { |x| x * x } fn square_fn() -> impl Fn(u32) -> u32 { |x| x * x } fn main() { iterator(); //~ ERROR unused implementer of `std::iter::Iterator` that must be used future(); //~ ERROR unused impleme...
MyFuture }
random_line_split
must_use-in-stdlib-traits.rs
#![deny(unused_must_use)] #![feature(futures_api, pin, arbitrary_self_types)] use std::iter::Iterator; use std::future::Future; use std::task::{Poll, LocalWaker}; use std::pin::Pin; use std::unimplemented; struct MyFuture; impl Future for MyFuture { type Output = u32; fn poll(self: Pin<&mut Self>, lw: &Local...
fn future() -> impl Future { MyFuture } fn square_fn_once() -> impl FnOnce(u32) -> u32 { |x| x * x } fn square_fn_mut() -> impl FnMut(u32) -> u32 { |x| x * x } fn square_fn() -> impl Fn(u32) -> u32 { |x| x * x } fn main() { iterator(); //~ ERROR unused implementer of `std::iter::Iterator` that must...
{ std::iter::empty::<u32>() }
identifier_body
install.rs
use crate::paths; use std::env::consts::EXE_SUFFIX; use std::path::{Path, PathBuf}; /// Used by `cargo install` tests to assert an executable binary /// has been installed. Example usage: /// /// assert_has_installed_exe(cargo_home(), "foo"); pub fn assert_has_installed_exe<P: AsRef<Path>>(path: P, name: &'static ...
(name: &str) -> String { format!("{}{}", name, EXE_SUFFIX) }
exe
identifier_name
install.rs
use crate::paths; use std::env::consts::EXE_SUFFIX; use std::path::{Path, PathBuf}; /// Used by `cargo install` tests to assert an executable binary /// has been installed. Example usage: /// /// assert_has_installed_exe(cargo_home(), "foo"); pub fn assert_has_installed_exe<P: AsRef<Path>>(path: P, name: &'static ...
pub fn assert_has_not_installed_exe<P: AsRef<Path>>(path: P, name: &'static str) { assert!(!check_has_installed_exe(path, name)); } fn check_has_installed_exe<P: AsRef<Path>>(path: P, name: &'static str) -> bool { path.as_ref().join("bin").join(exe(name)).is_file() } pub fn cargo_home() -> PathBuf { pat...
{ assert!(check_has_installed_exe(path, name)); }
identifier_body
install.rs
use crate::paths; use std::env::consts::EXE_SUFFIX; use std::path::{Path, PathBuf};
/// assert_has_installed_exe(cargo_home(), "foo"); pub fn assert_has_installed_exe<P: AsRef<Path>>(path: P, name: &'static str) { assert!(check_has_installed_exe(path, name)); } pub fn assert_has_not_installed_exe<P: AsRef<Path>>(path: P, name: &'static str) { assert!(!check_has_installed_exe(path, name));...
/// Used by `cargo install` tests to assert an executable binary /// has been installed. Example usage: ///
random_line_split
average_top_3_scores.py
import sys import operator import collections import random import string import heapq # @include def find_student_with_highest_best_of_three_scores(name_score_data): student_scores = collections.defaultdict(list) for line in name_score_data: name, score = line.split() if len(student_scores[na...
if __name__ == '__main__': main()
simple_test() n = int(sys.argv[1]) if len(sys.argv) == 2 else random.randint(1, 10000) with open('scores.txt', 'w') as ofs: for i in range(n): test_num = random.randint(0, 20) name = rand_string(random.randint(5, 10)) for _ in range(test_num): print(n...
identifier_body
average_top_3_scores.py
import sys import operator import collections import random import string import heapq # @include def find_student_with_highest_best_of_three_scores(name_score_data): student_scores = collections.defaultdict(list) for line in name_score_data: name, score = line.split() if len(student_scores[na...
main()
conditional_block
average_top_3_scores.py
import sys import operator import collections import random import string import heapq # @include def find_student_with_highest_best_of_three_scores(name_score_data): student_scores = collections.defaultdict(list) for line in name_score_data: name, score = line.split() if len(student_scores[na...
def rand_string(length): return ''.join(random.choice(string.ascii_lowercase) for _ in range(length)) def simple_test(): with open('scores.txt', 'w') as ofs: ofs.write('''adnan 100 amit 99 adnan 98 thl 90 adnan 10 amit 100 thl 99 thl 95 dd 100 dd 100 adnan 95''') with open('scores.txt') as name_sc...
# @exclude
random_line_split
average_top_3_scores.py
import sys import operator import collections import random import string import heapq # @include def find_student_with_highest_best_of_three_scores(name_score_data): student_scores = collections.defaultdict(list) for line in name_score_data: name, score = line.split() if len(student_scores[na...
(): simple_test() n = int(sys.argv[1]) if len(sys.argv) == 2 else random.randint(1, 10000) with open('scores.txt', 'w') as ofs: for i in range(n): test_num = random.randint(0, 20) name = rand_string(random.randint(5, 10)) for _ in range(test_num): ...
main
identifier_name
rehuman_semantics.py
from tqdm import tqdm from collections import defaultdict import h5py import networkx as nx import struct import numpy as np # hl = None # ml = None # with h5py.File('/usr/people/it2/seungmount/research/datasets/blended_piriform_157x2128x2128/all/human_semantic_labels.h5','r') as f: # hl = f['main'][:] # with h5py.F...
f.create_dataset('expanded',data=exp)
exp[i,:,:,:] = f['main'][:,:,:] == i
conditional_block
rehuman_semantics.py
from tqdm import tqdm from collections import defaultdict import h5py import networkx as nx import struct import numpy as np # hl = None # ml = None # with h5py.File('/usr/people/it2/seungmount/research/datasets/blended_piriform_157x2128x2128/all/human_semantic_labels.h5','r') as f: # hl = f['main'][:] # with h5py.F...
with h5py.File('/usr/people/it2/seungmount/research/datasets/blended_piriform_157x2128x2128/all/sparse_semantic_labels.h5') as f: exp = np.zeros(shape=(4,157,2128,2128)) for i in range(5): exp[i,:,:,:] = f['main'][:,:,:] == i f.create_dataset('expanded',data=exp)
random_line_split
html_whitespaces.ts
/** * @license * Copyright Google Inc. All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ import * as html from './ast'; import {ParseTreeResult} from './parser'; import {NGSP_UNICODE} from './tags'; expor...
interface SiblingVisitorContext { prev: html.Node|undefined; next: html.Node|undefined; } function visitAllWithSiblings(visitor: WhitespaceVisitor, nodes: html.Node[]): any[] { const result: any[] = []; nodes.forEach((ast, i) => { const context: SiblingVisitorContext = {prev: nodes[i - 1], next: nodes[i...
{ return new ParseTreeResult( html.visitAll(new WhitespaceVisitor(), htmlAstWithErrors.rootNodes), htmlAstWithErrors.errors); }
identifier_body
html_whitespaces.ts
/** * @license * Copyright Google Inc. All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ import * as html from './ast'; import {ParseTreeResult} from './parser'; import {NGSP_UNICODE} from './tags'; expor...
(comment: html.Comment, context: any): any { return comment; } visitExpansion(expansion: html.Expansion, context: any): any { return expansion; } visitExpansionCase(expansionCase: html.ExpansionCase, context: any): any { return expansionCase; } } export function removeWhitespaces(htmlAstWithErrors: ParseTreeResu...
visitComment
identifier_name
html_whitespaces.ts
/** * @license * Copyright Google Inc. All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ import * as html from './ast'; import {ParseTreeResult} from './parser'; import {NGSP_UNICODE} from './tags'; expor...
return null; } visitComment(comment: html.Comment, context: any): any { return comment; } visitExpansion(expansion: html.Expansion, context: any): any { return expansion; } visitExpansionCase(expansionCase: html.ExpansionCase, context: any): any { return expansionCase; } } export function removeWhitesp...
if (isNotBlank || hasExpansionSibling) { return new html.Text( replaceNgsp(text.value).replace(WS_REPLACE_REGEXP, ' '), text.sourceSpan, text.i18n); }
random_line_split
html_whitespaces.ts
/** * @license * Copyright Google Inc. All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ import * as html from './ast'; import {ParseTreeResult} from './parser'; import {NGSP_UNICODE} from './tags'; expor...
}); return result; }
{ result.push(astResult); }
conditional_block
mallet_lda_tags.py
#!/usr/bin/python # -*- coding: utf-8 -*- import sys import os import logging import traceback import mallet_lda class MalletTagTopics(mallet_lda.MalletLDA): """ Topic modeling with separation based on tags """ def _basic_params(self): self.name = 'mallet_lda_tags'
self.dry_run = False self.topics = 50 self.dfr = len(self.extra_args) > 0 if self.dfr: self.dfr_dir = self.extra_args[0] def post_setup(self): if self.named_args is not None: if 'tags' in self.named_args: self.tags = self.named_args['t...
self.categorical = False self.template_name = 'mallet_lda'
random_line_split
mallet_lda_tags.py
#!/usr/bin/python # -*- coding: utf-8 -*- import sys import os import logging import traceback import mallet_lda class MalletTagTopics(mallet_lda.MalletLDA): """ Topic modeling with separation based on tags """ def _basic_params(self):
def post_setup(self): if self.named_args is not None: if 'tags' in self.named_args: self.tags = self.named_args['tags'] for filename in self.metadata.keys(): my_tags = [x for (x, y) in self.tags.iteritems() if i...
self.name = 'mallet_lda_tags' self.categorical = False self.template_name = 'mallet_lda' self.dry_run = False self.topics = 50 self.dfr = len(self.extra_args) > 0 if self.dfr: self.dfr_dir = self.extra_args[0]
identifier_body
mallet_lda_tags.py
#!/usr/bin/python # -*- coding: utf-8 -*- import sys import os import logging import traceback import mallet_lda class MalletTagTopics(mallet_lda.MalletLDA): """ Topic modeling with separation based on tags """ def _basic_params(self): self.name = 'mallet_lda_tags' self.categorical ...
if __name__ == '__main__': try: processor = MalletTagTopics(track_progress=False) processor.process() except: logging.error(traceback.format_exc())
if 'tags' in self.named_args: self.tags = self.named_args['tags'] for filename in self.metadata.keys(): my_tags = [x for (x, y) in self.tags.iteritems() if int(self.metadata[filename]['itemID' ]) in y] ...
conditional_block
mallet_lda_tags.py
#!/usr/bin/python # -*- coding: utf-8 -*- import sys import os import logging import traceback import mallet_lda class
(mallet_lda.MalletLDA): """ Topic modeling with separation based on tags """ def _basic_params(self): self.name = 'mallet_lda_tags' self.categorical = False self.template_name = 'mallet_lda' self.dry_run = False self.topics = 50 self.dfr = len(self.extra...
MalletTagTopics
identifier_name
q.js
/************************************************************* * * MathJax/jax/output/HTML-CSS/entities/q.js * * Copyright (c) 2010-2013 The MathJax Consortium * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may ob...
'questeq': '\u225F', 'quot': '\u0022' }); MathJax.Ajax.loadComplete(MATHML.entityDir+"/q.js"); })(MathJax.InputJax.MathML);
'quatint': '\u2A16', 'quest': '\u003F',
random_line_split
storage.js
// resultsHandler: // A callback function that will receive three arguments. The // first argument is one of three values: dojo.storage.SUCCESS, // dojo.storage.FAILED, or dojo.storage.PENDING; these values // determine how the put request went. In some storage systems // users can deny a storage re...
{ return false; }
conditional_block
storage.js
receive three arguments. The // first argument is one of three values: dojo.storage.SUCCESS, // dojo.storage.FAILED, or dojo.storage.PENDING; these values // determine how the put request went. In some storage systems // users can deny a storage request, resulting in a // dojo.storage.FAILED, while...
} };
random_line_split
user_group_pill.js
"use strict"; const {strict: assert} = require("assert"); const {zrequire} = require("../zjsunit/namespace"); const {run_test} = require("../zjsunit/test"); const user_groups = zrequire("user_groups"); const user_group_pill = zrequire("user_group_pill"); const admins = { name: "Admins", description: "foo", ...
members: [20, 50, 30, 40], }; const admins_pill = { id: admins.id, group_name: admins.name, type: "user_group", display_value: admins.name + ": " + admins.members.length + " users", }; const testers_pill = { id: testers.id, group_name: testers.name, type: "user_group", display_value...
const testers = { name: "Testers", description: "bar", id: 102,
random_line_split
user_group_pill.js
"use strict"; const {strict: assert} = require("assert"); const {zrequire} = require("../zjsunit/namespace"); const {run_test} = require("../zjsunit/test"); const user_groups = zrequire("user_groups"); const user_group_pill = zrequire("user_group_pill"); const admins = { name: "Admins", description: "foo", ...
(group_name, current_items, expected_item) { const item = user_group_pill.create_item_from_group_name(group_name, current_items); assert.deepEqual(item, expected_item); } test_create_item(" admins ", [], admins_pill); test_create_item("admins", [testers_pill], admins_pill); test_create_...
test_create_item
identifier_name
user_group_pill.js
"use strict"; const {strict: assert} = require("assert"); const {zrequire} = require("../zjsunit/namespace"); const {run_test} = require("../zjsunit/test"); const user_groups = zrequire("user_groups"); const user_group_pill = zrequire("user_group_pill"); const admins = { name: "Admins", description: "foo", ...
test_create_item(" admins ", [], admins_pill); test_create_item("admins", [testers_pill], admins_pill); test_create_item("admins", [admins_pill], undefined); test_create_item("unknown", [], undefined); }); run_test("get_stream_id", () => { assert.equal(user_group_pill.get_group_name_from_item(adm...
{ const item = user_group_pill.create_item_from_group_name(group_name, current_items); assert.deepEqual(item, expected_item); }
identifier_body
pce_extrae_detalle_contrato.py
Page = "https://contrataciondelestado.es/wps/portal/!ut/p/b1/lZDLDoIwEEU_aaYParssrwLxAVZQujEsjMH42Bi_30rcGCPq7CZz7pzkgoOWKC6kYBPYgDt3t37fXfvLuTs-die2PFlEUZpRlJbFSKdxXYvMrybwQOsB_DAah3xopdQh0YislqhFVUXK_0HFnvmARbwpmlLY3CDmWRpPaxKgoeI3_4jgxW_sjPhzwkRAkRhLn_mPAvqn_13wJb8GNyBjDQzAWMXjEgrz7HLaQeuxyVY3SaVzxXARLj1WlLNVaShB5LC...
if driverType == 1: self.driver = webdriver.Firefox() elif driverType == 2: self.driver = webdriver.PhantomJS(phantonPath, service_args=['--ignore-ssl-errors=true']) self.driver.set_window_size(1120, 550) self.extraeDetalles() def cargaPagina(self): ...
""" Clase que devuelve los detalles de un contrato por nº expediente y Órgano de contratación numExpediente OrgContratacion driverType=1 (Firefox, online) / 2(phantomjs) """ driver = "" driverType = 1 estadoLic = "" procedimiento = "" enlacelic = '' codigo...
identifier_body
pce_extrae_detalle_contrato.py
= "https://contrataciondelestado.es/wps/portal/!ut/p/b1/lZDLDoIwEEU_aaYParssrwLxAVZQujEsjMH42Bi_30rcGCPq7CZz7pzkgoOWKC6kYBPYgDt3t37fXfvLuTs-die2PFlEUZpRlJbFSKdxXYvMrybwQOsB_DAah3xopdQh0YislqhFVUXK_0HFnvmARbwpmlLY3CDmWRpPaxKgoeI3_4jgxW_sjPhzwkRAkRhLn_mPAvqn_13wJb8GNyBjDQzAWMXjEgrz7HLaQeuxyVY3SaVzxXARLj1WlLNVaShB5LCCNoG...
elif driverType == 2: self.driver = webdriver.PhantomJS(phantonPath, service_args=['--ignore-ssl-errors=true']) self.driver.set_window_size(1120, 550) self.extraeDetalles() def cargaPagina(self): #Carga página if self.driverType == 2: self.driver.i...
f.driver = webdriver.Firefox()
conditional_block
pce_extrae_detalle_contrato.py
= "https://contrataciondelestado.es/wps/portal/!ut/p/b1/lZDLDoIwEEU_aaYParssrwLxAVZQujEsjMH42Bi_30rcGCPq7CZz7pzkgoOWKC6kYBPYgDt3t37fXfvLuTs-die2PFlEUZpRlJbFSKdxXYvMrybwQOsB_DAah3xopdQh0YislqhFVUXK_0HFnvmARbwpmlLY3CDmWRpPaxKgoeI3_4jgxW_sjPhzwkRAkRhLn_mPAvqn_13wJb8GNyBjDQzAWMXjEgrz7HLaQeuxyVY3SaVzxXARLj1WlLNVaShB5LCCNoG...
lf, numExpediente, OrgContratacion, driverType=1): self.driverType = driverType self.numExpediente = numExpediente self.OrgContratacion = OrgContratacion if driverType == 1: self.driver = webdriver.Firefox() elif driverType == 2: self.driver = webdriver.P...
nit__(se
identifier_name
pce_extrae_detalle_contrato.py
= "https://contrataciondelestado.es/wps/portal/!ut/p/b1/lZDLDoIwEEU_aaYParssrwLxAVZQujEsjMH42Bi_30rcGCPq7CZz7pzkgoOWKC6kYBPYgDt3t37fXfvLuTs-die2PFlEUZpRlJbFSKdxXYvMrybwQOsB_DAah3xopdQh0YislqhFVUXK_0HFnvmARbwpmlLY3CDmWRpPaxKgoeI3_4jgxW_sjPhzwkRAkRhLn_mPAvqn_13wJb8GNyBjDQzAWMXjEgrz7HLaQeuxyVY3SaVzxXARLj1WlLNVaShB5LCCNoG...
class detalleContrato(): """ Clase que devuelve los detalles de un contrato por nº expediente y Órgano de contratación numExpediente OrgContratacion driverType=1 (Firefox, online) / 2(phantomjs) """ driver = "" driverType = 1 estadoLic = "" procedimiento = "...
#contratacionPage="https://contrataciondelestado.es"
random_line_split
application.py
__author__ = 'hujin' import sys from os import path from twisted.internet import reactor from twisted.web import server, resource from twisted.python import log from dockerman.storage import ServiceStore from dockerman.api import Root from dockerman.docker import Client from dockerman.manager import Manager from d...
self.store = ServiceStore(store_file) self.store.applicaion = self host = self.config['docker_host'] port = self.config['docker_port'] self.client = Client(host, port) self.dispatcher = Dispatcher(self) self.manager = Manager(self.client, self.store, self.dis...
open(store_file, 'w').close()
conditional_block
application.py
__author__ = 'hujin' import sys from os import path from twisted.internet import reactor from twisted.web import server, resource from twisted.python import log from dockerman.storage import ServiceStore from dockerman.api import Root from dockerman.docker import Client from dockerman.manager import Manager from d...
self.manager = Manager(self.client, self.store, self.dispatcher) def get_config(self, name, default=None): try: return self.config[name] except KeyError: return default def _on_event(self, message): self.manager.handle_event(message) def start(self,...
def __init__(self, config): self.config = config log.startLogging(sys.stdout) self._initialize() def _initialize(self): store_file = self.config['store_file'] if not path.exists(store_file): open(store_file, 'w').close() self.store = ServiceStore(store_...
identifier_body
application.py
__author__ = 'hujin' import sys from os import path from twisted.internet import reactor from twisted.web import server, resource from twisted.python import log from dockerman.storage import ServiceStore from dockerman.api import Root from dockerman.docker import Client from dockerman.manager import Manager from d...
site = server.Site(Root(self)) reactor.listenTCP(port, site)
random_line_split
application.py
__author__ = 'hujin' import sys from os import path from twisted.internet import reactor from twisted.web import server, resource from twisted.python import log from dockerman.storage import ServiceStore from dockerman.api import Root from dockerman.docker import Client from dockerman.manager import Manager from d...
(self): store_file = self.config['store_file'] if not path.exists(store_file): open(store_file, 'w').close() self.store = ServiceStore(store_file) self.store.applicaion = self host = self.config['docker_host'] port = self.config['docker_port'] self....
_initialize
identifier_name
header.js
class Client_Viewport_Header extends View_Browser { initElements() { super.initElements(); this.enable(); } handleSessionAuthenticated() { if (this.subviews.context_menu) { this.subviews.context_menu.show(); } } handleSessionUnauthenticated() { if (this.subviews.context_menu) { this.subviews.c...
} } ObjectHelper.extend(Client_Viewport_Header.prototype, { template: Client_Viewport_Header_Template_Index, sections: { context_menu: Client_Viewport_Header_View_ContextMenu } }); module.exports = Client_Viewport_Header;
{ this.coupleToSession(this.session); }
conditional_block
header.js
class Client_Viewport_Header extends View_Browser { initElements() { super.initElements(); this.enable(); }
} handleSessionUnauthenticated() { if (this.subviews.context_menu) { this.subviews.context_menu.hide(); } } handleSessionAuthenticatedChange(session) { if (session.isAuthenticated()) { this.handleSessionAuthenticated(); } else { this.handleSessionUnauthenticated(); } } coupleToSession(sessio...
handleSessionAuthenticated() { if (this.subviews.context_menu) { this.subviews.context_menu.show(); }
random_line_split
header.js
class Client_Viewport_Header extends View_Browser { initElements() { super.initElements(); this.enable(); } handleSessionAuthenticated() { if (this.subviews.context_menu) { this.subviews.context_menu.show(); } } handleSessionUnauthenticated() { if (this.subviews.context_menu) { this.subviews.c...
decoupleFromSession(session) { session.off( 'change:account_id', this.handleSessionAuthenticatedChange, this ); this.handleSessionUnauthenticated(); } setSession(session) { if (this.session) { this.decoupleFromSession(this.session); } this.session = session; if (this.session) { thi...
{ session.on( 'change:account_id', this.handleSessionAuthenticatedChange, this ); this.handleSessionAuthenticatedChange(session); }
identifier_body
header.js
class Client_Viewport_Header extends View_Browser { initElements() { super.initElements(); this.enable(); } handleSessionAuthenticated() { if (this.subviews.context_menu) { this.subviews.context_menu.show(); } } handleSessionUnauthenticated() { if (this.subviews.context_menu) { this.subviews.c...
(session) { session.off( 'change:account_id', this.handleSessionAuthenticatedChange, this ); this.handleSessionUnauthenticated(); } setSession(session) { if (this.session) { this.decoupleFromSession(this.session); } this.session = session; if (this.session) { this.coupleToSession(this...
decoupleFromSession
identifier_name
config_env.rs
use envconfig::Envconfig; use crate::domain::key_derivation::KeyDerivationFunction; lazy_static! { static ref APP_ENV_CONFIG: AppEnvConfig = AppEnvConfig::init().unwrap(); } pub fn get_app_env_config() -> &'static AppEnvConfig { return &APP_ENV_CONFIG } #[derive(Envconfig, Debug)] pub struct AppEnvConfig { ...
}
{ env::remove_var("NEW_AGENT_KDF"); let app_config = AppEnvConfig::init().unwrap(); assert_eq!(app_config.new_agent_kdf, KeyDerivationFunction::Raw, "Default new_agent_kdf should be Raw"); env::set_var("NEW_AGENT_KDF", "RAW"); let app_config = AppEnvConfig::init().unwrap(); ...
identifier_body
config_env.rs
use envconfig::Envconfig; use crate::domain::key_derivation::KeyDerivationFunction; lazy_static! { static ref APP_ENV_CONFIG: AppEnvConfig = AppEnvConfig::init().unwrap(); } pub fn get_app_env_config() -> &'static AppEnvConfig { return &APP_ENV_CONFIG } #[derive(Envconfig, Debug)] pub struct
{ #[envconfig(from = "NEW_AGENT_KDF", default = "RAW")] pub new_agent_kdf: KeyDerivationFunction, #[envconfig(from = "RESTORE_ON_DEMAND", default = "false")] pub restore_on_demand: bool, } #[cfg(test)] mod tests { use super::*; use std::env; #[test] fn should_construct_app_env_config_...
AppEnvConfig
identifier_name
config_env.rs
use envconfig::Envconfig; use crate::domain::key_derivation::KeyDerivationFunction; lazy_static! { static ref APP_ENV_CONFIG: AppEnvConfig = AppEnvConfig::init().unwrap(); } pub fn get_app_env_config() -> &'static AppEnvConfig { return &APP_ENV_CONFIG } #[derive(Envconfig, Debug)] pub struct AppEnvConfig { ...
env::set_var("NEW_AGENT_KDF", "RAW"); let app_config = AppEnvConfig::init().unwrap(); assert_eq!(app_config.new_agent_kdf, KeyDerivationFunction::Raw, "Expected new_agent_kdf to be Raw."); env::set_var("NEW_AGENT_KDF", "ARGON2I_INT"); let app_config = AppEnvConfig::init().unwrap...
fn should_construct_app_env_config_with_correct_kdf() { env::remove_var("NEW_AGENT_KDF"); let app_config = AppEnvConfig::init().unwrap(); assert_eq!(app_config.new_agent_kdf, KeyDerivationFunction::Raw, "Default new_agent_kdf should be Raw");
random_line_split
angular-paginate.js
/** * Angular Paginate * @homepage https://github.com/darthwade/angular-paginate * @author Vadym Petrychenko https://github.com/darthwade * @license The MIT License (http://www.opensource.org/licenses/mit-license.php) * @copyright 2014 Vadym Petrychenko */ (function (factory) { if (typeof define === 'function' ...
}(function (angular) { 'use strict'; angular.module('darthwade.paginate', []) .provider('$paginate', function () { var provider = this; provider.templateUrl = 'angular-paginate.html'; provider.options = { perPage: 10, // Items count per page. range: 5, // Number of pages ne...
{ // Browser globals factory(window.angular) }
conditional_block
angular-paginate.js
/** * Angular Paginate * @homepage https://github.com/darthwade/angular-paginate * @author Vadym Petrychenko https://github.com/darthwade * @license The MIT License (http://www.opensource.org/licenses/mit-license.php) * @copyright 2014 Vadym Petrychenko */ (function (factory) { if (typeof define === 'function' ...
var self = this; var defaultOptions = { $page: 1, $objects: [], $totalCount: 0, $startIndex: 0, $endIndex: 0, $totalPages: 0, onPageChange: angular.noop }; self.page = function (page) { if (self.$page === p...
random_line_split
tx_processor.rs
// Copyright 2018 Mozilla // // Licensed under the Apache License, Version 2.0 (the "License"); you may not use // this file except in compliance with the License. You may obtain a copy of the // License at http://www.apache.org/licenses/LICENSE-2.0 // Unless required by applicable law or agreed to in writing, software...
{} pub struct DatomsIterator<'dbtx, 't, T> where T: Sized + Iterator<Item=Result<TxPart>> + 't { at_first: bool, at_last: bool, first: &'dbtx TxPart, rows: &'t mut Peekable<T>, } impl<'dbtx, 't, T> DatomsIterator<'dbtx, 't, T> where T: Sized + Iterator<Item=Result<TxPart>> + 't { fn new(first: &'...
Processor
identifier_name