code stringlengths 4 4.48k | docstring stringlengths 1 6.45k | _id stringlengths 24 24 |
|---|---|---|
def slice_location_finder(slicepath2metadata): <NEW_LINE> <INDENT> slicepath2midpix = {} <NEW_LINE> slicepath2position = {} <NEW_LINE> for sp, metadata in slicepath2metadata.iteritems(): <NEW_LINE> <INDENT> if 'sax' in sp: <NEW_LINE> <INDENT> image_orientation = metadata["ImageOrientationPatient"] <NEW_LINE> image_posi... | :param slicepath2metadata: dict with arbitrary keys, and metadata values
:return: | 625941d3cb5e8a47e48b7c74 |
def __enter__(self): <NEW_LINE> <INDENT> return self | Compatability with 'with' statement | 625941d392d797404e304356 |
def set_connection(self, json_body): <NEW_LINE> <INDENT> self.disconnect() <NEW_LINE> self._session = iRODSSession( host=json_body["host"], port=json_body["port"], user=json_body["user"], password=json_body["password"], zone=json_body["zone"]) <NEW_LINE> self.set_root() | Create a session and set it as current, using the fields of the given JSON object. | 625941d33d592f4c4ed1d237 |
def save_html_file(links): <NEW_LINE> <INDENT> images = [] <NEW_LINE> for link in links: <NEW_LINE> <INDENT> images.append( "<div class='grid-item'><img src='{}' alt='' /></div>".format(link.url) ) <NEW_LINE> <DEDENT> filein = open("food_template.html", 'r') <NEW_LINE> src = Template(filein.read()) <NEW_LINE> if not os... | Opens food_template.html and writes the <img> tag with links to images.
Creates a new file based on food_template.html | 625941d3097d151d1a223024 |
def prep_score(self): <NEW_LINE> <INDENT> rounded_score = self.stats.get_rounded_score() <NEW_LINE> score_str = "Score: {:,}".format(rounded_score) <NEW_LINE> self.score_image = self.font.render(score_str, True, self.text_colour, None) <NEW_LINE> self.score_rect = self.score_image.get_rect() <NEW_LINE> self.score_rect.... | Turn the score into a rendered image. | 625941d3711fe17d82542535 |
def set_output(self, output): <NEW_LINE> <INDENT> self.output = output <NEW_LINE> self.logger.info("assigning output to %s" % self.output) | Set the output path for the job. Optional if the runner has been
instantiated with a prefix. | 625941d3de87d2750b85ff5f |
def is_basic_val_of_type(tp, obj): <NEW_LINE> <INDENT> return is_basic_val(obj) and obj["type"] is tp | Checks whether ``obj`` is a valid unannotated literal Venture object of the given type.
Only checks the top level, not recursively. Types as in `val`. | 625941d34428ac0f6e5ba9be |
def __init__(self, environ=None): <NEW_LINE> <INDENT> self.bind(environ or {},) | Create a new Request instance.
You usually don't do this but use the global `bottle.request`
instance instead. | 625941d315baa723493c4142 |
def __str__(self): <NEW_LINE> <INDENT> return self.title | string for representing the model object | 625941d366656f66f7cbc378 |
def _deleteStyleFile( self, fname ): <NEW_LINE> <INDENT> msg = "Unable to delete style file '%s'. This method should not be " "called directly, rather it should be called on a sub-class of " "StyleManager." % fname <NEW_LINE> raise Exception( msg ) | : Delete the persistent files for a style.
= INPUT VARIABLES
- fname The name of the style file to delete. | 625941d31f5feb6acb0c4d1a |
def sell(self, wallet, price, quantity=None): <NEW_LINE> <INDENT> if quantity == None or quantity > self.getQuantity(): <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> elif quantity == self.getQuantity(): <NEW_LINE> <INDENT> self.setOwned(False) <NEW_LINE> self.setQuantity(0) <NEW_LINE> self.setCostPrice(0) <NEW_LI... | Whenever the stock is sold, the quantity is updated with the
new quantiy | 625941d3a219f33f34628b33 |
def __call__(self, inputs, h_1, c_1, h_2, c_2, h_3, c_3, z_1, z_2): <NEW_LINE> <INDENT> z_1 = z_1[:, None] <NEW_LINE> z_2 = z_2[:, None] <NEW_LINE> prefix = _p(self._prefix, 'first') <NEW_LINE> logits_1 = self.f_hmlstm(inputs, h_1, z_1 * h_2, prefix=prefix) <NEW_LINE> f_1, i_1, o_1, j_1 = _lstm_gates(logits_1[:, :-1], ... | Hierarchical Multiscale Long Short-Term Memory (HM-LSTM) cell.
State is a tuple of the first-layer c_1 and h_1, the second-layer
c_2 and h_2, the third-layer c_3 and h_3, the first-layer boundary
detector z_1 and the second-layer boundary detector z_2 at previous
time step. | 625941d344b2445a33932260 |
def threejs_offline_scripts(self): <NEW_LINE> <INDENT> from sage.env import SAGE_SHARE <NEW_LINE> scripts = [os.path.join(SAGE_SHARE, 'threejs', script) for script in ['three.min.js', 'OrbitControls.js']] <NEW_LINE> if sys.platform == 'cygwin': <NEW_LINE> <INDENT> import cygwin <NEW_LINE> scripts = [cygwin.cygpath(scri... | Three.js scripts for the IPython command line
OUTPUT:
String containing script tags
EXAMPLES::
sage: from sage.repl.rich_output.backend_ipython import BackendIPythonCommandline
sage: backend = BackendIPythonCommandline()
sage: backend.threejs_offline_scripts()
'...<script ...</script>...' | 625941d3fbf16365ca6f6393 |
def boxedRun_args_(self, method, args): <NEW_LINE> <INDENT> self.scriptName = self.fileName() <NEW_LINE> libpath = LibraryFolder() <NEW_LINE> libDir = libpath.libDir <NEW_LINE> if not self.scriptName: <NEW_LINE> <INDENT> curDir = os.getenv("HOME") <NEW_LINE> self.scriptName = "<untitled>" <NEW_LINE> <DEDENT> else: <NEW... | Runs the given method in a boxed environment.
Boxed environments:
- Have their current directory set to the directory of the file
- Have their argument set to the filename
- Have their outputs redirect to an output stream.
Returns:
A tuple containing:
- A boolean indicating whether the run was successful
... | 625941d38e71fb1e9831d975 |
@pytest.mark.parametrize("Hvib, params, expected_result", [ ( [generate_hvib_data(1)], generate_params(1), 0.9942 ), ]) <NEW_LINE> def test_lz(Hvib, params, expected_result): <NEW_LINE> <INDENT> params["istate"] = 1 <NEW_LINE> params["T"] = 300.0 <NEW_LINE> params["target_space"] = 1 ... | Tests that the LZ probabilities are computed correctly according to the NBRA BLSH scheme | 625941d3b5575c28eb68e1cc |
def manhattanDis(position1, position2): <NEW_LINE> <INDENT> xy1 = position1 <NEW_LINE> xy2 = position2 <NEW_LINE> return abs(xy1[0] - xy2[0]) + abs(xy1[1] - xy2[1]) | The Manhattan distance heuristic for a PositionSearchProblem | 625941d3a8370b7717052a6a |
def Meta(): <NEW_LINE> <INDENT> return _DataModel.Amplitude_Meta() | Meta() -> MetaObject | 625941d345492302aab5e491 |
def __init__(self, parent=None): <NEW_LINE> <INDENT> super(TargetQualityDelegate, self).__init__(parent) <NEW_LINE> self.parent = parent | Class initializer. | 625941d37c178a314d6ef62c |
def sock_receive(): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> while running: <NEW_LINE> <INDENT> time.sleep(0.1) <NEW_LINE> <DEDENT> <DEDENT> except Exception as e: <NEW_LINE> <INDENT> print("Deu bosta ...", e) | Loop for Bluetooth Read | 625941d357b8e32f52483667 |
def update_selection_rect(self): <NEW_LINE> <INDENT> if self.tileset_widget.main_gui.project is None or self.tileset_widget.main_gui.header is None or self.tileset_widget.main_gui.footer is None or self.tileset_widget.main_gui.tileset_primary is None or self.tileset_widget.main_gui.tileset_secondary is None ... | Updates the selection rectangle. | 625941d34e696a04525c9617 |
def tests(self): <NEW_LINE> <INDENT> gc = GeneralChess() <NEW_LINE> self.assertEqual(gc.attack_positions(["0, 0"]), ["-2,-1", "-2,1", "-1,-2", "-1,2", "1,-2", "1,2", "2,-1", "2,1"]) <NEW_LINE> self.assertEqual(gc.attack_positions(["2,1", "-1,-2"]), ["0,0", "1,-1"]) | Tests. | 625941d3d7e4931a7ee9e0e9 |
def setup_platform(hass, config, add_devices, discovery_info=None): <NEW_LINE> <INDENT> import pywink <NEW_LINE> if discovery_info is None: <NEW_LINE> <INDENT> token = config.get(CONF_ACCESS_TOKEN) <NEW_LINE> if token is None: <NEW_LINE> <INDENT> logging.getLogger(__name__).error( "Missing wink access_token. " "Get one... | Sets up the Wink platform. | 625941d3656771135c3eba3b |
def retype(self, ctxt, volume, new_type, diff, host): <NEW_LINE> <INDENT> if volume['host'] != host['host']: <NEW_LINE> <INDENT> if self._check_volume_attachment(volume): <NEW_LINE> <INDENT> LOG.warning( 'Volume %(volume_id)s cannot be retyped ' 'during attachment.', { 'volume_id': volume['id']}) <NEW_LINE> return Fals... | Convert the volume to be of the new type. | 625941d34f88993c3716c232 |
def minDepth(self, root): <NEW_LINE> <INDENT> if not root: <NEW_LINE> <INDENT> return 0 <NEW_LINE> <DEDENT> right=self.minDepth(root.right) <NEW_LINE> left=self.minDepth(root.left) <NEW_LINE> if right and left: <NEW_LINE> <INDENT> return min(right,left)+1 <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return right+left+... | :type root: TreeNode
:rtype: int | 625941d367a9b606de4a8084 |
def GetNumberOfPixels(self): <NEW_LINE> <INDENT> return _ITKRegionsPython.itkImageRegion3_GetNumberOfPixels(self) | GetNumberOfPixels(self) -> unsigned long | 625941d366673b3332b9225d |
def _get_cell_data(self, index: str) -> str: <NEW_LINE> <INDENT> return self._current_book[index].value | :param index: str in excel format (exm: "L43")
:return: | 625941d344b2445a33932261 |
def phi12_rotmat(alpha,delta): <NEW_LINE> <INDENT> R_phi12_radec = np.array([[ 0.04842439, 0.30207466, -0.95205356],[-0.99433193, 0.10490506, -0.01728974],[ 0.09465244, 0.9474945 , 0.30544245]]) <NEW_LINE> vec_radec = np.array([np.cos(alpha*np.pi/180.)*np.cos(delta*np.pi/180.),np.sin(alpha*np.pi/180.)*np.cos(delta*... | Converts coordinates (alpha,delta) to ones defined by a rotation matrix R_phi12_radec, applied on the original coordinates
Critical: All angles must be in degrees | 625941d35f7d997b87174c64 |
def create(self, organization: str, project: str) -> _IssueType: <NEW_LINE> <INDENT> uri = '/repos/{org!s}/{project!s}/issues'.format(org=organization, project=project) <NEW_LINE> payload = {key: value for key, value in attr.asdict(self).items() if value is not None} <NEW_LINE> response, _ = self._call(uri, payload=pay... | Create an issue. | 625941d394891a1f4081bc75 |
def start(self): <NEW_LINE> <INDENT> pass | start positioning | 625941d3a79ad161976cc312 |
def get_rmsds(self, x): <NEW_LINE> <INDENT> rmsd_neg = np.sqrt((x * x * (x < 0)).mean()) <NEW_LINE> gradient = np.dot(self.a, x) - self.b <NEW_LINE> free = x > 0 <NEW_LINE> if self.nl > 0: <NEW_LINE> <INDENT> a_free, b_free, r_free, s_free = self.get_free_problem(free) <NEW_LINE> g_free = np.dot(a_free, x[free]) - b_fr... | Quantify how far x deviates from a local solution
**Returns:**
gradient
The gradient projected onto the equality constraints, if any.
rmsd_free
The gradient RMSD for the non-zero components
rmsd_frozen
The gradient RMSD for the zero components. Only contributions
from negative components are inc... | 625941d399cbb53fe6792db2 |
def gen_outputs(self, ds_fn, break_points, num_outputs, ckpt_saved=False, init_before_restore=False, sparse_tensors=False, verify_exhausted=True): <NEW_LINE> <INDENT> outputs = [] <NEW_LINE> def get_ops(): <NEW_LINE> <INDENT> if ckpt_saved: <NEW_LINE> <INDENT> saver = self._import_meta_graph() <NEW_LINE> init_op, get_n... | Generates elements from input dataset while stopping at break points.
Produces `num_outputs` outputs and saves the state of the iterator in the
Saver checkpoint.
Args:
ds_fn: 0-argument function that returns the dataset.
break_points: A list of integers. For each `break_point` in
`break_points`, we produce ou... | 625941d37cff6e4e81117b51 |
def __init__(self, name, sources=[], is_lib=True, compiler=None): <NEW_LINE> <INDENT> Extension.__init__(self, name, sources=sources) <NEW_LINE> self.runtime = sysconfig.get_python_lib() + "Python.Runtime.dll" <NEW_LINE> self.is_lib = is_lib <NEW_LINE> self.compiler = compiler | Args:
name:
sourcedir: | 625941d3a4f1c619b28b0202 |
def has_directories_in_path(*args, **kwargs): <NEW_LINE> <INDENT> return ndirectories_in_path(*args, **kwargs) > 0 | This function ...
:param args:
:param kwargs:
:return: | 625941d3adb09d7d5db6c95b |
def __clear_temp_data(self): <NEW_LINE> <INDENT> self.__temp_class = None <NEW_LINE> self.__temp_parser = None <NEW_LINE> return self | Method should clear temp data:
:rtype - self | 625941d391f36d47f21ac6bf |
def is_04_01_test(test_suite_url, node_ip, node_port, node_version, test_start_delay): <NEW_LINE> <INDENT> print('Running test IS-04-01:') <NEW_LINE> print(' Node API {} {}:{}'.format(node_version, node_ip, node_port)) <NEW_LINE> if test_start_delay: <NEW_LINE> <INDENT> data = { "DNS_SD_ADVERT_TIMEOUT": test_start_d... | IS-04 Node API | 625941d3627d3e7fe0d6901d |
def openbrowser(url): <NEW_LINE> <INDENT> browser = RoboBrowser(parser='html.parser') <NEW_LINE> browser.open(url) <NEW_LINE> return browser | Open url on RoboBrowser.
:param str url: Opened url
:return: Opened url RoboBrowser | 625941d323e79379d52ee72e |
def sources_source_id_get(self, source_id, **kwargs): <NEW_LINE> <INDENT> kwargs['_return_http_data_only'] = True <NEW_LINE> if kwargs.get('callback'): <NEW_LINE> <INDENT> return self.sources_source_id_get_with_http_info(source_id, **kwargs) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> (data) = self.sources_source_id_... | Get source
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please define a `callback` function
to be invoked when receiving the response.
>>> def callback_function(response):
>>> pprint(response)
>>>
>>> thread = api.sources_source_id_get(source_id, callback=callback_f... | 625941d3596a897236089c8b |
def getMemoKeyForAccount(self, name): <NEW_LINE> <INDENT> account = self.rpc.get_account(name) <NEW_LINE> key = self.getPrivateKeyForPublicKey(account["options"]["memo_key"]) <NEW_LINE> if key: <NEW_LINE> <INDENT> return key <NEW_LINE> <DEDENT> return False | Obtain owner Memo Key for an account from the wallet database
| 625941d3796e427e537b0793 |
def get(list_of_dict, key, value): <NEW_LINE> <INDENT> o = filter(lambda dictionary: dictionary.__dict__[key] == value, list_of_dict) <NEW_LINE> return o | Retrieve dictionaries matching the key-value pair from a list of
dictionaries. | 625941d3aad79263cf390c0f |
def _bobber_version(log: str) -> str: <NEW_LINE> <INDENT> version = re.findall(r'version_\d+_\d+_\d+', log) <NEW_LINE> if len(version) != 1: <NEW_LINE> <INDENT> raise ValueError(f'Could not parse Bobber version from {log} file!') <NEW_LINE> <DEDENT> version = version[0].replace('version_', '') <NEW_LINE> return version... | Returns a ``string`` representation of the Bobber version tested, such as
'6.3.1'.
Parameters
----------
log : str
A ``string`` of the filename for a single log.
Returns
-------
str
Returns a ``string`` of the Bobber version tested, such as '6.3.1'.
Raises
------
ValueError
Raises a ``ValueError`` if the... | 625941d3d6c5a10208144217 |
def dbConnect(self, config): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> ENGINE = config.get('database', 'engine') <NEW_LINE> DATABASE = config.get('database', 'database') <NEW_LINE> HOST = None if not config.has_option('database', 'host') else config.get('database', 'host') <NEW_LINE> USER = None if not config.has_op... | Connect to the retrosheet database, using the config.ini file
| 625941d323849d37ff7b325b |
def load_from_state(state_dict, model): <NEW_LINE> <INDENT> tem_dict = dict() <NEW_LINE> for k in state_dict.keys(): <NEW_LINE> <INDENT> tem_dict[k.replace('module.', '')] = state_dict[k] <NEW_LINE> <DEDENT> state_dict = tem_dict <NEW_LINE> ckpt_key = set(state_dict.keys()) <NEW_LINE> model_key = set(model.state_dict()... | Loads the state dict of a checkpoint into model. | 625941d399cbb53fe6792db3 |
def test_modify_ticket(self): <NEW_LINE> <INDENT> print("(" + self.test_modify_ticket.__name__ + ")", self.test_modify_ticket.__doc__) <NEW_LINE> resp = self.client.put(self.url1, data=json.dumps(self.modified_ticket1_req), headers={"Content-Type": JSON}) <NEW_LINE> self.assertEqual(resp.status_code, 204) <NEW_LINE> re... | Checks that PUT Ticket modifies the user correctly in the system
and returns correct response | 625941d38c0ade5d55d3eb87 |
def run(self): <NEW_LINE> <INDENT> self.helper.log_info("Starting RiskIQ connector...") <NEW_LINE> while True: <NEW_LINE> <INDENT> self.helper.log_info("Running RiskIQ connector...") <NEW_LINE> run_interval = self._CONNECTOR_RUN_INTERVAL_SEC <NEW_LINE> try: <NEW_LINE> <INDENT> self.helper.log_info(f"Connector interval ... | Run RiskIQ connector. | 625941d39f2886367277aa59 |
def serialize(self, outputStream): <NEW_LINE> <INDENT> super( WarfareFamilyPdu, self ).serialize(outputStream) <NEW_LINE> self.firingEntityID.serialize(outputStream) <NEW_LINE> self.targetEntityID.serialize(outputStream) | serialize the class | 625941d3a934411ee375185f |
def Main(): <NEW_LINE> <INDENT> matches = [] <NEW_LINE> directories = [ 'crypto', 'net', 'debug' ] <NEW_LINE> cc_re = re.compile(r'.+\.(cc|h)$', re.IGNORECASE) <NEW_LINE> for dirs in directories: <NEW_LINE> <INDENT> for root, dirnames, filenames in os.walk(dirs): <NEW_LINE> <INDENT> for name in filenames: <NEW_LINE> <I... | Search own project directories for *.cc and *.h files | 625941d33c8af77a43ae396d |
def deleteSection(self, token: str, dataid: str) -> dict: <NEW_LINE> <INDENT> r = requests.delete(f"{self.api_url}{token}/{dataid}", headers=self._headers) <NEW_LINE> if r.status_code == 200: <NEW_LINE> <INDENT> return r.json() <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> raise StatusNotOk(r.status_code, r.text) | Delete a section. This will delete a single section in an entry
:param token: Valid token for the entry
:type token: str
:param dataid: Valid dataid for the section to delete
:type dataid: str
:raises StatusNotOk: Exception on fail
:return: OK object
:rtype: dict
>>> from saramPy.api import SaramAPI
>>> saram = Saram... | 625941d3046cf37aa974cf13 |
def downgrade(): <NEW_LINE> <INDENT> conn = op.get_bind() <NEW_LINE> conn.execute("DELETE FROM ecosystems WHERE name = 'nuget'") <NEW_LINE> op.alter_column('package_gh_usage', 'ecosystem_backend', existing_type=postgresql.ENUM('none', 'npm', 'maven', 'pypi', 'rubygems', 'scm', 'crates', 'nuget', name='ecosystem_backend... | Downgrade the database to an older revision. | 625941d376d4e153a657ecfe |
@gitreceive_api.route('/push-data', methods=['POST']) <NEW_LINE> @streaming(TextStreamingResponse) <NEW_LINE> def api_pushdata(request, app): <NEW_LINE> <INDENT> deployment, service = request.args['name'].split('/', 1) <NEW_LINE> request.files['tarball'] <NEW_LINE> ctx.cintf.provide_data( deployment, service, {'app': r... | Called by git received with a new tarball from git.
| 625941d307f4c71912b11650 |
def __init__(self, pan_pin, tilt_pin): <NEW_LINE> <INDENT> self.pan_controller = SineController(Servo(pan_pin)) <NEW_LINE> self.tilt_controller = SineController(Servo(tilt_pin)) <NEW_LINE> print('PanTilt initialized, pan_pin is %s, tilt_pin is %s' % (pan_pin, tilt_pin)) | Pins use BCM numbering
:param pan_pin: this is the PWM pin connected to the pan axis.
:param tilt_pin: this is the PWM pin connected to the tilt axis. | 625941d391f36d47f21ac6c0 |
def generate_LCM(p, q): <NEW_LINE> <INDENT> return p *q // generate_gcd(p, q)[0] | give lcm of p and q
p is first prime number -1
q is second prime number -1 | 625941d3a219f33f34628b34 |
def mask_modules(*modnames): <NEW_LINE> <INDENT> def _inner(fun): <NEW_LINE> <INDENT> @wraps(fun) <NEW_LINE> def __inner(*args, **kwargs): <NEW_LINE> <INDENT> realimport = __builtin__.__import__ <NEW_LINE> def myimp(name, *args, **kwargs): <NEW_LINE> <INDENT> if name in modnames: <NEW_LINE> <INDENT> raise ImportError("... | Ban some modules from being importable inside the context
For example:
>>> @missing_modules("sys"):
>>> def foo():
... try:
... import sys
... except ImportError:
... print "sys not found"
sys not found
>>> import sys
>>> sys.version
(2, 5, 2, 'final', ... | 625941d331939e2706e4d035 |
def frequencySort(self, s): <NEW_LINE> <INDENT> dic = {} <NEW_LINE> res = [] <NEW_LINE> max = 0 <NEW_LINE> s_set = set(s) <NEW_LINE> for i in s_set: <NEW_LINE> <INDENT> count = s.count(i) <NEW_LINE> if count > max: max = count <NEW_LINE> dic[i] = count <NEW_LINE> <DEDENT> for i in range(max + 1): <NEW_LINE> <INDENT> fo... | :type s: str
:rtype: str | 625941d3c4546d3d9de72c01 |
def update_org_ip_address_monitoring_state(ip_uuid=None, state=None, db_session=None): <NEW_LINE> <INDENT> update_dict = { "is_monitored": state, } <NEW_LINE> update_org_ip_address( ip_uuid=ip_uuid, update_dict=update_dict, db_session=db_session, ) | Update the given IpAddress's current monitoring status.
:param ip_uuid: The UUID of the IpAddress to update.
:param state: The state to set.
:param db_session: A SQLAlchemy session.
:return: None | 625941d385dfad0860c3b027 |
def test_get_mode_display_name_unknown_slug(self): <NEW_LINE> <INDENT> mode = CourseMode(mode_slug='Blah!') <NEW_LINE> assert self.course.get_mode_display_name(mode) == mode.mode_slug | Verify the method returns the slug if it has no known mapping. | 625941d3097d151d1a223025 |
def causticFreqHelp(uvec, ax, ay, m, n): <NEW_LINE> <INDENT> ux, uy = uvec <NEW_LINE> psi10, psi01 = lensg(ux, uy) <NEW_LINE> psi20, psi02, psi11 = lensh(ux, uy) <NEW_LINE> H = psi20*psi02 - psi11**2 <NEW_LINE> ratio = ax/ay <NEW_LINE> A = m*H <NEW_LINE> B = psi20*psi01 + m*psi02*psi10 + H*(n - uy - m*ux) <NEW_LINE> C ... | Returns coefficients for system of equations that determines caustic locations in the frequency line at fixed u'. | 625941d3a8ecb033257d3299 |
def GetHTML(self): <NEW_LINE> <INDENT> raise NotImplementedError() | Returns an HTML representation of this measurement. | 625941d301c39578d7e75008 |
def create_model(self, params=True): <NEW_LINE> <INDENT> if params: <NEW_LINE> <INDENT> if self.model_type == 'xgb': <NEW_LINE> <INDENT> self.model = xgboost.XGBRegressor(**self.param) <NEW_LINE> <DEDENT> elif self.model_type == 'cat': <NEW_LINE> <INDENT> self.model = CatBoostRegressor(**self.param) <NEW_LINE> <DEDENT>... | Create model based on the model type class | 625941d3b7558d58953c50df |
def __init__(self, radius): <NEW_LINE> <INDENT> if radius <= 0: <NEW_LINE> <INDENT> raise ValueError('Radius must be >0') <NEW_LINE> <DEDENT> self._radius = radius | Initializes Circle with given radius.
Args:
radius (int) : radius of circle | 625941d39c8ee82313fbb942 |
def update(self, user_id: int=None, password=None, name=None, email=None, role=None): <NEW_LINE> <INDENT> data = extract_parameters() <NEW_LINE> if user_id is None: <NEW_LINE> <INDENT> data.pop('role', None) <NEW_LINE> return self.client.send_command_put('user/me', data=data)['user_info'] <NEW_LINE> <DEDENT> else: <NEW... | PUT user/me/
PUT user/<user_id>/ only admin | 625941d37d847024c06be48a |
def total_seconds(timedelta): <NEW_LINE> <INDENT> if hasattr(timedelta, 'total_seconds'): <NEW_LINE> <INDENT> return timedelta.total_seconds() <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> secs = (timedelta.seconds + timedelta.days * 24 * 3600) * 10**6 <NEW_LINE> return (timedelta.microseconds + secs) / 10.0**6 | Compatibility method because the total_seconds method has been introduced
in Python 2.7
:param timedelta: a timedelta object
:rtype: float | 625941d32eb69b55b151ca7d |
def streamStart(self, xs): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> self.authid = self.xmlstream.sid <NEW_LINE> if "no_events" not in self.attrs: <NEW_LINE> <INDENT> self.xmlstream.addOnetimeObserver("/auth", self.stanzaHandler) <NEW_LINE> self.xmlstream.addOnetimeObserver("/response", self.stanzaHandler) <NEW_LINE... | A xmpp stream has started | 625941d3283ffb24f3c55acc |
def fast_change(amount, coins): <NEW_LINE> <INDENT> def fast_change_helper(amount, coins, memo): <NEW_LINE> <INDENT> if (amount, coins) in memo: <NEW_LINE> <INDENT> return memo[(amount, coins)] <NEW_LINE> <DEDENT> if amount==0: <NEW_LINE> <INDENT> memo[(amount, coins)]=0 <NEW_LINE> return 0 <NEW_LINE> <DEDENT> elif coi... | Takes an amount and a list of coin denominations as input.
Returns the number of coins required to total the given amount.
Use memoization to improve performance. | 625941d3167d2b6e31218d62 |
def add_import(self, path): <NEW_LINE> <INDENT> self.imports[path] = None | Accepts a path to another .clif file in this case we defer tokenization
and parsing for later
:param String path, path to a referenced .clif file
:return None | 625941d3566aa707497f4733 |
def _make_xy_sfunc(func, ndim_output=False): <NEW_LINE> <INDENT> if ndim_output: <NEW_LINE> <INDENT> sfunc = lambda x, y: np.array([func(a, y.ravel()) for a in x])[:, 0] <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> sfunc = lambda x, y: np.array([func(a, y.ravel()) for a in x]) <NEW_LINE> <DEDENT> sfunc.__name__ = '.'.... | Aux function | 625941d3090684286d50eeb3 |
def get_best_roundtrip(self): <NEW_LINE> <INDENT> for slug, spread in self.spreads.items(): <NEW_LINE> <INDENT> B = slug.split('_')[0] <NEW_LINE> C = slug.split('_')[1] <NEW_LINE> if spread > 1: <NEW_LINE> <INDENT> self.log.info('check_profit_oneway({}, {}, {}) : {}'.format(self.target, B, C, spread)) <NEW_LINE> <DEDEN... | Calculate the optimal roundtrip for you to execute
Takes the form of 3 trades that are computed to fill specific quantities of orders
in each of 3 different markets in a single exchange. | 625941d332920d7e50b2839e |
def add_list(self): <NEW_LINE> <INDENT> self.update_progress_bar(0) <NEW_LINE> self.update_status_bar("Waiting for input") <NEW_LINE> list_name, ok = QtWidgets.QInputDialog.getText( self, "Add New List", "Enter a name for the new list: " ) <NEW_LINE> if ok: <NEW_LINE> <INDENT> if len(list_name) == 0: <NEW_LINE> <INDENT... | Add a new list of todos. | 625941d3d486a94d0b98e313 |
def move( UserName, UserNode, direc ): <NEW_LINE> <INDENT> global board <NEW_LINE> global player <NEW_LINE> global snakes <NEW_LINE> global server <NEW_LINE> global users <NEW_LINE> global moves <NEW_LINE> if ( direc == 'quit' ): <NEW_LINE> <INDENT> return remove_player( UserName, UserNode ) <NEW_LINE> <DEDENT> else: <... | move( UserName, UserNode, direc ):
An interface function called by an external erlang
process to feed player moves to the game for digestion.
Move returns a call to an internal function _move_check,
which handles the logic and validity of the move
Inputs: UserName: The name of the user, for key... | 625941d3f548e778e58cd74b |
def _generateExpandedEOCs(self, obj, **args): <NEW_LINE> <INDENT> return [] | Returns the expanded embedded object characters for an object. | 625941d3091ae35668667129 |
def visit_get(self, expr): <NEW_LINE> <INDENT> self.resolve(expr.object) | Visits a property get expression | 625941d3d268445f265b503b |
def ex_list_reserved_nodes(self): <NEW_LINE> <INDENT> params = {'Action': 'DescribeReservedInstances'} <NEW_LINE> response = self.connection.request(self.path, params=params).object <NEW_LINE> return self._to_reserved_nodes(response, 'reservedInstancesSet/item') | List all reserved instances/nodes which can be purchased from Amazon
for one or three year terms. Reservations are made at a region level
and reduce the hourly charge for instances.
More information can be found at http://goo.gl/ulXCC7.
:rtype: ``list`` of :class:`.EC2ReservedNode` | 625941d3ff9c53063f47c3c0 |
def preprocess(self, images): <NEW_LINE> <INDENT> images = ModelColorize.imtransform(images) <NEW_LINE> if len(images.shape) is 3: <NEW_LINE> <INDENT> self.images_data = np.repeat(images[np.newaxis, :, :, :], self.batch_size, axis=0) <NEW_LINE> <DEDENT> elif len(images.shape) is 4: <NEW_LINE> <INDENT> num_images = imag... | Default preprocessing pipeline
Converts input image from single channel to 3 channel grayscale
Prepare the data to be fed to the network. Weighted mask is computed
and images and masks are duplicated to fill the batch.
Arguments:
image - input image
Returns:
None | 625941d3bde94217f3682fbc |
def translatestr(strIn): <NEW_LINE> <INDENT> strIn = strIn.lower().split() <NEW_LINE> strOut = [] <NEW_LINE> ixWord = 0 <NEW_LINE> while ixWord < len(strIn): <NEW_LINE> <INDENT> wordIDd = False <NEW_LINE> for dictKey in DICTIONARYKEYS: <NEW_LINE> <INDENT> dictKeySplit = dictKey.split() <NEW_LINE> correct = True <NEW_LI... | Parse a user response for known words and phrases. | 625941d3377c676e91272375 |
def unload(self): <NEW_LINE> <INDENT> for action in self.actions: <NEW_LINE> <INDENT> self.iface.removePluginMenu( self.tr(u'&Geometry Updater'), action) <NEW_LINE> self.iface.removeToolBarIcon(action) <NEW_LINE> <DEDENT> del self.toolbar | Removes the plugin menu item and icon from QGIS GUI. | 625941d3566aa707497f4734 |
def get_selected(self, cols, sprites): <NEW_LINE> <INDENT> x1, y1 = self.first <NEW_LINE> x2, y2 = self.last <NEW_LINE> if x1 == -1 or x2 == -1: <NEW_LINE> <INDENT> return None, 0, 0 <NEW_LINE> <DEDENT> max_x, min_x = (x1, x2) if x1 > x2 else (x2, x1) <NEW_LINE> max_y, min_y = (y1, y2) if y1 > y2 else (y2, y1) <NEW_LIN... | get the sprites within the selected region
@param cols:
@param sprites:
@return:
the sprites and the columns and rows for this generation | 625941d360cbc95b062c6710 |
def send_to_all_clients(message): <NEW_LINE> <INDENT> global clients <NEW_LINE> alive_clients = [] <NEW_LINE> for client in clients: <NEW_LINE> <INDENT> if not client.closed: <NEW_LINE> <INDENT> alive_clients.append(client) <NEW_LINE> client.send(message) <NEW_LINE> <DEDENT> <DEDENT> clients = alive_clients | gửi message tới tất cả các clients | 625941d385dfad0860c3b028 |
def __hash__(self) -> int: <NEW_LINE> <INDENT> return hash(self.dtype._literal_value_hash_key(self.value)) | Return the hash of a literal value.
We override this method to make sure that we can handle things that
aren't eminently hashable like an ``array<array<int64>>``. | 625941d38a43f66fc4b54231 |
def obj_jacobian(u): <NEW_LINE> <INDENT> error_jacobian = 2 * self.B.T.dot(self.B.dot(u) - wrench) <NEW_LINE> effort_jacobian = np.transpose(u).dot(2 * thrust_cost) <NEW_LINE> return error_jacobian + effort_jacobian | Compute the jacobian of the objective function
[1] Scalar-By-Matrix derivative identities [Online]
Available: https://en.wikipedia.org/wiki/Matrix_calculus#Scalar-by-vector_identities | 625941d37b25080760e39626 |
def somme_tuple(tuple_a_sommer): <NEW_LINE> <INDENT> somme = 0 <NEW_LINE> for element in tuple_a_sommer: <NEW_LINE> <INDENT> somme += element <NEW_LINE> <DEDENT> return(somme) | goal: find he sum of all the element of a tuple
input: tuple
output: integer | 625941d31d351010ab855ce9 |
def read_msr(msr, cpu=0): <NEW_LINE> <INDENT> if not os.path.exists("/dev/cpu/0/msr"): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> os.system("/sbin/modprobe msr") <NEW_LINE> logging.debug("Ran modprobe sucessfully") <NEW_LINE> <DEDENT> except: <NEW_LINE> <INDENT> pass <NEW_LINE> return None <NEW_LINE> <DEDENT> <DEDENT... | reads the msr number given from the file /dev/cpu/0/msr
Reuturns the value | 625941d345492302aab5e492 |
def get_tpu_system_metadata(self): <NEW_LINE> <INDENT> cluster_spec = self.cluster_spec() <NEW_LINE> cluster_def = cluster_spec.as_cluster_def() if cluster_spec else None <NEW_LINE> tpu_system_metadata = ( tpu_system_metadata_lib._query_tpu_system_metadata( self.master(), cluster_def=cluster_def, query_topology=False))... | Returns the metadata of the TPU system.
Users can call this method to get some facts of the TPU system, like
total number of cores, number of TPU workers and the devices. E.g.
```python
resolver = tf.distribute.cluster_resolver.TPUClusterResolver(tpu='')
tpu_system_metadata = resolver.get_tpu_system_metadata()
num_ho... | 625941d3fff4ab517eb2f60a |
def bin_coeff(a,b): <NEW_LINE> <INDENT> assert (a-b)>=0, "a is supposed to be greater or equal b!" <NEW_LINE> return (mm.factorial(a))/(mm.factorial(b)*mm.factorial(a-b)) | returns binomial coefficient of a over b
| 625941d307d97122c4178a5b |
def ways(N): <NEW_LINE> <INDENT> facs = factors(N) <NEW_LINE> nf = len(facs) <NEW_LINE> if nf == 1: <NEW_LINE> <INDENT> return ((N,),) <NEW_LINE> <DEDENT> w = () <NEW_LINE> for i in range(1,nf): <NEW_LINE> <INDENT> combos = set(it.combinations(facs, i)) <NEW_LINE> for combo in combos: <NEW_LINE> <INDENT> p = 1 <NEW_LIN... | Return a list of arrays, each containing M integers, such that
the product of all integers within each array gives N. The arrays
represent *ALL* possible ways of getting N through products of integers. | 625941d34a966d76dd5511dd |
def testComparison_001(self): <NEW_LINE> <INDENT> mysql1 = MysqlConfig() <NEW_LINE> mysql2 = MysqlConfig() <NEW_LINE> self.assertEqual(mysql1, mysql2) <NEW_LINE> self.assertTrue(mysql1 == mysql2) <NEW_LINE> self.assertTrue(not mysql1 < mysql2) <NEW_LINE> self.assertTrue(mysql1 <= mysql2) <NEW_LINE> self.assertTrue(not ... | Test comparison of two identical objects, all attributes None. | 625941d34a966d76dd5511de |
def get_sync_report_with_http_info(self, sync_report_id, **kwargs): <NEW_LINE> <INDENT> all_params = ['sync_report_id'] <NEW_LINE> all_params.append('async') <NEW_LINE> all_params.append('_return_http_data_only') <NEW_LINE> all_params.append('_preload_content') <NEW_LINE> all_params.append('_request_timeout') <NEW_LINE... | get_sync_report # noqa: E501
View a single SyncIQ report. # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async=True
>>> thread = api.get_sync_report_with_http_info(sync_report_id, async=True)
>>> result = thread.get()
:param async bool
:param ... | 625941d3ec188e330fd5a96a |
def start(self) -> None: <NEW_LINE> <INDENT> self.bus.subscribe("speak:muted", self.muted) <NEW_LINE> self.bus.subscribe("speak:muted:scheduled", self.muted_by_schedule) <NEW_LINE> self.bus.subscribe("speak:muted:temporarily", self.muted_temporarily) <NEW_LINE> self.bus.subscribe("speak:mute", self.mute) <NEW_LINE> sel... | Define the CherryPy messages to listen for.
This plugin owns the speak prefix. | 625941d3cb5e8a47e48b7c76 |
def send_response(self, name, data): <NEW_LINE> <INDENT> with buffer_handler.lock: <NEW_LINE> <INDENT> log_output = buffer_handler.stream.getvalue() <NEW_LINE> buffer_handler.stream.truncate(0) <NEW_LINE> buffer_handler.stream.seek(0) <NEW_LINE> <DEDENT> if not log_output.endswith("\n"): <NEW_LINE> <INDENT> log_output ... | Sends a response to backend.
| 625941d3287bf620b61d3c31 |
def toString(self): <NEW_LINE> <INDENT> from io import BytesIO <NEW_LINE> stack = self.stack <NEW_LINE> self.stack = [] <NEW_LINE> output = BytesIO() <NEW_LINE> for line in stack: <NEW_LINE> <INDENT> if not callable(line): <NEW_LINE> <INDENT> output.write(line) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> value = line... | :return: Text written to the :class:`Stack` when a :class:`Template` is
rendered.
:Example:
>>> s = Stack()
>>> s.write("This is a test\n")
>>> s.write(lambda: "Second line\n")
>>> s.write("Final line")
>>> print s.toString()
This is a test
Second line
Final line | 625941d38e71fb1e9831d976 |
def command_subproc_stop(self, proc): <NEW_LINE> <INDENT> self.printer.debug('[LOCAL CMD] Stopping Local Subprocess Command [pid: %s]' % proc.pid) <NEW_LINE> proc.terminate() | Stop a running subprocess. | 625941d30c0af96317bb83b6 |
@journal.route("/journals", methods=["GET"]) <NEW_LINE> def get_all_journals(): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> journals = Journal.query.all() <NEW_LINE> <DEDENT> except exc.SQLAlchemyError as errors: <NEW_LINE> <INDENT> return jsonify( status="ERROR", message="DATABASE SESSION ERROR", error=errors._messag... | Return all journals in the database
{
"data": [
{
"content": "Cant think of ",
"updated_date": "2019-10-02T14:36:54",
"id": 1,
"title": "New Journal"
},
{
"content": "Cant think of ",
"updated_date": "2019-10-02T14:36:58",
"id": 2,
"title": "2nd Journal"
},
{
"con... | 625941d3a17c0f6771cbe21e |
def save_user_preferences(self, prefs, overwrite=None): <NEW_LINE> <INDENT> return self.client.User.User_savePreferences( prefs=prefs, overwrite=overwrite).result() | Save user preferences.
:param prefs:
:param overwrite: If true, will overwrite all existing preferences. | 625941d3dd821e528d63b376 |
def phase_offset(self, *args, **kwargs): <NEW_LINE> <INDENT> return _filter_swig.pfb_arb_resampler_ccf_sptr_phase_offset(self, *args, **kwargs) | phase_offset(pfb_arb_resampler_ccf_sptr self, float freq, float fs) -> float
Calculates the phase offset expected by a sine wave of frequency and sampling rate (assuming input sine wave has 0 degree phase). | 625941d35fc7496912cc3b4b |
def test__collect_cases__classic_layout(tmp_path): <NEW_LINE> <INDENT> CLASSIC_LAYOUT.build(tmp_path) <NEW_LINE> os.chdir(tmp_path / CLASSIC_LAYOUT.name) <NEW_LINE> case_manager = CaseManager() <NEW_LINE> case_manager.collect_cases() <NEW_LINE> assert len(case_manager.cases) == 2 <NEW_LINE> os.chdir(tmp_path / CLASSIC_... | Must find all cases in classic layout type directory
| 625941d357b8e32f52483669 |
def test_simple_if_else(self): <NEW_LINE> <INDENT> input_string = 'func start { if 1 {} else {} }' <NEW_LINE> real_ast = _parse(input_string) <NEW_LINE> expected_ast = _std_module() <NEW_LINE> expected_ast.decl_list[0].body.append( ast.If( condition=ast.Number(1), branch_if=[], branch_else=[], ) ) <NEW_LINE> misc.asser... | Parse if-else stmt. | 625941d345492302aab5e493 |
def backup(): <NEW_LINE> <INDENT> clear() <NEW_LINE> print("Backing up current tnsnames.ora from:") <NEW_LINE> print(tnsnames) <NEW_LINE> if access(tnsnames, R_OK) == True: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> copy2(tnsnames, tnsnamesTemp) <NEW_LINE> <DEDENT> except IOError as e: <NEW_LINE> <INDENT> print("\n")... | Backs up current tnsnames if it exists | 625941d391af0d3eaac9bbe8 |
def send_chat_msg(self, msg): <NEW_LINE> <INDENT> self.connection.call('privmsg', u'' + self._encode_msg(msg), u'#262626,en') | Send a chat room message.
:param msg: str the message to send. | 625941d3baa26c4b54cb12ec |
def view(self): <NEW_LINE> <INDENT> return self.__view | Return the QTreeView instance used.
| 625941d326068e7796caeeaf |
def api_v1_network_device_autocomplete_get(self, **kwargs): <NEW_LINE> <INDENT> kwargs['_return_http_data_only'] = True <NEW_LINE> if kwargs.get('async_req'): <NEW_LINE> <INDENT> return self.api_v1_network_device_autocomplete_get_with_http_info(**kwargs) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> (data) = self.api_v... | Retrieves all network devices # noqa: E501
Gets the list of first 500 network devices sorted lexicographically based on host name. It can be filtered using management IP address, mac address, hostname and location name. If id param is provided, it will be returning the list of network-devices for the given id's and o... | 625941d3dc8b845886cb5703 |
def doc_to_sentence(self, text: str): <NEW_LINE> <INDENT> a = self.__sentence_detector.tokenize(text) <NEW_LINE> return a | Split input into sentences, and remove all non-alphanumerical characters
:param text:
:return: | 625941d371ff763f4b54985b |
def initiate_figure(self): <NEW_LINE> <INDENT> fig = plt.figure("Interactive frequency selection for the Fourier " "Transform.", figsize=(9, 4)) <NEW_LINE> plt.subplots_adjust(hspace=0.03, wspace=0.04, bottom=0.15, top=0.9) <NEW_LINE> ax1 = plt.subplot2grid((3, 2), (0, 0), rowspan=2) <NEW_LINE> plt.grid('on', alpha=0.4... | Create the figure. | 625941d3a79ad161976cc314 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.