query
stringlengths
9
9.05k
document
stringlengths
10
222k
negatives
listlengths
19
20
metadata
dict
Reduce mean when distributed training.
def reduce_mean(tensor): if not (dist.is_available() and dist.is_initialized()): return tensor tensor = tensor.clone() dist.all_reduce(tensor.div_(dist.get_world_size()), op=dist.ReduceOp.SUM) return tensor
[ "def vm_impl_reduce_mean(self):\n\n def vm_impl(x, axis):\n x = x.asnumpy()\n out = vm.mean(x, axis)\n return Tensor(out)\n\n return vm_impl", "def average_all(tensor):\n require_init()\n if not using_deepspeed:\n return tensor\n\n require_torch_distributed_init()\n #...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
GoldsteinPrice's objective function. Only takes two dimensions and has a global minimum at
def goldstein_func(x): if not x.shape[1] == 2: raise IndexError('Goldstein function only takes two-dimensional ' 'input.') if not np.logical_and(x >= -2, x <= 2).all(): raise ValueError('Input for Goldstein-Price function must be within ' '[-2, 2...
[ "def objective2(x1, x2, x3, x4, x5, x6):\n return x1 ** 2 + x2 ** 2 + x3 ** 2 + x4 ** 2 + x5 ** 2 + x6 ** 2", "def add_minimize(self, co, var):", "def _objective_fn(\n pair: gaussian_mixture_pair.GaussianMixturePair,\n obs0: Observations,\n obs1: Observations,\n ) -> jnp.ndarray:\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Does message equalization work for simple, scalar messages in weighted mean and information matrix parameterization?
def test_GaussianWeightedMeanInfoScalar(self): msg_a = GaussianWeightedMeanInfoMessage([[0]], [[2]]) msg_b = GaussianWeightedMeanInfoMessage([[2]], [[2]]) msg_c = msg_a.combine(msg_b) self.assertEqual(msg_c.weighted_mean, [[2]]) self.assertEqual(msg_c.info, [[4]]) msg_a...
[ "def test_message_weighting(self):\n self._test(\n weights=self.instance(source=self.source, target=self.target, message=self.message, x_e=self.x_e),\n shape=self.message.shape,\n )", "def test_GaussianWeightedMeanInfoVector(self):\n\n msg_a = GaussianWeightedMeanInfoMes...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Does message equalization work for simple, vector messages in weighted mean and information matrix parameterization?
def test_GaussianWeightedMeanInfoVector(self): msg_a = GaussianWeightedMeanInfoMessage(weighted_mean=[[1], [0]], info=[[2, 0], [0, 3]]) msg_b = GaussianWeightedMeanInfoMessage(weighted_mean=[[2], [0]], info=[[3, 0], [0, 1]]) msg_c = msg_a.combine(msg_b) np.testing.assert_allclose(msg_c....
[ "def test_GaussianWeightedMeanInfoScalar(self):\n\n msg_a = GaussianWeightedMeanInfoMessage([[0]], [[2]])\n msg_b = GaussianWeightedMeanInfoMessage([[2]], [[2]])\n msg_c = msg_a.combine(msg_b)\n self.assertEqual(msg_c.weighted_mean, [[2]])\n self.assertEqual(msg_c.info, [[4]])\n\n...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Converts a KML file with multiple Documents into geojson to store in an output file
def kml_multiple_to_geojson(infile_path, outdir_path, geojson_properties={}): data = __read_file(infile_path) coord_dict = __get_all_coords(data) if not os.path.exists(outdir_path): os.makedirs(outdir_path) for section_id, coords in list(coord_dict.items()): ...
[ "def kml_to_geojson(infile_path, outfile_path, geojson_properties={}):\n data = __read_file(infile_path) \n \tcoords = __get_coords(data)\n\toutfile = open(outfile_path, 'w')\n\toutfile.write(__to_geojson(coords))\n\toutfile.close()", "def kml_to_geometry(cls, filename):\n # open local\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Converts a KML file to geojson to store in an output file.
def kml_to_geojson(infile_path, outfile_path, geojson_properties={}): data = __read_file(infile_path) coords = __get_coords(data) outfile = open(outfile_path, 'w') outfile.write(__to_geojson(coords)) outfile.close()
[ "def kml_multiple_to_geojson(infile_path, outdir_path, geojson_properties={}):\n data = __read_file(infile_path)\n coord_dict = __get_all_coords(data)\n if not os.path.exists(outdir_path):\n os.makedirs(outdir_path) \n for section_id, coords in list(coord_dict.items...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Validates kml located at filepath.
def validate_kml(filepath, schema = "https://developers.google.com/kml/schema/kml21.xsd"): schema_gomaps = Schema(schema) data = "" with open(filepath, "r") as temp: data = temp.read() assert(data != "") doc = parser.fromstring(data) return schema_ogc.assertValid(doc)
[ "def validate(self):\n file_content = filesystem_utils.get_content(self._file_path)\n self.parse_yaml_file(file_content)", "def validate_file(file_path):\n if not os.path.exists(file_path):\n raise FileNotFoundError(\"[Error] File not found!\")", "def __validateFile(self):\n\n xml...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Converts a section into a kml file
def section_to_kml(section, color, outfile_path="", write=True): line_style_id = "line-%s-5" % color red = "FF1212" green = "00B80C" start_icon_style_id = "icon-%s" % color end_icon_style_id = "icon-%s" % color make_coord = lambda p: (",".join([str(x) for x in p["...
[ "def section(c32, name):\n\n entries = documents.entries\n\n if 'document' == name:\n return c32.template('2.16.840.1.113883.3.88.11.32.1')\n if 'allergies' == name:\n el = c32.template('2.16.840.1.113883.3.88.11.83.102')\n if el.is_empty():\n el = c32.template('2.16.840.1.1...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Reads in UUIDs from the file user_uuid.secret
def read_uuids(): from uuid import UUID f = open("user_uuid.secret","r") user_uuid = {} for line in f: user, uuid = [c.strip() for c in line.split(":")] user_uuid[user] = UUID(uuid) return user_uuid
[ "def read_secrets_file( secrets_file ):\n try:\n sf = open( secrets_file, \"r\" )\n except Exception, e:\n raise MDMethodFailed( \"read_secrets_file\", e )\n\n users = []\n lineno = 0\n while True:\n line = sf.readline()\n lineno += 1\n \n if len(line) == 0:\n break\n...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Run art_illumina read simulator
def sim_reads_art(workdir, coverage=30, readlen=150, meanfrag=400, insertsd=50, instrument="HS25"): ret = cmd_exe("which art_illumina") if ret.ret_code != 0: logging.error("Cannot fine art_illumina executable in the environment") exit(ret.retcode) try: os.chdir(workdir) except OS...
[ "def sim_reads_art(workdir, coverage=30, readlen=150, meanfrag=400, insertsd=50, instrument=\"HS25\", keep_bam=False):\n ret = cmd_exe(\"which art_illumina\")\n if ret.ret_code != 0:\n logging.error(\"Cannot find art_illumina executable in the environment\")\n exit(ret.ret_code)\n try:\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
KLUERE micro f1 (except no_relation)
def klue_re_micro_f1(preds, labels, binary): if binary: label_list = ['org:top_members/employees', 'org:members', 'org:product', 'per:title', 'org:alternate_names', 'per:employee_of', 'org:place_of_headquarters', 'per:product', 'org:number_of_employees/members', 'per:children', ...
[ "def klue_re_micro_f1(preds, labels):\n label_list = ['no_relation', 'org:top_members/employees', 'org:members',\n 'org:product', 'per:title', 'org:alternate_names',\n 'per:employee_of', 'org:place_of_headquarters', 'per:product',\n 'org:number_of_employees/members', 'per:children',\n 'pe...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
if age includes 85andover, just have an upper bound over 85
def build_ages(self, lowerAge, upperAge): #Checking that upper is > than lower #Standardizing on the 5 year categories age_list = [] count = self.get_age_categories(lowerAge, upperAge) #this is a hacky way to get around the all morta...
[ "def constrain(amt: float, low: float, high: float) -> float:\n return low if amt < low else high if amt > high else amt", "def bounded(self):\n return self.lower > -np.inf or self.upper < np.inf", "def calcul_age_2050(age):\n return age+(2050-2016)", "def past_half_life(self):\n return se...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Funtion to make pretty print sql
def Print_pretty_sql(self, sqlList,): return " \n".join(sqlList)
[ "def data_pretty_print(self, data):\n data_str = tabulate(data, headers=\"keys\", tablefmt=\"psql\")\n return data_str", "def print_query_sql(query=None, /, *, literal_binds: bool = True,\n pretty: bool = True,\n file=None, flush: bool = True):\n sql = get_qu...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Doc string CREATE TABLE mytable AS
def Create_table(self, tableName): return "CREATE TABLE {} AS \n".format(tableName)
[ "def create_table(self, table):\n sql = 'CREATE TABLE %s (\\n ' % table.name\n sql += ',\\n '.join(map(self.field, table.fields.values()))\n sql += ',\\n PRIMARY KEY (%s)\\n);\\n' % ', '.join(map(lambda _: _.name, table.primary_keys))\n sql += ''.join(map(self.index, table.index...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
This is the age adjusted death groups ,death_age_pop as ( SELECT FROM crosstab($$ with death_records as ( SELECT 1 as place_holder, decd_dth_yr as yr, CASE WHEN decd_age_yr >= 0 AND decd_age_yr = 5 AND decd_age_yr = 0 AND decd_age_yr <= 9 ) SELECT 1 as rec_id, concat(age_category,'_',yr) as category, count(1) FROM deat...
def age_adjusted_death(self, prettyPrint=True): dplist = [] dplist.append(", death_age_pop as") dplist.append("(") dplist.append("SELECT * FROM crosstab($$ ") dplist.append("with death_records as") dplist.append("(") dplist.append("SELECT 1 as place_holde...
[ "def age_pivot_table(age_df):\n # Group by heiarchical sorting.\n age_pivot_ser = age_df.groupby(by=['year', 'county', 'age',\n 'weight_indicator'\n ]\n ).birth_count.sum()\n\n # Unstack Series to ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
SELECT deaths_2011/est_pop_5_9_year_2011 as expected_death_rate_5_9_2011, deaths_2012/est_pop_5_9_year_2012 as expected_death_rate_5_9_2012, deaths_2013/est_pop_5_9_year_2013 as expected_death_rate_5_9_2013, deaths_2014/est_pop_5_9_year_2014 as expected_death_rate_5_9_2014, deaths_2015/est_pop_5_9_year_2015 as expected...
def death_rates(self, prettyPrint): death_rate = [] death_rate.append(", death_rates as") death_rate.append("(") death_rate.append("SELECT ") for c, y in enumerate(self.years): if c == 0: death_rate.append("deaths_%s/est_pop_%s as expected_dea...
[ "def create_death_rate_data(group_by_df: pd.DataFrame) -> pd.DataFrame:\n group_by_df[\"death_rate\"] = (\n group_by_df[\"total_deaths\"] / group_by_df[\"total_cases\"]\n ) * 100\n\n return group_by_df", "def percent_change_bachelors_2000s(df, sex='A'):\n df_2000 = df[(df['Year'...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
person_deaths as ( SELECT p.zcta_id, p.tract_id, p.person_id, p.geom, p.sex, p.age, p.race, (p.num_deaths_2011 + p.num_deaths_2012 + p.num_deaths_2013 + p.num_deaths_2014 + p.num_deaths_2015) as total_deaths FROM expected_deaths p )
def person_deaths(self, prettyPrint): person_deaths = [] person_deaths.append(", person_deaths as") person_deaths.append("(") person_deaths.append("SELECT p.zcta_id, p.tract_id, p.person_id, p.geom, p.sex, p.age, p.race ") #List comprehension to generate the sql ...
[ "def create_death_rate_data(group_by_df: pd.DataFrame) -> pd.DataFrame:\n group_by_df[\"death_rate\"] = (\n group_by_df[\"total_deaths\"] / group_by_df[\"total_cases\"]\n ) * 100\n\n return group_by_df", "def age_adjusted_death(self, prettyPrint=True):\n \n dplist = [...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
geog_unit_deaths as ( SELECT tract_id, sum(total_deaths) as total_deaths FROM person_deaths GROUP BY tract_id ),
def geog_unit_deaths(self, geogUnit, prettyPrint): geog_agg = [] geog_agg.append(", geog_unit_deaths as") geog_agg.append("(") geog_agg.append("SELECT {}, sum(total_deaths) as total_deaths ".format(geogUnit)) geog_agg.append("FROM person_deaths") geog_agg.append(...
[ "def grouper(df):\n print(\"performing groupby and sum\")\n\n df.loc[df['outcome_id'] != 'death2', 'outcome_id'] = 'case'\n\n groups = ['location_id', 'year_start', 'year_end', 'age_group_unit',\n 'age_group_id', 'sex_id', 'source', 'nid',\n 'facility_id', 'representative_id', 'di...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
the_population as ( SELECT g.tract_id, ST_Centroid(t.geom) as geom, g.total_deaths FROM geog_unit_deaths g INNER JOIN mn_census_tracts t ON (g.tract_id = t.gid) ),
def centroid_population_deaths(self, geogUnit, geogTable, geogJoinField, prettyPrint): geog_centroid_deaths = [] geog_centroid_deaths.append(", the_population as") geog_centroid_deaths.append("(") geog_centroid_deaths.append("SELECT g.{} as geog_id, ST_Centroid(t.geom) as geom,...
[ "def population_stats(df):\n\n return ...", "def get_census_tract(df):\n globals()['censusgeocode'] = __import__('censusgeocode')\n df = df.copy()\n df['tract_geocode'] = df.apply(_get_geocode_single, axis=1)\n return df", "def get_census_tract_attributes():\n if os.path.isfile(\"data/tracts_c...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
grid_person_join as ( SELECT gid, g.geom, tp.tract_id, ST_Distance(g.geom, ST_Transform(tp.geom,26915)) as distance, tp.total_deaths FROM grid g CROSS JOIN the_population tp ),
def grid_person_cross_join(self, prettyPrint): grid_person = [] grid_person.append(", grid_person_join as") grid_person.append("(") grid_person.append("SELECT gid, g.geom, tp.geog_id, ST_Distance(g.geom, ST_Transform(tp.geom,26915)) as distance, tp.total_deaths") grid_pe...
[ "def add_distance_from_galvanize(df):\n \n galvanize_coords = (47.5990148, -122.3338371)\n df['dist_from_galvanize'] = [geopy.distance.distance((df['lats'][i],df['longs'][i]), galvanize_coords).miles\n for i in range(len(df))]", "def grid_people(self,prettyPrint):\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
grid_people as ( SELECT gid, geom, distance, sum(total_deaths) OVER w as total_deaths FROM grid_person_join WINDOW w AS (PARTITION BY gid, geom ORDER BY distance ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW ) ),
def grid_people(self,prettyPrint): grid_people = [] grid_people.append(", grid_people as") grid_people.append("(") grid_people.append("SELECT gid, geom, distance, sum(total_deaths) OVER w as total_deaths") grid_people.append("FROM grid_person_join") grid_people.a...
[ "def window_sum(x, lag, win_size, win_geom):\n k = create_kernel(n=win_size, geom=win_geom)\n\n #create convolve function with reduced parameters for map_overlap\n pcon = functools.partial(convolve, weights=k)\n \n if isinstance(x, da.core.Array):\n conv_padding = int(win_size//2)\n res...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
buffer_definition as ( SELECT gid, geom, min(distance) as min_buffer_distance FROM grid_people WHERE total_deaths >= 50 For having 50 deaths in each buffer GROUP BY gid, geom ),
def buffer_definition(self, populationThreshold, prettyPrint): # should there be an input for total_deaths? buffer_definition = [] buffer_definition.append(", buffer_definition as") buffer_definition.append("(") buffer_definition.append("SELECT gid, geom, min(distance) as min_bu...
[ "def buffer_grid(gdf_admin, radius):\n data = gdf_admin.total_bounds\n box_data = box(*data)\n buffer = box_data.buffer(radius)\n bounds_extent = buffer.bounds\n return bounds_extent", "def get_age_grid(df, grdx, grdy, cfg=CFG):\n df = df.sort_values(\"age\", ascending=False) # sort oldest to y...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
filter_expected as ( SELECT b.gid, b.geom, b.min_buffer_distance, sum(gpj.total_deaths) as expected_deaths FROM grid_person_join gpj INNER JOIN buffer_definition b ON gpj.gid = b.gid WHERE gpj.distance <= b.min_buffer_distance GROUP BY b.gid, b.geom, b.min_buffer_distance ),
def filter_expected(self, prettyPrint): filter_calc = [] filter_calc.append(", filter_expected as") filter_calc.append("(") filter_calc.append("SELECT b.gid, b.geom, b.min_buffer_distance, sum(gpj.total_deaths) as expected_deaths") filter_calc.append("FROM grid_person_join gpj")...
[ "def spatial_filter_query(self, prettyPrint):\n \n spatial_filter = []\n spatial_filter.append(\"SELECT e.gid, e.geom, e.min_buffer_distance, e.expected_deaths, o.number_of_zctas_used, o.observed_deaths, coalesce(o.observed_deaths,0)/e.expected_deaths as ratio\")\n spatial_filter.append(...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
observed as ( SELECT d.decd_res_zip5 as zip, z.geom, COUNT(1) as observed_deaths FROM disparities.decd d
def observed(self, prettyPrint): observed_calc = [] observed_calc.append(", observed as") observed_calc.append("(") observed_calc.append("SELECT d.decd_res_zip5 as zip, z.geom, COUNT(1) as observed_deaths") observed_calc.append("FROM disparities.decd d ") observe...
[ "def filter_observed(self, prettyPrint):\n\n filter_obs = []\n filter_obs.append(\", filter_observed as\")\n filter_obs.append(\"(\")\n filter_obs.append(\"SELECT b.gid, count(o.observed_deaths) as number_of_zctas_used, sum(o.observed_deaths) as observed_deaths\")\n filter_obs.app...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
filter_observed as ( SELECT b.gid, count(o.observed_deaths) as number_of_zctas_used, sum(o.observed_deaths) as observed_deaths FROM buffer_definition b INNER JOIN observed o on ST_DWithin( b.geom, ST_Transform(ST_Centroid(o.geom), 26915), b.min_buffer_distance) GROUP BY b.gid, b.geom )
def filter_observed(self, prettyPrint): filter_obs = [] filter_obs.append(", filter_observed as") filter_obs.append("(") filter_obs.append("SELECT b.gid, count(o.observed_deaths) as number_of_zctas_used, sum(o.observed_deaths) as observed_deaths") filter_obs.append("FROM buffer_...
[ "def spatial_filter_query(self, prettyPrint):\n \n spatial_filter = []\n spatial_filter.append(\"SELECT e.gid, e.geom, e.min_buffer_distance, e.expected_deaths, o.number_of_zctas_used, o.observed_deaths, coalesce(o.observed_deaths,0)/e.expected_deaths as ratio\")\n spatial_filter.append(...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
SELECT e.gid, e.geom, e.min_buffer_distance, e.expected_deaths, o.number_of_zctas_used, o.observed_deaths, o.observed_deaths/e.expected_deaths as ratio FROM filter_expected e INNER JOIN filter_observed o ON e.gid=o.gid
def spatial_filter_query(self, prettyPrint): spatial_filter = [] spatial_filter.append("SELECT e.gid, e.geom, e.min_buffer_distance, e.expected_deaths, o.number_of_zctas_used, o.observed_deaths, coalesce(o.observed_deaths,0)/e.expected_deaths as ratio") spatial_filter.append("FROM filte...
[ "def fraction_licks_in_reward_zone(expt_grp):\n rew_intervals = ints.behavior(expt_grp, 'reward')\n licking_intervals = ints.behavior(expt_grp, 'licking')\n\n n_licks = licking_intervals.groupby('trial', as_index=False).agg(len)\n n_licks.rename(columns={'start': 'total_licks'}, inplace=True)\n del n...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Should work for MySQL messages larger than 100k bytes.
def test_larger_than_100k(self): self.render_config_template( mysql_ports=[3306], mysql_send_response=True ) self.run_packetbeat(pcap="mysql_long.pcap", debug_selectors=["mysqldetailed"]) objs = self.read_output() assert len(ob...
[ "def check_message(message):\n return False if len(message) > 20000 else True", "def test_message_exactly_buffsize(self):\n buf_message = \"It's 16 bytes eh\"\n self.send_message(buf_message)\n actual_sent, actual_reply = self.process_log()\n expected_sent = self.sending_msg.format(...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Function to fetch the peers from a blockchain node
def fetch_peers(): get_chain_address = "{}/chain".format(CONNECTED_NODE_ADDRESS) response = requests.get(get_chain_address) if response.status_code == 200: content = [] chain = json.loads(response.content) for peer in chain["peers"]: content.append(peer) global p...
[ "def get_peerlist():\n response = None\n for seed in SEED_NODES:\n url = \"http://%s/staeon/peerlist?top\" % seed\n print(url)\n try:\n response = requests.get(url).json()\n except (requests.exceptions.ConnectionError, ValueError) as exc:\n print(exc)\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Endpoint to send the last block mined to peers
def submit_block(): for peer in peers: if peer == host_address: continue url = "http://{}:8000/add_block".format(peer) headers = {'Content-Type': "application/json"} requests.post(url, data=json.dumps(blocks[0], sort_keys=True), ...
[ "def listen_broadcast(self):\n self.send_response(200)\n self.end_headers()\n\n rec_params = urlparse.parse_qs(urlparse.urlparse(self.path).query)\n block_params = {\"index\": int(rec_params[\"index\"][0]),\n \"data\": rec_params[\"data\"][0],\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Helper function that hides all widgets except home and selected widget
def hide_all_but(self, widget=None): for i in reversed(range(1, self.layout.count())): item = self.layout.itemAt(i) if isinstance(item, QWidgetItem): item.widget().hide() # or # item.widget().setParent(None) ...
[ "def hide(self):\n for widget in self.widgets:\n widget.hide()\n if self.label is not None:\n self.label.hide()", "def hide_status(self):\r\n self.hide()\r\n self._searchWidget._checkSensitive.setCheckState(Qt.Unchecked)\r\n self._searchWidget._checkWholeWo...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
checks if the ball is out of bounds
def out_of_bounds(): return ball.y > 600 or (ball.touches(hoop) and ball.speedy < 0)
[ "def ball_is_further_in(self):\n return ((self.ball_pos.y >= 0) and (self.pos.y > self.ball_pos.y)\n or (self.ball_pos.y < 0 and self.pos.y < self.ball_pos.y))", "def is_out_of_bounds(self, agent):\n x = agent.x\n y = agent.y\n\n if x < 0 or x >= self.width:\n ret...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
load lines from find.txt to search_dict
def load_db(): if not os.path.isfile("find.txt"): f = open("find.txt", "w") f.write("#test,yano,foobar\n") f.close() search_file = open("find.txt", "r") lines = search_file.readlines() search_file.close() search_dict = dict() for line in lines: result = None ...
[ "def _search_input(self):\n try:\n for line in fileinput.input(files=self.parsed_elements.args.files_names, mode='r'):\n res = self.regex.search_regex_in_data(line)\n for item in res:\n self.results.append({'file_name': fileinput.filename(), 'no_lin...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
save search_dict to find.txt
def save_db(search_dict): search_file = open("find.txt", "w") for channel in search_dict: if channel is not "": for nick in search_dict[channel]: for line in search_dict[channel][nick]: new = "%s,%s,%s\n" % (channel, nick, (line).encode('utf-8')) ...
[ "def writeResultToFile(results, filename='all_searches.txt'):\n with open(filename, 'w') as f:\n for query in results:\n f.writelines(query.__repr__() + '\\n')", "def write_results(self,results_dict):", "def write(self):\n\n d = {} # to contain mappings of term to file cursor value\...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Generates a graph of facilities from xml file Optional node_style argument (border style, border color) Requires networkx drawing, because nod takes too long
def generate_facilities_graph(graph, xml, style=(1, 'black')): network = etree.parse(xml) facilities = network.findall(".//facility") node_attr = {} node_attr['size'] = style[0] node_attr['color'] = style[1] for facility in facilities: current_node_attr = {} current_node_attr.u...
[ "def generate_network_graph(graph, xml, node_style=(0, 'white'), edge_style=(1, 'orange')):\n node_attr = {}\n node_attr['size'] = node_style[0]\n node_attr['color'] = node_style[1]\n \n edge_attr = {}\n edge_attr['occupied'] = 0\n edge_attr['size'] = edge_style[0]\n edge_attr['color'] = edg...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Generates a graph from network xml file Optional node_style argument (size, color, alpha) Optional edge_style argument (width, color) Returns a networkx graph
def generate_network_graph(graph, xml, node_style=(0, 'white'), edge_style=(1, 'orange')): node_attr = {} node_attr['size'] = node_style[0] node_attr['color'] = node_style[1] edge_attr = {} edge_attr['occupied'] = 0 edge_attr['size'] = edge_style[0] edge_attr['color'] = edge_style[1] ...
[ "def generate_netx(file):\n \n f = csv.reader(open(file))\n net = nx.Graph()\n for edge in f:\n net.add_edge(int(edge[0]),int(edge[1]),weight=float(edge[2]))\n #n_communities = nx.number_connected_components(net) networkx community finding algorithm, didnt work well.\n\n return net", "def...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
This function takes previous hidden state and memory tuple with input and outputs current hidden state.
def Lstm(self, previous_hidden_memory_tuple, x): previous_hidden_state,c_prev=tf.unstack(previous_hidden_memory_tuple) #Input Gate i= tf.sigmoid( tf.matmul(x,self.Wi)+tf.matmul(previous_hidden_state,self.Ui) + self.bi ) #Forget Gate ...
[ "def reset_hidden(self, hidden_state, done):\n if hidden_state.dim() != done.dim():\n if done.dim() == 2:\n done = done.unsqueeze(0)\n elif done.dim() == 1:\n done = done.unsqueeze(0).unsqueeze(2)\n hidden_state = hidden_state * (1 - done)\n r...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
This function takes hidden state and returns output
def get_output(self, hidden_state): output = tf.nn.relu(tf.matmul(hidden_state, self.Wo) + self.bo) return output
[ "def get_hidden(self, layer):", "def reset_hidden(self, hidden_state, done):\n if hidden_state.dim() != done.dim():\n if done.dim() == 2:\n done = done.unsqueeze(0)\n elif done.dim() == 1:\n done = done.unsqueeze(0).unsqueeze(2)\n hidden_state = hi...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Find the number of dots in nth pentagonal number.
def pentagonal(n: int) -> int: # Find the pentagonal number to nth degree. pentagonal_number = (n * ((3 * n) - 1) // 2) # Find the total number of dots. dots = ((n-1) ** 2) dots += pentagonal_number return dots
[ "def pentagonal_numbers(N, K):\n for n in range(K+1, N):\n # test whether (3n^2 - n)/2 - (3n^2 - 6nK - n + 3K^2 + K)/2 is pentagonal\n P_n_minus_P_n_K = (6*n*K - 3*K**2 - K)//2\n # if is_pentagonal(P_n_minus_P_n_K):\n # print(pentagonal_number(n))\n P_n_plus_P_n_K = pentago...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
The function asks a user to enter four numbers (width and height) for two envelops. If the entered values are valid it creates two class objects and calls the function 'compare_envelops' to make a decision if it is possible to fit one envelop into another one.
def main(): run = True while run: try: width1, height1 = [float(x) if validation(float(x)) else print(HELP_MSG) for x in get_user_input().split(',')] width2, height2 = [float(x) if validation(float(x)) else print(HELP...
[ "def evaluate_input(window, answer1, answer2, cube, cubies):\n\n string_of_answer1 = answer1.get()\n string_of_answer2 = answer2.get()\n\n if len(string_of_answer1) > 0 and len(string_of_answer2) > 0:\n # Converting the strings for a less difficult evaluation\n\n # Lower case\n string_...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
The function checks and returns 'True' if the entered values are numbers greater than 0. Otherwise it prints a message with the further instructions and returns 'False'.
def validation(value): if isinstance(value, float) and value > 0: return True else: print(HELP_MSG) return False
[ "def validation(value):\n\n if isinstance(value, int) and value > 0:\n return True\n else:\n print(HELP_MSG)\n return False", "def has_zero(self):\n if self.min() <= 0 and self.max() >= 0:\n return True\n else:\n return False", "def check_input(self...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Calculate the slope and aspect from the input DEM
def get_slope_aspect(input_dem, output_folder, mask): arcpy.env.overwriteOutput = True input_folder = os.path.dirname(input_dem) arcpy.env.workspace = input_folder dem_slope = pjoin(input_folder, 'slope') dem_aspect = pjoin(input_folder, 'aspect') # Derive slope and aspect ... cal_slope_a...
[ "def calculate_slope_and_aspect(dem: np.ndarray) -> tuple[np.ndarray, np.ndarray]:\n # TODO: Figure out why slope is called slope_px. What unit is it in?\n # TODO: Change accordingly in the get_horizontal_shift docstring.\n\n # Calculate the gradient of the slope\n gradient_y, gradient_x = np.gradient(d...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Find the common area of vegetation, slope and aspect to calculate BAL.
def find_common_area(veg_class, slope, aspect): output_folder = os.path.dirname(veg_class) arcpy.env.overwriteOutput = True # set directory work_folder = output_folder os.chdir(work_folder) arcpy.env.workspace = work_folder # get the common area of veg and dem # get the extent of inpu...
[ "def get_ab_area(self):\n\t\treturn la.norm(cross(self.a, self.b))/2", "def get_ab_area(self):\n\t\treturn la.norm(cross(self.a, self.b))", "def get_ah_area(self):\n\t\treturn la.norm(cross(self.a, self.h))", "def bal_calc(vegetation, dem, fdi, output_folder, remap, mask):\n arcpy.env.overwriteOutput = Tru...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Calcuate BAL based on vegetation map and DEM.
def bal_calc(vegetation, dem, fdi, output_folder, remap, mask): arcpy.env.overwriteOutput = True arcpy.AddMessage('Reclassify the vegetation map ... ') veg_class = reclass_veg(vegetation, dem, output_folder, remap, mask) arcpy.AddMessage('Reclassify slope and aspect ... ') slope, aspect = get_...
[ "def calc_dem_bent(self, dem_data, alt):\n self.dem = np.ma.zeros(self.N)\n self.dem[self.valid_idx] = (dem_data[self.i_idx_valid,\n self.j_idx_valid])\n self.dem.mask = ~self.valid_idx\n self.dem_bent = self.dem - alt", "def run():\n # ad...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Find the footprint of a raster
def get_footprint(raster, footprint): # set the environment variable and workspace arcpy.env.overwriteOutput = True input_folder = os.path.dirname(raster) arcpy.env.workspace = input_folder raster_extent = arcpy.Describe(raster).extent get_extent_mask(raster_extent, footprint) # add the ...
[ "def test_raster_shape(dem_rast):\n width = dem_rast.width\n height = dem_rast.height\n\n assert width == 1147 and height == 974", "def get_raster_pixels(raster_path):\n\n raster_pixels = arcpy.SearchCursor(raster_path).next().count\n\n return raster_pixels", "def find_footprint(self, member='tot...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Find the effective area of interest based on input vegetation map, DEM and extent.
def find_aoi(extent, dem, veg): # set the environment variable and workspace arcpy.env.overwriteOutput = True input_dem_folder = os.path.dirname(dem) input_veg_folder = os.path.dirname(veg) arcpy.env.workspace = input_dem_folder # derive the effective mask based on the input data arcpy.Add...
[ "def exposed_area(self):\r\n arg_str = p2e._base._util._convert_args_to_string(\"get.object.exposure\", \r\n self._object._eco_id)\r\n val = p2e._app.Request(arg_str)\r\n return p2e._base._util._convert_str_to_type(val, float)", "def get_avg...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Run the BAL calculations.
def run(): # add subfolders into path cmd_folder = os.path.realpath( os.path.abspath( os.path.split( inspect.getfile( inspect.currentframe()))[0])) if cmd_folder not in sys.path: sys.path.insert(0, cmd_folder) cmd_subfolder = pjoin(cmd_fol...
[ "def run(self):\n try:\n logger.info(\"start calculation cycle\")\n self.calculate()\n self.process()\n except:\n import traceback\n logger.error(\"failure during state cycle\")\n logger.error(traceback.format_exc())", "def run():\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Setup is used for creating a new instance of epg
def setUp(self): self.epg = epg()
[ "def setUp(self):\n models.Dog.objects.create(\n name='George',\n image_filename='13.jpg',\n age=12,\n gender='m',\n size='xl',\n )", "def setUp(self):\n self.game = game.Game()", "def setup_method(self):\n self.g = Game()", ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Test if we are able to retrieve channels
def testRetrieveChannel(self): self.assert_(self.epg.channels())
[ "def get_channels():", "def is_channel_available():\n try:\n client = _get_slack_client()\n channel_name = _get_slack_channel_name()\n response = client.conversations_list(limit=sys.maxsize)\n if response.status_code == 200:\n for channel in response.data['channels']:\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Test if we are able to retrieve genre
def testRetrieveGenre(self): self.assert_(self.epg.genres())
[ "def populateGenre(self):\r\n \r\n data = showInformation.getJson(self.infourl)\r\n if \"genres\" in data:\r\n return data[\"genres\"]\r\n else:\r\n return False", "def test_user_genre(self, test_client, headers):\n response = test_client.get(\"/api/user/ge...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Test if we are able to retrieve channels by genre
def testRetrieveChannelsByGenre(self): self.assert_(self.epg.channelsByGenre())
[ "def testRetrieveGenre(self):\n self.assert_(self.epg.genres())", "def testRetrieveMovieChannels(self):\n self.assert_(self.epg.movieChannels())", "def testRetrieveChannel(self):\n self.assert_(self.epg.channels())", "def get_movies_by_genre(self, genre):\r\n raise NotImplementedEr...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Test if we are able to retrieve movie channels (by genre name)
def testRetrieveMovieChannels(self): self.assert_(self.epg.movieChannels())
[ "def testRetrieveChannelsByGenre(self):\n self.assert_(self.epg.channelsByGenre())", "def testRetrieveGenre(self):\n self.assert_(self.epg.genres())", "def testRetrieveChannel(self):\n self.assert_(self.epg.channels())", "def get_movies_by_genre(self, genre):\r\n raise NotImplement...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Test if we are able to retrieve channel ids
def testRetrieveChannelIds(self): self.assert_(self.epg.channelIds())
[ "def testRetrieveChannel(self):\n self.assert_(self.epg.channels())", "def test_should_not_get_a_channel_by_id(self):\n\n response = self.client.get(\n '/api/v3/channel/0/',\n content_type='application/json',\n HTTP_AUTHORIZATION=self.auth)\n\n self.assertEqua...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Replace tokens by formatted data from appointment or contact returns messages dicts with keys sms, mail, chat and mail_subject containing the text with replaced variable
def _replace_tags_in_text(self, notification, contact, appointment): messages = { "sms": notification.sms_message, "mail": notification.mail_message, "chat": notification.chat_message, "mail_subject": notification.mail_subject, } if appointment.sl...
[ "def replace_ids(dialogue):\n movie_titles = dialogue[\"movieMentions\"]\n for message in dialogue[\"messages\"]:\n text = message[\"text\"]\n replaced = []\n for word in text.split():\n if word[0] == \"@\" and re.sub('\\\\D', '', word) in movie_titles:\n movie_id = re.sub('\\\\D', '', word)\...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Test case for nested lists passing a dictionary.
def test_remove_nested_loop_dict(self): expected = {} result = nested_lists.remove_nested_loop(expected) self.assertFalse(result)
[ "def p_1():\n nested_list = [[], [], [], [], []]\n # Tests\n print(nested_list)\n\n return 0", "def test31(self):\n self.check('aDict.nestedDict')", "def test_second_level_retrieval(nested_dict):\n\n l = ['first', 'second']\n\n val = get_nested_value(d=nested_dict, keys=l)\n\n assert...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Test case for nested lists passing a nested list.
def test_remove_nested_loop_nested_list(self): expected = [1, 2, [3, 4], 5] result = nested_lists.remove_nested_loop(expected) expected = [1, 2, 3, 4, 5] self.assertEqual(result, expected)
[ "def p_1():\n nested_list = [[], [], [], [], []]\n # Tests\n print(nested_list)\n\n return 0", "def p_2():\n nested_list = [[0,0,0],[0,0,0],[0,0,0],[0,0,0],[0,0,0]]\n # Tests\n print(nested_list)\n return 0", "def test_pydata_list_nested(self):\n\n intype = [1, ['two', 'three'], [...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Whether or not tests are currently running on one of our public CIs.
def running_on_public_ci() -> bool: return os.getenv("GITHUB_ACTIONS") == "true"
[ "def in_ci():\n for key in ('CI', 'TRAVIS'):\n if os.environ.get(key, '') not in [False, '', '0', 'false']:\n return True\n return False", "def inside_test():\n return 'inside_test' in testing.environment and testing.environment.inside_test", "def is_interactive(self):\n return...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Calculate the sleep time based on the number of past attempts. The sleep time grows exponentially with the attempts up to a maximum of 10 seconds.
def calc_sleep(self, attempt): return min(10, pow(2, attempt))
[ "def _calc_sleep_time(self, retry_index):\n # If we have already passed the retry index that would return the max timeout\n # then there is no reason to calculate the timeout.\n if self._max_retry_index is not None and self._max_retry_index <= self._retry_count:\n return self._max_re...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Return the unproxied object
def unproxied_object(self): return self._unproxied_object
[ "def get_proxy (self):\n return self.proxy", "def WrappedObject(self) -> object:", "def GetRealObj(obj: Any) -> Any:\n if IsWeakRef(obj):\n return obj()\n if isinstance(obj, LambdaType):\n return obj()\n return obj", "def deref_safe ( self ):\n obj = self.deref_unsafe()\n i...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Change le groupe du membre.
def opt_changer_groupe(self, arguments): membre = self.objet squelette = membre.parent nom_groupe = arguments.strip() squelette.changer_groupe_membre(membre.nom, nom_groupe) self.actualiser()
[ "def agrupar(self, grupo):\n self.grupos[grupo.tipo] = grupo", "def change_group_name(self, user_id: int, group_name: str):\n self.cursor.execute(f\"UPDATE public.users SET group_name = '{group_name}' WHERE user_id = {user_id}\")\n self.conn.commit()", "def update_groups(self, uid, groups, ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Get lyrics from a artist/songtitle
def get_lyrics_for_song(soap_url, artist, songtitle): soap = lyricwiki.LyricWikiBindingSOAP(soap_url) song = lyricwiki.getSongRequest() song.Artist = artist song.Song = songtitle result = soap.getSong(song) lyrics = result.Return.Lyrics if not lyrics or "not found" in lyrics.splitlines()[0]....
[ "def scrape(title, artist):\r\n # Format artist and title for building url\r\n title = format(title)\r\n artist = format(artist)\r\n\r\n # Build url\r\n url = \"http://www.metrolyrics.com/{}-lyrics-{}.html\".format(title, artist)\r\n\r\n # Request url\r\n try:\r\n log.debug(\"Requesting ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
get the name of a given player
def name(player): return player['name']
[ "def get_player_name():\n\n return player.get(\"player_name\")", "def get_name(self):\r\n return self._player_name", "def get_player_name(self):\r\n return self.__name", "def get_other_player_name(self) :\n return self.players[1]", "def get_player_name(self, player_number):\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
get the coin used by given player
def coins(player): return player['coins']
[ "def get_player_money(player):\r\n\r\n game_db = _load_game_db()\r\n\r\n if not player_exists(player):\r\n raise ValueError('player %s does not exists' % player)\r\n\r\n return game_db['players'][player]['money']", "def get_result(self, player):\n\t\t# return 0 if (self.knockedOut[player]) else 1\...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Get all true permissions for a user excluding ones that have been explicitly revoked.
def _get_adjusted_true_permissions(cls, user): from rolepermissions.permissions import available_perm_status default_true_permissions = set() user_permission_states = available_perm_status(user) adjusted_true_permissions = set() # Grab the default true permissions from each of ...
[ "def get_user_permissions(cls, user):\n return set(user.permissions.values_list(\"name\", flat=True))", "def get_effective_permissions(cls, user):\n if user.is_superuser:\n return set(Permission.objects.values_list(\"name\", flat=True))\n perms = set()\n # User permissions\n...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Get a Role object from a role name.
def retrieve_role(role_name): return RolesManager.retrieve_role(role_name)
[ "def get_role(cls, name):\n return cls.query.filter_by(name=name).first()", "def get_role(obj, role_name):\n for role in obj.roles:\n if role.name == role_name:\n return role\n return None", "async def get_role_by_name(guild: Guild, role_name: str) -> Role:\n role = None\n i...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Assign a role to a user.
def assign_role(user, role): return _assign_or_remove_role(user, role, "assign_role_to_user")
[ "async def assign_role(self, ctx, * , role: CustomRoleConverter):\n settable_role = find(lambda r: r.id in self.settable_roles, ctx.guild.roles)\n if role == settable_role and self.lockdown:\n await ctx.send(\"Server on lockdown due to high amount of people joining try again in a day or two...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Remove a role from a user.
def remove_role(user, role): return _assign_or_remove_role(user, role, "remove_role_from_user")
[ "def removeRole(self, role):\n pass", "def remove_role(self, user, targetUser, role):\n if self.can_grant_permissions(user):\n if role in self[\"roles\"]:\n if targetUser in self[\"roles\"][role]:\n self[\"roles\"][role].remove(targetUser)\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Remove all roles from a user.
def clear_roles(user): roles = get_user_roles(user) for role in roles: role.remove_role_from_user(user) return roles
[ "def delete_all_roles(self):\n if not self.user_roles:\n raise UserNotHasRole\n\n for user_role in self.user_roles:\n user_role.delete(commit=True)\n db.session.commit()", "def remove_users(self, *users):\n entries = CourseAccessRole.objects.filter(\n u...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Add files to the output list which tells ARC CE which files to upload
def create_output_list(files, init_dir, ddmconf): if not ddmconf: raise PilotException("copy_out() failed to resolve ddmconf from function arguments", code=ErrorCodes.STAGEOUTFAILED, state='COPY_ERROR') for fspec in files: arcturl = fsp...
[ "def write_files(self, outpath=None):\n files = '\\n'.join(self.files + [''])\n if outpath:\n with open(outpath, 'w') as outfile:\n outfile.write(files)\n print(outpath)\n else:\n print(files)", "def inputFiles(self):\n pass", "def on_a...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Da un nuevo contorno donde sus elementos son mas grandes que dim_min_contuor
def filtro_contornos(contuors, dim_min_contuor, dim_max_contuor): new_contuors = [] for contuor in contuors: if len(contuor) > dim_min_contuor and len(contuor) < dim_max_contuor: new_contuors.append(contuor) return new_contuors
[ "def consistance_noeuds(self):\n\n for c in self.contraintes:\n if c.dimension() == 1:\n # /!\\ iterer sur domaine[:], sinon on ne peut pas supprimer d'elements\n for v in c.variables[0].domaine[:]:\n if not c.est_valide(v):\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns the minified version of a template.
def minify(self): return htmlmin.minify(self.render().decode('utf8'), remove_comments=True, remove_empty_space=True)
[ "def get_source_template():", "def minify_js(file_path, src):\n in_str = StringIO(src)\n out_str = StringIO()\n JavascriptMinify().minify(in_str, out_str)\n src = out_str.getvalue()\n in_str.close()\n out_str.close()\n return src", "def minify_code(file_path) -> str:\n # Open the file an...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Writes the minified version of a template to the output directory. If use_subdir is True, then it is written to index.html in a subdirectory of OUTPUT_PATH with the same name as the template.
def export(self, use_subdir=True): if use_subdir: os.makedirs(os.path.join(OUTPUT_PATH, self.name)) path_to_write = os.path.join(OUTPUT_PATH, self.name, 'index.html') else: path_to_write = os.path.join(OUTPUT_PATH, 'index.html') with open(path_to_write, 'w') ...
[ "def main():\n dest_dir = \".public\"\n if os.path.isdir(dest_dir):\n shutil.rmtree(dest_dir)\n os.mkdir(dest_dir)\n\n env = Environment(\n loader=FileSystemLoader('templates'),\n autoescape=select_autoescape(['html'])\n )\n\n ignore_files = ignoreFile()\n files_in_dir = os...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Test the repr for a flip sign operator.
def test_repr(): op = qml.FlipSign([0, 1], wires=("a", "b")) expected = "FlipSign([0, 1], wires=['a', 'b'])" assert repr(op) == expected
[ "def _invert_signs(signs):\n return signs[0] < 0", "def is_sign_reversing(func):\r\n\tfor i in func.domain():\r\n\t\tif func(i).get_sign() != -i.get_sign():\r\n\t\t\treturn False\r\n\treturn True", "def _sign(x):\n if _copysign(1.0, x) == -1.0:\n return \"-\"\n else:\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Assert error raised when length of basis state and wires length does not match
def test_length_not_match_error(self, n_status, n_wires): with pytest.raises( ValueError, match="Wires length and flipping state length does not match, they must be equal length ", ): qml.FlipSign(n_status, wires=n_wires)
[ "def test_param_invalid_input_array_param_length(self):\n\t\twith self.assertRaises(IndexError):\n\t\t\tresult = arrayfunc.takewhile('==', self.dataempty, self.dataout, 100.0)", "def test_validate_invalid_final_state_non_str(self):\n with nose.assert_raises(exceptions.InvalidStateError):\n self....
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Espera hasta detectar el evento de impresion. grid_timer_traza connect here
def grid_detect_traza(self): if self.main.grid_traza_control: self.grid_timer_traza.stop() if self.scan_check.isChecked(): self.grid_scan_signal() else: self.grid_detect()
[ "def grid_detect_scan(self):\n if self.grid_scan_control:\n self.grid_timer_scan.stop()\n self.grid_detect()", "def process_timer(ctx, key, time):\n raise Exception('process_timer not implemented')", "def teleopPeriodic(self) -> None:\n ...", "def addTimerCallback(*args, **kwarg...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Espera hasta detectar el scan completo. grid_timer_scan connect here
def grid_detect_scan(self): if self.grid_scan_control: self.grid_timer_scan.stop() self.grid_detect()
[ "def grid_detect_traza(self):\n if self.main.grid_traza_control:\n self.grid_timer_traza.stop()\n if self.scan_check.isChecked():\n self.grid_scan_signal()\n else:\n self.grid_detect()", "def man_scan(self, asynchron=True):\r\n interval = self.Stat.interval\r\n...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Watch for Hangouts bridge chat invites and add them to `hangouts_jids_seen`.
def roster_subscription_request(self, presence): from_jid = presence['from'] if from_jid.domain == TALK_BRIDGE_DOMAIN: # Hangouts users get these goofy jids. # Replying to them doesn't seem to work, but replying to resources under it will. # So, we store the bare ji...
[ "def detect_hangouts_jids(self, presence):\n\n # TODO this should probably be removed, since it's diverged from the normal handler\n\n from_jid = presence['from']\n if from_jid.bare in self.hangouts_jids_seen and from_jid.resource:\n self.hangouts_jids_seen.remove(from_jid.bare)\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Watch for Hangouts bridge jids coming online and respond to any in `hangouts_jids_seen`.
def detect_hangouts_jids(self, presence): # TODO this should probably be removed, since it's diverged from the normal handler from_jid = presence['from'] if from_jid.bare in self.hangouts_jids_seen and from_jid.resource: self.hangouts_jids_seen.remove(from_jid.bare) if ...
[ "def roster_subscription_request(self, presence):\n\n from_jid = presence['from']\n\n if from_jid.domain == TALK_BRIDGE_DOMAIN:\n # Hangouts users get these goofy jids.\n # Replying to them doesn't seem to work, but replying to resources under it will.\n # So, we store...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns an Upvote instance
def create_upvote(count=0, upvoters=None): if upvoters is None: upvoters = [] return Upvote(count, upvoters)
[ "def upvote(self):\n self._authenticated_action_click(NinegagXPaths.Post.UPVOTE_BUTTON, 'Upvoting')", "def upvotePost(self):\n self.votes = self.votes + 1\n self.save()", "def upvote(checkin_id):\n\n\tvote = \"up\"\n\n\treturn update_vote(checkin_id, vote)", "def test_update_add_upvote(se...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Tests creation of Upvote model
def test_init(self): u = create_upvote() self.assertTrue(isinstance(u, Upvote))
[ "def test_update_add_upvote(self):\n self.test_uuid = str(uuid.uuid4())\n u = Upvote(1, ['upvoter 1 uuid'])\n u.save(self.test_uuid, db)\n u.update_add_upvote('upvoter 2 uuid', 2, self.test_uuid, db)\n\n _u = Upvote.get(self.test_uuid, db)\n self.assertEqual(u.to_dict(), _u...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Tests adding a new upvote
def test_update_add_upvote(self): self.test_uuid = str(uuid.uuid4()) u = Upvote(1, ['upvoter 1 uuid']) u.save(self.test_uuid, db) u.update_add_upvote('upvoter 2 uuid', 2, self.test_uuid, db) _u = Upvote.get(self.test_uuid, db) self.assertEqual(u.to_dict(), _u.to_dict())
[ "def test_create_vote(self):\n\n res = self.client.post('/api/v1/votes', json=self.new_vote)\n data = res.get_json()\n\n self.assertEqual(data['status'], 201)\n self.assertEqual(data['message'], 'Success')\n self.assertEqual(res.status_code, 201)", "def test_ajax_vote(self):\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Tests removing an existing upvote
def test_update_remove_upvote(self): self.test_uuid = str(uuid.uuid4()) u = Upvote(1, ['upvoter 1 uuid']) u.save(self.test_uuid, db) u.update_remove_upvote('upvoter 1 uuid', 0, self.test_uuid, db) _u = Upvote.get(self.test_uuid, db) self.assertEqual(u.to_dict(), _u.to_di...
[ "def remove_votes(checkin, vote):\n\n\t# update database\n\tif vote == \"up\":\n\t\t# remove upvote\n\t\tcheckin.upvotes -= 1\n\telif vote == \"down\":\n\t\t# remove downvote\n\t\tcheckin.downvotes -= 1\n\n\t# commit changes to database\n\tmodel.db.session.commit()", "def test_update_add_upvote(self):\n se...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Form a density from observing masss in specific bins. This is different from hist in that the bins are specified and not assumed equally spaced. The height of the bars is the mass within the bin divided by the length of bin.
def PL_density(mass, binpoints, facecolor='red', alpha=0.8, edgecolor='black', ax=None, **opts): if ax is None: fig = plt.gcf() ax = fig.add_subplot(111) opts['facecolor'] = facecolor opts['alpha'] = alpha opts['edgecolor'] = edgecolor mass = n...
[ "def create_mass_hist(dfr, costh_bin=None):\n if costh_bin is not None:\n plot_data = dfr[get_bin_cut_df(dfr, lambda d: d.costh_HX.abs(),\n *costh_bin)]\n else:\n plot_data = dfr\n\n return create_histogram(plot_data.chicMass, (75, 3.325, 3.725))", "def...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Initializes the Fleetspeak connector.
def Init(service_client=None): global CONN global label_map if service_client is None: service_client_cls = fs_client.InsecureGRPCServiceClient fleetspeak_message_listen_address = ( config.CONFIG["Server.fleetspeak_message_listen_address"] or None) fleetspeak_server = config.CONFIG["Server.f...
[ "def setup_connector():\n connector = ConnectorMatrix(\n {\n \"room\": \"#test:localhost\",\n \"mxid\": \"@opsdroid:localhost\",\n \"password\": \"hello\",\n \"homeserver\": \"http://localhost:8008\",\n }\n )\n return connector", "def initialize_f...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
The x, y, z acceleration values returned in a
def acceleration(self): # read the 6 bytes of acceleration data current_range = self.range scale = 1.0 if current_range == 3: scale = 512.0 if current_range == 2: scale = 1024.0 if current_range == 1: scale = 2048.0 if current_...
[ "def get_vector(self):\n return self.x, self.y, self.z", "def acceleration(self) -> Tuple[float, float, float]:\n # pylint: disable=no-else-return\n # This needs to be refactored when it can be tested\n # Read 6 bytes for 16-bit X, Y, Z values.\n self._read_into(_MMA8451_REG_OUT...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Enables tap detection with configurable parameters.
def enable_tap_detection( self, *, tap_count=1, threshold=25, long_initial_window=True, long_quiet_window=True, double_tap_window=TapDuration.DURATION_250_MS ): self._tap_shock = not long_initial_window self._tap_quiet = long_quiet_window ...
[ "def addTap(id):\n logging.debugv(\"functions/linux.py->addTap(id)\", [id])\n dev = 'tap' + str(id)\n if chkIf(dev):\n if ifUp(dev):\n return dev\n else:\n return False\n cmd = [locations.OPENVPN, '--mktun', '--dev', dev]\n if runWrapper(cmd):\n if ifUp(dev)...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
`True` if a single or double tap was detected, depending on the value of the\ ``tap_count`` argument passed to ``enable_tap_detection``
def tapped(self): if self._tap_count == 0: return False motion_int_status = self._motion_int_status if motion_int_status == 0: # no interrupts triggered return False if self._tap_count == 1 and motion_int_status & 1 << 5: return True if sel...
[ "def supports_multi_touch(self):\n ret = self._get_attr(\"supportsMultiTouch\")\n return ret", "def multi_touch_supported(self):\n ret = self._get_attr(\"multiTouchSupported\")\n return ret", "def was_touched(self,touch):\n if \"on_touch\" in self.__dict__:\n if tou...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Given an array of integer values, identify the three values that can create the triangle with the largest perimeter. In the case of multiple triangles with the same perimeter, choose the one with the longest side. In the case of a tie, choose one with the longest minimum side.
def identify_maximum_perimeter_triangle(values): if len(values) < 3: raise ValueError('Unable to identify triangle with less than three values') sorted_values = sorted(values) for index in range(len(sorted_values) - 1, 1, -1): if sorted_values[index] < sorted_values[index - 1] + sorted_val...
[ "def find_largest_block(array):\n best_size = 0\n best_index = 0\n for i in range(len(array)):\n size = array[i][2] * array[i][3]\n if size > best_size:\n best_size = size\n best_index = i\n return array[best_index]", "def longest_side(a,b):\n\treturn math.sqrt(a*a+...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Is it a runfolder? >>> print is_runfolder('090630_HWUSIEAS999_0006_30LNFAAXX') True >>> print is_runfolder('hello') False
def is_runfolder(name): if re.match("^[0-9]{6}_[-A-Za-z0-9_]*$", name): return True else: return False
[ "def is_folder(path: str) -> bool:\n pass", "def is_folder(file):\r\n return file.rfind('.') < 0", "def isfolder(self):\n return False", "def is_folder(inputfolder, boolean=False):\n if not inputfolder or not isdir(inputfolder):\n if boolean:\n return False\n logger.er...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Return the directory in path that is a subdirectory of root. e.g. >>> print get_top_dir('/a/b/c', '/a/b/c/d/e/f') d >>> print get_top_dir('/a/b/c/', '/a/b/c/d/e/f') d >>> print get_top_dir('/a/b/c', '/g/e/f') None >>> print get_top_dir('/a/b/c', '/a/b/c')
def get_top_dir(root, path): if path.startswith(root): subpath = path[len(root):] if subpath.startswith('/'): subpath = subpath[1:] return subpath.split(os.path.sep)[0] else: return None
[ "def get_topdir():\n path = Path(os.path.dirname(__file__))\n while True:\n if (path / \".top\").exists():\n return path\n if path.parent == path:\n # Seems like we reached the home /\n raise ValueError(\"Couldn't determine root directory.\")\n path = path...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Read the json file containing holdings info. See sample for more information on formatting
def read_data(data_file): with open(data_file) as json_data: all_data = json.load(json_data) urls = all_data["urls"] holdings = all_data["holdings"] return urls, holdings
[ "def get_standings_raw(self, league_id):\n with open(self.dir_path + \"/sample.standings.json\", \"r\") as f:\n return json.load(f)", "def read_data():\n with open(\"stagnationPointNu.json\", \"r\") as ifile:\n data = json.load(ifile)\n return data", "def _read_json(self,fname):\n...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Printer the header for the table
def print_headers(): print("symbol\t count\t price\t\t total") print("-" * 71)
[ "def print_header():\n header = \"| {:<18} | {:<18} | {:<21} | {:<21} |\".format(\"ROLL_NUMBER\",\n \"NAME\",\n \"DATE-OF-BIRTH\",\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Get the price from a given URL
def get_price(url): global ALLOWANCE source = "" try: source = requests.get(url).text source = json.loads(source) ALLOWANCE = source["allowance"]["remaining"] except: print("\nError loading {}:\n{}".format(url, source)) return "0" return source["result"]["pric...
[ "def get_price(url, retries=0):\n findprice = '<span id=\"totalPrice\">(.*)</span>'\n\n if retries > 10: return\n try:\n htmlpage = urllib2.urlopen(url).read()\n price = re.findall(findprice, htmlpage)[0]\n int_price = float(price.replace('$','').replace(',',''))\n return int_pr...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Logic that sets keys from state definition that are used to uniquely identify IAM Roles
def _set_unique_keys(self): self.unique_keys = IAMRole.UNIQUE_KEYS
[ "def generate_state_key(self, state, role):\n\n pass", "def id_replace(self):\n aws_lookup = self.lookup()\n var_lookup_list = pcf_util.find_nested_vars(self.desired_state_definition, var_list=[])\n for (nested_key, id_var) in var_lookup_list:\n if id_var[0] == \"lookup\":\n...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Check for IAM Policy parents and sets the IAM Policy IDs
def get_iam_policies(self): desired_policy = self.custom_config.get('policy_arns', []) if len(self.parents) > 0: iam_policy_parents = list(filter(lambda x: x.flavor == IAMPolicy.flavor, self.parents)) if iam_policy_parents: for policy_parent in iam_policy_paren...
[ "def process_parents(self):\n\t\tfor student in self.students.get_objects():\n\t\t\tparent = self.parents.make_parent(student)\n\t\t\tstudent.add_parent(parent)", "def setParents(self,parents):\n if not isinstance(parents, list):\n raise TypeError, utils.mapping(_(\"Parents ($1) must be a list: ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Determines if states are equivalent. Uses equivalent_states defined in the IAMRole class.
def is_state_equivalent(self, state1, state2): return IAMRole.equivalent_states.get(state1) == IAMRole.equivalent_states.get(state2)
[ "def _are_equal_states(\n self,\n state1: Dict[str, Any],\n state2: Dict[str, Any],\n ) -> bool:\n if set(state1.keys()) != set(state2.keys()):\n return False\n for state_name, value1 in state1.items():\n value2 = state2[state_name]\n if type(va...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns the ipaFeatures dict with added ipa_symbols and description.
def final_ipa_dict() -> dict: ipa_dict = ipaFeatures_dict() with open("ipa_new.csv", "r") as f: f.readline() for row in f: row = row.split(",") if row[0] not in ipa_dict and len(row[0].split()) == 1: ipa_dict[row[0]] = [row[0], row[2].rstrip(), row[1]] ...
[ "def e_features(filename):\n features = {}\n try:\n pe = pefile.PE(filename, fast_load=False)\n\n # File Header\n features['filename'] = os.path.basename(filename)\n features['machine'] = pe.FILE_HEADER.Machine\n features['number of sections'] = pe.FILE_HEADER.NumberOfSectio...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Concise method for how long to wait for browser to load ... in seconds.
def wait_for(self, seconds): if seconds < 0: return self.browser.implicitly_wait(5) return self.browser.implicitly_wait(seconds)
[ "def remainingTimeToWait(self) -> int:\n ...", "def time_to_interactive(self) -> float:\n return self.navigation_timing.dom_complete", "def loading_time_secs(self):\n return self.__loading_time", "def wait_for_page(self, url=None) -> None:\r\n script = 'return document.readyState =...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
A utilty/shortcut method to fetch the comment_form container on a page.
def get_comment_form(self): comment_form = self.browser.find_element_by_id('comment_form') return comment_form
[ "def get_form():\n from django_comments.forms import CommentForm\n\n return CommentForm", "def show_comment_form(self, req, page):\n page_id = self.env.get_real_filename(page)[:-4]\n ajax_mode = req.args.get('mode') == 'ajax'\n target = req.args.get('target')\n page_comment_mode ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Clear the contents of the current Axes object
def clear(self): self._ax.clear()
[ "def clear_axes(self):\r\n # Remove lines and selection as they can't be reloaded properly\r\n for plot in self.sub_plots:\r\n self.figure.delaxes(plot.axes)\r\n plot.axes=None\r\n plot.y2_axis = None\r\n plot.selection = None\r\n plot.lines = []\...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
do_send_to_client_paypal send withdrawal amount to the client's paypal account
def do_send_to_client_paypal(self, transaction: WalletTransactionsModel) -> Future: # TODO use paypal SDK to send transactions to paypal here # TODO then update transaction to reflect that transaction was sent # NOTE: Could also listen to an _ipn to find out if transaction succeeded on paypal si...
[ "async def withdraw(self, **params):\r\n return await self.client_helper(\"withdraw\", **params)", "async def withdraw(self, ctx, amount: int):\n data = await BonfideCoin(self.bot).get(ctx.guild.id, ctx.author.id)\n if data is None:\n await self.add_to_db(ctx.guild.id, ctx.author.i...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }