code stringlengths 4 4.48k | docstring stringlengths 1 6.45k | _id stringlengths 24 24 |
|---|---|---|
def __getattr__(self, name): <NEW_LINE> <INDENT> if name.startswith('configure_fetchmail_'): <NEW_LINE> <INDENT> return (lambda self: self.configure_fetchmail(name[10:])) <NEW_LINE> <DEDENT> return super(fetchmail_config_settings, self).__getattr__(name) | catch calls to 'configure_fetchmail_XXX' | 625941d8d8ef3951e32437b0 |
def simplify(expr): <NEW_LINE> <INDENT> expr = propagate(expr, (None, True)) <NEW_LINE> if type(expr) == bool: <NEW_LINE> <INDENT> return PBB.mk_const_expr(expr) <NEW_LINE> <DEDENT> return expr | Tries to simplify expressions very niavely. | 625941d87d847024c06be531 |
def __init__(self): <NEW_LINE> <INDENT> pass | Dummy
:return: | 625941d83c8af77a43ae3a14 |
def diffusion3d(i): <NEW_LINE> <INDENT> return random.randrange(L-w+1) | Choose a position at random | 625941d8e64d504609d74ab3 |
def test_check_mandatory_keys_method_call(self): <NEW_LINE> <INDENT> broken_method_call = { "class_context": "test" } <NEW_LINE> self.assertRaises(ncf.NcfError, ncf.check_technique_method_call, "test_bundle", broken_method_call) | Test if a broken metadata raise a correct NcfError exception | 625941d81f5feb6acb0c4dbf |
def len2(seq): <NEW_LINE> <INDENT> if not isinstance(seq, _Seqs): <NEW_LINE> <INDENT> seq = list(seq) <NEW_LINE> <DEDENT> return len(seq), seq | Make built-in function L{len} work for generators, iterators,
etc. since those can only be started exactly once.
@param seq: Generator, iterator, list, range, tuple, etc.
@return: 2-Tuple (number, ...) of items (C{int}, C{list} or
C{range} or C{tuple}). | 625941d85e10d32532c5f199 |
def open_file(name_or_obj,mode='rb'): <NEW_LINE> <INDENT> fd = name_or_obj <NEW_LINE> close_file = False <NEW_LINE> if isinstance(fd,basestring): <NEW_LINE> <INDENT> fd = open(fd,mode=mode) <NEW_LINE> close_file = True <NEW_LINE> <DEDENT> return fd, close_file | return an open file object from a filename or open file object
If a new file object was opened, it the return variable close_file
will be True. | 625941d88a349b6b435e83e6 |
def test_quick_sort_sorts_small_list(): <NEW_LINE> <INDENT> from quick import quick_sort <NEW_LINE> assert quick_sort([4, 10, 7, 1, 9]) == [1, 4, 7, 9, 10] | Test that quick sort sorts small list. | 625941d83c8af77a43ae3a15 |
def canParse(self, data, unitSize=AbstractType.defaultUnitSize(), endianness=AbstractType.defaultEndianness(), sign=AbstractType.defaultSign()): <NEW_LINE> <INDENT> if data is None: <NEW_LINE> <INDENT> raise TypeError("data cannot be None") <NEW_LINE> <DEDENT> if len(data) == 0: <NEW_LINE> <INDENT> return False <NEW_LI... | This method returns True if data is a Integer.
For the moment its always true because we consider
the integer type to be very similar to the raw type.
>>> from netzob.all import *
>>> Integer().canParse(TypeConverter.convert("hello netzob", ASCII, Raw))
True
:param data: the data to check
:type data: python raw
:retu... | 625941d84e4d5625662d4648 |
def is_modular_correspondence(self,A,verbose=0): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> if not hasattr(A,"a"): <NEW_LINE> <INDENT> a=A[0,0]; b=A[0,1]; c=A[1,0]; d=A[1,1] <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> a=A.a(); b=A.b(); c=A.c(); d=A.d() <NEW_LINE> <DEDENT> <DEDENT> except TypeError: <NEW_LINE> <INDE... | Check if A is a modular correspondence for self. That is, if A is in PGL(2,Z) s.t. A^2 in self
and A preserves cusp classes. | 625941d810dbd63aa1bd2e15 |
def kumo_brekaut_02(row): <NEW_LINE> <INDENT> global BUDZET <NEW_LINE> global TRANS_ID <NEW_LINE> global TRANS <NEW_LINE> global COUNT <NEW_LINE> global STOCK <NEW_LINE> global data <NEW_LINE> global BE_VERBOSE <NEW_LINE> if not TRANS.in_transaction: <NEW_LINE> <INDENT> condition = True <NEW_LINE> if ((row['kumo'] == 1... | Kumo breakout modified, removed c_1 > c_26
1.
total: 34600.39, percent: 31.74%, years: 10, percent/year: 3.17%,
number -: 60, sum -: -20757.86, number +: 49, sum +: 55358.25, ATR_RAIO: 0.5
2. | 625941d894891a1f4081bd1d |
def vote(predict, vote_num, pred, points_idx): <NEW_LINE> <INDENT> bs, np = points_idx.shape <NEW_LINE> for i in range(bs): <NEW_LINE> <INDENT> for j in range(np): <NEW_LINE> <INDENT> pred_ = pred[i, j, :] <NEW_LINE> pidx_ = points_idx[i, j] <NEW_LINE> predict[pidx_, :] += pred_ <NEW_LINE> vote_num[pidx_, 0] += 1 <NEW_... | numpy array
:param predict: (pn,21) float
:param vote_num: (pn,1) int
:param pred: (bs,np,21) float
:param points_idx: (bs,np) int | 625941d8d6c5a102081442bf |
def __init__(self, cursor_id : int , restore_normal_cursor: bool = True ) -> None: <NEW_LINE> <INDENT> self._restore_normal_cursor = restore_normal_cursor <NEW_LINE> self._cursor_id = cursor_id | Constructor.
Args:
cursor_id: int
The applicative identifier of this cursor.
restore_normal_cursor: bool
Set this to True to restore the 'normal' cursor
image after deletion of this cursor. Set this
to False to not restore the 'normal' cursor
otherwise. Defaults to... | 625941d84a966d76dd551284 |
def input_sex() -> bool: <NEW_LINE> <INDENT> while True: <NEW_LINE> <INDENT> sex = input('Enter your biological sex (m/f):\n') <NEW_LINE> if sex in valid_f_sex: <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> elif sex in valid_m_sex: <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> pri... | Input and validate biological sex | 625941d8e76e3b2f99f3aa7b |
def send_skate_dates_email(): <NEW_LINE> <INDENT> recipients = Profile.objects.filter( womens_hockey_email=True).select_related('user') <NEW_LINE> for recipient in recipients: <NEW_LINE> <INDENT> if recipient.user.is_active: <NEW_LINE> <INDENT> to_email = [recipient.user.email] <NEW_LINE> from_email = 'no-reply@mg.oicw... | Sends email to Users letting them know when Womens Hockey skate dates are added. | 625941d8a219f33f34628bda |
def update_function_type_variables(self, fun_type: CallableType, defn: FuncItem) -> None: <NEW_LINE> <INDENT> with self.tvar_scope_frame(self.tvar_scope.method_frame()): <NEW_LINE> <INDENT> a = self.type_analyzer() <NEW_LINE> fun_type.variables = a.bind_function_type_variables(fun_type, defn) | Make any type variables in the signature of defn explicit.
Update the signature of defn to contain type variable definitions
if defn is generic. | 625941d88e05c05ec3eea5e9 |
def case8(self,glyph): <NEW_LINE> <INDENT> point_list = list() <NEW_LINE> first = list() <NEW_LINE> middle = list() <NEW_LINE> final = list() <NEW_LINE> output = list() <NEW_LINE> for i in range(0,len(glyph.contours)): <NEW_LINE> <INDENT> if self.infoDict["final label4"] == self.infoDict[glyph.name + '/' + str(i)]: <N... | 종성O , 중성 그룹5 | 625941d84e696a04525c96bf |
def _spawnProcess(self, proto, sibling, *args, **kw): <NEW_LINE> <INDENT> args = [sys.executable, b"-m", b"twisted.test." + sibling, reactor.__class__.__module__] + list(args) <NEW_LINE> return reactor.spawnProcess( proto, sys.executable, args, env=properEnv, **kw) | Launch a child Python process and communicate with it using the
given ProcessProtocol.
@param proto: A L{ProcessProtocol} instance which will be connected
to the child process.
@param sibling: The basename of a file containing the Python program
to run in the child process.
@param *args: strings which will be passed... | 625941d866656f66f7cbc41f |
def provideUtility(providedInterface, component, name='', info=''): <NEW_LINE> <INDENT> pass | Provide a utility
A utility is a component that provides an interface. | 625941d8eab8aa0e5d26ddcc |
def draw_graph(g,image_idx): <NEW_LINE> <INDENT> image_name = 'https://s3-us-west-1.amazonaws.com/facesdb/mutrk_db_fixed/' + str(image_idx) + '/original.jpg' <NEW_LINE> dir_name = 'graphs' <NEW_LINE> if not os.path.isdir(dir_name): <NEW_LINE> <INDENT> os.makedirs(dir_name) <NEW_LINE> <DEDENT> node_map = relabel_nodes(g... | Generates visualization for the pairwise graph
DEBUG-ONLY feature | 625941d8d99f1b3c44c677ff |
def copy_subject(sub): <NEW_LINE> <INDENT> newSub = { 'init': np.copy(sub['init']), 'proteins': sub['proteins'], 'alphas': np.copy(sub['alphas']), 'M': np.copy(sub['M']), 'type': np.copy(sub['type']), 'Kd': np.copy(sub['Kd']), 'deg_type': np.copy(sub['deg_type']), 'deltas': np.copy(sub['deltas']), 'Km': np.copy(sub['Km... | Kopiranje osebka
:param sub: Osebek ki ga kopiramo
:return: Nov kopiran osebek | 625941d85e10d32532c5f19a |
def generate(self): <NEW_LINE> <INDENT> macros = [] <NEW_LINE> i = 1 <NEW_LINE> for prefix, cmd, suffix, label, in self._commands: <NEW_LINE> <INDENT> if not cmd: <NEW_LINE> <INDENT> continue <NEW_LINE> <DEDENT> macros.append( Macro(cmd, sequence=i, prefix=prefix, suffix=suffix, label=label) ) <NEW_LINE> i += 1 <NEW_LI... | Generates Macro objects based on the commands supplied to the MacroFactory.
:rtype: list[Macro]
:return: A list of generated Macro objects. | 625941d8ab23a570cc2503f7 |
def test(): <NEW_LINE> <INDENT> active_context_manager = MyContextManager() <NEW_LINE> inactive_context_manager = MyContextManager() <NEW_LINE> iterator = iter_with(range(5), active_context_manager) <NEW_LINE> for i, j in zip(iterator, range(5)): <NEW_LINE> <INDENT> assert i == j == active_context_manager.counter <NEW_... | Test the basic workings of `iter_with`. | 625941d8fb3f5b602dac3909 |
def do_show_templates(self, args): <NEW_LINE> <INDENT> cmd.Cmd.onecmd(self, 'show_template "*"') | DESCRIPTION:
This command shows all templates defined in the system.
COMMAND:
show_templates | 625941d8507cdc57c6306f53 |
def GetPolicyDynamics(P, R, pi): <NEW_LINE> <INDENT> if P.ndim != 3 or R.ndim != 2 or pi.ndim != 2: <NEW_LINE> <INDENT> raise AssertionError('Invalid input') <NEW_LINE> <DEDENT> nS = P.shape[0] <NEW_LINE> nA = P.shape[1] <NEW_LINE> P_pi = np.zeros((nS, nS)) <NEW_LINE> R_pi = np.zeros((nS)) <NEW_LINE> for i in range(nS)... | Calculate the dynamics when following the policy pi
Parameters:
P: [nS x nA x nS] transitions probabilities matrix P_{s,a,s'}=P(s'|s,a)
R: [nS x nA] mean rewards matrix R
pi: [nS x nA] matrix representing pi(a|s)
Returns:
P_pi: [nS x nS] transitions matrix when following the policy pi (P_pi)_{s,s'} P^pi(s'|s... | 625941d8462c4b4f79d1d943 |
def clear_streams(self): <NEW_LINE> <INDENT> self.streams = [] <NEW_LINE> for host in self.hosts.values(): <NEW_LINE> <INDENT> host.clear_streams() | Stop and remove all streams.
| 625941d87c178a314d6ef6d6 |
def use_filter(filter_func, url, input): <NEW_LINE> <INDENT> output = filter_func(url, input) <NEW_LINE> if output is None: <NEW_LINE> <INDENT> return input <NEW_LINE> <DEDENT> return output | Apply a filter function to input from an URL | 625941d8fbf16365ca6f643a |
def rotation_root_2angle(r): <NEW_LINE> <INDENT> sy = np.sqrt(r[0, 0] ** 2 + r[1, 0] ** 2) <NEW_LINE> rotate_angle = np.array([0.0, 0.0, 0.0]) <NEW_LINE> singular = sy < 1e-6 <NEW_LINE> if not singular: <NEW_LINE> <INDENT> rotate_angle[0] = math.atan2(r[2, 1], r[2, 2]) / np.pi * 180.0 <NEW_LINE> rotate_angle[1] = math.... | :param r: rotation matrix
:return: euler angle in radian | 625941d8d58c6744b4257ed2 |
def getDebug(self): <NEW_LINE> <INDENT> return self.iDebug; | Returns the current debug level. | 625941d826238365f5f0f0e5 |
def onClose(self): <NEW_LINE> <INDENT> self._rssRecorder.close() <NEW_LINE> RDPClientQt.onClose(self) | @summary: Call when stack is close | 625941d8e8904600ed9f21a3 |
def standardize(self, value): <NEW_LINE> <INDENT> return self._processValue(value, self.standardprocessors) | Converts the value from any form (input form, db form) into a form that's
friendly for the user to access via dot notation or dict-like notation in a
Document object. (i.e. standard form) (example: string to unicode etc.)
This method will be called on __setattr__.
Must be able to handle None.
Args:
value: The valu... | 625941d8a17c0f6771cbe2c3 |
@pytest.mark.tier1 <NEW_LINE> def test_positive_end_to_end_crud(module_org, module_location, module_hostgroup): <NEW_LINE> <INDENT> searches = [ 'CPU_Count = 1', 'disk_count < 5', 'memory > 500', 'model = KVM', 'Organization = Default_Organization', ] <NEW_LINE> name = gen_choice(list(valid_data_list().values())) <NEW_... | Create a new discovery rule with several attributes, update them
and delete the rule itself.
:id: 25366930-b7f4-4db8-a9c3-a470fe4f3583
:expectedresults: Rule should be created, modified and deleted successfully
with given attributes.
:CaseImportance: Critical | 625941d8d268445f265b50e2 |
def solarized(color_str): <NEW_LINE> <INDENT> sol_colors = { 'base03': '#002b36', 'base02': '#073642', 'base01': '#586e75', 'base00': '#657b83', 'base0': '#839496', 'base1': '#93a1a1', 'base2': '#eee8d5', 'base3': '#fdf6e3', 'yellow': '#b58900', 'orange': '#cb4b16', 'red': '#dc322f', 'magen... | return dictionary value if it exists, otherwise raise KeyError | 625941d83539df3088e2e5be |
def test_get_all_cities(self): <NEW_LINE> <INDENT> self.client.get('http://localhost:5000/weather/london') <NEW_LINE> self.client.get('http://localhost:5000/weather/paris') <NEW_LINE> self.client.get('http://localhost:5000/weather/porto') <NEW_LINE> response = self.client.get('http://localhost:5000/weather?max=5') <NEW... | Test if return the correct response quantity
with different max queries | 625941d87b180e01f3dc4a6d |
def condition(*args, **kwargs): <NEW_LINE> <INDENT> pass | This command creates a new named condition object whose true/false value is calculated by running a mel script.
Returns: None | 625941d866673b3332b92305 |
def centroid_distance(dimer): <NEW_LINE> <INDENT> cent_1=ha.find_centroid(dimer[0:int(len(dimer)/2)]) <NEW_LINE> cent_2=ha.find_centroid(dimer[int(len(dimer)/2):len(dimer)]) <NEW_LINE> return ds.vector_distance(cent_1[0],cent_1[1],cent_1[2],cent_2[0],cent_2[1],cent_2[2]) | Calculates the centroid distances between two molecules of a dimer | 625941d8460517430c3943f4 |
def var_fraction ( a , b , name = '' , title = '' ) : <NEW_LINE> <INDENT> f1 = isinstance ( v1 , num_types ) <NEW_LINE> f2 = isinstance ( v2 , num_types ) <NEW_LINE> if f1 and f2 : <NEW_LINE> <INDENT> r = float ( v1) / ( float ( v1 ) + float ( v1 ) ) <NEW_LINE> return ROOT.RooRealConstant.value ( r ) <NEW_LINE> <DEDENT... | ``Fraction'' f(x) = a/(a+b)
>>> a = ...
>>> b = ...
>>> e = var_fraction ( a , b ) | 625941d8dd821e528d63b41b |
def bajacli(dni): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> conexion.cur.execute('delete from clientes where dni = ?', (dni,)) <NEW_LINE> conexion.conex.commit() <NEW_LINE> <DEDENT> except sqlite3.OperationalError as e: <NEW_LINE> <INDENT> print(e) <NEW_LINE> conexion.conex.rollback() | Elimina un cliente de la base de datos.
:param dni: dni del cliente a borrar
:return: void
Excepciones: Error de operación en SQLite, muestra el error y hace rollback | 625941d829b78933be1e591c |
def transform(self, input_df): <NEW_LINE> <INDENT> _df = input_df.copy(deep=False) <NEW_LINE> for column in self.cat_columns: <NEW_LINE> <INDENT> if column not in _df: <NEW_LINE> <INDENT> raise RuntimeError('Required column {:s} not found'.format(column)) <NEW_LINE> <DEDENT> if _df[column].dtype == 'object': <NEW_LINE>... | Convert the dataframe to a matrix (numpy ndarray)
Args:
input_df (dataframe): The dataframe to convert | 625941d8cb5e8a47e48b7d1b |
def publish_to_iot_core(self, *, topic_name: typing.Optional[str] = None, qos: typing.Optional[str] = None, payload: typing.Optional[typing.Union[bytes, str]] = None) -> model.PublishToIoTCoreResponse: <NEW_LINE> <INDENT> return self.publish_to_iot_core_async(topic_name=topic_name, qos=qos, payload=payload).result() | Perform the PublishToIoTCore operation synchronously.
Args:
topic_name:
qos: QOS enum value
payload: | 625941d87d43ff24873a2f15 |
def test_reverseColormap(cartavisInstance, tempImageDir, cleanSlate): <NEW_LINE> <INDENT> imageName = 'mexinputtest_cubehelix_reversed.png' <NEW_LINE> i = cartavisInstance.getImageViews() <NEW_LINE> c = cartavisInstance.getColormapViews() <NEW_LINE> i[0].loadFile(os.getcwd() + '/data/mexinputtest.fits') <NEW_LINE> c[0]... | Test that the colormap is reversed properly. | 625941d8a4f1c619b28b02a9 |
def aggregate_quantiles_r(bag: List[pd.DataFrame], quantiles: Iterable[float]) -> pd.DataFrame: <NEW_LINE> <INDENT> all_samples = pd.concat([r_sample for r_sample in bag], axis=0) <NEW_LINE> all_samples['R_mean'] = all_samples.a_posterior * all_samples.b_posterior <NEW_LINE> all_samples['R_var'] = all_samples.a_posteri... | Compute median quantiles of many samples of R | 625941d8a934411ee3751908 |
def peakIndexInMountainArray(self, A): <NEW_LINE> <INDENT> if(len(A) >= 3): <NEW_LINE> <INDENT> i = A.index(max(A)) <NEW_LINE> <DEDENT> return i | :type A: List[int]
:rtype: int | 625941d863d6d428bbe44764 |
def update(self, other): <NEW_LINE> <INDENT> self.max_word_num = max(self.max_word_num, other.max_word_num) <NEW_LINE> self.max_word_length = max(self.max_word_length, other.max_word_length) <NEW_LINE> self.max_ui_object_num = max(self.max_ui_object_num, other.max_ui_object_num) <NEW_LINE> self.max_ui_object_word_num =... | Update max value from another MaxValues instance.
This will be used when want to merge several MaxValues instances:
max_values_list = ...
result = MaxValues()
for v in max_values_list:
result.update(v)
Then `result` contains merged max values in each field.
Args:
other: another MaxValues instance, conta... | 625941d8498bea3a759b9d23 |
def test_create_os(self): <NEW_LINE> <INDENT> name = generate_name(6) <NEW_LINE> major_version = generate_string('numeric', 1) <NEW_LINE> minor_version = generate_string('numeric', 1) <NEW_LINE> os_family = "Redhat" <NEW_LINE> self.login.login(self.katello_user, self.katello_passwd) <NEW_LINE> self.navigator.go_to_oper... | create new OS | 625941d807f4c71912b116f8 |
def get_agencies(self): <NEW_LINE> <INDENT> available_agencies = [agency.source_key for agency in self.session.query(Agency).all()] <NEW_LINE> return set(available_agencies) | Returns a set containing the measure agencies. | 625941d891f36d47f21ac768 |
def c2s_get_realtime_pvp_state(self): <NEW_LINE> <INDENT> c2s = realtime_PVP_pb2.c2s_get_realtime_pvp_state() <NEW_LINE> return c2s | 获取实时pvp状态
:param: 不需要参数 | 625941d82eb69b55b151cb26 |
def __init__(self, id=None, name=None, bio_security=None, ordinal=None): <NEW_LINE> <INDENT> self._id = None <NEW_LINE> self._name = None <NEW_LINE> self._bio_security = None <NEW_LINE> self._ordinal = None <NEW_LINE> self.discriminator = None <NEW_LINE> if id is not None: <NEW_LINE> <INDENT> self.id = id <NEW_LINE> <D... | Location - a model defined in Swagger | 625941d8f9cc0f698b14086e |
def non_leaf_handler(self,lcache): <NEW_LINE> <INDENT> desc = self.leaf <NEW_LINE> pdesc = self.pdesc <NEW_LINE> desc['leaf'] = False <NEW_LINE> pdesc['non_leaf_son_paths'].append(copy.deepcopy(desc['path'])) <NEW_LINE> lcache.ndata.append(self.data) <NEW_LINE> lcache.ndesc.append(desc) | #nonleaf child handler | 625941d83eb6a72ae02ec756 |
def setUp(self): <NEW_LINE> <INDENT> super(CertificateSearchTests, self).setUp() <NEW_LINE> self.course = CourseFactory( org=self.CERT_COURSE_KEY.org, course=self.CERT_COURSE_KEY.course, run=self.CERT_COURSE_KEY.run, ) <NEW_LINE> self.course.cert_html_view_enabled = True <NEW_LINE> certificates = [ { 'id': 1, 'name': '... | Create a course | 625941d857b8e32f52483710 |
def __init__(self, data): <NEW_LINE> <INDENT> self.name = data.get('name') <NEW_LINE> self.email = data.get('email') <NEW_LINE> self.password = self._generate_hash(data.get('password')) <NEW_LINE> self.fav_poke = data.get('fav_poke') | takes in a json request body
and parses to instance attributes
password gets generated into a bcrypt
hash before storage | 625941d8d18da76e2353274c |
def test_post(self): <NEW_LINE> <INDENT> self.assertEqual(Entry.objects.count(), 1) <NEW_LINE> self.client.login(username=self.user.username, password='test') <NEW_LINE> self.client.delete(self.url) <NEW_LINE> self.assertEqual(Entry.objects.count(), 0) | Also deletes | 625941d88a43f66fc4b542d7 |
def __init__(self, kek_datum): <NEW_LINE> <INDENT> self.kek_label = kek_datum.kek_label <NEW_LINE> self.plugin_name = kek_datum.plugin_name <NEW_LINE> self.algorithm = kek_datum.algorithm <NEW_LINE> self.bit_length = kek_datum.bit_length <NEW_LINE> self.mode = kek_datum.mode <NEW_LINE> self.plugin_meta = kek_datum.plug... | Plugins should not have to create their own instance of this class.
kek_datum is typically a barbican.model.models.KEKDatum instance. | 625941d83346ee7daa2b2fe1 |
def minPathSum(self, grid): <NEW_LINE> <INDENT> if len(grid) == 0 or len(grid[0]) == 0: <NEW_LINE> <INDENT> return 0 <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> dp = [[0 for _ in range(len(grid[0]))] for _ in range(len(grid))] <NEW_LINE> dp[0][0] = grid[0][0] <NEW_LINE> for i in range(len(grid)): <NEW_LINE> <INDENT> ... | :type grid: List[List[int]]
:rtype: int | 625941d8ec188e330fd5aa0f |
def get_thumbnail_by_screen(self, screen): <NEW_LINE> <INDENT> return self.home_photo.image[ "{screen}_{shape}".format(screen=screen, shape=self.home_photo.get_shape_display()) ].url | Devuelve el thumbnail según la resolución y al forma de la foto | 625941d894891a1f4081bd1e |
def set_misc_options(self): <NEW_LINE> <INDENT> log.info("Setting miscellaneous analysis options ...") <NEW_LINE> self.analysis_options.misc.path = self.misc_path <NEW_LINE> self.analysis_options.misc.fluxes = True <NEW_LINE> self.analysis_options.misc.images = True <NEW_LINE> self.analysis_options.misc.write_intermedi... | This function ...
:return: | 625941d8adb09d7d5db6ca03 |
def turn_on_auto_takeoff(self): <NEW_LINE> <INDENT> command_tuple = self.command_parser.get_command_tuple("minidrone", "Piloting", "AutoTakeOffMode") <NEW_LINE> return self.drone_connection.send_param_command_packet(command_tuple, param_tuple=[1], param_type_tuple=["u8"]) | Turn on the auto take off (throw mode)
:return: True if the command was sent and False otherwise | 625941d8e1aae11d1e749f2d |
def __init__(self, server_addr, sock, event, version = V_SOCKS5, logger = None): <NEW_LINE> <INDENT> if ((logger and not isinstance(logger, logging.Logger)) or not isinstance(sock, socket.socket) or version not in _VERSIONS): <NEW_LINE> <INDENT> raise ValueError("Recieved invalid argument.") <NEW_LINE> <DEDENT> if not ... | Initialize instance variables.
sock must be a connected TCP socket (if SOCKS server use Forwarder sock
need to be TCP socket connected to the SOCKS client). If a SocksClient
object use Forwarder the sock need to be the SockSocket.
version is theSOCKS version.
logger must be a configured logging.Logger object or None | 625941d89c8ee82313fbb9ea |
def get_doBackup(self): <NEW_LINE> <INDENT> odir = self.desc.getConf_dir() + 'backups/' <NEW_LINE> outfile, msg = self.do_backup(params.confdir, odir, self.excl_conf) <NEW_LINE> self['backups'] = os.path.basename(outfile) <NEW_LINE> return msg | Perform configuration backup. | 625941d8287bf620b61d3cd7 |
def addText(o, inText, key='StandardParseBODYKEY'): <NEW_LINE> <INDENT> if key in o.keyValueReplacementList: <NEW_LINE> <INDENT> o.keyValueReplacementList[key] = o.keyValueReplacementList[key] + inText <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> o.keyValueReplacementList[key] = inText <NEW_LINE> o.usedKeys.append(key... | Because its LaTeX everything boils down to adding text at
the correct position. So each method will just prepare the text and
use ultimately THIS method to queue it in the insertion queue via the
dictionary KEY VALUE combination.
:param inText:
:param key:
:return: | 625941d8442bda511e8be68a |
def dense_to_one_hot(labels_dense, n_class): <NEW_LINE> <INDENT> num_labels = labels_dense.shape[0] <NEW_LINE> index_offset = numpy.arange(num_labels) * n_class <NEW_LINE> labels_one_hot = numpy.zeros((num_labels, n_class)) <NEW_LINE> labels_one_hot.flat[index_offset + labels_dense.ravel()] = 1 <NEW_LINE> return labels... | Convert class labels from scalars to one-hot vectors.
:param labels_dense: dense labels
:param n_class: number of classes | 625941d8596a897236089d33 |
def __init__(self, smiles=None, smiles_file=None, vocab_file=None, training_split=0.9): <NEW_LINE> <INDENT> if smiles: <NEW_LINE> <INDENT> self.smiles = smiles <NEW_LINE> <DEDENT> elif smiles_file: <NEW_LINE> <INDENT> self.smiles = read_smiles(smiles_file) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> raise ValueError(... | Can be initiated from either a list of SMILES, or a line-delimited
file.
Args:
smiles (list): the complete set of SMILES that constitute the
training dataset
smiles_file (string): line-delimited file containing the complete
set of SMILES that constitute the training dataset
vocab_file (string):... | 625941d83eb6a72ae02ec757 |
def basic(arrei): <NEW_LINE> <INDENT> if not len(arrei): <NEW_LINE> <INDENT> logging.error("There is no data to comute stats; given array is empty.") <NEW_LINE> return None <NEW_LINE> <DEDENT> from collections import OrderedDict <NEW_LINE> sts = OrderedDict() <NEW_LINE> sts['length'] = len(arrei) <NEW_LINE> if all([ ha... | Outputs in a dictionary:
- min
- max
- mean
- std
- quantiles (1,2,3) | 625941d885dfad0860c3b0d0 |
def attach(self, tasklet): <NEW_LINE> <INDENT> self.runtime.tasklet = tasklet <NEW_LINE> self.runtime.update(dict(timeout=self.timeout, cnt=0)) | Attach task to tasklet
:param tasklet:
:return: | 625941d8ff9c53063f47c467 |
def getTextLength(self): <NEW_LINE> <INDENT> return len(self.attack.name) | Return the printable length of the Entry's Text | 625941d871ff763f4b549904 |
def as_flight(self): <NEW_LINE> <INDENT> flight = rasp.Flight() <NEW_LINE> flight.rname = self.title <NEW_LINE> flight.ename = self.stages[0].enginefile <NEW_LINE> flight.verbose = self.mode > 0 <NEW_LINE> flight.site_alt = self.sitealt <NEW_LINE> flight.coast_base = self.coasttime <NEW_LINE> flight.base_temp = self.si... | convert RocketBat to Flight | 625941d857b8e32f52483711 |
def _get_report_data_with_builds(self, form, builds): <NEW_LINE> <INDENT> plans_count = self.plans_count(form) <NEW_LINE> runs_count = self.runs_count(form) <NEW_LINE> status_matrix = self.status_matrix_groupby_builds(form) <NEW_LINE> runs_subtotal = self.runs_subtotal_groupby_builds(form) <NEW_LINE> tested_by_ids = []... | Get report data when user selects one or more builds
@param form: the valid form containing report criteria
@type form: L{RunForm}
@param builds: selected builds by user
@type builds: list
@return: report data containing all necessary data grouped by selected
builds and tested_bys
@rtype: dict | 625941d80a50d4780f667108 |
def set_knowledge_for_pit_or_wumpus(self, obstacle, x, y): <NEW_LINE> <INDENT> sensory_input = "" <NEW_LINE> if obstacle == "P": <NEW_LINE> <INDENT> sensory_input = "B" <NEW_LINE> <DEDENT> elif obstacle == "W": <NEW_LINE> <INDENT> sensory_input = "S" <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> print("Obstacle %s does... | Takes coordinates of a possible obstacle and adds implications into
our knowledge base. | 625941d8187af65679ca5393 |
def custom_score_2(game, player): <NEW_LINE> <INDENT> if game.is_loser(player): <NEW_LINE> <INDENT> return float("-inf") <NEW_LINE> <DEDENT> if game.is_winner(player): <NEW_LINE> <INDENT> return float("inf") <NEW_LINE> <DEDENT> open_move = open_move_score(game, player) <NEW_LINE> correlated = improved_score(game, playe... | Calculate the heuristic value of a game state from the point of view
of the given player.
Note: this function should be called from within a Player instance as
`self.score()` -- you should not need to call this function directly.
Parameters
----------
game : `isolation.Board`
An instance of `isolation.Board` enco... | 625941d8187af65679ca5394 |
def call(self): <NEW_LINE> <INDENT> m = xmlrpclib.MultiCall(self.rt_obj._get_conn()) <NEW_LINE> for call in self.calls: <NEW_LINE> <INDENT> method, args = call <NEW_LINE> rpc_call = getattr(method, "rpc_call") <NEW_LINE> getattr(m, rpc_call)(*args) <NEW_LINE> <DEDENT> results = m() <NEW_LINE> results = tuple(results) <... | Execute added multicall calls
@return: the results (post-processed), in the order they were added
@rtype: tuple | 625941d8a8ecb033257d3341 |
def __TCP_connect(self, ip, port_number, delay, output, message): <NEW_LINE> <INDENT> curr_os = platform.system() <NEW_LINE> if curr_os == 'Windows': <NEW_LINE> <INDENT> TCP_sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) <NEW_LINE> TCP_sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) <NEW_LINE> TCP_... | Perform status checking for a given port on a given ip address using TCP handshake
:param ip: the ip address that is being scanned
:type ip: str
:param port_number: the port that is going to be checked
:type port_number: int
:param delay: the time in seconds that a TCP socket waits until timeout
:type delay: int
:para... | 625941d8a8370b7717052b13 |
def execute_script(self, script_content: str) -> Tuple[subprocess.CompletedProcess, str]: <NEW_LINE> <INDENT> cubemx_script_file, cubemx_script_name = tempfile.mkstemp() <NEW_LINE> try: <NEW_LINE> <INDENT> with open(cubemx_script_file, mode='w+b', buffering=0) as cubemx_script: <NEW_LINE> <INDENT> cubemx_script.write(s... | CubeMX can be fed with the script file to read commands from (see PDF manual). This method manages a temp file
for such script.
:param script_content: multi-line string
:return: tuple of subprocess.CompletedProcess instance and recorded STDOUT output | 625941d8d10714528d5fff5a |
def getDuplicatedGeomRecords(self, cl, geometryColumn, keyColumn): <NEW_LINE> <INDENT> self.checkAndOpenDb() <NEW_LINE> tupleList = [] <NEW_LINE> tableSchema, tableName = self.getTableSchema(cl) <NEW_LINE> sql = self.gen.getDuplicatedGeom(tableSchema, tableName, geometryColumn, keyColumn) <NEW_LINE> query = QSqlQuery(s... | Gets duplicated records
cl: class to be checked
geometryColumn: geometryColumn
keyColumn: pk column | 625941d8e64d504609d74ab5 |
def _sincfunc(x, dx, dampfac=3.25): <NEW_LINE> <INDENT> if dx != 0.0: <NEW_LINE> <INDENT> xx = (x+dx)*np.pi <NEW_LINE> return np.exp( -(xx/(dampfac*np.pi))**2 ) * np.sin(xx) / xx <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> xx = np.zeros(len(x)) <NEW_LINE> xx[len(x)//2] = 1.0 <NEW_LINE> return xx | sinc helper function for sincshift() | 625941d856ac1b37e6264441 |
def test(): <NEW_LINE> <INDENT> import doctest, pyproj <NEW_LINE> failure_count, test_count = doctest.testmod(pyproj,verbose=True) <NEW_LINE> return failure_count | run the examples in the docstrings using the doctest module | 625941d8cc40096d61595bc5 |
def proc_dam(filename): <NEW_LINE> <INDENT> with np.load(filename) as damobj: <NEW_LINE> <INDENT> damfile = damobj.items()[0][1].flatten() <NEW_LINE> <DEDENT> filename = os.path.basename(filename[:-12]+'.dam') <NEW_LINE> signals = [res.flatten() for res in damfile['signal']] <NEW_LINE> stimIndexes = [int(res[0, 0].toli... | Load an dam file that has already been processed by the official matlab
file converter. That matlab data is saved to an m-file, which is then
converted to a numpy '.npz' file. This numpy file is the file actually
loaded. This function converts it to a neo block and returns the block.
This block can be compared to th... | 625941d844b2445a33932309 |
def parse_args(func, querydict, alloy_empty: bool, *keys: str) -> list: <NEW_LINE> <INDENT> ret = [] <NEW_LINE> for key in keys: <NEW_LINE> <INDENT> if alloy_empty and not querydict.get(key): <NEW_LINE> <INDENT> ret.append(None) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> d = func(querydict.g... | парсит аргументы keys из querydict с помощью func (может быть parse_date, parse_time, parse_datetime) | 625941d823849d37ff7b3302 |
def rebuildNoiseReplacer(exposure, measCat): <NEW_LINE> <INDENT> algMetadata = measCat.getMetadata() <NEW_LINE> noiseReplacerConf = NoiseReplacerConfig() <NEW_LINE> noiseReplacerConf.noiseSeedMultiplier = algMetadata.getScalar(SFMT.NOISE_SEED_MULTIPLIER) <NEW_LINE> noiseReplacerConf.noiseSource = algMetadata.get... | Recreate the `NoiseReplacer` used in measurement.
Given a measurement catalog and the exposure on which the measurements
were made, reconstruct the `NoiseReplacer` object that was used to mask
out sources during measurement.
Parameters
----------
exposure : `lsst.afw.exposure.Exposure`
The image on which measurem... | 625941d892d797404e304400 |
def divideSeries(requestContext, dividendSeriesList, divisorSeriesList): <NEW_LINE> <INDENT> if len(divisorSeriesList) != 1: <NEW_LINE> <INDENT> raise ValueError( "divideSeries second argument must reference exactly 1 series") <NEW_LINE> <DEDENT> divisorSeries = divisorSeriesList[0] <NEW_LINE> results = [] <NEW_LINE> f... | Takes a dividend metric and a divisor metric and draws the division result.
A constant may *not* be passed. To divide by a constant, use the scale()
function (which is essentially a multiplication operation) and use the
inverse of the dividend. (Division by 8 = multiplication by 1/8 or 0.125)
Example::
&target=di... | 625941d8dc8b845886cb57ab |
def _create_agents(self): <NEW_LINE> <INDENT> prosumer_dict = {} <NEW_LINE> if self.complex_batt_pv_scenario == 1: <NEW_LINE> <INDENT> battery_nums = [50]*self.number_of_participants <NEW_LINE> pvsizes = [100]*self.number_of_participants <NEW_LINE> <DEDENT> elif self.complex_batt_pv_scenario ==2: <NEW_LINE> <INDENT> pv... | Purpose: Create the prosumers in the local energy market.
We create a market with n players, where n = self.number_of_participants
Args:
None
Returns:
prosumer_dict: Dictionary of prosumers | 625941d84c3428357757c59c |
def _generate_examples(self, file_names, dl_manager): <NEW_LINE> <INDENT> for fname in file_names: <NEW_LINE> <INDENT> folder, archive_name = os.path.split(fname) <NEW_LINE> speaker_id = archive_name.split('-')[0] <NEW_LINE> label_idx = folder.index('/Trunk') - 2 <NEW_LINE> label = folder[label_idx:label_idx + 2] <NEW_... | Yields examples. | 625941d856b00c62f0f148cf |
def center_quad_transform(quad, src_quad): <NEW_LINE> <INDENT> w = quad[2] - quad[0] <NEW_LINE> h = quad[3] - quad[1] <NEW_LINE> nw = src_quad[0:2] <NEW_LINE> sw = src_quad[2:4] <NEW_LINE> se = src_quad[4:6] <NEW_LINE> ne = src_quad[6:8] <NEW_LINE> x0, y0 = nw <NEW_LINE> As = 1.0 / w <NEW_LINE> At = 1.0 / h <NEW_LINE> ... | center_quad_transfrom transforms the center pixel coordinates
from ``quad`` to ``src_quad`` by using affine transformation
as used by PIL.Image.transform. | 625941d85166f23b2e1a53ce |
def findLengthOfLCIS(self, nums): <NEW_LINE> <INDENT> if len(nums) == 0 or nums is None: <NEW_LINE> <INDENT> return 0 <NEW_LINE> <DEDENT> n = len(nums) <NEW_LINE> dp = [1] * n <NEW_LINE> for i in range(1, n): <NEW_LINE> <INDENT> if nums[i] > nums[i-1]: <NEW_LINE> <INDENT> dp[i] = dp[i-1] + 1 <NEW_LINE> <DEDENT> <DEDENT... | :type nums: List[int]
:rtype: int | 625941d823849d37ff7b3303 |
def evaluate_hand(self): <NEW_LINE> <INDENT> points, has_ace = self.transform_cards_to_points() <NEW_LINE> if not points: <NEW_LINE> <INDENT> return 0, 0 <NEW_LINE> <DEDENT> if has_ace: <NEW_LINE> <INDENT> sum_with_small_ace = sum( 1 if point == 11 else point for point in points ) <NEW_LINE> sum_with_big_ace = sum( 11 ... | Method that computes the sum of the cards. | 625941d8cb5e8a47e48b7d1c |
def on_welcome(self, connection, event): <NEW_LINE> <INDENT> logging.info("! Connected to server '%s': %s", event.source, event.arguments[0]) <NEW_LINE> connection.join("#cohorte") | Server welcome: we're connected | 625941d87cff6e4e81117bfa |
@app.route('/items/add/', methods=['GET', 'POST']) <NEW_LINE> def addItem(): <NEW_LINE> <INDENT> if request.method == 'POST': <NEW_LINE> <INDENT> if 'username' not in login_session: <NEW_LINE> <INDENT> return redirect(url_for('showLogin')) <NEW_LINE> <DEDENT> if request.form.get('add', None) == 'add': <NEW_LINE> <INDEN... | Displays the add item page. | 625941d831939e2706e4d0dc |
def A_star_search(initial_state): <NEW_LINE> <INDENT> goal_state = [0,1,2,3,4,5,6,7,8] <NEW_LINE> frontier = Frontier() <NEW_LINE> frontierset = {} <NEW_LINE> frontiersetkeys = set() <NEW_LINE> maxdepth = 0 <NEW_LINE> curdepth = 0 <NEW_LINE> md = calculate_manhattan_dist(initial_state.config, 3) <NEW_LINE> frontier.ins... | A * search | 625941d88e05c05ec3eea5eb |
def ae83(order=2, **kwargs): <NEW_LINE> <INDENT> model = __get_ae_nd(order)(64, [3, 3, 3, 3, 3], block='bottleneck', **kwargs) <NEW_LINE> return model | Constructs a resnet.AE-83 model.
Configurations:
Network depth: 5
Network block: bottleneck
Stage details: [3, 3, 3, 3, 3]
First channel number: 64
Arguments:
order: the dimension of the network. For example, when
order=2, the nn.Conv2d would be used.
Other Arguments (see mdnc.modules.res... | 625941d8fff4ab517eb2f6b2 |
def test_uglify__filename(): <NEW_LINE> <INDENT> assert uglify.filename( 'Intel Core(TM) i7-7700 CPU') == 'intel_core_i7-7700_cpu' <NEW_LINE> assert uglify.filename('Intel(R) Xeon(R) Platinum 8180 CPU @ 2.50GHz' ) == 'intel_xeon_platinum_8180_cpu_2.50ghz' | uglify::filename | 625941d88c3a873295158631 |
def __str__(self): <NEW_LINE> <INDENT> return 'Failed to write file "%s"' % self.filepath | Return description of this error. | 625941d8d164cc6175782fc3 |
def parse_delete(self, read_id, alignment_position, length, ref_sequence): <NEW_LINE> <INDENT> start = alignment_position + 1 <NEW_LINE> stop = start + length <NEW_LINE> self.mismatch_count[alignment_position] += 1 <NEW_LINE> for i in range(start, stop): <NEW_LINE> <INDENT> self.base_dictionary[read_id][i] = ('.', MIN_... | Process a cigar operation that is a delete
:param alignment_position: Alignment position
:param length: Length of the delete
:param ref_sequence: Reference sequence of delete
:return:
This method updates the candidates dictionary. | 625941d896565a6dacc8f940 |
def post(self): <NEW_LINE> <INDENT> sid = str(uuid.uuid1()) <NEW_LINE> data = request.json['data'] <NEW_LINE> print(data) <NEW_LINE> folder = "/tmp/chemkin/webserver/{}".format(sid) <NEW_LINE> os.makedirs(folder, exist_ok=True) <NEW_LINE> with open(os.path.join(folder, "data.xml"), "w") as f: <NEW_LINE> <INDENT> f.writ... | Create a new session
Returns
-------
response containing session id and species list (if succeed) or failure information (if failed) | 625941d863f4b57ef0001389 |
def fetch_group_path(group): <NEW_LINE> <INDENT> group_key = group if group in DATASET_SYNONYMS else next( (key for (key, synonyms) in DATASET_SYNONYMS.items() if group in synonyms), group) <NEW_LINE> return get_node_tree().id, get_ip_by_handle(group_key) | given a group, finds the path in the Network that corresponds to it | 625941d866656f66f7cbc421 |
def __rmul__(self, other): <NEW_LINE> <INDENT> return self.__mul__(other) | Return a new AutoDiff object, which is a product of new AutoDiff object and the given AutoDiff object.
Implement a reverse product of __mul__().
EXAMPLES
=======
>>> a = AutoDiff(5)
>>> f = 2 * a
>>> print(f.val, f.der)
10 [2. 0. 0.] | 625941d8046cf37aa974cfbb |
def test_post_when_no_webresources(self): <NEW_LINE> <INDENT> self.webresource_1.delete() <NEW_LINE> self.webresource_2.delete() <NEW_LINE> response = self._post( json.dumps({ 'order': [ self.webresource_2.id, self.webresource_1.id ] }), self.admin ) <NEW_LINE> self.assertEqual(response.status_code, 404) | Test POST with with admin, when project has no web resources.
It should return 404 response. | 625941d807d97122c4178b05 |
def _get_patterns(installed_only=None): <NEW_LINE> <INDENT> patterns = {} <NEW_LINE> doc = dom.parseString(__salt__['cmd.run'](('zypper --xmlout se -t pattern'), output_loglevel='trace')) <NEW_LINE> for element in doc.getElementsByTagName('solvable'): <NEW_LINE> <INDENT> installed = element.getAttribute('status') == 'i... | List all known patterns in repos. | 625941d85e10d32532c5f19c |
def getInstalledExtensions(): <NEW_LINE> <INDENT> import imp <NEW_LINE> extensions = [] <NEW_LINE> for extension in getCSExtensions(): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> extension = '%sDIRAC' % extension <NEW_LINE> imp.find_module( extension ) <NEW_LINE> extensions.append( extension ) <NEW_LINE> <DEDENT> exce... | Return list of extensions registered in the CS and available in local installation | 625941d8d10714528d5fff5b |
def unique_id(): <NEW_LINE> <INDENT> return '_id_' + random_hash() | Call ``random_hash`` and prepend ``_id_`` to it. | 625941d810dbd63aa1bd2e18 |
def check_tokenizer(tokenize: Callable[[str], List[Word]]) -> None: <NEW_LINE> <INDENT> tokens = ["楽しい", "本", "を", "よく", "読み", "ます"] <NEW_LINE> conj_tokens = ["楽しい", "読み", "ます"] <NEW_LINE> words = tokenize("".join(tokens)) <NEW_LINE> if len(words) != len(tokens): <NEW_LINE> <INDENT> raise InvalidTokenizerError("/".join... | Check that the tokenize function is working properly.
Parameters
----------
tokenize : function
Tokenize function.
Returns
-------
None
Return None when the tokenize function is working properly.
Raises
------
InvalidTokenizerError
If the tokenize function is not working properly. | 625941d826238365f5f0f0e7 |
def run_ransac(self, index=None) -> np.ndarray: <NEW_LINE> <INDENT> max_iter_times = self.max_iter_times <NEW_LINE> iter_times = 0 <NEW_LINE> best_M = None <NEW_LINE> while iter_times < max_iter_times: <NEW_LINE> <INDENT> M = self.random_calculate(index) <NEW_LINE> if M is False: <NEW_LINE> <INDENT> return best_M <NEW_... | 进行计算
Returns:
计算的透视变换矩阵 | 625941d850812a4eaa59c595 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.