function
stringlengths
11
56k
repo_name
stringlengths
5
60
features
list
def len_support(self): return len(self.votes_positive)
ecreall/nova-ideo
[ 22, 6, 22, 9, 1417421268 ]
def len_opposition(self): return len(self.votes_negative)
ecreall/nova-ideo
[ 22, 6, 22, 9, 1417421268 ]
def withdraw_vote(self, user): oid = get_oid(user) if oid in self.votes_positive: self.votes_positive.pop(oid) elif oid in self.votes_negative: self.votes_negative.pop(oid)
ecreall/nova-ideo
[ 22, 6, 22, 9, 1417421268 ]
def has_negative_vote(self, user): oid = get_oid(user) return oid in self.votes_negative
ecreall/nova-ideo
[ 22, 6, 22, 9, 1417421268 ]
def __init__(self, **kwargs): super(Tokenable, self).__init__(**kwargs) self.set_data(kwargs) self.allocated_tokens = OOBTree() self.len_allocated_tokens = PersistentDict({})
ecreall/nova-ideo
[ 22, 6, 22, 9, 1417421268 ]
def remove_token(self, user): user_oid = get_oid(user) if user_oid in self.allocated_tokens: evaluation_type = self.allocated_tokens.pop(user_oid) self.len_allocated_tokens.setdefault(evaluation_type, 0) self.len_allocated_tokens[evaluation_type] -= 1
ecreall/nova-ideo
[ 22, 6, 22, 9, 1417421268 ]
def evaluation(self, user): user_oid = get_oid(user, None) return self.allocated_tokens.get(user_oid, None)
ecreall/nova-ideo
[ 22, 6, 22, 9, 1417421268 ]
def user_has_token(self, user, root=None): if hasattr(user, 'has_token'): return user.has_token(self, root) return False
ecreall/nova-ideo
[ 22, 6, 22, 9, 1417421268 ]
def len_support(self): return self.len_allocated_tokens.get(Evaluations.support, 0)
ecreall/nova-ideo
[ 22, 6, 22, 9, 1417421268 ]
def clean_seeing(self): data = self.cleaned_data['seeing'] if data and data not in list(range(1, 6)): raise forms.ValidationError(_("Please enter a value between 1 and 5.")) return data
astrobin/astrobin
[ 90, 26, 90, 17, 1510218687 ]
def setUp(self): super(TestCarepointImporterMapper, self).setUp() self.Importer = mapper.CarepointImportMapper self.model = 'carepoint.carepoint.store' self.mock_env = self.get_carepoint_helper( self.model ) self.importer = self.Importer(self.mock_env)
laslabs/odoo-connector-carepoint
[ 1, 1, 1, 2, 1449883667 ]
def __init__(self, **_unused): ITER_STARTED.connect(self.read_console_vars) ITER_FINISHED.connect(self.print_console_vars)
NifTK/NiftyNet
[ 1325, 408, 1325, 103, 1504079743 ]
def test_gaussian_result_frame_model_id(): d = h2o.import_file(path=pyunit_utils.locate("smalldata/logreg/prostate.csv")) my_y = "GLEASON" my_x = ["AGE","RACE","CAPSULE","DCAPS","PSA","VOL","DPROS"]
h2oai/h2o-3
[ 6169, 1943, 6169, 208, 1393862887 ]
def run_sample(): """Runs the sample.""" # TODO(developer): Replace this variable with your Google Analytics 4 # property ID before running the sample. property_id = "YOUR-GA4-PROPERTY-ID" run_report_with_property_quota(property_id)
googleapis/python-analytics-data
[ 114, 29, 114, 9, 1600119359 ]
def setUp(self): self.fd, self.path = tempfile.mkstemp()
rbuffat/pyidf
[ 20, 7, 20, 2, 1417292720 ]
def train_evaluate(params, max_epochs=100): model = IrisClassification(**params) dm = IrisDataModule() dm.setup(stage="fit") trainer = pl.Trainer(max_epochs=max_epochs) mlflow.pytorch.autolog() trainer.fit(model, dm) trainer.test(datamodule=dm) test_accuracy = trainer.callback_metrics.get("test_acc") return test_accuracy
mlflow/mlflow
[ 13810, 3230, 13810, 1042, 1528214758 ]
def test_redeploy_start_time(serve_instance): """Check that redeploying a deployment doesn't reset its start time.""" controller = serve.api._global_client._controller @serve.deployment def test(_): return "1" test.deploy() deployment_info_1, route_1 = ray.get(controller.get_deployment_info.remote("test")) start_time_ms_1 = deployment_info_1.start_time_ms time.sleep(0.1) @serve.deployment def test(_): return "2" test.deploy() deployment_info_2, route_2 = ray.get(controller.get_deployment_info.remote("test")) start_time_ms_2 = deployment_info_2.start_time_ms assert start_time_ms_1 == start_time_ms_2
ray-project/ray
[ 24488, 4264, 24488, 2914, 1477424310 ]
def service_check(self, env): import params env.set_params(params) mahout_command = format("mahout seqdirectory --input /user/{smokeuser}/mahoutsmokeinput/sample-mahout-test.txt " "--output /user/{smokeuser}/mahoutsmokeoutput/ --charset utf-8") test_command = format("fs -test -e /user/{smokeuser}/mahoutsmokeoutput/_SUCCESS")
arenadata/ambari
[ 3, 7, 3, 3, 1478181309 ]
def setUp(self): super(DsTcResnetTest, self).setUp() config = tf1.ConfigProto() config.gpu_options.allow_growth = True self.sess = tf1.Session(config=config) tf1.keras.backend.set_session(self.sess) tf.keras.backend.set_learning_phase(0) test_utils.set_seed(123) self.params = utils.ds_tc_resnet_model_params(True) self.model = ds_tc_resnet.model(self.params) self.model.summary() self.input_data = np.random.rand(self.params.batch_size, self.params.desired_samples) # run non streaming inference self.non_stream_out = self.model.predict(self.input_data)
google-research/google-research
[ 27788, 6881, 27788, 944, 1538678568 ]
def test_ds_tc_resnet_stream_tflite(self): """Test for tflite streaming with external state.""" tflite_streaming_model = utils.model_to_tflite( self.sess, self.model, self.params, Modes.STREAM_EXTERNAL_STATE_INFERENCE) interpreter = tf.lite.Interpreter(model_content=tflite_streaming_model) interpreter.allocate_tensors() # before processing new test sequence we reset model state inputs = [] for detail in interpreter.get_input_details(): inputs.append(np.zeros(detail['shape'], dtype=np.float32)) stream_out = inference.run_stream_inference_classification_tflite( self.params, interpreter, self.input_data, inputs) self.assertAllClose(stream_out, self.non_stream_out, atol=1e-5)
google-research/google-research
[ 27788, 6881, 27788, 944, 1538678568 ]
def my_pipeline(text: str = 'Hello world!'): component_1 = component_op_1(text=text).set_display_name('Producer') component_2 = component_op_2( input_gcs_path=component_1.outputs['output_gcs_path']) component_2.set_display_name('Consumer')
kubeflow/pipelines
[ 3125, 1400, 3125, 892, 1526085107 ]
def _extract_raw_features_from_token( cls, feature_name: Text, token: Token, token_position: int, num_tokens: int,
RasaHQ/rasa_nlu
[ 15758, 4259, 15758, 111, 1476448069 ]
def required_components(cls) -> List[Type]: """Components that should be included in the pipeline before this component.""" return [Tokenizer]
RasaHQ/rasa_nlu
[ 15758, 4259, 15758, 111, 1476448069 ]
def get_default_config() -> Dict[Text, Any]: """Returns the component's default config.""" return { **SparseFeaturizer.get_default_config(), FEATURES: [ ["low", "title", "upper"], ["BOS", "EOS", "low", "upper", "title", "digit"], ["low", "title", "upper"], ], }
RasaHQ/rasa_nlu
[ 15758, 4259, 15758, 111, 1476448069 ]
def validate_config(cls, config: Dict[Text, Any]) -> None: """Validates that the component is configured properly.""" if FEATURES not in config: return # will be replaced with default feature_config = config[FEATURES] message = ( f"Expected configuration of `features` to be a list of lists that " f"that contain names of lexical and syntactic features " f"(i.e. {cls.SUPPORTED_FEATURES}). " f"Received {feature_config} instead. " ) try: configured_feature_names = set( feature_name for pos_config in feature_config for feature_name in pos_config ) except TypeError as e: raise InvalidConfigException(message) from e if configured_feature_names.difference(cls.SUPPORTED_FEATURES): raise InvalidConfigException(message)
RasaHQ/rasa_nlu
[ 15758, 4259, 15758, 111, 1476448069 ]
def train(self, training_data: TrainingData) -> Resource: """Trains the featurizer. Args: training_data: the training data Returns: the resource from which this trained component can be loaded """ self.warn_if_pos_features_cannot_be_computed(training_data) feature_to_idx_dict = self._create_feature_to_idx_dict(training_data) self._set_feature_to_idx_dict(feature_to_idx_dict=feature_to_idx_dict) if not self._feature_to_idx_dict: rasa.shared.utils.io.raise_warning( "No lexical syntactic features could be extracted from the training " "data. In order for this component to work you need to define " "`features` that can be found in the given training data." ) self.persist() return self._resource
RasaHQ/rasa_nlu
[ 15758, 4259, 15758, 111, 1476448069 ]
def _create_feature_to_idx_dict( self, training_data: TrainingData
RasaHQ/rasa_nlu
[ 15758, 4259, 15758, 111, 1476448069 ]
def _map_tokens_to_raw_features( self, tokens: List[Token]
RasaHQ/rasa_nlu
[ 15758, 4259, 15758, 111, 1476448069 ]
def _build_feature_to_index_map( feature_vocabulary: Dict[Tuple[int, Text], Set[Text]]
RasaHQ/rasa_nlu
[ 15758, 4259, 15758, 111, 1476448069 ]
def process(self, messages: List[Message]) -> List[Message]: """Featurizes all given messages in-place. Args: messages: messages to be featurized. Returns: The same list with the same messages after featurization. """ for message in messages: self._process_message(message) return messages
RasaHQ/rasa_nlu
[ 15758, 4259, 15758, 111, 1476448069 ]
def _process_message(self, message: Message) -> None: """Featurizes the given message in-place. Args: message: a message to be featurized """ if not self._feature_to_idx_dict: rasa.shared.utils.io.raise_warning( f"The {self.__class__.__name__} {self._identifier} has not been " f"trained properly yet. " f"Continuing without adding features from this featurizer." ) return tokens = message.get(TOKENS_NAMES[TEXT]) if tokens: sentence_features = self._map_tokens_to_raw_features(tokens) sparse_matrix = self._map_raw_features_to_indices(sentence_features) self.add_features_to_message( # FIXME: create sentence feature and make `sentence` non optional sequence=sparse_matrix, sentence=None, attribute=TEXT, message=message, )
RasaHQ/rasa_nlu
[ 15758, 4259, 15758, 111, 1476448069 ]
def create( cls, config: Dict[Text, Any], model_storage: ModelStorage, resource: Resource, execution_context: ExecutionContext,
RasaHQ/rasa_nlu
[ 15758, 4259, 15758, 111, 1476448069 ]
def load( cls, config: Dict[Text, Any], model_storage: ModelStorage, resource: Resource, execution_context: ExecutionContext, **kwargs: Any,
RasaHQ/rasa_nlu
[ 15758, 4259, 15758, 111, 1476448069 ]
def __new__(mcs, name, bases, attrs): meta = attrs.pop('Meta', None) new_class = type.__new__(mcs, name, bases, attrs) if meta: meta.model_name = name.lower() meta.concrete_model = new_class setattr(new_class, '_meta', meta) else: raise AttributeError('Class %s has no "class Meta" definition' % name) return new_class
erigones/esdc-ce
[ 106, 27, 106, 56, 1478554493 ]
def __new__(cls, *args, **kwargs): # noinspection PyArgumentList obj = super(_DummyDataModel, cls).__new__(cls, *args, **kwargs) obj._data = {} return obj
erigones/esdc-ce
[ 106, 27, 106, 56, 1478554493 ]
def __getattr__(self, key): if key.startswith('_'): # noinspection PyUnresolvedReferences return super(_DummyDataModel, self).__getattr__(key) else: return self._data[key]
erigones/esdc-ce
[ 106, 27, 106, 56, 1478554493 ]
def __delattr__(self, key): if key.startswith('_'): return super(_DummyDataModel, self).__delattr__(key) else: return self._data.__delitem__(key)
erigones/esdc-ce
[ 106, 27, 106, 56, 1478554493 ]
def __setstate__(self, state): self._data = state
erigones/esdc-ce
[ 106, 27, 106, 56, 1478554493 ]
def __getitem__(self, item): return self._data.__getitem__(item)
erigones/esdc-ce
[ 106, 27, 106, 56, 1478554493 ]
def update(self, data): self._data.update(data)
erigones/esdc-ce
[ 106, 27, 106, 56, 1478554493 ]
def _decode(xdata): """Unpickle data from DB and return a PickleDict object""" data = pickle.loads(base64.decodestring(xdata)) if not isinstance(data, PickleDict): data = PickleDict(data) return data
erigones/esdc-ce
[ 106, 27, 106, 56, 1478554493 ]
def _encode(xdata): """Pickle a dict object and return data, which can be saved in DB""" if not isinstance(xdata, dict): raise ValueError('json is not a dict') return base64.encodestring(pickle.dumps(copy.copy(dict(xdata))))
erigones/esdc-ce
[ 106, 27, 106, 56, 1478554493 ]
def json(self): return self._decode(self.enc_json)
erigones/esdc-ce
[ 106, 27, 106, 56, 1478554493 ]
def json(self, data): self.enc_json = self._encode(data)
erigones/esdc-ce
[ 106, 27, 106, 56, 1478554493 ]
def save_items(self, save=True, metadata=None, **key_value): """Save multiple items in json""" _json = self.json if metadata: if metadata not in _json: _json[metadata] = {} _json[metadata].update(key_value) else: _json.update(key_value) self.json = _json if save: return self.save() else: return True
erigones/esdc-ce
[ 106, 27, 106, 56, 1478554493 ]
def __init__(self, *args, **kwargs): super(_StatusModel, self).__init__(*args, **kwargs) self._orig_status = self.status
erigones/esdc-ce
[ 106, 27, 106, 56, 1478554493 ]
def status_key(pk): # public helper for accessing the cache key return str(pk) + ':status'
erigones/esdc-ce
[ 106, 27, 106, 56, 1478554493 ]
def status_change_key(pk): # public helper for accessing the cache key return str(pk) + ':status-change'
erigones/esdc-ce
[ 106, 27, 106, 56, 1478554493 ]
def obj_status_key(self): return _StatusModel.status_key(self.pk)
erigones/esdc-ce
[ 106, 27, 106, 56, 1478554493 ]
def obj_status_change_key(self): return _StatusModel.status_change_key(self.pk)
erigones/esdc-ce
[ 106, 27, 106, 56, 1478554493 ]
def unlock(self): self._lock = False
erigones/esdc-ce
[ 106, 27, 106, 56, 1478554493 ]
def save_status(self, new_status=None, **kwargs): """Just update the status field (and other related fields)""" if new_status is not None: self.status = new_status return self.save(update_fields=('status', 'status_change'), **kwargs)
erigones/esdc-ce
[ 106, 27, 106, 56, 1478554493 ]
def post_delete_status(sender, instance, **kwargs): """Clean cache after removing the object - call from signal""" # noinspection PyProtectedMember if instance._cache_status: # remove the cache entries cache.delete(instance.obj_status_key) cache.delete(instance.obj_status_change_key)
erigones/esdc-ce
[ 106, 27, 106, 56, 1478554493 ]
def __unicode__(self): return '%s' % self.name
erigones/esdc-ce
[ 106, 27, 106, 56, 1478554493 ]
def _add_task(user_id, task_id, info): return UserTasks(user_id).add(task_id, info)
erigones/esdc-ce
[ 106, 27, 106, 56, 1478554493 ]
def _pop_task(user_id, task_id): return UserTasks(user_id).pop(task_id)
erigones/esdc-ce
[ 106, 27, 106, 56, 1478554493 ]
def _get_tasks(user_id): return UserTasks(user_id).tasks
erigones/esdc-ce
[ 106, 27, 106, 56, 1478554493 ]
def default_apiview(self): """Return dict with object related attributes which are always available in apiview""" return {}
erigones/esdc-ce
[ 106, 27, 106, 56, 1478554493 ]
def tasks(self): return self.get_tasks()
erigones/esdc-ce
[ 106, 27, 106, 56, 1478554493 ]
def tasks_rw(self): return self.get_tasks(match_dict={'method': RWMethods})
erigones/esdc-ce
[ 106, 27, 106, 56, 1478554493 ]
def _create_task_info(cls, pk, apiview, msg, additional_apiview=None): """Prepare task info dict (will be stored in UserTasks cache)""" if apiview is None: apiview = {} if additional_apiview: apiview.update(additional_apiview) if 'time' not in apiview: apiview['time'] = timezone.now().isoformat() return {cls._pk_key: pk, 'msg': msg, 'apiview': apiview}
erigones/esdc-ce
[ 106, 27, 106, 56, 1478554493 ]
def _tasks_add(cls, pk, task_id, apiview, msg='', **additional_apiview): """Add task to pending tasks dict in cache.""" info = cls._create_task_info(pk, apiview, msg, additional_apiview=additional_apiview) return cls._add_task(owner_id_from_task_id(task_id), task_id, info)
erigones/esdc-ce
[ 106, 27, 106, 56, 1478554493 ]
def _tasks_del(cls, task_id, apiview=None, **additional_apiview): """Delete task from pending tasks dict in cache.""" if apiview is None: info = cls._pop_task(owner_id_from_task_id(task_id), task_id) apiview = info.get('apiview', {}) if additional_apiview: apiview.update(additional_apiview) # Store task info for socket.io que monitor cache.set('sio-' + task_id, apiview, 60) return apiview
erigones/esdc-ce
[ 106, 27, 106, 56, 1478554493 ]
def get_log_name_lookup_kwargs(cls, log_name_value): """Return lookup_key=value DB pairs which can be used for retrieving objects by log_name value""" return {cls._log_name_attr: log_name_value}
erigones/esdc-ce
[ 106, 27, 106, 56, 1478554493 ]
def get_content_type(cls): # Warning: get_content_type will be deprecated soon. New models should implement get_object_type() return ContentType.objects.get_for_model(cls)
erigones/esdc-ce
[ 106, 27, 106, 56, 1478554493 ]
def get_object_type(cls, content_type=None): if content_type: return content_type.model return cls.get_content_type().model
erigones/esdc-ce
[ 106, 27, 106, 56, 1478554493 ]
def get_object_by_pk(cls, pk): # noinspection PyUnresolvedReferences return cls.objects.get(pk=pk)
erigones/esdc-ce
[ 106, 27, 106, 56, 1478554493 ]
def get_pk_key(cls): return cls._pk_key
erigones/esdc-ce
[ 106, 27, 106, 56, 1478554493 ]
def log_name(self): return getattr(self, self._log_name_attr)
erigones/esdc-ce
[ 106, 27, 106, 56, 1478554493 ]
def log_alias(self): # noinspection PyUnresolvedReferences return self.alias
erigones/esdc-ce
[ 106, 27, 106, 56, 1478554493 ]
def log_list(self): return self.log_name, self.log_alias, self.pk, self.__class__
erigones/esdc-ce
[ 106, 27, 106, 56, 1478554493 ]
def get_disk_map(self): """Return real_disk_id -> disk_id mapping""" self._vm_disks = self.vm.json_active_get_disks() return self.vm.get_disk_map(self._vm_disks)
erigones/esdc-ce
[ 106, 27, 106, 56, 1478554493 ]
def array_disk_id(self): if self._vm_disk_map is None: self._vm_disk_map = self.get_disk_map() return self._vm_disk_map[self.disk_id] + 1
erigones/esdc-ce
[ 106, 27, 106, 56, 1478554493 ]
def disk_size(self): disk_id = self.array_disk_id - 1 return self._vm_disks[disk_id]['size']
erigones/esdc-ce
[ 106, 27, 106, 56, 1478554493 ]
def zfs_filesystem(self): disk_id = self.array_disk_id - 1 return self._vm_disks[disk_id]['zfs_filesystem']
erigones/esdc-ce
[ 106, 27, 106, 56, 1478554493 ]
def get_real_disk_id(disk_or_path): """Return integer disk suffix from json.disks.*.path attribute""" if isinstance(disk_or_path, dict): disk_path = disk_or_path['path'] else: disk_path = disk_or_path return int(re.split('-|/', disk_path)[-1].lstrip('disk'))
erigones/esdc-ce
[ 106, 27, 106, 56, 1478554493 ]
def get_disk_id(cls, vm, array_disk_id): """Return real_disk_id from vm's active_json""" disk = vm.json_active_get_disks()[array_disk_id - 1] return cls.get_real_disk_id(disk)
erigones/esdc-ce
[ 106, 27, 106, 56, 1478554493 ]
def _new_periodic_task(self): """Return instance of PeriodicTask. Define in descendant class""" return NotImplemented # return self.PT(name=, task=, args=, kwargs=, expires=)
erigones/esdc-ce
[ 106, 27, 106, 56, 1478554493 ]
def crontab_to_schedule(c): """Return string representation of CrontabSchedule model""" def s(f): return f and str(f).replace(' ', '') or '*' return '%s %s %s %s %s' % (s(c.minute), s(c.hour), s(c.day_of_month), s(c.month_of_year), s(c.day_of_week))
erigones/esdc-ce
[ 106, 27, 106, 56, 1478554493 ]
def active(self): """Return enabled boolean from periodic task""" if self._active is None: # init if self.periodic_task: self._active = self.periodic_task.enabled else: self._active = True # default return self._active
erigones/esdc-ce
[ 106, 27, 106, 56, 1478554493 ]
def active(self, value): """Cache active attribute - will be updated/created later in save()""" self._active = value
erigones/esdc-ce
[ 106, 27, 106, 56, 1478554493 ]
def schedule(self): """Return cron entry from periodic task""" if self._schedule is None and self.periodic_task and self.periodic_task.crontab: # init self._schedule = self.crontab_to_schedule(self.periodic_task.crontab) return self._schedule
erigones/esdc-ce
[ 106, 27, 106, 56, 1478554493 ]
def schedule(self, value): """Cache cron entry - will be updated/created later in save()""" self._schedule = value
erigones/esdc-ce
[ 106, 27, 106, 56, 1478554493 ]
def save(self, *args, **kwargs): """Create or update periodic task and cron schedule in DB""" # Save first, because the periodic_task needs this object's ID super(_ScheduleModel, self).save(*args, **kwargs) do_save = False pt = self.periodic_task if not pt: pt = self._new_periodic_task() if not pt.crontab: pt.crontab = self._save_crontab(CrontabSchedule()) do_save = True elif self.schedule != self.crontab_to_schedule(pt.crontab): self._save_crontab(pt.crontab) do_save = True # Need to update PeriodicTask, because it will signal the Scheduler to reload if self.active != pt.enabled: pt.enabled = self.active do_save = True if not pt.pk: pt.save() # New periodic task object self.periodic_task = pt self.save(update_fields=('periodic_task',)) # Update this object elif do_save: pt.save(update_fields=('enabled', 'crontab', 'date_changed')) # Update periodic task
erigones/esdc-ce
[ 106, 27, 106, 56, 1478554493 ]
def make_table(rows, insert_header=False): col_widths = [max(len(s) for s in col) for col in zip(*rows[1:])] rows[0] = [x[:l] for x, l in zip(rows[0], col_widths)] fmt = '\t'.join('%%-%ds' % width for width in col_widths) if insert_header: rows.insert(1, ['─' * width for width in col_widths]) return '\n'.join(fmt % tuple(row) for row in rows)
hankcs/HanLP
[ 28293, 7950, 28293, 9, 1412836576 ]
def pretty_tree_horizontal(arrows, _do_print_debug_info=False): """Print the dependency tree horizontally Args: arrows: _do_print_debug_info: (Default value = False) Returns: """ # Set the base height; these may increase to allow room for arrowheads after this. arrows_with_deps = defaultdict(set) for i, arrow in enumerate(arrows): arrow['underset'] = set() if _do_print_debug_info: print('Arrow %d: "%s" -> "%s"' % (i, arrow['from'], arrow['to'])) num_deps = 0 start, end, mn, mx = _start_end(arrow) for j, other in enumerate(arrows): if arrow is other: continue o_start, o_end, o_mn, o_mx = _start_end(other) if ((start == o_start and mn <= o_end <= mx) or (start != o_start and mn <= o_start <= mx)): num_deps += 1 if _do_print_debug_info: print('%d is over %d' % (i, j)) arrow['underset'].add(j) arrow['num_deps_left'] = arrow['num_deps'] = num_deps arrows_with_deps[num_deps].add(i) if _do_print_debug_info: print('') print('arrows:') pprint(arrows) print('') print('arrows_with_deps:') pprint(arrows_with_deps) # Render the arrows in characters. Some heights will be raised to make room for arrowheads. sent_len = (max([max(arrow['from'], arrow['to']) for arrow in arrows]) if arrows else 0) + 1 lines = [[] for i in range(sent_len)] num_arrows_left = len(arrows) while num_arrows_left > 0: assert len(arrows_with_deps[0]) arrow_index = arrows_with_deps[0].pop() arrow = arrows[arrow_index] src, dst, mn, mx = _start_end(arrow) # Check the height needed. height = 3 if arrow['underset']: height = max(arrows[i]['height'] for i in arrow['underset']) + 1 height = max(height, 3, len(lines[dst]) + 3) arrow['height'] = height if _do_print_debug_info: print('') print('Rendering arrow %d: "%s" -> "%s"' % (arrow_index, arrow['from'], arrow['to'])) print(' height = %d' % height) goes_up = src > dst # Draw the outgoing src line. if lines[src] and len(lines[src]) < height: lines[src][-1].add('w') while len(lines[src]) < height - 1: lines[src].append(set(['e', 'w'])) if len(lines[src]) < height: lines[src].append({'e'}) lines[src][height - 1].add('n' if goes_up else 's') # Draw the incoming dst line. lines[dst].append(u'β–Ί') while len(lines[dst]) < height: lines[dst].append(set(['e', 'w'])) lines[dst][-1] = set(['e', 's']) if goes_up else set(['e', 'n']) # Draw the adjoining vertical line. for i in range(mn + 1, mx): while len(lines[i]) < height - 1: lines[i].append(' ') lines[i].append(set(['n', 's'])) # Update arrows_with_deps. for arr_i, arr in enumerate(arrows): if arrow_index in arr['underset']: arrows_with_deps[arr['num_deps_left']].remove(arr_i) arr['num_deps_left'] -= 1 arrows_with_deps[arr['num_deps_left']].add(arr_i) num_arrows_left -= 1 return render_arrows(lines)
hankcs/HanLP
[ 28293, 7950, 28293, 9, 1412836576 ]
def render_span(begin, end, unidirectional=False): if end - begin == 1: return ['───►'] elif end - begin == 2: return [ '──┐', '──┴►', ] if unidirectional else [ '◄─┐', '◄─┴►', ] rows = [] for i in range(begin, end): if i == (end - begin) // 2 + begin: rows.append(' β”œβ–Ί') elif i == begin: rows.append('──┐' if unidirectional else '◄─┐') elif i == end - 1: rows.append('β”€β”€β”˜' if unidirectional else 'β—„β”€β”˜') else: rows.append(' β”‚') return rows
hankcs/HanLP
[ 28293, 7950, 28293, 9, 1412836576 ]
def list_to_tree(L): if isinstance(L, str): return L return Tree(L[0], [list_to_tree(child) for child in L[1]])
hankcs/HanLP
[ 28293, 7950, 28293, 9, 1412836576 ]
def main(): # arrows = [{'from': 1, 'to': 0}, {'from': 2, 'to': 1}, {'from': 2, 'to': 4}, {'from': 2, 'to': 5}, # {'from': 4, 'to': 3}] # lines = pretty_tree_horizontal(arrows) # print('\n'.join(lines)) # print('\n'.join([ # '◄─┐', # ' β”‚', # ' β”œβ–Ί', # ' β”‚', # 'β—„β”€β”˜', # ])) print('\n'.join(render_span(7, 12)))
hankcs/HanLP
[ 28293, 7950, 28293, 9, 1412836576 ]
def evalute_field(record, field_spec): """Evalute a field of a record using the type of the field_spec as a guide. Args: record: field_spec: Returns: """ if type(field_spec) is int: return str(record[field_spec]) elif type(field_spec) is str: return str(getattr(record, field_spec)) else: return str(field_spec(record))
hankcs/HanLP
[ 28293, 7950, 28293, 9, 1412836576 ]
def __init__(self, action: str = None) -> None: super().__init__(prefix, action)
cloudtools/awacs
[ 386, 98, 386, 14, 1364415387 ]
def __init__(self, resource: str = "", region: str = "", account: str = "") -> None: super().__init__( service=prefix, resource=resource, region=region, account=account )
cloudtools/awacs
[ 386, 98, 386, 14, 1364415387 ]
def test_read_filtered_data(compression, shuffle, fletcher32, gzip_level): # Make the filters dict. filts = {'compression': compression, 'shuffle': shuffle, 'fletcher32': fletcher32} if compression == 'gzip': filts['compression_opts'] = gzip_level # Make some random data. dims = random.randint(1, 4) data = random_numpy(shape=random_numpy_shape(dims, max_array_axis_length), dtype=random.choice(tuple( set(dtypes) - set(['U'])))) # Make a random name. name = random_name() # Write the data to the file with the given name with the provided # filters and read it back. with tempfile.TemporaryDirectory() as folder: filename = os.path.join(folder, 'data.h5') with h5py.File(filename, mode='w') as f: f.create_dataset(name, data=data, chunks=True, **filts) out = hdf5storage.read(path=name, filename=filename, matlab_compatible=False) # Compare assert_equal(out, data)
frejanordsiek/hdf5storage
[ 73, 20, 73, 16, 1387523795 ]
def test_write_filtered_data(compression, shuffle, fletcher32, gzip_level): # Make some random data. The dtype must be restricted so that it can # be read back reliably. dims = random.randint(1, 4) dts = tuple(set(dtypes) - set(['U', 'S', 'bool', 'complex64', \ 'complex128'])) data = random_numpy(shape=random_numpy_shape(dims, max_array_axis_length), dtype=random.choice(dts)) # Make a random name. name = random_name() # Write the data to the file with the given name with the provided # filters and read it back. with tempfile.TemporaryDirectory() as folder: filename = os.path.join(folder, 'data.h5') hdf5storage.write(data, path=name, filename=filename, store_python_metadata=False, matlab_compatible=False, compress=True, compress_size_threshold=0, compression_algorithm=compression, gzip_compression_level=gzip_level, shuffle_filter=shuffle, compressed_fletcher32_filter=fletcher32) with h5py.File(filename, mode='r') as f: d = f[name] filts = {'fletcher32': d.fletcher32, 'shuffle': d.shuffle, 'compression': d.compression, 'gzip_level': d.compression_opts} out = d[...] # Check the filters assert fletcher32 == filts['fletcher32'] assert shuffle == filts['shuffle'] assert compression == filts['compression'] if compression == 'gzip': assert gzip_level == filts['gzip_level'] # Compare assert_equal(out, data)
frejanordsiek/hdf5storage
[ 73, 20, 73, 16, 1387523795 ]
def get_dependencies(): dep_file = path.join(HERE, 'requirements.in') if not path.isfile(dep_file): return [] with open(dep_file, encoding='utf-8') as f: return f.readlines()
DataDog/integrations-extras
[ 193, 546, 193, 29, 1455263728 ]
def mock_execute(args, **kwargs): return 'SEARCH_DIR("/dir1")\nSEARCH_DIR("=/dir2")\n'
jimporter/bfg9000
[ 68, 20, 68, 13, 1424839632 ]
def __init__(self, *args, **kwargs): super().__init__(clear_variables=True, *args, **kwargs)
jimporter/bfg9000
[ 68, 20, 68, 13, 1424839632 ]
def test_lang(self): class MockBuilder: lang = 'c++' ld = LdLinker(MockBuilder(), self.env, ['ld'], 'version') self.assertEqual(ld.lang, 'c++')
jimporter/bfg9000
[ 68, 20, 68, 13, 1424839632 ]
def test_gnu_ld(self): version = 'GNU ld (GNU Binutils for Ubuntu) 2.26.1' ld = LdLinker(None, self.env, ['ld'], version) self.assertEqual(ld.brand, 'bfd') self.assertEqual(ld.version, Version('2.26.1'))
jimporter/bfg9000
[ 68, 20, 68, 13, 1424839632 ]
def test_unknown_brand(self): version = 'unknown' ld = LdLinker(None, self.env, ['ld'], version) self.assertEqual(ld.brand, 'unknown') self.assertEqual(ld.version, None)
jimporter/bfg9000
[ 68, 20, 68, 13, 1424839632 ]