query
stringlengths
9
9.05k
document
stringlengths
10
222k
negatives
listlengths
19
20
metadata
dict
Checks that the initial force/acceleration is sufficient to start rolling. It needs to be 2.52 times higher than rolling friction force.
def init_acc(a): Roll_fric = 0.02 # [-] Rolling friction coefficient of airplane wheels if a[1] >= 2.5*Roll_fric: return True else: return False
[ "def __check_initial_conditions_feasibility(self):\n for chromosome in self.starting_gen:\n if len(chromosome) is not len(self.variables):\n raise Exception('Length of chromosome is not equal to ' +\n 'length of defined variables')", "def gravity(sel...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Function that can be used for engine sizing, it shows the required torque and power at the different RPM for both the ring gear and engine. It also indicates performance of the existing engine.
def EGTS_tor_rpm_pow(torque, power, velocity, GR): # Efficiencies n_gear = 0.9875 # Gear efficiency (torque loss -> power loss) amount_gears = 2 n_emotor = 0.95 # Electricmotor efficiency (electrical loss - power loss) torque_out = (1/n_gear)**amount_gears*np.array(torque) # [Nm] Required engine...
[ "def EGTS_only_perf(GR):\n #Power available\n P_APU = 62 # [kW] Available apu power\n P_sen = 0 # [kW]\n P_comp = 0 # [kW]\n P_av_e = (P_APU-P_sen-P_comp)*1000/2 # [W] APU power available per engine\n\n # Efficiencies powertrain\n n_circuit = 0.97\n...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Function that calculates the (peak) power required to power each car wheel based upon the acceleration and speed.
def car_power(a, v, ratio, pow_wheel=4): # cte w_rad_car_1 = 0.537 # [m] wheel radius front tires external truck w_rad_car_2 = 0.537 # [m] wheel radius rear tires external truck 0.496 m_plane = 97400 # [kg] MRW m_car = 22000 # [kg] Weight of external vehicle...
[ "def calcPower(speed, resistance_level):\r\n satoridata = [\r\n {\r\n 'level': 1,\r\n 'slope': 3.73,\r\n 'intercept': -28.67\r\n },\r\n {\r\n 'level': 2,\r\n 'slope': 5.33,\r\n 'intercept': -36.67\r\n },\r\n {\r\...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
This function calculates the egts only performance based upon the available APU power. It also plots this performance.
def EGTS_only_perf(GR): #Power available P_APU = 62 # [kW] Available apu power P_sen = 0 # [kW] P_comp = 0 # [kW] P_av_e = (P_APU-P_sen-P_comp)*1000/2 # [W] APU power available per engine # Efficiencies powertrain n_circuit = 0.97 n_gear = 0...
[ "def elia_activatedreserves_graphs(dfpricevol, price_vol, fromdate, todate, producttypes):\r\n \r\n if (producttypes == \"all\"):\r\n producttypes = [\"Bids+\", \"Bids-\", \"ICH\", \"IGCC-\", \"IGCC+\", \"R2+\", \"R2-\",\"R3 flex\",\"R3 std\", \"R3+\",\"R3-\",\"SR\",\"NRV\"]\r\n \r\n volumesl...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
View the connections tables as widget.
def view_election_connections_table(self, request): @request.after def add_last_modified(response): add_last_modified_header(response, self.last_modified) return { 'model': self, 'layout': ElectionLayout(self, request), 'connections': get_connection_results_api(self, object...
[ "def viewdatabase(self):\r\n try:\r\n if self.vertical_widget.isHidden():\r\n self.vertical_widget.setVisible(True)\r\n else:\r\n self.vertical_widget.setVisible(False)\r\n except Exception as e:\r\n print(e)", "def show(self):\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
View the connections as SVG.
def view_election_connections_svg(self, request): layout = ElectionLayout(self, request, 'connections') return { 'path': layout.svg_path, 'name': layout.svg_name }
[ "def visualize(self):\n return nx.draw_networkx(self.graph_Hz)", "def to_svg(self, separate=False, include_junctions=False):\n serialize_as_svg(\n self.output, separate=separate, include_junctions=include_junctions\n )", "def draw(self):\n nx.drawing.draw_networkx(self.gra...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Create a template database entry
def make_template(self): missing = TEMPLATE_REQUIRED.difference(self.data) if missing: return ("<h3>Template must have %s filled in.</h3>" % ', '.join(missing)) # Write a database entry xline = """insert into template (description, comment, calor...
[ "def _create_template(self):\n Template.objects.create(\n resume=\"a test\",\n shortcut='atest',\n subject=\"a subject\",\n body=\"A body {{ testme }}\"\n )", "def create(self, template):\n raise NotImplementedError('Create Template not implemented'...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Knock down the wall between cells self and other.
def knock_down_wall(self, other, wall): self.walls[wall] = False other.walls[Cell.wall_pairs[wall]] = False
[ "def break_wall(self, other):\n if self.i == other.i:\n if self.j == other.j - 1:\n self.walls['right'] = False\n other.walls['left'] = False\n elif self.j == other.j + 1:\n self.walls['left'] = False\n other.walls['right'] = F...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns the accuracy of a proposed partition with reference to a known true partition. Pr(A|B) is the probability of inferring relationship of type A between two individuals given that the true relationship is type B. This function estimates the total proportion of pairwise relationships inferred correctly, as well as ...
def partition_accuracy(true, proposed, rtype='all'): if rtype not in ['all', 'fs', 'hs']: print "rtype must be one of 'all', 'fs' or 'hs'." #return None real_FS = relation_matrix(true) part_FS = relation_matrix(proposed) r_given_r = real_FS == part_FS if rtype is 'all': cor...
[ "def testAnalyaticalPartitionIsCorrect(self):\n # Here we enumerate a set of positive rational numbers n/d alongside\n # numerically approximated values of Z(n / d) up to 10 digits of precision,\n # stored as (n, d, Z(n/d)). This was generated with an external mathematica\n # script.\n ground_truth_r...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Test if omdf.policy is installed in portal_wuickinstaller.
def test_product_installed(self): installer = getToolByName(self.portal, 'portal_quickinstaller') self.assertTrue(installer.isProductInstalled('reptheory.policy'))
[ "def _has_access_policy(self, sysmeta_pyxb):\n return bool(getattr(sysmeta_pyxb, \"accessPolicy\", False))", "def test_dependencies_installed(self):\n installer = getToolByName(self.portal, 'portal_quickinstaller')\n self.assertTrue(installer.isProductInstalled('ContentWellPortlets'))", "de...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Test that all product dependencies are installed.
def test_dependencies_installed(self): installer = getToolByName(self.portal, 'portal_quickinstaller') self.assertTrue(installer.isProductInstalled('ContentWellPortlets'))
[ "def test_product_installed(self):\n self.assertTrue(self.installer.isProductInstalled('collective.sassy'))", "def test_get_installs(self):\n pass", "def test_product_installed(self):\n self.assertTrue(self.installer.isProductInstalled('rapido.plone'))", "def test_product_installed(self):...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Gets the errormessage of this UnexpectedError.
def errormessage(self): return self._errormessage
[ "def get_api_error_message(self):\n if self.has_error(self.last_json_result[\"EOXRecord\"][0]):\n msg = \"%s (%s)\" % (self.get_error_description(self.last_json_result[\"EOXRecord\"][0]),\n self.last_json_result[\"EOXRecord\"][0]['EOXError']['ErrorID'])\n r...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Outputs a time series DataFrame with t ,t1, t2, t3, Age, Age1, Age2, Age3 for each playerseason. Since it's grouped into playerseasons, players can be seen multiple times
def combine_playerseasons(): # import name, year, minutes, my_stat dfs = pd.read_excel('NBA_proj.xlsx', sheet_name=[0,1,2,3,4,5,6], usecols='A:B,E,V') # filter for player-seasons with > 500 minutes for k in dfs.keys(): dfs[k] = dfs[k][dfs[k]['Minutes'] > 500] # con...
[ "def player_season_stats(player_name, player_id):\n\n try:\n player_gamelog = playergamelog.PlayerGameLog(player_id=str(player_id), season='2020',\n season_type_all_star='Regular Season')\n except:\n raise Exception(f'Failed to get data on play...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Display a message about what I'm learning.
def display_message(): msg = "I'm learning to store code in functions." print(msg)
[ "def print_greeting():\n print(\n \"\\nHi there! \\nI can help you figure out the notes of a scale or mode of your choice!\"\n )", "def greet_user(self):\n print(\"Greetings \" + self.f_name.title() + \" \" + self.l_name.title() + \" we hope you enjoy your stay with us!\")", "def greet_user(...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Return a tuple containing start/end strings of offering (UTC).
def getTimeIntervalOffering(self): codec16 = QtCore.QTextCodec.codecForName("UTF-16") start = unicode(codec16.fromUnicode(self.lblStartTime.text()), 'UTF-16') end = unicode(codec16.fromUnicode(self.lblEndTime.text()), 'UTF-16') #print "SOS:234", type(start), start, end return (st...
[ "def get_str_dates(self):\r\n start_str = self.start_datetime.strftime(\"%B %d, %Y\")\r\n end_str = self.end_datetime.strftime(\"%B %d, %Y\")\r\n return start_str + \" - \" + end_str", "def get_start_end_info(info):\n starttime = None\n stoptime = None\n startdate = None\...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Set index for PyQT4 list box, based on a list of text items.
def set_listbox(box, text_list): if not isinstance(text_list, list): text_list = [text_list,] result = False # sorry, no.\\ for text in text_list: items = box.findItems(text, QtCore.Qt.MatchFixedString) if items: it...
[ "def indexFromItem(self, QListWidgetItem): # real signature unknown; restored from __doc__\n pass", "def listItemSelected(self, index):\n self.selectedTitle = self.listBox.getSelectedItem()\n if self.selectedTitle == \"\":\n self.outputArea.setText(\"\")\n else:\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Remove all offering details when no SOS is selected.
def removeOfferings(self): self.clearOfferingRelatedItems() self.lbxOfferings.clear()
[ "def clearOfferingRelatedItems(self):\n self.lblDescription.setText('-')\n self.lblTL_X.setText('-')\n self.lblTL_Y.setText('-')\n self.lblBR_X.setText('-')\n self.lblBR_Y.setText('-')\n self.lblSRS.setText('-')\n self.lblEndTime = QtGui.QLabel('-')\n self.lbl...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Reset all displayed values related to offering and request.
def clearOfferingRelatedItems(self): self.lblDescription.setText('-') self.lblTL_X.setText('-') self.lblTL_Y.setText('-') self.lblBR_X.setText('-') self.lblBR_Y.setText('-') self.lblSRS.setText('-') self.lblEndTime = QtGui.QLabel('-') self.lblStartTime = Q...
[ "def clear_all(self):\n self.food_type_dropdown.set(\"\")\n self.food_names_dropdown.set(\"\")\n self.servings_dropdown.set(\"\")", "def reset(self):\n self.name.set('')\n self.number.set('')", "def Reset(self):\r\n self.grid = self.EmptyGrid()\r\n self.count = s...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Update offering details containers when new offering selected.
def offeringsChanged(self): self.clearOfferingRelatedItems() if self.lbxOfferings.selectedItems(): # assumes that a max of one offering can be selected selected_offering = self.lbxOfferings.selectedItems()[0].text() else: selected_offering = None if se...
[ "def offering_detail(request, course_sec_id):\n\n offering = get_object_or_404(Offering, course_sec_id=course_sec_id)\n\n # Is this offering already in ScheduleBuilder?\n try:\n builder = Builder.objects.get(profile=request.user.profile, offering=offering)\n scheduled = True\n except:\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Load the offerings from the service metadata.
def loadOfferings(self): if self.parent_widget.service and self.parent_widget.service.service_valid: self.removeOfferings() # clear current data self.contents = self.parent_widget.service.service.__dict__['contents'] #print "SOS:401 self.contents", self.contents ...
[ "def parse_offer(self, response):", "def list(cls, api_client, **kwargs):\n\n cmd = {}\n cmd.update(kwargs)\n if 'account' in kwargs.keys() and 'domainid' in kwargs.keys():\n cmd['listall'] = True\n return api_client.listServiceOfferings(**cmd)", "def load_biothings(self):...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Return a valid EPSG srsName according to OGC 09048r3
def get_valid_srs(self, srsURN): srs = None try: srs_items = srsURN.split(':') code = srs_items[len(srs_items) - 1] #print "SOS:427", srs_items, code if code and int(code) > 0: return 'urn:ogc:def:crs:EPSG::' + code # omit any version no. ...
[ "def check_epsg_code(str):\n crs = pyproj.CRS(str)\n return crs.to_epsg()", "def epsg_from_crs(crs): # -> int | None:\n ...", "def explicit_crs_from_epsg(crs=..., epsg=...): # -> CRS:\n ...", "def projection(self):\n try:\n return '{0} (EPSG:{1})'.format(self.dataset().GetProje...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Generate a calculator for the potential, given a slab
def calculator(self): self.logger.debug('Recieved a calculator access call') return potential.load(self.potentialname,self.element, self.slab)
[ "def select_calculator(model_name, n=150, size=(10, 40, 100)):\n a, b, c = size\n d_factor = 0.06 # for paracrystal models\n if model_name == 'sphere':\n calculator = build_model(\n 'sphere', n=n, radius=c)\n a = b = c\n elif model_name == 'sc_paracrystal':\n a = b = c\n...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Write the results_dict to the database
def write_results(self,results_dict):
[ "def export_results_to_db(db_conn, output_dict):\n print_log_msg(log_str='Export core GF completeness results to TRAPID database.')\n cursor = db_conn.cursor()\n # Kind of dumb way to create the request, but it works.\n columns = ', '.join(sorted(output_dict))\n values = ', '.join([\"\\'{insert_value...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
CMS interface to reversion api helper function. Registers model for reversion only if reversion is available. Auto excludes publisher fields.
def reversion_register(model_class, fields=None, follow=(), format="xml", exclude_fields=None): if not 'reversion' in settings.INSTALLED_APPS: return if fields and exclude_fields: raise ValueError("Just one of fields, exclude_fields arguments can be passed.") opts = model_clas...
[ "def register_model_version_relation(self, version: Text,\n model_id: int,\n project_snapshot_id: int = None) -> ModelVersionRelationMeta:\n try:\n model_version_relation = MetaToTable.model_version_relation_to_table(ver...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Build a Key with given urlsafe
def get_key_from_urlsafe(urlsafe): return ndb.Key(urlsafe=urlsafe)
[ "def _make_cache_key(url, permanent=False):\n return \"WebTemplate:%s:%s\" % (url, {True: \"p\", False: \"t\"}[permanent])", "def encode_key_as_urlsafe(obj):\n return obj.urlsafe()", "def construct_unique_key_google(google_baseurl, params):\n google_unique_key = f\"UNIQUE_KEY---{str(google_baseurl)}---{s...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Return model class from any query. Note that the model needs to be imported once in the application
def get_model_class_from_query(query): return ndb.Model._lookup_model(query.kind)
[ "def query_class(self):\n return self.query_class_loader.get_class(name=self.query_class_name)", "def model_class(self):\n try:\n entity = self._only_full_mapper_zero(\"\")\n except Exception: # pragma: no cover\n class_ = None\n else:\n class_ = entit...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Build a Key with given urlsafe and get the object
def get_object_from_urlsafe(urlsafe): return get_key_from_urlsafe(urlsafe)
[ "def get_key_from_urlsafe(urlsafe):\n return ndb.Key(urlsafe=urlsafe)", "def encode_key_as_urlsafe(obj):\n return obj.urlsafe()", "def key(self, key: any):\n self.suburl(str(key))\n return self", "def _make_cache_key(url, permanent=False):\n return \"WebTemplate:%s:%s\" % (url, {True: \"p...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Return all middleware classes
def get_middlewares(): middlewares = [] for middleware in settings.get('MIDDLEWARE_CLASSES', []): middlewares.append(load_class(middleware)()) return middlewares
[ "def all_adapters():\n return AdapterHandler().get_all_classes()", "def inspect_middleware(app: App) -> 'MiddlewareInfo':\n types_ = app_helpers.prepare_middleware(app._unprepared_middleware, True, app._ASGI)\n\n type_infos = []\n for stack in types_:\n current = []\n for method in stack...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Computes the roofline model for the given platforms. Returns The achievable performance
def roofline(num_platforms, peak_performance, peak_bandwidth, intensity): assert isinstance(num_platforms, int) and num_platforms > 0 assert isinstance(peak_performance, numpy.ndarray) assert isinstance(peak_bandwidth, numpy.ndarray) assert isinstance(intensity, numpy.ndarray) assert (num_platforms...
[ "def process(hw_platforms, sw_apps, xkcd):\n assert isinstance(hw_platforms, list)\n assert isinstance(sw_apps, list)\n assert isinstance(xkcd, bool)\n\n # arithmetic intensity\n arithmetic_intensity = numpy.logspace(START, STOP, num=N, base=2)\n # Hardware platforms\n platforms = [p[0] for p i...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Processes the hw_platforms and sw_apps to plot the Roofline.
def process(hw_platforms, sw_apps, xkcd): assert isinstance(hw_platforms, list) assert isinstance(sw_apps, list) assert isinstance(xkcd, bool) # arithmetic intensity arithmetic_intensity = numpy.logspace(START, STOP, num=N, base=2) # Hardware platforms platforms = [p[0] for p in hw_platform...
[ "def initialize_geometries(self):\n process = self.dataselector.selected_process\n\n if process == 'Diffractie (Kd)':\n # Lines from location to breakwater head\n for name in self.result_locations['Naam'].array:\n self.elements[name], = self.ax.plot([], [], color='...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Reads CSV file and returns a list of row_lenary tuples
def read_file(filename, row_len, csv_name): assert isinstance(row_len, int) elements = [] try: in_file = open(filename, 'r', encoding='utf-8') \ if filename is not None else sys.stdin reader = csv.reader(in_file, dialect='excel') for row in reader: if len(...
[ "def get_csv_rows(file_path):\n # log.info(\"Module: {} Function: {}\".format(__name__, sys._getframe().f_code.co_name))\n list = []\n # log.info(file_path)\n if not os.path.isfile(file_path):\n err_msg = \"File does not exist: {}\".format(file_path)\n raise Exception(err_msg)\n with open(file_path, mode...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Add column to list of sentences
def add_column(sentences, columns): new_sentences = [] for sentence, column in zip(sentences, columns): new_sentences.append( [tup + [col] for tup, col in zip(sentence, column)] ) return new_sentences
[ "def get_column(sentences, i):\n columns = []\n for sentence in sentences:\n columns.append([tup[i] for tup in sentence])\n return columns", "def add_tokenized_column(self, df, column_name_to_tokenize):\n COL = column_name_to_tokenize\n df_with_tokens = df.assign(**{f'tokens_{COL}': lambda df:...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Get a column of information from sentences
def get_column(sentences, i): columns = [] for sentence in sentences: columns.append([tup[i] for tup in sentence]) return columns
[ "def separate_columns(parser_regex, line_text):\n raw_columns = re.search(parser_regex, line_text).groups()\n return [c.strip() for c in raw_columns]", "def get_doc_text(self, doc_name):\n doc_sents = []\n doc_sents_start_idx = []\n\n tmp = self._db_select(\"SELECT id FR...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Convert a tag sequence from conll format to other format.
def tags_from_conll(tags, scheme='bio'): def entity_span_from_conll(entity_span, scheme=scheme): if not entity_span: return entity_span # Logic are performed in order of precedence. if 'e' in scheme: entity_span[-1] = 'E' + entity_span[-1][1:] if 'b' in scheme: entity_span[0] = 'B' +...
[ "def tags_to_conll(tags):\n def entity_span_to_conll(entity_span, prev_is_same_entity=False):\n if not entity_span:\n return entity_span\n for i in range(len(entity_span)):\n entity_span[i] = 'I' + entity_span[i][1:]\n if prev_is_same_entity:\n entity_span[0] = 'B' + entity_span[0][1:]\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Convert a tag sequence to conll format from our format.
def tags_to_conll(tags): def entity_span_to_conll(entity_span, prev_is_same_entity=False): if not entity_span: return entity_span for i in range(len(entity_span)): entity_span[i] = 'I' + entity_span[i][1:] if prev_is_same_entity: entity_span[0] = 'B' + entity_span[0][1:] return entit...
[ "def _iob1_to_iob2(tags: List[str]) -> List[str]:\n # https://gist.github.com/allanj/b9bd448dc9b70d71eb7c2b6dd33fe4ef\n\n result = []\n for i, tag in enumerate(tags):\n if tag == \"O\":\n result.append(\"O\")\n continue\n\n split = tag.split(\...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Convert sentences to conll format. Can also be used to convert a sequence of tags to conll format.
def data_to_conll(sentences): new_sentences = [] for sentence in sentences: tags = [tup[-1] for tup in sentence] new_tags = tags_to_conll(tags) new_sentences.append([ tup[:-1] + [tag] for tup, tag in zip(sentence, new_tags) ]) return new_sentences
[ "def taggedsents_to_conll(sentences):\n for sentence in sentences:\n yield from taggedsent_to_conll(sentence)\n yield \"\\n\\n\"", "def tags_to_conll(tags):\n def entity_span_to_conll(entity_span, prev_is_same_entity=False):\n if not entity_span:\n return entity_span\n for i in range(...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Register a listener function for the given target.
def listen( target: Any, identifier: str, fn: Callable[..., Any], *args: Any, **kw: Any ) -> None: _event_key(target, identifier, fn).listen(*args, **kw)
[ "def listens_for(\n target: Any, identifier: str, *args: Any, **kw: Any\n) -> Callable[[Callable[..., Any]], Callable[..., Any]]:\n\n def decorate(fn: Callable[..., Any]) -> Callable[..., Any]:\n listen(target, identifier, fn, *args, **kw)\n return fn\n\n return decorate", "def listen(self,...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Decorate a function as a listener for the given target + identifier.
def listens_for( target: Any, identifier: str, *args: Any, **kw: Any ) -> Callable[[Callable[..., Any]], Callable[..., Any]]: def decorate(fn: Callable[..., Any]) -> Callable[..., Any]: listen(target, identifier, fn, *args, **kw) return fn return decorate
[ "def listen(\n target: Any, identifier: str, fn: Callable[..., Any], *args: Any, **kw: Any\n) -> None:\n\n _event_key(target, identifier, fn).listen(*args, **kw)", "def listen(name, highlander=False, singleton=False):\n def decorator(func):\n\n listeners = _events.get(name, [])\n if highlan...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Sets the given option. Might raise a ValueError.
def _set_option(msat_config, name, value): check = mathsat.msat_set_option(msat_config, name, value) if check != 0: raise PysmtValueError("Error setting the option '%s=%s'" % (name,value))
[ "def set(self, *args, **kargs):\n self.set_option(*args, **kargs)", "def set_option(self, key, value):\n self.options.set(key, value)", "def set_server_option(self, option): # real signature unknown; restored from __doc__\n pass", "def setOption(name, value):\n \n if _fwk is not Non...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
After a call to solve() yielding UNSAT, returns the unsat core as a set of formulae
def get_unsat_core(self): self._check_unsat_core_config() if self.options.unsat_cores_mode == "all": terms = mathsat.msat_get_unsat_core(self.msat_env()) if terms is None: raise InternalSolverError( mathsat.msat_last_error_message(self.msat_en...
[ "def stickel_method(U: Set[Equation], ac_symbol: Function) -> SubstituteTerm:\n # Gather all variables for fresh var calculation\n ALL_VARS = vars_from_equations(U)\n original_from_generalized : Dict[Variable, Term] = dict()\n\n def generalize_term(t: Term) -> Variable:\n \"\"\"\n Returns ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
After a call to solve() yielding UNSAT, returns the unsat core as a dict of names to formulae
def get_named_unsat_core(self): self._check_unsat_core_config() if self.options.unsat_cores_mode == "named": assumptions = mathsat.msat_get_unsat_assumptions(self.msat_env()) pysmt_assumptions = set(self.converter.back(t) for t in assumptions) res = {} n...
[ "def stickel_method(U: Set[Equation], ac_symbol: Function) -> SubstituteTerm:\n # Gather all variables for fresh var calculation\n ALL_VARS = vars_from_equations(U)\n original_from_generalized : Dict[Variable, Term] = dict()\n\n def generalize_term(t: Term) -> Variable:\n \"\"\"\n Returns ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns the most generic, yet compatible type between ty1 and ty2
def _most_generic(self, ty1, ty2): if ty1 == ty2: return ty1 assert ty1 in [types.REAL, types.INT], str(ty1) assert ty2 in [types.REAL, types.INT], str(ty2) return types.REAL
[ "def get_precedent_type(type1, type2):\n if type1 == complex or type2 == complex:\n return complex\n\n if type1 == float or type2 == float:\n return float\n\n return int", "def _merge_tensor_type(old_type, obtained_type, backend):\n if old_type is None:\n return obtained_type\n # Updat...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns the signature of the given term.
def _get_signature(self, term, args): decl = mathsat.msat_term_get_decl(term) tag = mathsat.msat_decl_get_tag(self.msat_env(), decl) try: return self.term_sig[tag](term, args) except KeyError: raise ConvertExpressionError("Unsupported expression:", ...
[ "def _get_signature(self, req):\r\n sig = req.params.get('Signature') or req.params.get('X-Amz-Signature')\r\n if sig is None and 'Authorization' in req.headers:\r\n auth_str = req.headers['Authorization']\r\n sig = auth_str.partition(\"Signature=\")[2].split(',')[0]\r\n\r\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Create a function that for the given op. This is used in the construction of back_fun, to simplify the code.
def _back_adapter(self, op): def back_apply(term, args): return op(*args) return back_apply
[ "def _e_op_func(self, e_op):\n if isinstance(e_op, Qobj):\n return lambda t, ado_state: (ado_state.rho * e_op).tr()\n elif isinstance(e_op, QobjEvo):\n return lambda t, ado_state: e_op.expect(t, ado_state.rho)\n elif callable(e_op):\n return e_op\n raise ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Convert a PySMT formula into a MathSat Term. This function might throw a InternalSolverError exception if an error during conversion occurs.
def convert(self, formula): # Rewrite to avoid UF with bool args rformula = self._ufrewriter.walk(formula) res = self.walk(rformula) if mathsat.MSAT_ERROR_TERM(res): msat_msg = mathsat.msat_last_error_message(self.msat_env()) raise InternalSolverError(msat_msg) ...
[ "def make_sympy(self, xml=None): # lint-amnesty, pylint: disable=too-many-statements\n\n if self.the_sympy:\n return self.the_sympy\n\n if xml is None:\t # root\n if not self.is_mathml():\n return my_sympify(self.expr)\n if self.is_presentation_mathml()...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Convert a pySMT type into a MathSAT type.
def _type_to_msat(self, tp): if tp.is_bool_type(): return self.boolType elif tp.is_real_type(): return self.realType elif tp.is_int_type(): return self.intType elif tp.is_function_type(): stps = [self._type_to_msat(x) for x in tp.param_type...
[ "def _msat_type_to_type(self, tp):\n if mathsat.msat_is_bool_type(self.msat_env(), tp):\n return types.BOOL\n elif mathsat.msat_is_rational_type(self.msat_env(), tp):\n return types.REAL\n elif mathsat.msat_is_integer_type(self.msat_env(), tp):\n return types.IN...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Converts a MathSAT type into a PySMT type.
def _msat_type_to_type(self, tp): if mathsat.msat_is_bool_type(self.msat_env(), tp): return types.BOOL elif mathsat.msat_is_rational_type(self.msat_env(), tp): return types.REAL elif mathsat.msat_is_integer_type(self.msat_env(), tp): return types.INT e...
[ "def _type_to_msat(self, tp):\n if tp.is_bool_type():\n return self.boolType\n elif tp.is_real_type():\n return self.realType\n elif tp.is_int_type():\n return self.intType\n elif tp.is_function_type():\n stps = [self._type_to_msat(x) for x in ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Initialize the Quantifier Eliminator using 'fm' or 'lw'.
def __init__(self, environment, logic=None, algorithm='lw'): if algorithm not in ['fm', 'lw']: raise PysmtValueError("Algorithm can be either 'fm' or 'lw'") if logic is not None and (not logic <= LRA and algorithm != "lw"): raise PysmtValueError("MathSAT quantifi...
[ "def initialize(fmp_file, lo_freq, lo_multiply=8, fm_rate=5.0):\n dt = 1.0 / float(fm_rate)\n listfreq = fmlolc.listfreq(fmp_file, lo_freq, lo_multiply)\n\n finalize()\n\n with fmlolc.SCPI(**fmlolc.INFO_XFFTS) as xffts:\n xffts('XFFTS:CMDUSEDSECTIONS 1 1 1 1')\n xffts('XFFTS:CMDSYNCTIME {0...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Gets product name and price from the user
def input_product(): product_name = input("Enter the name:") product_price = input("Enter the price:") return product_name, product_price
[ "def input_name_and_price():\n obj_product = Product(product_name='', product_price=0)\n try:\n obj_product.product_name = str(input('Product name: '))\n obj_product.product_price = str(input('Product price: '))\n except Exception as e:\n print(e)\n retur...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Path to repository on the ci (locally).
def repo_dir(self):
[ "def get_repositories_path(self):\n return os.path.abspath(os.path.join(os.path.dirname(__file__), \"../../packages\"))", "def repo_path(conf, repo):\n\n return os.path.join(conf[\"mirrors\"], repo_name(repo))", "def get_git_repo_path():\n return os.path.join(DEEPSPEECH_CLONE_PATH, '.git')", "def...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
takes a list of words and computes all posible permutations of the words in the string seperated by spaces. E.g. it receives ['a','b',..] and returns ['a b', 'b a',...]
def permute_words(n, r): return [" ".join(map(str, comb)) for comb in permutations(n, r)]
[ "def permute(letter_list):\n results = []\n re_str = '^'+''.join(map(lambda w: w+'?', sorted(letter_list)))+'$'\n for word in WORDS:\n letters = ''.join(sorted(word))\n if re.search(re_str, letters):\n results.append(word)\n return map_results(sorted(results, key=len, reverse=Tr...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
takes a set of words and filters out the ones with letters not in anagram.
def filter_words(words): word_bag = set() for line in words: word = line.rstrip('\n') if (is_anagram(word)): word_bag.add(word) return word_bag
[ "def filterCipher(charsequence):\n return filter(lambda x: x in anagram_characters, charsequence)", "def find_matching_words(anagram, word_list):\r\n pass", "def unscramble_words(scrambled_words, word_list):\n output = []\n for i in scrambled_words:\n for k in word_list:\n if len(i) ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
builds phrases of certain length using word_candids_map and check if the phrase is one of the phrases we are looking for.
def search_for_phrases(word_candids_map, phrase_len, word_len_map, start_time): candid_comb_len = phrase_len - 1 phrase = [""] * phrase_len # take one word at a time and build phrases with it and different # combination of its candidates for word, candids in word_candids_map.items(): candid_combos = combinat...
[ "def match_phrases(post, common_words, phrase_length, phrase_map):\n result = set()\n trimmed_words = post.words_removed(common_words, True)\n for i in range(len(trimmed_words) - (phrase_length - 1)):\n phrase = tuple(trimmed_words[i:i+phrase_length])\n try:\n result.add(phrase_map...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Place elements at starting thing locations.
def place_starts(self): # Create a list of things that the grid generation starts at. start_things = [] for thing_type in self.config.start_thing_types: start_things.extend(self.map_data.get_thing_list(thing_type)) # Add the initial things as initial element...
[ "def place_grid(grid, final_grid, start_x):\n for x in range(grid.width):\n for y in range(grid.height):\n cell = grid.get_cell(x, y)\n final_grid.set_cell(start_x + x, y, cell)", "def setup_locators(self):\n for i in range(0, 9):\n locator = cmd.spaceLocator(n=se...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Remove elements from the elements_prune set from the element list.
def remove_pruned_elements(self): # Filter prune elements from the element list. self.elements = filter(lambda element: element not in self.element_prune, self.elements) # Remove pruned elements from the element hash table. for element in self.element_prune: ...
[ "def subtract_list_from_other_via_set_diff(lista, elems_to_remove):\n s1 = set(lista)\n s2 = set(elems_to_remove)\n remains_in_s1 = s1 - s2\n lista = list(remains_in_s1)\n return lista", "def filter_out_elements(self, eles):\n\n if isinstance(eles, list):\n for ele in eles:\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns an element at the x,y,z coordinates, or None if no element exists at those coordinates.
def get_element_xyz(self, x, y, z): element_hash = x + (y * self.size.x) elements = self.element_hash.get(element_hash) if elements is not None: return elements.get(z) return None
[ "def getElementByCoordinates(x, y, z, dim=-1, strict=False):", "def get_object(self, x, y, z):\r\n for block in self._blocks:\r\n if (x, y, z) == block.location():\r\n return block\r\n if (x, y, z) == self._drone.location():\r\n return self._drone\r\n retu...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns a list of elements at the 2d coordinates, or None if no list exists at those coordinates.
def get_element_list(self, pos2): element_hash = pos2.x + (pos2.y * self.size.x) return self.element_hash.get(element_hash)
[ "def get_objs(self,x,y):\n if self.inworldv(x,y):\n return self.objs[x][y]\n return None", "def points2D(self) -> tuple[Point2D, ...]:\n return tuple(map(Point2D, self._xs, self._ys))", "def get_coordinates(w, target):\n \n returned_list = []\n \n for i in range(len(w...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Maps a 2d map position to an element position.
def map_to_element(self, pos2): return ((pos2.x / self.element_size) + 1, (pos2.y / self.element_size) + 1)
[ "def element_to_map(self, pos2):\n \n return ((pos2.x * self.element_size) - (self.element_size / 2), (pos2.y * self.element_size) - (self.element_size / 2))", "def position_map(context, map):\n ob = context.active_object\n scn = context.scene\n nodes = map['mat'].node_tree.nodes\n #\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Maps the center of a 2d element position to a map position.
def element_to_map(self, pos2): return ((pos2.x * self.element_size) - (self.element_size / 2), (pos2.y * self.element_size) - (self.element_size / 2))
[ "def xy2center(self, x, y):\n x = x - 10.97 / 2\n y = y - 23.78 / 2\n return x, y", "def map_to_element(self, pos2):\n \n return ((pos2.x / self.element_size) + 1, (pos2.y / self.element_size) + 1)", "def mkmapcoords(self, pts):\n return(mk_mapcoords(pts, self.vol_verts...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Sets an element's properties (but not flags) from sector flags.
def set_element_properties(self, sector_index, element): sector = self.map_data.sectors[sector_index] # Set sector damage flag. if sector.damage > 0: if sector.damage <= 5: element.flags |= Element.FLAG_DAMAGE_LOW elif...
[ "def set_flags(obj, flag_field, flags):\n\n for flag, value in flags:\n if value & flag_field:\n obj.__dict__[flag] = True\n else:\n obj.__dict__[flag] = False", "def _set_attr_reg(self):\n tmos_v = self._meta_data['bigip']._meta_data['tmos_version']\n attribut...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
count elements and attributes used based on DTD
def count_elements(node, stats): # test that we are an element and not a comment nor processing instruction if isinstance(node, (etree._Comment, etree._ProcessingInstruction)): return # key the hash on the local name of the element key = node.xpath('local-name(.)') # get stats counter for ...
[ "def get_html_attributes(html):\n attributes = set()\n for element in html.iter():\n for attribute in element.keys():\n element_attribute = ' '.join([element.tag, attribute])\n attributes.add(element_attribute)\n return Counter(attributes)", "def numeroElements(self):\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
read XML version of the DTD to figure out allowed attributes
def allowed_attributes(key): return DTD.xpath(''.join(["/dtd/attlist[@name='", key, "']/attribute/@name"]))
[ "def get_valid_attributes(self, buf, pos):\n node = buf.xml_node_at_pos(pos)\n if node is None: return None\n #print \"get_valid_attributes NODE %s:%s xmlns[%s] %r\"%(tree.prefix(node),node.localName,node.ns,node.tag)\n already_supplied = node.attrib.keys()\n handlerclass = buf.xm...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Read and resize volume
def process_scan(path): volume = read_nifti_file(path) volume = normalize(volume) volume = resize_volume(volume) return volume
[ "def process_scan(path):\r\n # Read scan\r\n volume = read_nifti_file(path)\r\n # Normalize\r\n # volume = normalize(volume)\r\n # Resize width, height and depth\r\n volume = resize_volume(volume)\r\n return volume", "def resize(self, size):\r\n self.instance.resize_volume(size)\r\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Read the point group msg published either from ROS2 or Unity and convert it to a dictionary so that it can be saved as a .yaml file
def _pointGroupsCallback(self, msg : PointGroups) -> None: self.pointGroupsDict = [] for group in msg.groups: tmp_dict = [{'map_pos' : [tmp for tmp in group.map_pos], 'group_id' : group.group_id, 'map_origin' : [group.ma...
[ "def _bot_group_proto_to_tuple(msg, trusted_dimensions):\n dimensions = {unicode(k): set() for k in trusted_dimensions}\n for dim_kv_pair in msg.dimensions:\n # In validated config 'dim_kv_pair' is always 'key:value', but be cautious.\n parts = unicode(dim_kv_pair).split(':', 1)\n if len(parts) != 2:\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Updates the value of each trainable with SGD.
def sgd_update(trainables, learning_rate=1e-2): # Performs SGD # # Loop over the trainables for t in trainables: # Change the trainable's value by subtracting the learning rate # multiplied by the partial of the cost with respect to this # trainable. partial = t.gradients...
[ "def sgd_update(trainables, learning_rate=1e-2):\n for node in trainables:\n node.value -= learning_rate * node.gradients[node]", "def sgd(self):\n import math\n for i, j, r in self.samples:\n # Computer prediction and error\n prediction = self.get_rating(i, j)\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
GET Request for article recommendation
def article(title): try: idx = INDEX[title.lower()] if not isinstance(idx, np.int64): idx = np.int64(list(idx)[0]) # Get 5 recommendations based on similar post rec = list(ARTICLE_MODEL.recommend_from_interactions([idx], k=5)) # Get post_id of recommended posts ...
[ "def get(self):\n app.logger.info(\"Request for recommendations list\")\n\n recommendations = Recommendation.all()\n\n results = [recommendation.serialize() for recommendation in recommendations]\n return results, status.HTTP_200_OK", "def test_get_recommendations(self):\n taste...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Function to scan one dac and save the frames
def scanDac(self, dac, start, stop, step=1, tacq=1, nacq=1, filename=None, format='i16', binary=False, sparsexy=False, append=False, tp=False, pulseHeigh=0.2, pulseCount=100): # Check the range of the scan maxdac = self.DACs.max(dac) if start < 0: raise PmError('inva...
[ "def thlScan(self, dac, start, stop,\n step=1,\n tacq=1,\n nacq=1,\n filename=None,\n format='i16',\n binary=False,\n sparsexy=False,\n append=False,\n useTestPulses=False,\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Function to scan thl dac and save the frames
def thlScan(self, dac, start, stop, step=1, tacq=1, nacq=1, filename=None, format='i16', binary=False, sparsexy=False, append=False, useTestPulses=False, saveLo...
[ "def scanDac(self, dac, start, stop, step=1, tacq=1, nacq=1, filename=None, format='i16', binary=False,\n sparsexy=False, append=False, tp=False, pulseHeigh=0.2, pulseCount=100):\n\n # Check the range of the scan\n maxdac = self.DACs.max(dac)\n if start < 0:\n raise Pm...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
search the 3 different modules for a similar title and return a list sorted by similarity
def get_similar_titles(title: str) -> list: light_novel_results = BakaUpdates.get_similar_titles(title) visual_novel_results = VisualNovelDatabase.get_similar_titles(title) anime_results = MyAnimeList.get_similar_titles(title) results = [] passed_titles = [] for result_list in (light_novel_res...
[ "def find_items(self, title: str) -> list:\n title_list = []\n for library_item in self._item_list:\n title_list.append(library_item.get_title())\n results = difflib.get_close_matches(title, title_list, cutoff=0.5)\n return results", "def find_movies_by_title(self, title):\n...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Search the 3 different modules for an alternative title of the given title and return a dictionary split into the different languages
def get_alternative_titles(title: str = '') -> dict: light_novel_results = BakaUpdates.get_alternative_titles(title=title) visual_novel_results = VisualNovelDatabase.get_alternative_titles(title=title) anime_results = MyAnimeList.get_alternative_titles(title=title) alternative_titles = {} for resu...
[ "def get_languages(self, title: str) -> dict:\n logging.info(\"Searching wikipedia for languages for article with title '{}'\".format(title))\n url: str = \"/w/api.php\"\n http_params: dict = {\n \"action\": \"query\",\n \"titles\": title.replace(\" \", \"%20\"),\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Checks if the model was migrated correctly.
def _check_model_validity(self, original_model, migrated_model): self.assertEqual( migrated_model.committer_id, original_model.committer_id) self.assertEqual( migrated_model.commit_type, original_model.commit_type) self.assertEqual( mig...
[ "def should_migrate() -> bool:\n\n # Check if there is database to migrate.\n if not QUANDL_DATABASE_PATH.is_file():\n print(f'No existing database {QUANDL_DATABASE_PATH} to migrate.')\n\n # Delete info json if it exists; something went wrong with previous migration.\n if INFO_PATH.is_fil...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Combine a secondary evolution line with this one.
def combine_evo_lines(self, second_evo_first_step: EvolutionStep): if self.first.pokemon_name != second_evo_first_step.pokemon_name: raise Exception("UNEQUAL PARENTS") else: self._combine_evo_lines([self.first.pokemon_name], second_evo_first_step.next)
[ "def _combine_evo_lines(self, path: list, secondary: list):\n for pkmn in secondary:\n if not EvolutionLine.is_part_of_evo_line(self.first, pkmn.pokemon_name):\n self._insert(path.copy(), pkmn.pokemon_name, pkmn.ndex, pkmn.evo_stage)\n new_path = path.copy()\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Combine a secondary evolution line with this one recursively
def _combine_evo_lines(self, path: list, secondary: list): for pkmn in secondary: if not EvolutionLine.is_part_of_evo_line(self.first, pkmn.pokemon_name): self._insert(path.copy(), pkmn.pokemon_name, pkmn.ndex, pkmn.evo_stage) new_path = path.copy() new_path.a...
[ "def combine_evo_lines(self, second_evo_first_step: EvolutionStep):\n if self.first.pokemon_name != second_evo_first_step.pokemon_name:\n raise Exception(\"UNEQUAL PARENTS\")\n else:\n self._combine_evo_lines([self.first.pokemon_name], second_evo_first_step.next)", "def wedge(s...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Yields tupil of (name, ndex)
def yield_all_name_ndex(self): yield from self._yield_all_name_ndex(self.first)
[ "def _yield_all_name_ndex(self, current_node):\n\n current_node = current_node\n\n yield current_node.pokemon_name, current_node.ndex\n\n for next_evolution in current_node.next:\n yield from self._yield_all_name_ndex(next_evolution)", "def test_namedtuple_tuple(self):\n wit...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Recursive function to yield tupils of (name, ndex)
def _yield_all_name_ndex(self, current_node): current_node = current_node yield current_node.pokemon_name, current_node.ndex for next_evolution in current_node.next: yield from self._yield_all_name_ndex(next_evolution)
[ "def yield_all_name_ndex(self):\n yield from self._yield_all_name_ndex(self.first)", "def generate_names(args):\n index = 0\n for _, decl in args:\n index += 1\n yield decl.name or 'arg{0}'.format(index)", "def getNodeWildIter(self, name, *usage):\n for nid in self._getNodeWildIter(n...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns the number of feet in the given number of miles.
def miles_to_feet(miles): return miles * 5280
[ "def inches(feets):\n return 12*feets", "def height_US_to_centimeters(feet, inches):\r\n total_inches = (feet * inches_per_foot) + inches # Total inches\r\n centimeters = total_inches * centimeters_per_inch\r\n return centimeters", "def numTiles(wRoom,lRoom,sTile):\n sizeRoom = wRoom * lRoom\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Scan the target CIDR address using Nmap. The flags "A oX" are used by default.
def nmap_scan(outDir, address, flags="-A"): nmap = {} nmap = nm.PortScanner() nmap.scan(address, arguments=flags) with open(outDir + "nmap.xml", 'w') as outFile: outFile.write(nmap.get_nmap_last_output()) return nmap
[ "def scan_net(sub_net):\n sub_net = str(sub_net)\n list_host = []\n str_nmap = subprocess.run([\"nmap\", \"-sP\", sub_net],capture_output=True)\n str_nmap = str_nmap.stdout.decode(\"utf-8\")\n arr_host = str_nmap.split(\"Nmap scan report for\")\n del arr_host[0]\n active_hosts = map(filter_addr...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Instantiates a NASNet model. Optionally loads weights pretrained on ImageNet. This model is available for TensorFlow only, and can only be used with inputs following the TensorFlow data format `(width, height, channels)`. You should set `image_data_format='channels_last'` in your Keras config located at ~/.keras/keras....
def NASNet_large_do(net_type, include_top=True, do_rate=0.3, weights='imagenet', input_tensor=None, input_shape=None, total_training_steps=None, penultimate_filters=4032, num_blocks=6, stem_block_filters=96, skip_reduction=True, filter_multiplier=2, pooling=None, classes=1000): ...
[ "def build_model(classes, height, width):\n print(\"> Building Keras neural network...\")\n network_model = model.simple_3(classes=classes, height=height, width=width)\n return network_model", "def init_model_scratch(args):\n img_size = args.img_size\n channels = args.channels\n num_class = args...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Renders the template for the given step, returning an HttpResponse object. Override this method if you want to add a custom context, return a different MIME type, etc. If you only need to override the template name, use get_template() instead.
def render_template( self, request, form, previous_fields, step, context=None ): if IsDebug: print "render: %s" % step context = context or {} context.update(self.extra_context) context_instance = RequestContext(request) template = self.get_template(step) fie...
[ "def render(\n request, template_name, context=None, content_type=None, status=None, using=None\n):\n content = loader.render_to_string(template_name, context, request, using=using)\n return HttpResponse(content, content_type, status)", "def render_step(self, **kwargs):\n if self.templated:\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Extract challenge tag list and get the combination of 2 and 3 tags.
def get_challenge_tag_combination_count() -> tuple[pd.DataFrame, pd.DataFrame, pd.DataFrame, pd.DataFrame]: def count_tag_combination(challenge_tag_it: Iterator) -> pd.DataFrame: tag_combinatio_count = (pd.DataFrame .from_records( pd.Series...
[ "def getTags(src):\n tags = []\n if len(src) == 1:\n tags = ['S']\n elif len(src) == 2:\n tags = ['B', 'E']\n else:\n m_num = len(src) - 2\n tags.append('B')\n tags.extend(['M'] * m_num)\n tags.append('S')\n return tags", "def compute_tag_feature() -> list[...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Calculate Tag combination's softmax score from frequency count. Separate this part of logic from `get_challenge_tag_combination_count` to preserve the total combination count df.
def get_tag_combination_softmax() -> list[pd.DataFrame]: def compute_softmax(tag_combination: pd.DataFrame): """ Calculate softmax for tag combination DataFrame.""" top_n = tag_combination.head(S.CHALLENGE_TAG_COMB_TOP).copy() top_n['count_softmax'] = TML.softmax(np.log(top_n['count'])) ...
[ "def compute_softmax(tag_combination: pd.DataFrame):\n top_n = tag_combination.head(S.CHALLENGE_TAG_COMB_TOP).copy()\n top_n['count_softmax'] = TML.softmax(np.log(top_n['count']))\n return top_n", "def compute_tag_feature() -> list[dict]:\n tag_comb_softmax: list[pd.DataFrame] = get_tag_co...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Calculate softmax for tag combination DataFrame.
def compute_softmax(tag_combination: pd.DataFrame): top_n = tag_combination.head(S.CHALLENGE_TAG_COMB_TOP).copy() top_n['count_softmax'] = TML.softmax(np.log(top_n['count'])) return top_n
[ "def get_tag_combination_softmax() -> list[pd.DataFrame]:\n def compute_softmax(tag_combination: pd.DataFrame):\n \"\"\" Calculate softmax for tag combination DataFrame.\"\"\"\n top_n = tag_combination.head(S.CHALLENGE_TAG_COMB_TOP).copy()\n top_n['count_softmax'] = TML.softmax(np.log(top_n[...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Use the tag combination softmax table to caluate the softmax score of a challenge's tags. And encode the binary array.
def compute_tag_feature() -> list[dict]: tag_comb_softmax: list[pd.DataFrame] = get_tag_combination_softmax() challenge_tag = DB.TopcoderMongo.run_challenge_aggregation([ *DB.TopcoderMongo.scoped_challenge_with_text_query, {'$project': {'id': True, 'tags': True, '_id': False}}, ]) def m...
[ "def get_tag_combination_softmax() -> list[pd.DataFrame]:\n def compute_softmax(tag_combination: pd.DataFrame):\n \"\"\" Calculate softmax for tag combination DataFrame.\"\"\"\n top_n = tag_combination.head(S.CHALLENGE_TAG_COMB_TOP).copy()\n top_n['count_softmax'] = TML.softmax(np.log(top_n[...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Encode the tag list into onehot list and sum of softmax. Short var name `tc` stands for `tag_combination`.
def map_tag_lst_to_softmax(tags: list[str]) -> dict[str, dict]: feature_dct = {} for comb_r, tc_softmax in enumerate(tag_comb_softmax, 1): tc_lst = tags if comb_r == 1 else [tuple(sorted(tc)) for tc in itertools.combinations(tags, comb_r)] softmax_score = tc_softmax.loc[tc_softma...
[ "def tags2onehot(tags, label_list):\n m = len(label_list)\n n = len(tags)\n y = np.zeros((n,m))\n \n for i in range(n):\n tags_i = tags[i].split()\n for tag in tags_i:\n index = label_list.index(tag)\n y[i, index] = 1\n return y", "def onehot_encode(seq):\n\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Compute the document vector representation of a challenge description with given similarity, frequency and token length threshold.
def compute_challenge_desc_docvec() -> dict[str, list]: model, corpus = train_challenge_desc_doc2vec() return {doc.tags[0]: model.docvecs[doc.tags[0]].tolist() for doc in corpus}
[ "def calculate_similarity(source_doc,\n target_doc,\n embedding=\"Glove\",\n threshold=0):\n def w2v_vectorize(doc):\n \"\"\"Identify the vector values for each word in the given document\"\"\"\n doc = [i.lower().split() for i ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Verifies if the certificate is up to date
def validate_certificate(self, certificate): dates = (certificate.not_valid_before.timestamp(),certificate.not_valid_after.timestamp()) date_now=datetime.now().timestamp() return dates[0]< date_now < dates[1]
[ "def check_certificate():\n server = get_odoo_server_url()\n if server:\n path = Path('/etc/ssl/certs/nginx-cert.crt')\n if path.exists():\n with path.open('r') as f:\n cert = crypto.load_certificate(crypto.FILETYPE_PEM, f.read())\n cert_end_date = dateti...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Validates the server certificate purpose
def validate_server_purpose(self,certificate): server_auth = x509.oid.ExtendedKeyUsageOID.SERVER_AUTH extended_key_usages = certificate.extensions.get_extension_for_oid(ExtensionOID.EXTENDED_KEY_USAGE) return any(extension for extension in extended_key_usages.value if extension.dotted_string == server_auth.d...
[ "def test_validHostnameInvalidCertificate(self):\n cProto, sProto, cWrapped, sWrapped, pump = self.serviceIdentitySetup(\n u\"valid.example.com\",\n u\"valid.example.com\",\n validCertificate=False,\n )\n\n self.assertEqual(cWrapped.data, b'')\n self.asse...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Validate the Signature of a Certificate The issuer parameter represents the certificate of the issuer The subject parameter represents the certificate we want to verify
def validate_signature(self,issuer,subject): issuer_pub_key = issuer.public_key() try: issuer_pub_key.verify( subject.signature, subject.tbs_certificate_bytes, pd.PKCS1v15(), subject.signature_hash_algorithm, ) return True except: logger.error("Could not Validate the Signatu...
[ "def ValidateCertificateSignature(self, signed_cert, signing_cert):\n # First the naive way -- note this does not check expiry / use etc.\n signed_m2 = M2_X509.load_cert_der_string(der_encoder.encode(signed_cert))\n signing_cert_text=der_encoder.encode(signing_cert)\n signing_m2 = M2_X509.load_cert_der_...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Validate if certificate is in list of the revocated certificates
def crl_validation(self, cert): return all(crl.get_revoked_certificate_by_serial_number(cert.serial_number) == None for crl in self.crls_list)
[ "def check_certif_revokation_list(self, cert, index):\n # 12. Revokation list check\n # - Subject public key\n # - Issuer or certificate serial number\n if (self.context_revoked_certificates_id or\n self.context_revoked_public_keys):\n self.error(\"Revokation li...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Checks if the server certificate chain is valid
def validate_cert_chain(self): chain = self.trusting_chain if len(self.trusting_chain) <= 1: return False for i in range(0, len(chain) - 1): if not self.validate_certificate(chain[i]): return False #verifies if the signatures are valid if not self.validate_signature(chain[i+1], cha...
[ "def check_certificate():\n server = get_odoo_server_url()\n if server:\n path = Path('/etc/ssl/certs/nginx-cert.crt')\n if path.exists():\n with path.open('r') as f:\n cert = crypto.load_certificate(crypto.FILETYPE_PEM, f.read())\n cert_end_date = dateti...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Loads Certificates from disk
def load_certs(self, path): try: with os.scandir(path) as it: for entry in it: if entry.name.endswith('crt') and entry.is_file(): with open(path + entry.name,'rb') as cert: data=cert.read() cr = x509.load_pem_x509_certificate(data) if self.validate_certificate(cr): ...
[ "def load_ca_certs(ctx):\n for path in find_ca_cert_files():\n logging.debug('loading certs from %s', path)\n ctx.load_verify_locations(path)", "def load(filename):\n\t\tbuffer = [];\n\t\tb64_contents = \"\";\n\t\ttry:\n\t\t\thandle = open(filename, \"r\");\n\t\t\traw_contents = handle.readlines(...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Loads CRLs from disk
def load_crl(self,path): try: with os.scandir(path) as it: for entry in it: if entry.name.endswith('crl') and entry.is_file(): with open(path + entry.name,'rb') as f: crl_data = f.read() crl = x509.load_der_x509_crl(crl_data) self.crls_list.append(crl) logge...
[ "def load_certs(self, path):\r\n\t\ttry:\r\n\t\t\twith os.scandir(path) as it:\r\n\t\t\t\tfor entry in it:\r\n\t\t\t\t\tif entry.name.endswith('crt') and entry.is_file():\r\n\t\t\t\t\t\twith open(path + entry.name,'rb') as cert:\r\n\t\t\t\t\t\t\tdata=cert.read()\r\n\t\t\t\t\t\t\tcr = x509.load_pem_x509_certificate(...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Builds the certificate chain of a given certificate
def build_cert_chain(self,certificate): chain = [] last = None logger.info("Starting to build trusting chain..") while True: if last == certificate: self.trusting_chain = [] return last = certificate chain.append(certificate) issuer = certificate.issuer.rfc4514_string() ...
[ "def _get_cert_chain(ssl_info):\n\n cert = M2Crypto.X509.load_cert_string(ssl_info.get(\"cert\", \"\"))\n chain = M2Crypto.X509.X509_Stack()\n for c in ssl_info.get(\"chain\", []):\n aux = M2Crypto.X509.load_cert_string(c)\n chain.push(aux)\n return cert, chain", ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Checks if the client has already negotiated algs
def has_negotiated(self): return not (self.cipher is None or self.digest is None)
[ "def negotiate_algs(self):\r\n\r\n\t\tdata = {\r\n\t\t\t'method': \"NEGOTIATE_ALG\",\r\n\t\t\t'ciphers': self.ciphers,\r\n\t\t\t'digests': self.digests,\r\n\t\t\t'ciphermodes': self.ciphermodes\r\n\t\t}\r\n\t\trequest = requests.post(f'{SERVER_URL}/api/protocols',json=data, headers={'Content-Type': 'application/jso...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Negotiates algorithms with the server Sends all the available algorithms and waits for the server to choose one
def negotiate_algs(self): data = { 'method': "NEGOTIATE_ALG", 'ciphers': self.ciphers, 'digests': self.digests, 'ciphermodes': self.ciphermodes } request = requests.post(f'{SERVER_URL}/api/protocols',json=data, headers={'Content-Type': 'application/json'}) response = json.loads(reque...
[ "def run_default(self):\n\n if self.complete_pipelines or self.dataset.depth + 1 >= self.max_pipeline_depth:\n candidates = CLASSIFIERS.keys()\n else:\n candidates = ALGORITHMS.keys()\n for algo_type in candidates:\n try:\n LOGGER.info('Starting n...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Exchange keys with the server
def dh_exchange_key(self): if self.state =='DH_START': logger.info('Sending POST Request to exchange DH Shared key') key = self.public_key.public_bytes(encoding=serialization.Encoding.PEM, format=serialization.PublicFormat.SubjectPublicKeyInfo) data = { 'method': 'KEY_EXCHANGE', 'pub_...
[ "def put_zmqkeys(appname):\n pub_key, secret_key = zmq.curve_keypair()\n\n try:\n etcd_put(\"/Publickeys/\" + appname, pub_key)\n except RuntimeError:\n logging.error(\"Error putting Etcd public key for %s\", appname)\n\n try:\n etcd_put(\"/\" + appname + \"/private_key\", secret_ke...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Reads citizen card certificates and private key
def read_cc(self): print("-------+---------") pkcs11 = PyKCS11.PyKCS11Lib() pkcs11.load(lib) self.slots =pkcs11.getSlotList() for slot in self.slots: print(pkcs11.getTokenInfo(slot)) #slot=pkcs11.getSlotList(tokenPresent=Tru)[0] self.session=pkcs11.openSession(slot) all_attributes = li...
[ "def get_citizen_certificates(self, library=\"/usr/local/lib/libpteidpkcs11.so\"):\n # init certificates as a list\n certificates = []\n # start session\n card_session = self._start_session(library)\n if not isinstance(card_session, PyKCS11.Session):\n return certificat...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Generates a key that identifies the given chunk and media
def chunk_identification(self, chunk_id, media_id): return (self.shared_key.decode('latin') + media_id + str(chunk_id)).encode('latin')
[ "def _generate_s3_metadata_key(self, file_id: str, location: str) -> str:\n return f'{location}/{file_id}.{self._get_metadata_location_extension(location)}'", "def objkey(oid, gen, mkey):\n return md5(mkey[:16] + struct.pack(\"<HBH\", oid&0xFFFF, oid>>16, gen) + b'sAlT')", "def _get_thumbnail_asset_ke...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Client sends to server his certificate in order to validate it, along side with a challenge.
def start_challenge(self): if self.state=='KEY_EXCHANGE': logger.info("Starting Challenge") nonce = os.urandom(16) self.challenge_nonce = nonce key, salt = self.derive_key(self.shared_key) if self.session_id != None: headers = { 'Content-Type': 'application/json', 'session_id' ...
[ "def test_handshake(self):\n cli, svr, p = connectedServerAndClient(\n ServerClass=SecurableProto,\n ClientClass=SecurableProto)\n\n okc = OKCert()\n svr.certFactory = lambda : okc\n\n cli.callRemote(\n amp.StartTLS, tls_localCertificate=okc,\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Verifies the server response to the challenge
def verify_challenge(self,crypt): try: self.server_cert.public_key().verify( crypt, self.challenge_nonce, pd.PSS( mgf=pd.MGF1(hashes.SHA256()), salt_length=pd.PSS.MAX_LENGTH), hashes.SHA256() ) logger.info("Challenge OK") return True except: logger.error("Challeng...
[ "def accept_challenge(self,nonce2):\r\n\t\tlogger.info(\"Sending POST to accept Challenge\")\r\n\t\tif self.state=='START_CHALLENGE':\r\n\t\t\tsnonce2 = self.sign_message(nonce2)\r\n\t\t\tself.challenge_nonce2 = snonce2\r\n\t\t\tkey, salt = self.derive_key(self.shared_key)\r\n\t\t\tif self.session_id != None:\r\n\t...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }