code
stringlengths
281
23.7M
class TestHelloWorld(BaseSkillTestCase): path_to_skill = Path(ROOT_DIR, 'packages', 'fetchai', 'skills', 'hello_world') is_agent_to_agent_messages = False def setup_method(self): self.message = 'Hello Something Custom!' config_overrides = {'behaviours': {'hello_world': {'args': {'message': s...
class Versions(): def get(): try: from google.protobuf import __version__ as proto_version from grpc import _grpcio_metadata as grpcmeta return (gui_version, grpcmeta.__version__, proto_version) except: return ('none', 'none', 'none')
def lazy_import(): from fastly.model.logging_common_response import LoggingCommonResponse from fastly.model.logging_generic_common_response import LoggingGenericCommonResponse from fastly.model.logging_openstack_additional import LoggingOpenstackAdditional from fastly.model.service_id_and_version_string...
def parseIntentFilter(parcel: ParcelParser, parent: Field) -> None: parcel.parse_field('mActions', '', parcel.readString16Vector, parent) category_nullcheck = parcel.parse_field('mCategories-nullcheck', '', parcel.readInt32, parent) if category_nullcheck.content: parcel.parse_field('mCategories', ''...
def main(stream=None): argparser = argparse.ArgumentParser(usage='usage: %(prog)s [options] <elf-file>', description=SCRIPT_DESCRIPTION, add_help=False, prog='readelf.py') argparser.add_argument('file', nargs='?', default=None, help='ELF file to parse') argparser.add_argument('-H', '--help', action='store_t...
def extractSplatanovelWordpressCom(item): (vol, chp, frag, postfix) = extractVolChapterFragmentPostfix(item['title']) if ((not (chp or vol)) or ('preview' in item['title'].lower())): return None tagmap = [('PRC', 'PRC', 'translated'), ('Loiterous', 'Loiterous', 'oel')] for (tagname, name, tl_typ...
def send_progress(monitor): play_data = get_playing_data(monitor.played_information) if (play_data is None): return log.debug('Sending Progress Update') player = xbmc.Player() play_time = player.getTime() total_play_time = player.getTotalTime() play_data['currentPossition'] = play_ti...
class NotebookTab(Gtk.EventBox): reorderable = True def __init__(self, notebook: SmartNotebook, page: 'NotebookPage', vertical: bool=False): Gtk.EventBox.__init__(self) self.set_visible_window(False) self.closable = True self.notebook = notebook self.page = page s...
class OptionSeriesTreemapTraverseupbuttonPosition(Options): def align(self): return self._config_get('right') def align(self, text: str): self._config(text, js_type=False) def verticalAlign(self): return self._config_get('top') def verticalAlign(self, text: str): self._co...
def test_extra_field_order(): (app, db, admin) = setup() (Model1, _) = create_models(db) view = CustomModelView(Model1, form_extra_fields={'extra_field': fields.StringField('Extra Field')}) admin.add_view(view) client = app.test_client() rv = client.get('/admin/model1/new/') assert (rv.statu...
class KShotNWaySequence(DeterministicSequence): def __init__(self, annotations, batch_size, k_shot, n_way, **kwargs): if ((batch_size is not None) and (batch_size != (n_way * k_shot))): warnings.warn('batch_size was set but not consistent with k_shot and n_way. Value is overridden.') ...
def array_serializer_generator(msg_context, package, type_, name, serialize, is_numpy): (base_type, is_array, array_len) = msgs.parse_type(type_) if (not is_array): raise MsgGenerationException(('Invalid array spec: %s' % type_)) var_length = (array_len is None) if (base_type in ['char', 'uint8'...
class SyncFolder(Core): def sync_folder(self, local_folder: str, remote_folder: str, flag: Optional[bool]=None, file_filter: Callable[([Union[(str, BaseFile)]], bool)]=(lambda x: False), ignore_content: bool=False, follow_delete: bool=False, drive_id: str=None): if (flag is None): self._auth.log...
def serve_ports(ports_socket, start_free_ports, min_free_ports): ports_q = collections.deque() free_ports = set() port_age = {} serialno = 0 def get_port(): while True: free_socket = socket.socket() free_socket.bind(('', 0)) free_port = free_socket.getsock...
class DynamicPostChildAttachment(AbstractObject): def __init__(self, api=None): super(DynamicPostChildAttachment, self).__init__() self._isDynamicPostChildAttachment = True self._api = api class Field(AbstractObject.Field): description = 'description' image_url = 'image_u...
class Solution(): def merge(self, intervals: List[List[int]]) -> List[List[int]]: intervals.sort() ret = [] for (i, interval) in enumerate(intervals): if (i == 0): ret.append(interval) continue if (interval[0] > ret[(- 1)][1]): ...
class OptionPlotoptionsPackedbubbleSonificationDefaultspeechoptionsMapping(Options): def pitch(self) -> 'OptionPlotoptionsPackedbubbleSonificationDefaultspeechoptionsMappingPitch': return self._config_sub_data('pitch', OptionPlotoptionsPackedbubbleSonificationDefaultspeechoptionsMappingPitch) def playDe...
class TargetingGeoLocationCity(AbstractObject): def __init__(self, api=None): super(TargetingGeoLocationCity, self).__init__() self._isTargetingGeoLocationCity = True self._api = api class Field(AbstractObject.Field): country = 'country' distance_unit = 'distance_unit' ...
def template_def(signature, code): if (not isinstance(signature, funcsigs.Signature)): kind = funcsigs.Parameter.POSITIONAL_OR_KEYWORD signature = funcsigs.Signature([funcsigs.Parameter(name, kind=kind) for name in signature]) template_src = (((("<%def name='_func" + str(signature)) + "'>\n") + ...
class PeriodicRunTaskEvent(SchedulingEvent): def __init__(self, workflow_execution_id: int, task_name: str): super().__init__(SchedulingEventType.PERIODIC_RUN_TASK) self.context = json.dumps({EventContextConstant.WORKFLOW_EXECUTION_ID: workflow_execution_id, EventContextConstant.TASK_NAME: task_name...
def get_normalized_bounding_box_for_page_coordinates_and_page_meta(coordinates: LayoutPageCoordinates, page_meta: LayoutPageMeta) -> LayoutPageCoordinates: page_coordinates = page_meta.coordinates assert (page_coordinates is not None) return LayoutPageCoordinates(x=(coordinates.x / page_coordinates.width), ...
def stream_content_to_json(buffer): values = [] try: content = parse_json(buffer) values.append({'content': content, 'raw': buffer}) buffer = '' except Exception: while True: pos = (buffer.find('\n') + 1) if (pos <= 0): break ...
def zendesk_erasure_data(zendesk_client: ZendeskClient, zendesk_erasure_identity_email: str) -> Generator: response = zendesk_client.create_user(zendesk_erasure_identity_email) assert response.ok user = response.json()['user'] response = zendesk_client.create_ticket(user['id']) assert response.ok ...
_custom_acc_mapper_fn(op_and_target=('call_method', 'std'), arg_replacement_tuples=[('input', 'input'), ('dim', 'dim'), ('unbiased', 'unbiased', this_arg_is_optional), ('keepdim', 'keepdim', this_arg_is_optional), ('dtype', 'dtype', this_arg_is_optional)]) _custom_acc_mapper_fn(op_and_target=('call_function', torch.std...
def filter_data(base: Any, updates: Any) -> Any: if (not isinstance(updates, type(base))): return updates if (not isinstance(base, dict)): if (base == updates): return SAME_MARK return updates new_keys = (set(updates.keys()) - set(base.keys())) common_keys = set(updat...
class ProductionTestCase(unittest.TestCase): def test_no_datetime(self): with self.assertRaises(Exception, msg='Datetime key must be present!'): validate_production(p1, 'FR') def test_no_zoneKey(self): with self.assertRaises(Exception, msg='zoneKey is required!'): validat...
def check_out_of_sync(proj_dir): check_exists_with_error() out_of_sync = False (status, status_output) = has_uncommitted_files(proj_dir) if status: out_of_sync = True log.warn("'{}' has uncommitted changes:".format(proj_dir)) log.info(status_output) branches_out_of_sync = Fal...
class EnKFMain(): def __init__(self, config: 'ErtConfig', read_only: bool=False) -> None: self.ert_config = config self._update_configuration: Optional[UpdateConfiguration] = None def update_configuration(self) -> UpdateConfiguration: if (not self._update_configuration): self...
def _decode(e: bytes, separator: bytes=SEPARATOR) -> Envelope: split = e.split(separator) if ((len(split) < 5) or (split[(- 1)] not in [b'', b'\n'])): raise ValueError('Expected at least 5 values separated by commas and last value being empty or new line, got {}'.format(len(split))) to = split[0].de...
('ecs_deploy.cli.get_client') def test_deploy_new_tag(get_client, runner): get_client.return_value = EcsTestClient('acces_key', 'secret_key') result = runner.invoke(cli.deploy, (CLUSTER_NAME, SERVICE_NAME, '-t', 'latest')) assert (result.exit_code == 0) assert (not result.exception) assert (u'Deploy...
class conv2d(Operator): def __init__(self, stride, pad, dilate=1, group=1) -> None: super().__init__() self._attrs['op'] = 'conv2d' self._attrs['stride'] = stride self._attrs['pad'] = pad self._attrs['dilate'] = dilate self._attrs['group'] = group self._attrs[...
class GenericOutputAdapter(ResponseRefactor): def __init__(self, config_json): ResponseRefactor.__init__(self, config_json=config_json) self.api_schema = None self._schema = None self._array_types = set(['array', 'numeric_array', 'string_array', 'mixed_array']) def _is_string(out...
class OptionPlotoptionsHeatmapSonificationDefaultinstrumentoptionsMappingPan(Options): def mapFunction(self): return self._config_get(None) def mapFunction(self, value: Any): self._config(value, js_type=False) def mapTo(self): return self._config_get(None) def mapTo(self, text: s...
def test_load_data(web_page_loader): page_url = ' mock_response = Mock() mock_response.status_code = 200 mock_response.content = '\n <html>\n <head>\n <title>Test Page</title>\n </head>\n <body>\n <div id="content">\n ...
(scope='module') def _pgs(): app = App(__name__) db = Database(app, config=sdict(uri=f"postgres://{os.environ.get('POSTGRES_URI')}", auto_connect=True)) db.define_models(SourceCustom, SourceMulti, DestCustomCustom, DestCustomMulti, DestMultiCustom, DestMultiMulti, DoctorCustom, PatientCustom, AppointmentCus...
def add_mode_of_payments(payment_mode, account, company): if (not frappe.db.get_value('Mode of Payment', payment_mode)): doc = frappe.new_doc('Mode of Payment') doc.mode_of_payment = payment_mode doc.enabled = 1 doc.type = 'General' doc.set('accounts', []) add_payment...
('script,expected', [param('tests/test_apps/passes_callable_class_to_hydra_main/my_app.py', dedent(' 123\n my_app\n '), id='passes_callable_class_to_hydra_main')]) def test_pass_callable_class_to_hydra_main(tmpdir: Path, script: str, expected: str) -> None: cmd = [script...
def _resolve_imports(api_to_calls: ImportToCallSiteDict, wrapper_set: WrapperSet, export_hashes: Optional[Dict[(int, int)]], md: Cs, process_controller: ProcessController) -> None: arch = process_controller.architecture page_size = process_controller.page_size def get_data(addr: int, size: int) -> bytes: ...
_type(EvpnEsi.ROUTER_ID) class EvpnRouterIDEsi(EvpnEsi): _TYPE_NAME = 'router_id' _VALUE_PACK_STR = '!4sIx' _VALUE_FIELDS = ['router_id', 'local_disc'] _TYPE = {'ascii': ['router_id']} def __init__(self, router_id, local_disc, type_=None): super(EvpnRouterIDEsi, self).__init__(type_) ...
def workflow_method(func=None, name=None, workflow_id=None, workflow_id_reuse_policy=WorkflowIdReusePolicy.AllowDuplicateFailedOnly, execution_start_to_close_timeout_seconds=7200, task_start_to_close_timeout_seconds=10, task_list=None): def wrapper(fn): if (not hasattr(fn, '_workflow_method')): ...
def test_generate_elasticsearch_query(): assert (ESPSCCodes.generate_elasticsearch_query({'require': [['Product', '1', '1111'], ['Research and Development']], 'exclude': [['Product', '1'], ['Research and Development', 'A', 'A5']]}, _QueryType.AWARDS).to_dict() == {'query_string': {'query': '((((A*)) AND (((NOT (A* ...
def test_retrieve(additionals, utils): additionals.emptySelector.start_indexing() additionals.emptySelector.start_retrieving() pth = additionals.emptySelector.disk.read_query('empty') images = [(pth / f'{x}/image.jpeg') for x in ['el1', 'el2', 'el3']] for img in images: assert os.path.isfile...
class WinterSnow(GraphCanvas.Canvas): name = 'Skin Winter Snow' _option_cls = OptSkins.OptionsSkin def cursors(self): pass _js__builder__ = '\n var requestAnimationFrame = window.requestAnimationFrame || window.mozRequestAnimationFrame || window.webkitRequestAnimationFrame || window.msRequestAn...
def verbose_option(dest='verbose', default=0, flag_value=1, callback=None, expose_value=False, show_default=False): def decorator(f): _context _flag_option(default=default, flag_value=flag_value, show_default=show_default) _verbose_flag_option() def new_func(ctx, *args, **kwargs): ...
class SystemChatMember(ChatMember): SYSTEM_ID = ChatID('__system__') def __init__(self, chat: 'Chat', *, name: str='', alias: Optional[str]=None, id: ChatID=ChatID(''), uid: ChatID=ChatID(''), vendor_specific: Dict[(str, Any)]=None, description: str='', middleware: Optional[Middleware]=None): name = (na...
class FridaProcessController(ProcessController): def __init__(self, pid: int, main_module_name: str, frida_session: frida.core.Session, frida_script: frida.core.Script): frida_rpc = frida_script.exports super().__init__(pid, main_module_name, _str_to_architecture(frida_rpc.get_architecture()), frida...
class AssistedHealHandler(THBEventHandler): interested = ['action_after'] def handle(self, evt_type, act): if ((evt_type == 'action_after') and isinstance(act, TryRevive)): if (not act.succeeded): return act assert act.revived_by tgt = act.target ...
class CourseCreatedList(mixins.CreateModelMixin, mixins.UpdateModelMixin, viewsets.ReadOnlyModelViewSet): queryset = Courses.objects.filter(is_delete=False) serializer_class = CreatedCourseSerializers pagination_class = StandardResultsSetPagination permission_classes = (IsAuthenticated, IsOwnerOrReadOnl...
def undervolt(config): if ((('UNDERVOLT.{:s}'.format(power['source']) not in config) and ('UNDERVOLT' not in config)) or ('UNDERVOLT' in UNSUPPORTED_FEATURES)): return for plane in VOLTAGE_PLANES: write_offset_mv = config.getfloat('UNDERVOLT.{:s}'.format(power['source']), plane, fallback=config....
class Annotation(): def __init__(self, type_, role=None, constant=False): self.type = Type.from_value(type_) if (role is None): if (len(self.type.shape) == 0): role = 's' elif constant: role = 'i' else: role = 'io' ...
def generate(logfilenames: typing.List[str], file: typing.TextIO) -> None: writer = csv.DictWriter(file, fieldnames=Row.names()) writer.writeheader() logs = parse_logs(logfilenames) for info in logs: row = Row.from_info(info=info) writer.writerow(rowdict=row.name_dict())
def test_refresh_reload_plugins(preference, plugin_engine): plugin_engine.collect() preference.run() plugin_list = Q.select(preference.widget, Q.props('name', 'plugin.list')) assert (Q.map(plugin_list, TV.model, len) == 2) for plugin in plugin_engine.all(): plugin_engine.remove(plugin) p...
class OptionPlotoptionsSolidgaugeSonificationDefaultspeechoptionsMappingPitch(Options): def mapFunction(self): return self._config_get(None) def mapFunction(self, value: Any): self._config(value, js_type=False) def mapTo(self): return self._config_get('undefined') def mapTo(self,...
def get_flow_stats(dp, waiters, flow=None, to_user=True): flow = (flow if flow else {}) table_id = UTIL.ofp_table_from_user(flow.get('table_id', dp.ofproto.OFPTT_ALL)) flags = str_to_int(flow.get('flags', 0)) out_port = UTIL.ofp_port_from_user(flow.get('out_port', dp.ofproto.OFPP_ANY)) out_group = U...
def test_analyzers_added_to_object(): random_analyzer_name = ''.join((choice(string.ascii_letters) for _ in range(100))) random_analyzer = analyzer(random_analyzer_name, tokenizer='standard', filter='standard') index = Index('i', using='alias') index.analyzer(random_analyzer) assert (index._analysis...
() def check_fee_validity(appointment, date=None, practitioner=None): if (not frappe.db.get_single_value('Healthcare Settings', 'enable_free_follow_ups')): return if isinstance(appointment, str): appointment = json.loads(appointment) appointment = frappe.get_doc(appointment) date = (...
class OptionSeriesTreegraphStatesInactive(Options): def animation(self) -> 'OptionSeriesTreegraphStatesInactiveAnimation': return self._config_sub_data('animation', OptionSeriesTreegraphStatesInactiveAnimation) def enabled(self): return self._config_get(True) def enabled(self, flag: bool): ...
.timeout(8) def test_table_keyinstances_crud(db_context: DatabaseContext) -> None: table = KeyInstanceTable(db_context) assert ([] == table.read()) table._get_current_timestamp = (lambda : 10) KEYINSTANCE_ID = 0 ACCOUNT_ID = 10 MASTERKEY_ID = 20 DERIVATION_DATA1 = b'111' DERIVATION_DATA2...
class YAMLObj1(object): yaml_tag = u'!obj:' def from_yaml(cls, loader, suffix, node): import srsly.ruamel_yaml obj1 = Obj1(suffix) if isinstance(node, srsly.ruamel_yaml.MappingNode): obj1.add_node(loader.construct_mapping(node)) else: raise NotImplementedE...
def _butterworth_args_check(data, frequency, cutoff, filter_type, order, axis, precision): if (not isinstance(data, _np.ndarray)): raise TypeError(f"'data' should be a numpy ndarray, not {type(data)}.") if ((not isinstance(frequency, int)) and (not isinstance(frequency, float))): raise TypeError...
class LifespanManager(): def __init__(self, app: ASGIApp, startup_timeout: typing.Optional[float]=5, shutdown_timeout: typing.Optional[float]=5) -> None: self._state: typing.Dict[(str, typing.Any)] = {} self.app = state_middleware(app, self._state) self.startup_timeout = startup_timeout ...
def start_proj(length, name, price, area, capacity): io.sendlineafter('Exit\n', '1') io.sendlineafter('name: ', str(length)) io.sendlineafter('name: ', name) io.sendlineafter('price: ', str(price)) io.sendlineafter('area: ', str(area)) io.sendlineafter('capacity: ', str(capacity))
class OptionSeriesBarSonificationContexttracksMappingLowpass(Options): def frequency(self) -> 'OptionSeriesBarSonificationContexttracksMappingLowpassFrequency': return self._config_sub_data('frequency', OptionSeriesBarSonificationContexttracksMappingLowpassFrequency) def resonance(self) -> 'OptionSeries...
def goodbye_email(use): domain = Site.objects.get_current().domain location = use.location c = {'first_name': use.user.first_name, 'location': use.location, 'booking_url': ((' + domain) + urlresolvers.reverse('booking_detail', args=(location.slug, use.booking.id))), 'new_booking_url': ((' + domain) + urlres...
class BankRestClient(Bank): API_URL = '/cosmos/bank/v1beta1' def __init__(self, rest_api: RestClient): self._rest_api = rest_api def Balance(self, request: QueryBalanceRequest) -> QueryBalanceResponse: response = self._rest_api.get(f'{self.API_URL}/balances/{request.address}/by_denom?denom={...
def profile(name, env, filename=None, verbose=False): if filename: filename = ((name + '-') + filename) print(('Profiling %s ==> %s' % (name, filename))) else: filename = None title = (name + ' profile') print() print(('=' * len(title))) print(title) ...
def upload(access_token: str, title: str, creator_name: str, description: str='', files: Collection[Union[(Path, str)]]=(), affiliation: str=None, orcid: str=None, gnd: str=None, upload_type: str='other', license: str='CC-BY-4.0', keywords: Collection[str]=(), related_identifiers: Collection[dict]=(), community_identif...
class TestExceptionHandlers(): .usefixtures('mock_config_redis_disabled') def test_redis_disabled(self, api_client: TestClient, generate_auth_header): auth_header = generate_auth_header([CLIENT_CREATE]) request_body = [{'requested_at': '2021-08-30T16:09:37.359Z', 'identity': {'email': 'customer-...
def extractShirohane(item): (vol, chp, frag, postfix) = extractVolChapterFragmentPostfix(item['title']) if ((not (chp or vol)) or ('preview' in item['title'].lower())): return None if ('WATTT' in item['tags']): return buildReleaseMessageWithType(item, 'WATTT', vol, chp, frag=frag, postfix=po...
class PlotScrollBar(NativeScrollBar): axis = Enum('index', 'value') plot = Property mapper = Property _plot = Any() _mapper = Any() _axis_index = Optional(Int) def force_data_update(self): self._handle_dataspace_update() def overlay(self, component, gc, view_bounds=None, mode='de...
class TensorOpsTest(unittest.TestCase): def test_gradients(self) -> None: for type_ in [torch.float32, torch.float64]: x = torch.randn(3, requires_grad=True, dtype=type_) prec = torch.Tensor([[1, 0.1, 0], [0.1, 2, 0.5], [0, 0.5, 3]]).to(type_) mu = torch.randn(3, dtype=ty...
class OptionSeriesVariwideSonificationContexttracksMappingTremoloDepth(Options): def mapFunction(self): return self._config_get(None) def mapFunction(self, value: Any): self._config(value, js_type=False) def mapTo(self): return self._config_get(None) def mapTo(self, text: str): ...
def construct_anonymization_context(text: str) -> str: prompt = f'''Please analyze the following text and identify any personal and sensitive information contained within it. For each instance of personal information, please provide a category and a confidence score. Categories could include, but should not be limi...
('ecs_deploy.cli.get_client') def test_scale_with_timeout(get_client, runner): get_client.return_value = EcsTestClient('acces_key', 'secret_key', wait=2) result = runner.invoke(cli.scale, (CLUSTER_NAME, SERVICE_NAME, '2', '--timeout', '1')) assert (result.exit_code == 1) assert (u'Scaling failed due to ...
class TestStrategy(): .parametrize(['step_dates_path', 'df_path', 'expected_path'], [('data/step_dates1.csv', 'data/df1.csv', 'data/expected1.csv'), ('data/step_dates2.csv', 'data/df2.csv', 'data/expected2.csv'), ('data/step_dates3.csv', 'data/df3.csv', 'data/expected3.csv')]) def test__cast_data(self, step_dat...
def get_metadata_files(vercodes): found_invalid = False metadatafiles = [] for appid in vercodes.keys(): f = (Path('metadata') / ('%s.yml' % appid)) if f.exists(): metadatafiles.append(f) else: found_invalid = True logging.critical((_('No such pack...
def otsu_mask(voxel_sims: Float[(torch.Tensor, 'n')], num_bins: int=100) -> Tuple[(Float[(torch.Tensor, 'n')], float)]: (sim_min, sim_max) = (voxel_sims.min(), voxel_sims.max()) voxel_sims_norm = ((voxel_sims - sim_min) / (sim_max - sim_min)) threshold_vals = torch.linspace(0, 1, num_bins).to(voxel_sims.dev...
class OptionPlotoptionsWindbarbStates(Options): def hover(self) -> 'OptionPlotoptionsWindbarbStatesHover': return self._config_sub_data('hover', OptionPlotoptionsWindbarbStatesHover) def inactive(self) -> 'OptionPlotoptionsWindbarbStatesInactive': return self._config_sub_data('inactive', OptionP...
def register_user(): request_data = request.get_json() user = User.query.filter_by(username=request_data.get('username')).first() if (not user): try: jsonschema.validate(request_data, register_user_schema) if (vuln and ('admin' in request_data)): if request_da...
class SavepathParser(object): helper = None cfg_savepath = None relative_to_path = None format_relative_path = None working_path = None def __init__(self, cfg_savepath, relative_to_path, format_relative_path, helper, working_path): self.helper = helper timestamp_execution = int(t...
class JITOption(click.Option): def __init__(self, param_decls: Union[(str, Sequence[str])], default: Union[(Callable[([], Any)], None, Any)]=None, help: Union[(Callable[([], str)], str, None)]=None, prompt: Union[(Callable[([], str)], str, None)]=None, **kwargs: Any): self.callable_default = default ...
def matrix_lines(et, pos, pos_cloned, edge_color: Iterable, alpha: Iterable, lw: Iterable, aes_kw: Dict): patches = [] for (r, d) in et.iterrows(): start = d['source'] end = d['target'] (x_start, y_start) = pos_y[start] (x_end, y_end) = pos[end] (x, y) = (max(x_start, y_s...
def do_the_useful_stuff(process_counter, task_id, worker_id, sleep): if ('FAIL_EARLY' in os.environ): raise Exception('sorry') redis = get_redis_connection(REDIS_OPTS) redis.hset(worker_id, 'started', 1) if ('FAIL_STARTED_PID' in os.environ): return 0 redis.hset(worker_id, 'PID', os....
def test_complex_list_columns(): (app, db, admin) = setup() with app.app_context(): (M1, M2) = create_models(db) m1 = M1('model1_val1') db.session.add(m1) db.session.add(M2('model2_val1', model1=m1)) db.session.commit() view = CustomModelView(M2, db.session, colum...
def add_elem_types_to_mm_info(mm_info, func_attrs): backend_spec = CUDASpec() elem_input_type = backend_spec.dtype_to_lib_type(func_attrs['inputs'][0]._attrs['dtype']) elem_output_type = backend_spec.dtype_to_lib_type(func_attrs['outputs'][0]._attrs['dtype']) return dataclasses.replace(mm_info, a_ptr=f'...
() ('bounds', nargs=4, type=float, metavar='MINX MINY MAXX MAXY') ('-s', '--step', type=float, help='Step between lines (in projected units)', required=True) ('-j', '--crs', type=str, default=None, help=crs_help2) ('-o', '--output', default=sys.stdout, type=click.File('wb'), help='Defaults to stdout') def graticule(bou...
def error(parent, message=None, markup=None): if (message is markup is None): raise ValueError('message or markup must be specified') dialog = Gtk.MessageDialog(buttons=Gtk.ButtonsType.CLOSE, message_type=Gtk.MessageType.ERROR, modal=True, transient_for=parent) if (markup is None): dialog.pr...
(tags=['audit'], description=docs.NAME_SEARCH) class AuditCandidateNameSearch(utils.Resource): filter_fulltext_fields = [('q', models.AuditCandidateSearch.fulltxt)] _kwargs(args.names) _with(schemas.AuditCandidateSearchListSchema()) def get(self, **kwargs): query = filters.filter_fulltext(models...
_production class Expression(AstNode, VarStateMixin): expression_value = synthesized(default=fail_on_access) expression_value_used = inherited(default=True, implicit_pushdown=False) def type_string(self) -> str: return self.type_descriptions['typeString'] def type_identifier(self) -> str: ...
def _remove_spaces(line: str) -> str: quotes = False comment = False new_line = '' for c in line: if ((c == ' ') and (not quotes)): if comment: new_line += c else: if ((c == "'") or (c == '"')): quotes = (not quotes) ...
class TestGeneral(BaseEvenniaCommandTest): def test_look(self): rid = self.room1.id self.call(general.CmdLook(), 'here', 'Room(#{})\nroom_desc'.format(rid)) def test_look_no_location(self): self.char1.location = None self.call(general.CmdLook(), '', 'You have no location to look ...
class task_(): def accepts_Invoke_level_kwargs(self): def body(c, parts): pass t = fabric.task(name='dadbod', aliases=['heavenly', 'check', 'shop'], default=True, help={'parts': 'See: the sum of'}, iterable=['parts'])(body) assert (t.body is body) assert (t.__doc__ == 'I ...
def _get_highest_punk_bid_per_index(punk_bids: List[PunkBid], punk_index: int) -> Optional[PunkBid]: highest_punk_bid = None for punk_bid in punk_bids: if (punk_bid.punk_index == punk_index): if (highest_punk_bid is None): highest_punk_bid = punk_bid elif (punk_bi...
class HttpDataTransform(): def __init__(self, steps: List[TransformStep], reverse: bool=False, build: str=None) -> None: self.tsteps: List[TransformStep] = steps self.rsteps: List[TransformStep] = steps[::(- 1)] if reverse: (self.tsteps, self.rsteps) = (self.rsteps, self.tsteps) ...
def fetch_historical_consumption(target_datetime: datetime, session: Session, logger: Logger=getLogger(__name__)): data_list = fetch_historical_data(session=session, target_datetime=target_datetime) result_list = TotalConsumptionList(logger) for data in data_list: result_list.append(datetime=(dateti...
_runner def directory(c, runner, path, user=None, group=None, mode=None): runner('mkdir -p {}'.format(path)) if (user is not None): group = (group or user) runner('chown {}:{} {}'.format(user, group, path)) if (mode is not None): runner('chmod {} {}'.format(mode, path))
def _evolve(shot: System, dt: float): for (ball_id, ball) in shot.balls.items(): (rvw, s) = evolve.evolve_state_motion(state=ball.state.s, rvw=ball.state.rvw, R=ball.params.R, m=ball.params.m, u_s=ball.params.u_s, u_sp=ball.params.u_sp, u_r=ball.params.u_r, g=ball.params.g, t=dt) ball.state = BallSt...
class OptionSeriesNetworkgraphTooltip(Options): def clusterFormat(self): return self._config_get('Clustered points: {point.clusterPointsAmount}') def clusterFormat(self, text: str): self._config(text, js_type=False) def dateTimeLabelFormats(self) -> 'OptionSeriesNetworkgraphTooltipDatetimela...
.django_db def test_statement_timeout_successfully_times_out(): test_timeout_in_seconds = 0.5 pg_sleep_in_seconds = 10 _db_timeout(test_timeout_in_seconds) def test_timeout_success(): with connection.cursor() as cursor: cursor.execute(f'SELECT pg_sleep({pg_sleep_in_seconds:.2f})') ...
def return_memory_map_for_pid(pid): hProcess = open_process(pid) memory_map = {} memory_map[pid] = set() if hProcess: pageStart = 0 while True: information = virtual_query_ex(hProcess, pageStart) if (information == 0): break if (informa...