query
stringlengths
9
9.05k
document
stringlengths
10
222k
negatives
listlengths
19
20
metadata
dict
r""" >>> t = Textile() >>> t.table('(rowclass). |one|two|three|\n|a|b|c|') '\t\n\t\t\n\t\t\tone\n\t\t\ttwo\n\t\t\tthree\n\t\t\n\t\t\n\t\t\ta\n\t\t\tb\n\t\t\tc\n\t\t\n\t\n\n'
def table(self, text): text = text + "\n\n" pattern = re.compile(r'^(?:table(_?%(s)s%(a)s%(c)s)\. ?\n)?^(%(a)s%(c)s\.? ?\|.*\|)\n\n' % {'s': self.table_span_re, 'a': self.align_re, 'c': self.c}, ...
[ "def test_multi_line(style):\n row = ['Row One\\nColumn One', 'Two', 'Three']\n table = BaseTable([row])\n actual = [tuple(i) for i in table.gen_row_lines(row, style, [10, 3, 5], 2)]\n expected = [\n ('|', ' Row One ', '|', ' Two ', '|', ' Three ', '|'),\n ('|', ' Column One ', '|', ' ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
>>> t = Textile() >>> t.fBlock("bq", "", None, "", "Hello BlockQuote") ('\\t\\n', '\\t\\t', 'Hello BlockQuote', '', '\\n\\t')
def fBlock(self, tag, atts, ext, cite, content): atts = self.pba(atts) o1 = o2 = c2 = c1 = '' m = re.search(r'fn(\d+)', tag) if m: tag = 'p' if m.group(1) in self.fn: fnid = self.fn[m.group(1)] else: fnid = m....
[ "def makeNewBlock(self):\n\n block = textlayout.Block(\n width=self._propertyToPoints(\"width\"),\n lineHeight=self._propertyToPoints(\"line_height\"),\n marginTop=self._propertyToPoints(\"margin_top\"),\n marginBottom=self._propertyToPoints(\"margin_bottom\"),\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
>>> t = Textile() >>> t.glyphs("apostrophe's") 'apostrophe&8217;s' >>> t.glyphs("back in '88") 'back in &8217;88' >>> t.glyphs('foo ...') 'foo &8230;' >>> t.glyphs('') '&8212;' >>> t.glyphs('FooBar[tm]') 'FooBar&8482;' >>> t.glyphs("Cat's Cradle by Vonnegut") 'Cat&8217;s Cradle by Vonnegut'
def glyphs(self, text): # fix: hackish text = re.sub(r'"\Z', '\" ', text) glyph_search = ( # apostrophe's re.compile(r"(\w)\'(\w)"), # back in '88 re.compile(r'(\s)\'(\d+\w?)\b(?!\')'), # single closing re.compil...
[ "def get_glyphs(self, text):\n glyph_renderer = None\n glyphs = [] # glyphs that are committed.\n for c in get_grapheme_clusters(str(text)):\n # Get the glyph for 'c'. Hide tabs (Windows and Linux render\n # boxes)\n if c == '\\t':\n c = ' '\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Capture and store URL references in self.urlrefs. >>> t = Textile()
def getRefs(self, text): pattern = re.compile(r'(?:(?<=^)|(?<=\s))\[(.+)\]((?:http(?:s?):\/\/|\/)\S+)(?=\s|$)', re.U) text = pattern.sub(self.refs, text) return text
[ "def RefExtract(self):\n Regex = r\"\\\\ref\\{.*?\\}\"\n self.RefRegex = re.compile(Regex, re.VERBOSE|re.DOTALL)\n\n RefExtracted = self.RefRegex.findall(self.ParsedText)\n\n for Reference in RefExtracted:\n ThisUID = self.GenerateUID()\n self.ParsedRef[ThisUID] = R...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
>>> t = Textile() >>> t.span(r"hello %(bob)span strong and bold% goodbye") 'hello span strong and bold goodbye'
def span(self, text): qtags = (r'\*\*', r'\*', r'\?\?', r'\-', r'__', r'_', r'%', r'\+', r'~', r'\^') pnct = ".,\"'?!;:(" for qtag in qtags: pattern = re.compile(r""" (?:^|(?<=[\s>%(pnct)s])|([\[{])) (%(qtag)s)(?!%(qtag)s) ...
[ "def _span_word(tag: Callable, text: Callable, word: str, score: float,\n colormap: Callable):\n bg = colormap(score)\n style = \"color:\" + _get_rgb(bg) + \";font-weight:bold;background-color: \" \\\n \"#ffffff\"\n with tag(\"span\", style=style):\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Apply Textile to a block of text.
def textile(text, head_offset=0, html_type='xhtml', auto_link=False, encoding=None, output=None): return Textile(auto_link=auto_link).textile(text, head_offset=head_offset, html_type=html_type)
[ "def __call__(self, text):\n for unit in self.units:\n text = unit.transform(text)\n return text", "def highlightBlock(self, text):\r\n self.highlight_function(text)", "def apply_to_fig_text(fig: mpl.figure.Figure, fn: Callable[[str], str]):\n for text in fig.findobj(match=plt.T...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Do batched inference on rays using chunk.
def batched_inference(models, embeddings, rays, N_samples, N_importance, use_disp, chunk, white_back): B = rays.shape[0] chunk = 1024*32 results = defaultdict(list) for i in range(0, B, chunk): rendered_ray_chunks = \ ...
[ "def batched_inference(models,\n coverage_models,\n embeddings,\n rays,\n N_samples,\n N_importance,\n use_disp,\n chunk,\n point_transform_func=Non...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Add current fitter to list for testing
def add_fitter(self): # Check to make sure the fit being added has the some number of # observations of the previous fit if len(self._fit_snapshot_dict) > 0: k = list(self._fit_snapshot_dict.keys())[0] other_num_obs = self._fit_snapshot_dict[k].fit_num_obs ...
[ "def test_added_to_list(*args, **kwargs):\n if (not loaded_from_fixture(kwargs)):\n update_unit_test_infos(kwargs[\"instance\"].test_list)", "def test_user_current_list_starred(self):\n pass", "def current_hitter(self, current_hitter):\n\n self._current_hitter = current_hitter", "def t...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Prints a message prompting the user to enter one of the commands and returns the uppercase input entered by the user. >>> display_prompt()
def display_prompt() -> str: user_input = input("\nL)oad image S)ave-as \n" + "2)-tone 3)tone X)treme contrast T)int sepia P)osterize \n" + "E)dge detect I)mproved edge detect V)ertical flip H)orizontal flip \n" + "Q...
[ "def userInput(prompt: str = \"\") -> str:\n return input(str).lower()", "def prompt(self):\n\t\t_globals._console.write(f'{self.prompt_str} ')", "def read_user_response(self, prompt: str=None) -> str:\n ch = userinput.read_response(prompt)\n return ch.lower()", "def step_see_prompt(context):...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Applies the filter. >>> apply_filter(input_entered, final_image)
def apply_filter(user_input: str, image: Image) -> Image: if user_input == "2": filtered_image = two_tone(image, 'yellow', 'cyan') elif user_input == "3": filtered_image = three_tone(image, 'yellow', 'magenta', 'cyan') elif user_input == "X": filtered_image = extrem...
[ "def run(self):\n filtered_image = self.filter_function(source=self.noisy_image, shape=self.shape, sigma=self.sigma)\n\n # Emit finished signal to end the thread\n self.finished.emit(filtered_image, self.combo_id)", "def spatially_filter_image(*args, **kwargs): # real signature unknown; resto...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns an image loaded by the user. >>> load()
def load() -> Image: image = load_image(choose_file()) show(image) return image
[ "def get_image():\r\n\r\n file = choose_file()\r\n \r\n if file == \"\":\r\n sys.exit(\"File Open cancelled, exiting program\")\r\n img = load_image(file)\r\n\r\n return img", "def load_image(file):\n return Image.open(os.path.abspath(file))", "def get_image():\n\n # Pop up a dialogu...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns True if the user_input is a command for a filter. Otherwise, it returns False. >>> is_command_filter(commands, input_entered) True
def is_command_filter(list_commands: list, user_input: str) -> bool: num_filters = 9 length_list = len(list_commands) for i in range((length_list - num_filters), length_list): if user_input == list_commands[i]: return True return False
[ "def is_valid(list_commands: list, user_input: str) -> bool:\r\n for command in list_commands:\r\n if user_input == command:\r\n return True\r\n print(\"No such command\")\r\n return False", "async def filter_command(self, command: commands.Command) -> bool:\n\n try:\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns True if the user_input is in the valid list of commands. Otherwise, it returns False. >>> is_valid(commands, input_entered) True
def is_valid(list_commands: list, user_input: str) -> bool: for command in list_commands: if user_input == command: return True print("No such command") return False
[ "def is_command_filter(list_commands: list, user_input: str) -> bool:\r\n num_filters = 9\r\n length_list = len(list_commands)\r\n for i in range((length_list - num_filters), length_list):\r\n if user_input == list_commands[i]:\r\n return True\r\n return False", "def is_valid_cmd(dcm...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Check that the given Jacobian approximation satisfies secant conditions for last `npoints` points.
def _check_secant(self, jac_cls, npoints=1, **kw): jac = jac_cls(**kw) jac.setup(self.xs[0], self.fs[0], None) for j, (x, f) in enumerate(zip(self.xs[1:], self.fs[1:])): jac.update(x, f) for k in range(min(npoints, j+1)): dx = self.xs[j-k+1] - self.xs[j-k...
[ "def bsplinederivfunc(knots, points, nderiv):\n m, n, degree, dim = get_lengths_and_degree(knots, points)\n def c(t):\n pt = np.zeros(dim)\n for i in range(n+1):\n basis = bsplinebasis_deriv(knots, i, degree, nderiv)(t)\n pt += map(lambda x: x * basis, points[i])\n r...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Methode establishing the chained list, by creating a list of nodes objects of integer.
def __init__(self, list_nodes): self.starter_node = Node(list_nodes[0]) current_node = self.starter_node for val in list_nodes[1:]: current_node.link = Node(val) current_node = current_node.link
[ "def linked_list_constructor(node_list: List[int]) -> ListNode:\n head = ListNode()\n curr = head\n for i in range(len(node_list)):\n curr.next = ListNode(node_list[i])\n curr = curr.next\n return head.next", "def node_chain(self, node_id: int) -> List[Node]:\n pass", "def __ini...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Insert a new node with the data in a chained list after the searched data node.
def inser_node_after(self, data_chosen: int, new_node: int): current_node = self.starter_node while current_node is not None: # search the index of the node for the searched data if current_node.data == data_chosen: break current_node = current_node.link ...
[ "def insert_after_node(self, key, data):\n node = ListNode(data)\n p = self.head\n while p is not None:\n if p.data == key:\n node.next = p.next\n p.next = node\n p = p.next", "def add_after_node(self, key, data):\n cur = self.head\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Delete nodes whom the value equal to data_chosen
def delete_node(self, data_chosen): node_del = self.starter_node if node_del is None: print("No node to be deleted") while node_del is not None: if node_del.data == data_chosen: node_del.link = node_del.limk.link node_del = node_del.link
[ "def test_delete_decision_tree_using_delete(self):\n pass", "def del_nodes(self, val):\n if val not in self.keys():\n raise ValueError(\"There is no value to delete.\")\n for node in self.values():\n if val in node:\n del node[val]\n del self[val]",...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Given the string representation of the rucksack, return two sets of its contents
def split_rucksack(input: str): return (set(input[:len(input)//2]), set(input[len(input)//2:]))
[ "def get_subsets(string: str) -> Set:\n strings = set()\n str_len = len(string) + 1\n [strings.add(string[start:stop]) for start in range(str_len) for stop in range(str_len) if stop > start]\n return strings", "def unpack_subreddits(subreddits_str):\n return set(subreddits_str.split('+'))", "def ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Initialize card with territory and symbol
def __init__(self, territory, symbol): self.territory = territory self.symbol = symbol
[ "def __init__(self, pos, card=None):\n self.pos = pos\n self.card = card", "def __init__(self, cards=[]):\n\n # decide which kind of header it belongs to\n try:\n if cards[0].key == 'SIMPLE':\n if 'GROUPS' in cards._keylist and cards['GROUPS'].value == True:\n...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Serialize to bytes. Normally, subclasses should override Packet_serialize.
def _to_bytes(self) -> bytes: x = self._serialize() return pack_varint(self.id) + pack_varint(len(x)) + x
[ "def serialize(self, packet):\n\t\tbuffer = bytearray()\n\t\tscratch = 0\n\t\tscratch_bits = 0\n\t\tfor index, data in enumerate(packet._raw):\n\t\t\tfield = packet.FIELDS[index]\n\t\t\tbits_remaining = field.size\n\n\t\t\twhile True:\n\t\t\t\tbits_used = min(8 - scratch_bits, bits_remaining)\n\n\t\t\t\tdata_to_cop...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Deserialize from bytes. Subclasses should override Packet._deserialize.
def _from_bytes(input: bytes) -> None: id, payload = unpack_varint(input) length, payload = unpack_varint(payload) return Packet.get_packet_by_id(id)._deserialize(payload)
[ "def deserialize(self, packet, packet_bytes):\n\t\tinstance = packet()\n\t\tcurrent_byte = 0\n\t\tcurrent_byte_offset = 0\n\t\tfor index, field in enumerate(packet.FIELDS):\n\n\t\t\tbits_required = field.size\n\t\t\tscratch = 0\n\t\t\tscratch_bits = 0\n\t\t\twhile True:\n\t\t\t\tbits_used = min(8 - current_byte_off...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Concatenates multiple boxes together
def concatenate(cls, boxes, axis=0): if len(boxes) == 0: raise ValueError('need at least one box to concatenate') if axis != 0: raise ValueError('can only concatenate along axis=0') format = boxes[0].format datas = [_view(b.toformat(format).data, -1, 4) for b in b...
[ "def concatenate(boxes_list:List[Boxes], fields:Collection[str]=None) -> Boxes:\n if not boxes_list:\n if fields is None:\n fields = []\n return empty(*fields)\n\n if fields is None:\n # Get fields common to all sub-boxes\n common_fields = set.intersection( *[set(x.get_f...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
is the backend fueled by numpy?
def is_numpy(self): return isinstance(self.data, np.ndarray)
[ "def has_numpy(self):\r\n self._check_numpy()\r\n return self._found_numpy", "def is_numpy_type(x):\n return type(x).__module__ == np.__name__", "def is_numpy_array(x):\n return _is_numpy(x)", "def _is_numpy_array(obj: object) -> bool:\n return _as_numpy_array(obj) is not None", "def ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
returns the kwarray.ArrayAPI implementation for the data
def _impl(self): return kwarray.ArrayAPI.coerce(self.data)
[ "def get_array(self): # real signature unknown; restored from __doc__\n pass", "def array(self) -> ArrayLike:\n # error: \"SingleDataManager\" has no attribute \"arrays\"; maybe \"array\"\n return self.arrays[0] # type: ignore[attr-defined]", "def array(self):\n raise NotImplemented...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Passthrough method to view or reshape
def view(self, *shape): data_ = _view(self.data, *shape) return self.__class__(data_, self.format)
[ "def getViewMatrix( self):", "def viewManip(bottomLeft=bool, drawCompass=bool, size=\"string\", bottomRight=bool, zoomToFitScene=bool, compassAngle=float, visible=bool, topRight=bool, restoreCenter=bool, dragSnap=bool, levelCamera=bool, minOpacity=float, topLeft=bool, fitToView=bool):\n pass", "def test_Imag...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Registers all connecting variables associated with this component to the gekko model. kwargs
def register_connecting(self, **kwargs): # Aliases a = self.aqua MV = self.m.MV SV = self.m.Var FV = self.m.FV # Initial Conditions T0 = kwargs.get('T0', 25) I0 = kwargs.get('I0', 5e6) N0 = kwargs.get('N0', 0) ppb0 = kwargs.get('ppb0', 1) ...
[ "def save_kwargs(self, kwargs: dict) -> None:\n d = kwargs.copy()\n d[\"eps\"] = self.eps\n d[\"torch_dtype\"] = self.torch_dtype\n d[\"importance_sampler\"] = self.importance_nested_sampler\n save_to_json(d, os.path.join(self.output, \"config.json\"))", "def __init__(self):\r\n...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Registers all equations and intermediates associated with this component to the gekko model. kwargs
def register_equations(self, **kwargs): # ------- # Aliases # ------- m = self.m a = self.aqua # ---------- # Parameters # ---------- # Growing bed definition beds = kwargs.get('beds', [(0, 30)]) # -------------------- #...
[ "def _set_up_model(self) -> None:\n self._add_vars_x_i_in_theta_i()\n self._add_vars_z_i()\n self._add_linear_cons()\n self._add_objective()", "def setup(self):\n # Convert initial params into matlab array\n self.initial_params_mat = matlab.double(list(self.initial_params...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Create a new HIT on AMT.
def create_hit(hit_options): options = settings.AMT_DEFAULT_HIT_OPTIONS options.update(hit_options) scheme = 'https' if options['use_https'] else 'http' from interface import AMT_INTERFACE path = AMT_INTERFACE.get_assignment_url() url = (scheme + '://' + settings.PUBLIC_DNS + ':8002' + path ...
[ "def create_hit(**kwargs):\n response = objective_turk.client().create_hit(**kwargs)\n logger.debug(response)\n #pylint: disable=protected-access\n return objective_turk.Hit._new_from_response(response['HIT'])", "def create_hit_with_hit_type(**kwargs):\n if 'HITTypeId' not in kwargs:\n raise...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Replace self.old_str by self.new_str. text arg from visit_file method of SearchInFiles class.
def word_matched(self, full_path, text): self.for_replace.append(full_path) if not self.only_print: old_str, new_str = self.search_word, self.new_str text = text.replace(old_str, new_str) open(full_path, 'w').write(text) print(f"Word => {old_str}\nReplaced...
[ "def ireplace(text, old, new):\n assert(isinstance(text, str) and isinstance(old, str))\n use_string_format = '%s' in new\n\n old_len = len(old)\n to_replace = []\n for match in iter_find(text.lower(), old.lower()):\n match = text[match:match+old_len]\n if match not in to_replace:\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
list the books of a given user by uid
def list_user_books(self,uid,start,end): sqls="SELECT a.bid,isbn10,isbn13,title,subtitle,author,translators,publisher,pubdate,price,pages,update_time,create_time,quantity,\ series,keywords,summary,b.status \ FROM "+TABLE_USERBOOK+" a RIGHT JOIN "+TABLE_BOOK+" b ON ...
[ "def get_listed_books(self, user_num):\n c = self.db.cursor()\n c.execute(\"\"\"\n SELECT \n B.title AS Title, \n B.ISBN AS ISBN, \n B.author AS Author, \n UB.points AS Points,\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
get book by isbn from douban and insert it into local db
def insert_book(self,isbn,uid=None): try: if not uid: uid=1 book = self.get_book_byisbn(isbn) if book and book.id: #check if it's already in user book list? sqls="select 1 FROM %s WHERE `uid`=%d and `bid`=%d" %(TABLE_USERBOOK,ui...
[ "def select_book(self, isbn):\n return self.cur.execute('SELECT * FROM books WHERE isbn=?', (isbn,)).fetchone()", "def add_ISBN(self, isbn, category, title, author, genre, views = 0):\n \n \n isbn = ISBN(ISBN=isbn,category=category,title=title,author=author,genre=genre)\n isbn.s...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
remove book from user book list
def remove_userbook(self,uid,bid): sqls="DELETE FROM %s WHERE `uid`=%d and `bid`=%d" %(TABLE_USERBOOK,uid,bid) db.query(sqls)
[ "def remove_book(self, book: Book):\n self.books.remove(book)", "def remove_book(self, in_title, in_author):\n title=in_title.lower()\n author=in_author.lower()\n if title and not title.isspace() and author and not author.isspace():\n for book in self.booklist:\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns a published pipeline by name and version
def get_published_pipeline(ws,name,version): published_pipelines = PublishedPipeline.list(ws) for pipe in published_pipelines: p_name = pipe.name p_version = pipe.version if(p_name == name and p_version is not None and p_version==version): return pipe else: ...
[ "def get_pipeline(self, pipeline_name):\n return self.find('*/pipeline[@name=\"%s\"]' % pipeline_name)", "def get_pipeline(self, project, pipeline_id, pipeline_version=None):\n route_values = {}\n if project is not None:\n route_values['project'] = self._serialize.url('project', pr...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
numpy compatible implementation of heaviside function
def npHeaviside(x): return np.piecewise(x, [x<0, x==0, x>0], [lambda arg: 0.0, lambda arg: 0.5, lambda arg: 1.0])
[ "def test_heaviside(self):\n self.assertEqual(m.heaviside(-1), 0)\n self.assertEqual(m.heaviside(0), 0.5)\n self.assertEqual(m.heaviside(1), 1)\n self.assertEqual(m.heaviside(-np.inf), 0)\n self.assertTrue(np.isnan(m.heaviside(np.nan)))\n self.assertEqual(m.heaviside(np.inf...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
numpy compatible implementation of dirac delta. This implementation is representing a disrete version of dirac with width h and height 1/h. Area under dirac is equal to 1.
def npDirac(x, h): return npHeaviside(x)*npHeaviside(h-x)*1.0/h
[ "def derivative(a,b,n):\n dx = (b-a)/(n-1)\n D=(1/2)*(np.eye(n+1,n+1,1)-np.eye(n+1,n+1,-1))\n D[0][0] = -1\n D[-1][-1] = 1\n D[0][1] = 1\n D[-1][-2] = -1\n D = D/(dx)\n return D", "def derivative(data, dt):\n\tdata = np.insert(data, 0, data[0])\n\tdata = np.diff(data/dt)\n\treturn data", ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
This function computes the coefficients of the fourier series representation of the function f, which is periodic on the interval [start,end] up to the degree N.
def coeff(f, start, end, N): return coeff_fft(f, start, end, N)
[ "def fourier_series(self, x, f, n=0):\n # Make the parameter objects for all the terms\n a0, *cos_a = parameters(','.join(['a{}'.format(i) for i in range(0, n + 1)]))\n sin_b = parameters(','.join(['b{}'.format(i) for i in range(1, n + 1)]))\n\n # Construct the series\n series = a...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
This function evaluates the fourier series of degree N with the coefficient vectors a and b and the period length T at the points in the array x.
def fourier_series(a, b, N, T, x): # numpy matrix version of code below a = a[:N+1] b = b[:N+1] """ y = np.zeros(x.shape) for k in range(N+1): kk = k * 2 * np.pi / T y += (b[k] * np.sin(kk*x) + a[k] * np.cos(kk*x)) """ k = np.arange(N+1) kk = k * 2 * np.pi / T y ...
[ "def fourier_series(x, *a):\n output = 0\n output += a[0]/2\n w = a[1]\n for n in range(2, len(a), 2):\n n_ = n/2\n val1 = a[n]\n val2 = a[n+1]\n output += val1*np.sin(n_*x*w)\n output += val2*np.cos(n_*x*w)\n return output", "def fourier_series(self, x, f, n=0):\...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns a string of a specific number of emojis based on the passedin number. >>> make_haiku_line(5)
def make_haiku_line(num): make_line = True line = [] while make_line: syllable = random.choice(EMOJI_LIST) line.append(emoji.emojize(syllable, use_aliases=True)) if len(line) >= num: make_line = False for emoticon in line: emoji.emojize(emoticon) return line
[ "def label_from_number(number):\n row_label_chars = []\n while number > 0:\n modulo = (number - 1) % 26\n row_label_chars.insert(0, chr(65 + modulo))\n number = (number - modulo) / 26\n return ''.join(row_label_chars)", "def repeat_string(word, number):\n\n a_number = int(number)\...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Tests that the function returns ValueError on an invalid email.
def testInvalidEmail(self): with self.assertRaises(ValueError): melange_db.email_validator(None, 'invalid_email_address')
[ "def test_email_parsing_fail():\n\n assert_raises(exceptions.InvalidEmail, email.validate, \"userexample.com\")\n assert_raises(exceptions.InvalidEmail, email.validate, \"user@examplecom\")\n assert_raises(exceptions.InvalidEmail, email.validate, \"userexamplecom\")", "def test_malformedEmailAddress(self...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Tests whether a correct dict is returned for a db model.
def testForDBModel(self): class Books(db.Model): item_freq = db.StringProperty() freq = db.IntegerProperty() details = db.TextProperty() released = db.BooleanProperty() entity = Books() entity.item_freq = '5' entity.freq = 4 entity.details = 'Test Entity' entity.released...
[ "def test_if_to_dict_returns_dict(self):\n b = BaseModel()\n self.assertTrue(type(b.to_dict()) is dict)", "def test_model_read_as_dict(self):\n tm = TestModel.create(count=8, text='123456789', a_bool=True)\n column_dict = {\n 'id': tm.id,\n 'count': tm.count,\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Print a list of n hits from Google
def get_n_results(query, n): from pprint import pprint gs = GoogleSearch(query) for hit in gs.get_results(n): pprint(hit) print
[ "def google_search(search_term, num_results=1):\r\n results = []\r\n for url in googlesearch.search(search_term, start=1, stop=1+num_results, num=1):\r\n results.append(url)\r\n return results", "def get_google_results(search):\r\n \r\n url='http://www.google.com/search?q='\r\n address = ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Determine if sentiment is positive, negative, or neutral algorithm to figure out if sentiment is positive, negative or neutral uses sentiment polarity from TextBlob, VADER Sentiment and sentiment from textprocessing URL
def sentiment_analysis(text): # pass text into sentiment url if True: ret = get_sentiment_from_url(text, sentimentURL) if ret is None: sentiment_url = None else: sentiment_url, neg_url, pos_url, neu_url = ret else: sentiment_url = None # pass tex...
[ "def sentiment_analysis_by_text(self,tweet):\n blob = TextBlob(tweet['text'].decode('ascii', errors=\"replace\"))\n sentiment_polarity = blob.sentiment.polarity\n if sentiment_polarity < 0:\n sentiment = self.NEGATIVE\n elif sentiment_polarity <= 0.25:\n sentiment =...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Coordinates (x,y,z) of all nodes
def node_coordinates(self): return self._nc
[ "def get_node_coordinates(self):\n xn = self._centers_to_nodes(self.x)\n yn = self._centers_to_nodes(self.y)\n gn = Grid2D(x=xn, y=yn)\n return gn.xy", "def get_coords(self):\n\t\treturn self.x, self.y, self.z", "def mesh_node_coords(self) -> np.ndarray:\n return self._mesh_no...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
provides a unique list of boundary codes
def boundary_codes(self): return [code for code in self.valid_codes if code > 0]
[ "def get_boundary_list(self):\n # TODO MAYBE: store boundaries in separate list (?)\n return [self[ii] for ii in range(self.n_obstacles) if self[ii].is_boubndary]", "def get_boundary_coords():\n coords = []\n for x in range(calib.M_SIZE_X):\n for y in range(calib.M_SIZE_Y):\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Are coordinates geographical (LONG/LAT)?
def is_geo(self): return self._projstr == "LONG/LAT"
[ "def is_geo(self) -> bool:\n return self._projstr == \"LONG/LAT\"", "def locn_is_latlong():\n s = read_command(\"g.region\", flags='pu')\n kv = parse_key_val(s, ':')\n if kv['projection'].split(' ')[0] == '3':\n return True\n else:\n return False", "def test_validate_coordinates...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
The maximum number of nodes for an element
def max_nodes_per_element(self): maxnodes = 0 for local_nodes in self.element_table: n = len(local_nodes) if n > maxnodes: maxnodes = n return maxnodes
[ "def number_of_nodes():\n return 3", "def max_component_size(self) -> int:\n nodes_len = len(self.nodes)\n stack: List[int] = []\n visited = [False]*nodes_len\n max_size = 0\n\n for u in range(nodes_len):\n if visited[u]:\n continue\n\n si...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Type is either mesh or Dfsu2D (2 horizontal dimensions)
def is_2d(self): return self._type <= 0
[ "def is_p2dg(mesh, dimension):\n\n return (mesh.continuity == -1 and\n mesh.shape.dimension == dimension and\n mesh.shape.type == 'lagrangian' and\n mesh.shape.degree == 2)", "def is2D(self, unit: 'int const'=0) -> \"SbBool\":\n return _coin.SoMultiTextureCoordinateEleme...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Does the mesh consist of triangles only?
def is_tri_only(self): return self.max_nodes_per_element == 3 or self.max_nodes_per_element == 6
[ "def test_vertex_only(self):\n\n v = g.random((1000, 3))\n v[g.np.floor(g.random(90) * len(v)).astype(int)] = v[0]\n\n mesh = g.trimesh.Trimesh(v)\n\n assert len(mesh.vertices) < 950\n assert len(mesh.vertices) > 900", "def using_triangle():\r\n return HAS_TRIANGLE", "def i...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
export elements to new geometry
def elements_to_geometry(self, elements, node_layers="all"): elements = np.sort(elements) # make sure elements are sorted! # extract information for selected elements node_ids, elem_tbl = self._get_nodes_and_table_for_elements( elements, node_layers=node_layers ) no...
[ "def deformGeometry(self):\r\n cmds.modelEditor('modelPanel4', e=True, nurbsCurves=True, polymeshes=True)\r\n #DeformLibrary.matchCircleDirectionTest(self.LocatorGrp)\r\n DeformLibrary.deformGeoToImage(self.LocatorGrp, self.ResolutionList)\r\n DeformLibrary.cleanUpforEdit2(self.LocatorGrp, self.Objects,...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Get list of top element ids based on element coordinates
def _get_top_elements_from_coordinates(self, ec=None): if ec is None: ec = self.element_coordinates d_eps = 1e-4 top_elems = [] x_old = ec[0, 0] y_old = ec[0, 1] for j in range(1, len(ec)): d2 = (ec[j, 0] - x_old) ** 2 + (ec[j, 1] - y_old) ** 2 ...
[ "def get_ids():", "def top_nodes(self):\n voffs = self.offset.take(self.bt_masks[1])*(self._mesh.layers-2)\n return np.unique(self.cell_node_list[:, self.bt_masks[1]] + voffs)", "def getNodeXY(id):\n for n in nodes:\n if n[0] == id:\n return (n[2], n[3])", "def _get_front_idxs_from_id(f...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
extract 2d geometry from 3d geometry Returns UnstructuredGeometry 2d geometry (bottom nodes)
def to_2d_geometry(self): if self._n_layers is None: return self # extract information for selected elements elem_ids = self.bottom_elements node_ids, elem_tbl = self._get_nodes_and_table_for_elements( elem_ids, node_layers="bottom" ) node_coords ...
[ "def get_3d(self) -> \"ProjectionGeometry\":\n if self.ndim == 2:\n if self.det_shape_vu is not None:\n new_det_shape_vu = np.ones(2, dtype=int)\n new_det_shape_vu[-len(self.det_shape_vu) :] = self.det_shape_vu\n else:\n new_det_shape_vu = No...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
list of nodes and element table for a list of elements
def _get_nodes_and_table_for_elements(self, elements, node_layers="all"): nodes = [] elem_tbl = [] if (node_layers is None) or (node_layers == "all") or self.is_2d: for j in elements: elem_nodes = self.element_table[j] elem_tbl.append(elem_nodes) ...
[ "def parse_table(element: WebElement) -> List[List[str]]:\n\n table_data = []\n\n # parse header columns\n header = []\n header_columns = element.find_elements_by_css_selector(\"thead tr th\")\n for column in header_columns:\n header.append(column.text)\n\n table_data.append(header)\n\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Find 3d elements of profile nearest to (x,y) coordinates
def find_nearest_profile_elements(self, x, y): if self.is_2d: raise InvalidGeometry("Object is 2d. Cannot get_nearest_profile") else: elem2d, _ = self._find_n_nearest_2d_elements(x, y) elem3d = self.e2_e3_table[elem2d] return elem3d
[ "def getElementByCoordinates(x, y, z, dim=-1, strict=False):", "def test_nearest(self):\n plugin = SpotExtraction(neighbour_selection_method='nearest')\n expected = self.neighbours[:, 0, 0:2].astype(int)\n result = plugin.extract_coordinates(self.neighbour_cube)\n self.assertArrayEqual...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
The 2dto3d element connectivity table for a 3d object
def e2_e3_table(self): if self._n_layers is None: print("Object has no layers: cannot return e2_e3_table") return None if self._e2_e3_table is None: res = self._get_2d_to_3d_association() self._e2_e3_table = res[0] self._2d_ids = res[1] ...
[ "def testStructuringElement3D(self):\n testse = structuringElement3D([0,4,5,6,9,12] , FACE_CENTER_CUBIC)\n testse2 = structuringElement3D([4,5,6,9,12] , CENTER_CUBIC)\n testse3 = structuringElement3D([0,4,5,6,9,12] , FACE_CENTER_CUBIC)\n self.assertTrue(testse.getDirections()==[0,4,5,6,9...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
The associated 2d element id for each 3d element
def elem2d_ids(self): if self._n_layers is None: raise InvalidGeometry("Object has no layers: cannot return elem2d_ids") # or return self._2d_ids ?? if self._2d_ids is None: res = self._get_2d_to_3d_association() self._e2_e3_table = res[0] sel...
[ "def get_element2dof_id_map(self):\n assert self.model_type == 'frame', 'this function assumes 6 dof each node for now!'\n return {int(e_id) : {0 : id_map[0:6], 1 : id_map[6:12]} \n for e_id, id_map in enumerate(self._sc_ins.get_element2dof_id_map())}", "def update_ids(self):\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Maximum number of layers
def n_layers(self): return self._n_layers
[ "def get_number_of_layers(self) -> int:\n pass", "def num_hidden_layers(self):\n return len(self.weight_matrices) - 1", "def num_perpception_layer_points(layer):\n return (layer + 1) * 4", "def max_num_boxes_batch(self):\n shape_list = list()\n for batch in self.batch_boxes.take...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Number of sigma layers
def n_sigma_layers(self): return self._n_sigma
[ "def get_number_of_layers(self) -> int:\n pass", "def sigmaToSize(sigma):\n return 2*int(kernelSize*sigma) + 1", "def num_hidden_layers(self):\n return len(self.weight_matrices) - 1", "def num_perpception_layer_points(layer):\n return (layer + 1) * 4", "def compute_kernel_size(sigma_...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Maximum number of zlayers
def n_z_layers(self): if self._n_layers is None: return None return self._n_layers - self._n_sigma
[ "def get_number_of_layers(self) -> int:\n pass", "def max_z(self):\n return self.origin[2] + self.size[2]", "def n_zlabels(self):\n return self._n_zlabels", "def max_ripples():\r\n return 8", "def num_perpception_layer_points(layer):\n return (layer + 1) * 4", "def z_step_size(s...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
generate matplotlib polygons from element table for plotting Returns list(matplotlib.patches.Polygon) list of polygons for plotting
def _to_polygons(self, geometry=None): if geometry is None: geometry = self from matplotlib.patches import Polygon polygons = [] for j in range(geometry.n_elements): nodes = geometry.element_table[j] pcoords = np.empty([len(nodes), 2]) fo...
[ "def extract_polygons(data):\n polygons = []\n for i in range(data.shape[0]):\n north, east, alt, d_north, d_east, d_alt = data[i, :]\n \n north_coord_min = north - d_north\n north_coord_max = north + d_north\n east_coord_min = east - d_east\n east_coord_max = east + ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Export mesh as shapely MultiPolygon Returns shapely.geometry.MultiPolygon polygons with mesh elements
def to_shapely(self): from shapely.geometry import Polygon, MultiPolygon polygons = [] for j in range(self.n_elements): nodes = self.element_table[j] pcoords = np.empty([len(nodes), 2]) for i in range(len(nodes)): nidx = nodes[i] ...
[ "def asMultiPolygon(context): # -> MultiPolygonAdapter:\n ...", "def export_mesh(vertices, triangles, filename, mesh_name=\"mcubes_mesh\"):\n \n import collada\n \n mesh = collada.Collada()\n \n vert_src = collada.source.FloatSource(\"verts-array\", vertices, ('X','Y','Z'))\n geom = colla...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
convert cellcentered data to nodecentered by pseudolaplacian method
def get_node_centered_data(self, data, extrapolate=True): nc = self.node_coordinates elem_table, ec, data = self._create_tri_only_element_table(data) node_cellID = [ list(np.argwhere(elem_table == i)[:, 0]) for i in np.unique(elem_table.reshape(-1,)) ] no...
[ "def recenter(cluster):\n tot = cluster.shape[0]\n return np.sum(cluster, axis=0) / tot", "def __update_centers(self):\n \n centers = [[] for i in range(len(self.__clusters))];\n \n for index in range(len(self.__clusters)):\n point_sum = [0] * len(self.__pointer_data...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Read header of mesh file and set object properties
def _read_mesh_header(self, filename): msh = MeshFile.ReadMesh(filename) self._source = msh self._projstr = msh.ProjectionString self._type = UnstructuredType.Mesh # geometry self._set_nodes_from_source(msh) self._set_elements_from_source(msh)
[ "def _read_primary_header(self):\n\n self._check_magic_number()\n\n self.f.seek(0)\n self.time, = np.fromfile(self.f, dtype='<f8', count=1)\n self._nbodies_tot, self._ncomp = np.fromfile(self.f, dtype=np.uint32,count=2)\n\n data_start = 16 # guaranteed first component location...\...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Read header of dfsu file and set object properties
def _read_dfsu_header(self, filename): dfs = DfsuFile.Open(filename) self._source = dfs self._projstr = dfs.Projection.WKTString self._type = UnstructuredType(dfs.DfsuFileType) self._deletevalue = dfs.DeleteValueFloat # geometry self._set_nodes_from_source(dfs) ...
[ "def __get_header(self):\n # try:\n self.header = self.hdulist[0].header\n # except:\n # self.hdulist = astropy.io.fits.open(self.map_name)\n # self.header = self.hdulist[0].header", "def _read_primary_header(self):\n\n self._check_magic_number()\n\n self.f...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Time step size in seconds
def timestep(self): return self._timestep_in_seconds
[ "def time_step(self):\n ts = float(rospy.get_param('/time_step_size', None))\n\n if ts is None:\n raise RuntimeError(\"No Time step has been set by the driving node..\")\n else:\n return ts", "def n_timesteps(self) -> int:\n if self.total_time < self.timestep:\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Change the code values of the nodes
def set_codes(self, codes): if len(codes) != self.n_nodes: raise Exception(f"codes must have length of nodes ({self.n_nodes})") self._codes = codes self._valid_codes = None
[ "def update_code(self, new_code):\n self.code = new_code # code from __inti ___\n\n # Fill in the rest", "def update_code(self, new_code):\n\n # Fill in the rest\n self.code = new_code\n # print(self.code) #for checking\n return self.code", "def handle_nodes(n...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Plot mesh boundary nodes and their codes
def plot_boundary_nodes(self, boundary_names=None): import matplotlib.pyplot as plt nc = self.node_coordinates c = self.codes if boundary_names is not None: if len(self.boundary_codes) != len(boundary_names): raise Exception( f"Number of ...
[ "def plot_fe_mesh(nodes, elements, element_marker=[0, 0.1]):\n plt.hold('on')\n all_x_L = [nodes[elements[e][0]] for e in range(len(elements))]\n element_boundaries = all_x_L + [nodes[-1]]\n for x in element_boundaries:\n plt.plot([x, x], element_marker, 'm--') # m gives dotted lines\n plt.pl...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Inorder traversal of graph blocks. Yields block and its depth.
def iterblocks(self): def traverse(b, depth): if type(b) is not tuple: return t, v = b v_type, v_start = t if v_type == 'block': yield v, depth else: for block in v: for...
[ "def iterateDepthFirst(self):\r\n gen = self.__iterateDepthFirst(self.root)\r\n for n in gen:\r\n yield n", "def _process_graph(graph, visited, inferred_types, backend):\n for i in range(graph.exit_index()):\n block = graph.block(i)\n if block not in visited:\n visited.add(blo...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Return list of files matching pattern in base folder.
def find_files(base, pattern): return [n for n in fnmatch.filter(os.listdir(base), pattern) if os.path.isfile(os.path.join(base, n))]
[ "def find_files(base, pattern):\n return [n for n in fnmatch.filter(os.listdir(base), pattern) if os.path.isfile(os.path.join(base, n))]", "def find_files(pattern, base='.'):\n regex = re.compile(pattern) # 为了效率而编译了它\n matches = list()\n for root, dirs, files in os.walk(base):\n for f in files...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Creates an instance of the NavBar class and associates it with this class.
def create_nav_bar(self): self.nav_bar = NavBar(self)
[ "def __init__(self):\n super(_MenuBar, self).__init__()\n\n # Create the sliding menu button\n self._menu_button = QPushButton(\"Show/hide menu\")\n self._menu_button.clicked.connect(lambda _: get_manager().menu.toggle())\n\n # Create the exit button\n self._exit_button = Q...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Creates an instance of the TextSection class and associates it with this class.
def create_text_section(self): y_scrollbar = ScrollBarComponent(self.root) y_scrollbar.set_options(RIGHT, Y) self.text_section = TextSection(self, yscrollcommand=y_scrollbar)
[ "def add_text(self, text, *args, **kwargs):\n # Pull down some kwargs.\n section_name = kwargs.pop('section', None)\n\n # Actually do the formatting.\n para, sp = self._preformat_text(text, *args, **kwargs)\n\n # Select the appropriate list to update\n if section_name is No...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Return the `NSImageView`_ that this object wraps.
def getNSImageView(self): return self._nsObject
[ "def native(self) -> Any:\n return self._widget._mgui_get_native_widget()", "def view(self, make_const=False):\n if make_const:\n return Image(image=_galsim.ConstImageView[self.dtype](self.image.view()),\n wcs=self.wcs)\n else:\n return Image(imag...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Set the image in the view. imagePath A file path to an image. imageNamed The name of an image already load as a `NSImage`_ by the application. imageObject A `NSImage`_ object.
def setImage(self, imagePath=None, imageNamed=None, imageObject=None): if imagePath is not None: image = NSImage.alloc().initWithContentsOfFile_(imagePath) elif imageNamed is not None: image = NSImage.imageNamed_(imageNamed) elif imageObject is not None: image...
[ "def setImage(self, path):\n\t\tpass", "def setImage(self, image, normalize = None):\n \n self.viewer.setImage(image, normalize)\n self.updateCaption()", "def setImage(self, img, regions, sizes, image_id=...) -> None:\n ...", "def setImage(self, image):\n if type(image) is n...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
The code below will need to be rewritten once the wordspider outputs csv with examples and translations. At present it takes input from a file containing example sentences on new lines, splits each line into words and removes punctuation marks, and generates urls based on the words.
def start_requests(self): with open('examples.csv', 'r') as file: fieldnames = [] for i, l in enumerate(file): fieldnames.append(i) with open('examples.csv') as csv_file: reader = csv.DictReader(csv_file) urls = [] baseurl = 'ht...
[ "def parse_sentences():\n with open('questions.hyp', 'r') as rf, open('webpages.txt', 'w') as wf: # open input and output files\n for line in rf: # iterate over lines in input file (questions.hyp has the language model transcriptions)\n # get the relevant info from the line\n ls = li...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Gets the shared storage from the redis server for the service.
def get_shared_storage(self): shared_storage = self.redis_client.get(self.service_type) shared_storage = json.loads(shared_storage) validate_json(shared_storage, self.schema) return shared_storage
[ "def star_storage_service(self) -> StorageService:\n return self.storage_services[self.config.storage.star]", "def set_shared_storage(self, shared_storage):\n validate_json(shared_storage, self.schema)\n shared_storage = json.dumps(shared_storage)\n self.redis_client.set(self.service_t...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Sets the shared storage in the redis server for the service.
def set_shared_storage(self, shared_storage): validate_json(shared_storage, self.schema) shared_storage = json.dumps(shared_storage) self.redis_client.set(self.service_type, shared_storage) return True
[ "def get_shared_storage(self):\n shared_storage = self.redis_client.get(self.service_type)\n shared_storage = json.loads(shared_storage)\n validate_json(shared_storage, self.schema)\n return shared_storage", "def store_shared_json_data(self, shared_id, json_data):\n try:\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
funtction to authenticate user activation from the email
def activate(request, uidb64, token): try: uid = force_text(urlsafe_base64_decode(uidb64)) user = User.objects.get(pk=uid) except (TypeError, ValueError, OverflowError, User.DoesNotExist): user = None if user is not None and account_activation_token.check_token(user, token): ...
[ "def activate(request, uidb64, token):\n try:\n uid = force_text(urlsafe_base64_decode(uidb64))\n user = User.objects.get(pk=uid)\n except(TypeError, ValueError, OverflowError, User.DoesNotExist):\n user = None\n if user is not None and account_activation_token.check_token(user, token)...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
rendering images by profile owner
def profile(request): current_user = request.user prof_details = User_prof.objects.filter(username = current_user.id).all() user_images = Image.objects.filter(username = current_user).all() return render(request, 'all_templates/profile.html', {'prof_data': prof_details,'user_images':user_images})
[ "def render_profile_pic(self, data: Dict[str, Any] = {}):\n profile_pic = data.get('profile', \"\")\n\n # with st.beta_container():\n # _, mid_column, _ = st.beta_columns(3)\n\n # with mid_column: \n # render_svg(\"./assets/images/Synergos-Logo.svg\")\n re...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Copy file at original_path to file at destination_path
def copy_file(original_path, destination_path): shutil.copyfile(original_path, destination_path)
[ "def copy_file(self, origin_path: str, dest_path: str):\n shutil.copy2(origin_path, dest_path)", "def copy_file(cls, path, source_dir, destination_dir):\n if not (source_dir / path).exists():\n return\n shutil.copyfile(str(source_dir / path), str(destination_dir / path))", "def c...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Rename the file at path to new_file_name, optionally appending a prefix, suffix, and changing the extension.
def rename(filepath, new_file_name=None, prefix=None, suffix=None, new_extension=None): old_file_path, old_extension = os.path.splitext(filepath) old_file_name = os.path.basename(old_file_path) file_dir = os.path.dirname(old_file_path) if not new_file_name: new_file_name = old_file_name if...
[ "def modify_filename_in_path(file_path, new_name=None, added=None,\n prefix=False):\n # Normalize input to Path object and build new file name.\n file_path = Path(file_path)\n if new_name is None:\n new_name = file_path.stem\n if added is not None:\n if prefix:\n...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Find a hobart compatible database in the given directory, if one exists.
def find_hobart_database(directory): if not path.is_directory(directory): raise exceptions.InvalidDirectoryError(directory) hobart_database_name = 'dbft?.db' hobart_glob = path.make_path(directory, hobart_database_name) results = glob.glob(hobart_glob) if not results or not len(results): ...
[ "def __discover_database_path__(self):\n for path in MIXXX_DATABASE_PATHS:\n if os.path.isfile(path):\n return path\n raise MixxxDatabaseError('Mixxx database not found')", "def find_config_db():\n search_path = [os.path.dirname(os.path.realpath(sys.argv[0])),\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Convert a mongodb collection (all elements must have same attributes) to a shapefile
def mongodb2shape(mongodb_server, mongodb_port, mongodb_db, mongodb_collection, output_shape): print ' Converting a mongodb collection to a shapefile ' connection = Connection(mongodb_server, mongodb_port) print 'Getting database MongoDB %s...' % mongodb_db db = connection[mongodb_db] ...
[ "def shape2mongodb(shape_path, mongodb_server, mongodb_port, mongodb_db, mongodb_collection, append, query_filter):\n print ' Converting a shapefile to a mongodb collection '\n driver = ogr.GetDriverByName('ESRI Shapefile')\n print 'Opening the shapefile %s...' % shape_path\n ds = driver.Open(shape_path...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Visits the current node printing the value
def visit(self): print self.val
[ "def _print_value(node):\n if is_red(node):\n return \"{red_color}{value}{reset_color}\".format(\n red_color=TERM_RED_COLOR,\n value=node.value,\n reset_color=TERM_RESET_COLOR\n )\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Build a string decision tree.
def build_decision_tree(t, v, d=''): n_nodes = t.tree_.node_count children_left = t.tree_.children_left children_right = t.tree_.children_right feature = t.tree_.feature threshold = t.tree_.threshold node_depth = np.zeros(shape=n_nodes) is_leaves = np.zeros(shape=n_nodes, dtype=bool) s...
[ "def build_tree(data):\n attributes = list(data.columns.values)\n target = attributes[-1]\n return create_decision_tree(data,attributes,target,IG)", "def build_tree(data):\n #print(\"Creating node from data...\")\n #pp.pprint(data)\n node = Node()\n\n # Check to see if all the labels are the ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Create simple decision tree.
def create_simple_tree(x, y): dec_tree = tree.DecisionTreeClassifier() return dec_tree.fit(x, y)
[ "def build_tree(data):\n attributes = list(data.columns.values)\n target = attributes[-1]\n return create_decision_tree(data,attributes,target,IG)", "def build_tree(data, impurity, p_val=1):\r\n \r\n \r\n ###########################################################################\r\n # TO...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Creates a DataFrame with fake "new experimental data" for testing purposes. Does this by instantiating a temporary CFM model and using the future_data it generates as a template. Then the template is filled with fake data.
def create_fake_CFM_exp_data(cfm_target_col='BL1-A', cfm_experimental_condition_cols=None): cfm_data = load_CFM_demo_data() if cfm_experimental_condition_cols is None: cfm_experimental_condition_cols = ['strain_name', 'inducer_concentration_mM'] temp_cfm = CircuitFluorescenceModel(initial_data=cfm_...
[ "def raw_data(self) -> pd.DataFrame:\n\n min_date = \"2016-01-01\"\n max_date = \"2019-12-13\"\n raw_data = [\n self.generate_data_for_one_customer(i, min_date, max_date)\n for i in range(100)\n ]\n raw_data = pd.concat(raw_data, axis=0)\n for i in ran...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Creates a DataFrame with fake "new experimental data" for testing purposes. Does this by instantiating a temporary HRM model and using the future_data it generates as a template. Then the template is filled with fake data.
def create_fake_HRM_exp_data(hrm_target_col="logFC_wt", hrm_experimental_condition_cols=None): hrm_data = load_HRM_demo_data() if hrm_experimental_condition_cols is None: hrm_experimental_condition_cols = ["ca_concentration", "iptg_concentration", "va_concentration", ...
[ "def create_fake_CFM_exp_data(cfm_target_col='BL1-A', cfm_experimental_condition_cols=None):\n cfm_data = load_CFM_demo_data()\n if cfm_experimental_condition_cols is None:\n cfm_experimental_condition_cols = ['strain_name', 'inducer_concentration_mM']\n\n temp_cfm = CircuitFluorescenceModel(initial...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Scrapes imdb top 250 page to find rank, title, year, rating, no of users rated, url for user reviews
def scrape_imdb_top250(): # IMDB top 250 Movies source = requests.get('https://www.imdb.com/chart/top/?ref_=nv_mv_250').text soup = BeautifulSoup(source, 'lxml') table = soup.find('tbody', class_='lister-list') rank = 1 movies = [] for rowRaw in table.find_all('tr'): row = rowRaw....
[ "def scrape_user_reviews(movies):\n user_reviews = []\n for movie in movies:\n review_count = 0\n review_movie_rank = movie[1]\n review_movie = movie[2]\n review_url = movie[6]\n # form the proper url\n review_url = f\"https://www.imdb.com/{review_url}reviews?sort=rev...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Scrapes the user review page for all movies and collects reviews from the top reviewers. The data from this can be further used for sentiment analysis and other data analysis.
def scrape_user_reviews(movies): user_reviews = [] for movie in movies: review_count = 0 review_movie_rank = movie[1] review_movie = movie[2] review_url = movie[6] # form the proper url review_url = f"https://www.imdb.com/{review_url}reviews?sort=reviewVolume&dir=...
[ "def fetch_data(movies):\n reviews = list()\n for key, val in movies.items():\n\n # sending request to access the particular url\n movie_url = val[1]\n print(\"Getting Data of Movie : {}\".format(key))\n response = requests.get(movie_url)\n soup = BeautifulSoup(response.cont...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Gets the socket_type_hash of this DestinyDefinitionsDestinyItemSocketEntryDefinition.
def socket_type_hash(self): return self._socket_type_hash
[ "def type(self) -> SocketType:\n return self._type", "def socket_id(self):\n return self._test_protocol.socket_id", "def getTypeId(self) -> \"SoType\":\n return _coin.SoKeyboardEvent_getTypeId(self)", "def getTypeId(self) -> \"SoType\":\n return _coin.ScXMLSendElt_getTypeId(self)",...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Sets the socket_type_hash of this DestinyDefinitionsDestinyItemSocketEntryDefinition.
def socket_type_hash(self, socket_type_hash): self._socket_type_hash = socket_type_hash
[ "def socket_type_hash(self):\n return self._socket_type_hash", "def type(self) -> SocketType:\n return self._type", "def write_socket(self, socket_info: int):\n self.write_metadata_by_name(self.SOCKET_KEY, str(socket_info))", "def set_guest_socket(self, guest_socket):\n \n s...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Gets the single_initial_item_hash of this DestinyDefinitionsDestinyItemSocketEntryDefinition. If a valid hash, this is the hash identifier for the DestinyInventoryItemDefinitionrepresenting the Plug that will be initially inserted into the item on item creation.Otherwise, this Socket will either start without a plug in...
def single_initial_item_hash(self): return self._single_initial_item_hash
[ "def _get_hash_partial(self):\n hash_value = 0\n \n # available\n hash_value ^= self.available\n \n # description\n description = self.description\n if (description is not None):\n hash_value ^= hash(description)\n \n # format\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Sets the single_initial_item_hash of this DestinyDefinitionsDestinyItemSocketEntryDefinition. If a valid hash, this is the hash identifier for the DestinyInventoryItemDefinitionrepresenting the Plug that will be initially inserted into the item on item creation.Otherwise, this Socket will either start without a plug in...
def single_initial_item_hash(self, single_initial_item_hash): self._single_initial_item_hash = single_initial_item_hash
[ "def single_initial_item_hash(self):\n return self._single_initial_item_hash", "def initialize_item_factory_state(self, state_key, initial_data):\n self._initialize_state(\n self._game_state['item_factories'], state_key, initial_data)", "def item_init(event):\n\n item_init.log.info(\...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Gets the reusable_plug_items of this DestinyDefinitionsDestinyItemSocketEntryDefinition.
def reusable_plug_items(self): return self._reusable_plug_items
[ "def reusable_config_values(self) -> pulumi.Input['ReusableConfigValuesArgs']:\n return pulumi.get(self, \"reusable_config_values\")", "def reusable_config(self) -> pulumi.Input[str]:\n return pulumi.get(self, \"reusable_config\")", "def hot_pluggable(self):\n ret = self._get_attr(\"hotPlug...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Sets the reusable_plug_items of this DestinyDefinitionsDestinyItemSocketEntryDefinition.
def reusable_plug_items(self, reusable_plug_items): self._reusable_plug_items = reusable_plug_items
[ "def reusable_plug_items(self):\n return self._reusable_plug_items", "def reusable_config_values(self) -> pulumi.Input['ReusableConfigValuesArgs']:\n return pulumi.get(self, \"reusable_config_values\")", "def reusable_config(self) -> pulumi.Input[str]:\n return pulumi.get(self, \"reusable_c...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Tests the neutron_utils.get_external_network_names to ensure the configured self.ext_net_name is contained within the returned list
def test_retrieve_ext_network_name(self): neutron = neutron_utils.neutron_client(self.os_creds, self.os_session) ext_networks = neutron_utils.get_external_networks(neutron) found = False for network in ext_networks: if network.name == self.ext_net_name: found ...
[ "def get_external_lns_names(self) -> List[Info]:\n return self.get_lns_names(domain=self.wallet.get_addresses(), inv=True)", "def ext_network_ok(default_gateway, external_netmask, external_ip_range):\n ext_network = to_network(default_gateway, external_netmask)\n ext_ip_low, ext_ip_high = [ipaddress....
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Tests the neutron_utils.create_network() function
def test_create_network(self): self.network = neutron_utils.create_network( self.neutron, self.os_creds, self.net_config.network_settings) self.assertEqual(self.net_config.network_settings.name, self.network.name) self.assertTrue(validate_network( ...
[ "def create_network():\n with settings(warn_only=True):\n run(f'docker network create {network_name}')", "def test_create_network_null_name(self):\n with self.assertRaises(Exception):\n self.network = neutron_utils.create_network(\n self.neutron, self.os_creds,\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Tests the neutron_utils.create_network() function with an empty network name
def test_create_network_empty_name(self): with self.assertRaises(Exception): self.network = neutron_utils.create_network( self.neutron, self.os_creds, network_settings=NetworkConfig(name=''))
[ "def test_create_network_null_name(self):\n with self.assertRaises(Exception):\n self.network = neutron_utils.create_network(\n self.neutron, self.os_creds,\n network_settings=NetworkConfig())", "def create_network():\n with settings(warn_only=True):\n run...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Tests the neutron_utils.create_network() function when the network name is None
def test_create_network_null_name(self): with self.assertRaises(Exception): self.network = neutron_utils.create_network( self.neutron, self.os_creds, network_settings=NetworkConfig())
[ "def test_create_network_empty_name(self):\n with self.assertRaises(Exception):\n self.network = neutron_utils.create_network(\n self.neutron, self.os_creds,\n network_settings=NetworkConfig(name=''))", "def create_network():\n with settings(warn_only=True):\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Tests the neutron_utils.create_neutron_subnet() function for an Exception when the subnet name is None
def test_create_subnet_null_name(self): self.network = neutron_utils.create_network( self.neutron, self.os_creds, self.net_config.network_settings) self.assertEqual(self.net_config.network_settings.name, self.network.name) self.assertTrue(validate_network( ...
[ "def test_create_subnet_null_cidr(self):\n self.net_config.network_settings.subnet_settings[0].cidr = None\n with self.assertRaises(Exception):\n self.network = neutron_utils.create_network(\n self.neutron, self.os_creds, self.net_config.network_settings)", "def test_create...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Tests the neutron_utils.create_neutron_subnet() function for an Exception when the subnet CIDR value is None
def test_create_subnet_null_cidr(self): self.net_config.network_settings.subnet_settings[0].cidr = None with self.assertRaises(Exception): self.network = neutron_utils.create_network( self.neutron, self.os_creds, self.net_config.network_settings)
[ "def test_create_subnet_empty_cidr(self):\n self.net_config.network_settings.subnet_settings[0].cidr = ''\n with self.assertRaises(Exception):\n self.network = neutron_utils.create_network(\n self.neutron, self.os_creds, self.net_config.network_settings)", "def test_create_...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }