query stringlengths 9 9.05k | document stringlengths 10 222k | negatives listlengths 19 20 | metadata dict |
|---|---|---|---|
QCoreApplication.winEventFilter(MSG) > (bool, int) | def winEventFilter(self, MSG): # real signature unknown; restored from __doc__
pass | [
"def user32_ChangeWindowMessageFilter(jitter):\n ret_ad, args = jitter.func_args_stdcall([\"message\", \"dwFlag\"])\n raise RuntimeError('API not implemented')\n jitter.func_ret_stdcall(ret_ad, ret_value)",
"def user32_ChangeWindowMessageFilterEx(jitter):\n ret_ad, args = jitter.func_args_stdcall([\"h... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
ajoute nb_out sorties, (1 ou 2) | def set_out(self, nb_out):
if nb_out > 0:
random_out1 = random.randrange(1, self.size - 1)
if self.direction_in == UP:
self.coord_sorties.append([self.size - 1, random_out1])
if self.direction_in == DOWN:
self.coord_sorties.append([0, random_ou... | [
"def sort(self):",
"def norders(self):\n return None",
"def countIncomparable(self, verbose=False):\n\t\ti=0\n\t\tn=len(self.partialOrder.nodes())\n\t\tlistOutcomes = list(self.partialOrder.nodes())\n\t\tcount=0\n\t\tfor i in range(n):\n\t\t\tfor j in range(i+1,n):\n\t\t\t\tif self.compareOutcomes(listOu... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
`{cmd}` 50/50 Heads or tails. Or... at least in theory. Some say there's a 1/6000 possibility of seeing the coin land on its side, though I've personally never seen it happen. | async def _cmdf_coin(self, substr, msg, privilege_level):
if random.randint(0,1) == 1:
buf = "Heads"
else:
buf = "Tails"
if random.randint(1,600) == 1:
buf = "The coin landed on its side."
buf += "\nThis happens every approx. 1/6000 times!"
buf += "\nhttp:/... | [
"def cute_head():\n print(part_hair_flat())\n print(part_eyes_winking())\n print(part_nose_bowtie())\n print(part_mouth_surprised())\n print(part_chin_squiggle())",
"def handle_coin(command: Command):\n if command.has_arg() and command.arg.isnumeric():\n flips = min(max(int(command.arg), ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
`{cmd}` Chooses a random member from this server. This command does not mention users. | async def _cmdf_colour(self, substr, msg, privilege_level):
random_member = random.choice(list(msg.server.members))
buf = "**Your random user is:** {0} (UID: {1})\n".format(random_member.name, random_member.id)
buf += "(Chosen out of {} users.)".format(str(len(msg.server.members))) # TODO: Fix concurr... | [
"def srandmember(self, key):\r\n return self.execute_command(\"SRANDMEMBER\", key)",
"def kick_random(client, author_id, message_object, thread_id, thread_type):\n gc_thread = Client.fetchThreadInfo(client, thread_id)[thread_id]\n persons_list = Client.fetchAllUsersFromThreads(self=client, threads=[g... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Adds a specified number of ZeroPadding and Covolution layers to the model, and a MaxPooling layer at the very end. | def ConvBlock(model, layers, filters):
for i in range(layers):
model.add(ZeroPadding2D((1, 1)))
model.add(Convolution2D(filters, 3, 3, activation='relu'))
model.add(MaxPooling2D((2, 2), strides=(2, 2))) | [
"def add_new_last_layer(base_model, nb_classes):\r\n x = base_model.output\r\n x = GlobalAveragePooling2D()(x)\r\n x = Dense(FC_SIZE, activation='relu')(x) #new FC layer, random init\r\n predictions = Dense(nb_classes, activation='softmax')(x) #new softmax layer\r\n model = Model(input=base_model.input, output... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Adds a fully connected layer of 4096 neurons to the model with a Dropout of 0.5 | def FCBlock(model):
model.add(Dense(4096, activation='relu'))
model.add(Dropout(0.5)) | [
"def FCBlock(self, dropoutP=0.5):\n model = self.model\n model.add(Dense(4096, activation='relu'))\n model.add(Dropout(dropoutP))",
"def __init__(self, max_pool_layer_index=1, dropout_ratio=0.5, last_layer_num_params=2):\n\n assert 1 <= max_pool_layer_index <= 3, \\\n f\"Inv... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Take an array of unsorted items and replace the contents of this priority queue by them. | def heapify(self, arg_items):
# cleaning the present PQ
self._array.clear()
#fill the array
for it in arg_items:
self._array.append(it)
#heapifying the unsorted input
n = len(self._array)
idx = n-1
parent_idx = self._... | [
"def replace(self, newInds, pop):\n\n pop = pop[np.argsort(pop)]\n pop[0:newInds.size] = newInds\n return pop",
"def ageQueue(self):\n [t.setPriority(t.getPriority() + 1) for t in self._queue]",
"def update_batch_priorities(self, priorities):\n if not self._sampled_unique: # ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Convert from geocentric spherical to geodetic coordinates. | def spherical_to_geodetic(geocentric_latitude, radius):
ellipsoid = get_ellipsoid()
k, big_d, big_z = _spherical_to_geodetic_parameters(geocentric_latitude, radius)
latitude = np.degrees(
2 * np.arctan(big_z / (big_d + np.sqrt(big_d ** 2 + big_z ** 2)))
)
height = (
(k + ellipsoid.fi... | [
"def geocentricToGeodetic(Latitude):\n return np.arctan((np.tan(Latitude)) / 0.99330562)",
"def geom2geog(lat, long):\n lat = np.deg2rad(lat)\n long = np.deg2rad(long)\n\n # Pole coordinates for 2015\n pole_lat = np.deg2rad(80.37)\n pole_long = np.deg2rad(-72.62)\n\n pole_lat_s = np.sin(pole_... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
receive payload from master and respond | def _receive(self):
payloadFromMaster = []
pos = 0
payloadFromMaster += [self.serial.read()]
while payloadFromMaster[pos] != chr(ETX):
payloadFromMaster += [self.serial.read()]
pos += 1
# read FCC
payloadFromMaster += [self.serial.read()]
... | [
"def recv(self):",
"def dataReceived(data):",
"def receive(self, api_spec, response):\n pass",
"def _processPayload(self):\n self.stringReceived(self._payload.getvalue()[:-1])",
"def receive(self):\n self.respone = None\n try:\n def callback(ch, method, properties, bod... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Extract the payload data part from the slave's response. | def _extractPayload(response):
# extract bytecount and check it
print "response:{}".format(repr(response))
pos = 2
bytecount = ord(response[pos])
pos += 1
if bytecount < 6:
raise ValueError(bytecount)
subframe = response[2:3+bytecount]
# extract DA
if ord(subframe[pos]) ==... | [
"def _extractPayload(self):\n if self._payloadComplete():\n remainingPayloadSize = (self._expectedPayloadSize -\n self._currentPayloadSize)\n self._payload.write(self._remainingData[:remainingPayloadSize])\n self._remainingData = self._remai... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Print the inputstring. To make it compatible with Python2 and Python3. | def _print_out(inputstring):
_checkString(inputstring, description='string to print')
sys.stdout.write(inputstring + '\n') | [
"def printout(string):\r\n print(string)",
"def format_string(console):\n\n pass",
"def prettyPrint(string):\n print('*'*75)\n print(string)\n print('*'*75)",
"def op_print(self):\n zstr_address = self._opdecoder.get_zstring()\n self._ui.screen.write(self._string.get(zstr_address)... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Generate a diagnostic string, showing the module version, the platform, current directory etc. | def _getDiagnosticString():
text = '\n## Diagnostic output from tacos2 ## \n\n'
text += 'Tacos2 version: ' + __version__ + '\n'
text += 'Tacos2 status: ' + __status__ + '\n'
text += 'File name (with relative path): ' + __file__ + '\n'
text += 'Full file path: ' + os.path.abspath(__file__) + '\n\n'
... | [
"def get_system_version_info() -> str:\n output_template = '{:<12} {}'\n line_separator = '-' * 60\n not_found_str = '[Not Found]'\n out_lines = []\n\n # System (Python, OS)\n out_lines += ['System Version Info', line_separator]\n out_lines += [\n output_template.format(name, version) fo... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Check das is equal to or less than dae. | def _checkAddress(das, dae):
if not(das <= dae):
raise ValueError('The DAS{0} must be equal to or less than DAE{0}'.format(das, dae)) | [
"def validate(ddtable):\n margin_upp = ddtable.sum(axis=1).transpose()\n count_upp = count_vec(margin_upp)\n remainder_upp = np.remainder(margin_upp, count_upp)\n\n margin_low = ddtable.sum(axis=0)\n count_low = count_vec(margin_low)\n remainder_low = np.remainder(margin_low, count_low)\n\n if ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Momentum as a function of angle for an isotropic wind | def isotropic_momentum(theta):
return 1.0 | [
"def get_heeling_moment(angle_to_wind):\n a = angle_to_wind % tau\n if a > pi:\n a -= tau\n if closest_starboard < a < closest_port:\n return 0\n return sin(0.5 * a) - 0.25 * sin(1.5 * a)",
"def anisotropic_momentum(theta):\n if theta <= np.pi/2:\n return np.cos(theta)**MOMENTU... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Momentum as a function of angle for a proplyd wind Proportional to sqrt(cos(theta)) in the head (theta pi/2). The tail value is set via the modulelevel variable DIFFUSE_BETA. | def proplyd_momentum(theta):
return DIFFUSE_BETA + (1.0 - DIFFUSE_BETA)*np.sqrt(max(0.0,np.cos(theta))) | [
"def isotropic_momentum(theta):\n return 1.0",
"def anisotropic_momentum(theta):\n if theta <= np.pi/2:\n return np.cos(theta)**MOMENTUM_K\n else:\n return 0.0",
"def get_heeling_moment(angle_to_wind):\n a = angle_to_wind % tau\n if a > pi:\n a -= tau\n if closest_starboar... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Momentum as a power law in cos(theta) on the forward hemisphere only | def anisotropic_momentum(theta):
if theta <= np.pi/2:
return np.cos(theta)**MOMENTUM_K
else:
return 0.0 | [
"def isotropic_momentum(theta):\n return 1.0",
"def proplyd_momentum(theta):\n return DIFFUSE_BETA + (1.0 - DIFFUSE_BETA)*np.sqrt(max(0.0,np.cos(theta)))",
"def moment_of_inertia(self):\n return (2 * self.mass() * self.radius ** 2) / 5",
"def _psi(self, m):\n return -self._twosigma2 * nump... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
The arguments w and w1 should be instances of the class Wind() The inner wind, w, should have origin=True, while the outer wind, w1, should have origin=False See the Shell() class for an easier to use wrapper around this class | def __init__(self, w, w1):
self.w = w # "inner" wind
self.w1 = w1 # "outer" wind
# We save the values of theta and theta1, so we can use them
# to find an initial estimate of theta1 for the next angle
# theta
self.th1_save = None
self.th_s... | [
"def wind(self) -> WindData:\n pass",
"def wind(self) -> ObservationsSummaryWind:\n return ObservationsSummaryWind(self.summary[\"wind\"])",
"def generate_wind():\n# Taken by converting UTM Zone 11 coordinates on\n# https://www.engineeringtoolbox.com/utm-latitude-longitude-d_1370.html\n# These val... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Find the spherical radius of the shell as a function of angle Should work with scalar or vector argument `theta`. Returns `radius`, but if positional argument `full` is `True`, then | def radius(self, theta, method='brent', full=False):
def _radius(theta):
"""Helper function to find the shell radius for a single angle, theta"""
if theta == 0.0:
# special treatment for the axis
return self.R0
elif theta >= self.th_infty:
... | [
"def sphere(radius):\n if not isinstance(radius, float) or radius <= 0:\n raise ValueError(f\"Incorrect value ({radius}) for radius\")\n substrate = _Substrate(\"sphere\", radius=radius)\n return substrate",
"def sphere(radius):\n M = np.diag([1., 1., 1., -(radius ** 2)])\n if radius... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Literal implementation of CRW96 Eq 6 for two winds w, w1 Returns the radius for a given pair of angles th and th1 in terms of the momentum rates injected by the two winds | def _radius_eq6(w, w1, th, th1):
numerator = w.Jdot(th) + w1.Jdot(th1)
denominator = (w.Pidot_r(th) + w1.Pidot_r(th1))*np.cos(th) \
- (w.Pidot_z(th) + w1.Pidot_z(th1))*np.sin(th)
return numerator/denominator | [
"def _radius_eq23(th, th1):\n return np.sin(th1)/np.sin(th+th1)",
"def __init__(self, w, w1):\n self.w = w # \"inner\" wind\n self.w1 = w1 # \"outer\" wind\n\n # We save the values of theta and theta1, so we can use them\n # to find an initial estimate of the... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Literal implementation of CRW Eq 23 Gives the radius in terms of the two angles th and th1 | def _radius_eq23(th, th1):
return np.sin(th1)/np.sin(th+th1) | [
"def _radius_eq6(w, w1, th, th1):\n numerator = w.Jdot(th) + w1.Jdot(th1)\n denominator = (w.Pidot_r(th) + w1.Pidot_r(th1))*np.cos(th) \\\n - (w.Pidot_z(th) + w1.Pidot_z(th1))*np.sin(th)\n return numerator/denominator",
"def right_circular_cone(r,h):\n s = sqrt((r**2) + (h**2))\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns the index of the point from allpoints closest to the passed point. Returns None if two points are equidistant. | def get_closest(point, allpoints):
best_index = None
best_distance = 999999999
is_dupe = False
for index, p in enumerate(allpoints):
# if p == point:
# continue
dist = getdist(point, p)
if dist <= best_distance:
if dist == best_distance:
i... | [
"def get_closest(self, point):\n distance = (self.dpath[:, 1] - point[1]) ** 2 + (self.dpath[:, 0] - point[0]) ** 2\n i = np.where(distance == distance.min())\n return i[0][0]",
"def nearest_point(point, points):\n\n # Note this uses euculidean distances -- so beware possible inaccuracy\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Lists the Amazon DynamoDB tables for the current account. | def list_tables(self):
try:
tables = []
for table in self.dyn_resource.tables.all():
print(table.name)
tables.append(table)
except ClientError as err:
logger.error(
"Couldn't list tables. Here's why: %s: %s",
... | [
"def list_tables():\r\n tables = []\r\n\r\n try:\r\n table_list = DYNAMODB_CONNECTION.list_tables()\r\n while True:\r\n for table_name in table_list[u'TableNames']:\r\n tables.append(get_table(table_name))\r\n\r\n if u'LastEvaluatedTableName' in table_list:\r... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Adds a movie to the table. | def add_movie(self, title, year, plot, rating):
try:
self.table.put_item(
Item={
'year': year,
'title': title,
'info': {'plot': plot, 'rating': Decimal(str(rating))}})
except ClientError as err:
logger.er... | [
"def add_movie(self, new_movie):\r\n self.movies.append(Movie(new_movie[0], new_movie[1], new_movie[2], new_movie[3]))",
"def add_movie(self, movie: Movie):\r\n raise NotImplementedError",
"def add_movie():\n movies.append(create_movie())\n print(\"\\nYour movie was successfully added!\")\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Gets movie data from the table for a specific movie. | def get_movie(self, title, year):
try:
response = self.table.get_item(Key={'year': year, 'title': title})
except ClientError as err:
logger.error(
"Couldn't get movie %s from table %s. Here's why: %s: %s",
title, self.table.name,
er... | [
"def find_movie(self, movie_id):\n return self.__repo.find(movie_id)",
"def get_movie_details(movie_id):\r\n\r\n url = \"https://api.themoviedb.org/3/movie/\" + \\\r\n str(movie_id) + \"?api_key=\" + config.FLASK_TMDB_API_KEY + \"&language=en-US\"\r\n\r\n # results = DB.Movie.find({\... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Updates rating and plot data for a movie in the table. | def update_movie(self, title, year, rating, plot):
try:
response = self.table.update_item(
Key={'year': year, 'title': title},
UpdateExpression="set info.rating=:r, info.plot=:p",
ExpressionAttributeValues={
':r': Decimal(str(rating... | [
"def update_rating(user_id, movie_id, rating):\n usermovie_rating = UserMovie.query.filter(UserMovie.user_id == user_id,\n UserMovie.movie_id == movie_id).first()\n if usermovie_rating:\n usermovie_rating.rating = rating\n db.session.commit()",
"def add... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Queries for movies that were released in the specified year. | def query_movies(self, year):
try:
response = self.table.query(KeyConditionExpression=Key('year').eq(year))
except ClientError as err:
logger.error(
"Couldn't query for movies released in %s. Here's why: %s: %s", year,
err.response['Error']['Code']... | [
"def get_movies_by_year(self, year):\r\n raise NotImplementedError",
"def _selectMovieByReleaseYear(entities):\n entities = map(lambda e: (e, _getYearFromDesc(e.description)), entities)\n entities.sort(key=lambda x: x[1], reverse=True)\n return entities[0][0]",
"def scan_movies(self, year_range)... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Scans for movies that were released in a range of years. Uses a projection expression to return a subset of data for each movie. | def scan_movies(self, year_range):
movies = []
scan_kwargs = {
'FilterExpression': Key('year').between(year_range['first'], year_range['second']),
'ProjectionExpression': "#yr, title, info.rating",
'ExpressionAttributeNames': {"#yr": "year"}}
try:
... | [
"def get_movies_by_year(self, year):\r\n raise NotImplementedError",
"def query_movies(self, year):\n try:\n response = self.table.query(KeyConditionExpression=Key('year').eq(year))\n except ClientError as err:\n logger.error(\n \"Couldn't query for movies... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Deletes a movie from the table. | def delete_movie(self, title, year):
try:
self.table.delete_item(Key={'year': year, 'title': title})
except ClientError as err:
logger.error(
"Couldn't delete movie %s. Here's why: %s: %s", title,
err.response['Error']['Code'], err.response['Error'... | [
"def delete_movie(self, movieid):\n query = 'DELETE FROM video_lib_movies WHERE MovieID = ?'\n self._execute_query(query, (movieid,))",
"def remove_movie(self, movie_id):\n self.__repo.delete(movie_id)",
"def delete_movies():\n movie_id = int(request.args.get('id', 0))\n\n if not ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Gets sample movie data, either from a local file or by first downloading it from the Amazon DynamoDB developer guide. | def get_sample_movie_data(movie_file_name):
if not os.path.isfile(movie_file_name):
print(f"Downloading {movie_file_name}...")
movie_content = requests.get(
'https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/samples/moviedata.zip')
movie_zip = ZipFile(BytesIO(movie... | [
"def download_movie(self, title):\n\n # Call the client method to get a dictionary with the movies' data.\n data = get_movie_data(title)\n\n # Check to see if there is a key in the dictionary called 'Error'\n if not \"Error\" in data:\n\n # Add the values to the database.\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Search for flights using an api | def search_for_flights(apikey, **kwargs):
flight_search_paramaters = kwargs
flight_search_paramaters['apikey'] = apikey
flight_search_paramaters['currency'] = "USD" # since US Dollars is the most popular currency
flight_search_response = requests.get(flight_booking_search, params=flight_search_paramat... | [
"def find_flight(payload):\r\n\r\n flight_search = request_server_response(requests.get, \"https://api.skypicker.com/flights?\", params=payload)\r\n\r\n flight_search_results = parse_json(flight_search)\r\n\r\n # if no results returned tell the user to fix the parameters\r\n if flight_search_results[\"_... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Search for hotel using an api | def search_for_hotels(apikey, **kwargs):
hotel_search_parameters = kwargs
hotel_search_parameters['apikey'] = apikey
hotel_search_parameters['currency'] = "USD" # since US Dollars is the most popular currency
hotel_api_response = requests.get(hotel_booking_search, params=hotel_search_parameters).json()... | [
"def test_hotel_searching():\n request_data = {'destination': 'e', 'checkin': '02-05-2018', 'checkout': '03-05-2018', 'is_bathroom': False,\n 'is_tv': False, 'is_wifi': False, 'is_bathhub': False, 'is_airconditioniring': False,\n 'sleeps': 1, 'price_from': 0, 'price_to': 0, ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Bundle up all amenities into one string. | def serialize_hotel_amenities(old_amenities):
new_amentities = ""
if old_amenities:
for old_amenity in old_amenities:
new_amentities = new_amentities + ', '+old_amenity['description']
return new_amentities+"."
else:
return new_amentities | [
"def gen_ambush_text(encounter):\n ls = [(x.name, x.nameplural) for x in encounter]\n ls.sort()\n ls2 = []\n num = 0\n name = \"\"\n for value in ls:\n if value[0] == name:\n num += 1\n else:\n if num == 1:\n ls2.append(\"a \" + FMT_ENEMY.format(v... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
find the number of samples in the directory | def find_num_samples(data_dir):
path, dirs, files = os.walk(data_dir).next()
assert path == data_dir
samples =[x for x in files if x.endswith('.jpg')]
numsample = len(samples)
for subdir in dirs:
numsample += find_num_samples(data_dir + '/' + subdir)
return numsample | [
"def count_samples(samples_path):\n samples = np.load(os.path.join(samples_path, 'samples.npy'))\n return len(samples)",
"def get_num_samples(self, split_name):",
"def count():\n\n return len(directory)",
"def get_sample_nr(path):\n path1 = Path(path)\n parent_path = str(path1.parent)\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns an adjacency matrix for a 2D cubic lattice with number of nodes specified by lattice_shape. If a directed network is requested with no bias, the default configuration is all bonds going from left to right and top to bottom. (recalling that we index nodes across rows then columns). The xbias and ybias give the p... | def create_adj_cubic_2d(lattice_shape, undirected=True, xbias=1, ybias=1 ):
num_ynodes, num_xnodes = lattice_shape
num_nodes = num_xnodes * num_ynodes
A = sparse.lil_matrix((num_nodes, num_nodes))
# Form bond arrays to fill in row bonds and column bonds of the lattice
x_bonds = np.ones(num... | [
"def cellular_automaton2d(rows, cols, r=1, neighbourhood='Moore', boundary=\"periodic\"):\n n = rows * cols\n if n < 9:\n raise Exception(\"There must be at least 9 cells\")\n adjacency_matrix = [[0. for j in range(n)] for i in range(n)]\n if boundary == \"periodic\":\n if neighbourhood ==... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
check vuln toolbar actions; there must be 2 rows to perform the test | def check_vulns_multiactions(sclnt, dt_id):
# there should be two rows in total
dt_elem = dt_wait_processing(sclnt, dt_id)
toolbar_elem = sclnt.find_element_by_id('%s_toolbar' % dt_id)
assert len(dt_elem.find_elements_by_xpath('//tbody/tr[@role="row"]')) == 2
# one cloud be be tagged
dt_elem.f... | [
"def test_has_action(self):\n self.assertIn('request_unsolvedcases_status', self.model_admim.actions)",
"def test_menu_item(main_window):\n if SPYDER6:\n main_menu = main_window.get_plugin(Plugins.MainMenu)\n run_menu = main_menu.get_application_menu(ApplicationMenus.Run)\n actions ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Update agent's velocity using the velocity function. | def update_velocity(self):
self.velocity = self.vel_func() * (
self.goal - self.current) / abs(self.goal - self.current) | [
"def update(self, **kwargs):\n self.apply_velocity()",
"def velocity(self, t):\n pass",
"def exec_velocity_cmd(self, cmd):\n self.set_joint_velocities(cmd, self._joint_ids)",
"def _updateVelocity(self):\n\t\t# Find difference between two vectors\n\t\tdifferenceVector = [0, 0]\n\t\tdiffere... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Remove marker from retVal and plot | def clearMarker(self):
self.retVal['x'] = None
self.retVal['y'] = None
self.retVal['subPlot'] = None
for i in range(self.nSubPlots):
subPlot = self.selectSubPlot(i)
for marker in self.markers:
if marker in subPlot.lines:
subPlot.lines.remove(marker)
self.markers = []
self.fi... | [
"def refresh_marker_display(self): \n if self.scalar_display:\n return\n self.removeMarkers()\n self.info_marker = None\n self.log_marker = None\n self.source_marker = None\n if self.is_combined_image:\n self.insert_marker_lines()\n# draw dividing lines for complex array,... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Get the nr of the subplot that has been clicked | def getSubPlotNr(self, event):
i = 0
axisNr = None
for axis in self.fig.axes:
if axis == event.inaxes:
axisNr = i
break
i += 1
return axisNr | [
"def row_num(ax: mpl.axes.Axes) -> int:\n return ax.get_subplotspec().rowspan.start",
"def onClick(self, event):\t\t\r\n\t\r\n\t\tsubPlotNr = self.getSubPlotNr(event)\t\t\r\n\t\tif subPlotNr == None:\r\n\t\t\treturn\r\n\t\t\r\n\t\tif event.button == 1:\t\t\t\t\r\n\t\t\r\n\t\t\tself.clearMarker()\r\n\t\t\tfor i i... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Process a mouse click event. If a mouse is right clicked within a subplot, the return value is set to a (subPlotNr, xVal, yVal) tuple and the plot is closed. With rightclicking and dragging, the plot can be moved. | def onClick(self, event):
subPlotNr = self.getSubPlotNr(event)
if subPlotNr == None:
return
if event.button == 1:
self.clearMarker()
for i in range(self.nSubPlots):
subPlot = self.selectSubPlot(i)
marker = plt.axvline(event.xdata, 0, 1, linestyle='--', \
l... | [
"def on_click(event):\n if not event.xdata or not event.ydata: # if not clicked on a cell\n return\n # get closes integer points\n cx = math.floor(round(event.xdata))\n cy = math.floor(round(event.ydata))\n replot(cx, cy)",
"def on_exc_click_release(self, event):\n\n... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Handle a keypress event. The plot is closed without return value on enter. Other keys are used to add a comment. | def onKey(self, event):
if event.key == 'enter':
plt.close()
return
if event.key == 'escape':
self.clearMarker()
return
if event.key == 'backspace':
self.comment = self.comment[:-1]
elif len(event.key) == 1:
self.comment += event.key
self.supTitle.set_text("comment... | [
"def on_key(event):\n if event.key == ' ':\n replot(0, 0, True)",
"def handle_keypress(self, e):\n if e.char == '\\r': # log new weight when user hits <Enter>\n self.e_w.config(fg='grey')\n self.submit_handler()\n self.show_graph()\n else: # switc... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Process scroll events. All subplots are scrolled simultaneously | def onScroll(self, event):
for i in range(self.nSubPlots):
subPlot = self.selectSubPlot(i)
xmin, xmax = subPlot.get_xlim()
dx = xmax - xmin
cx = (xmax+xmin)/2
if event.button == 'down':
dx *= 1.1
else:
dx /= 1.1
_xmin = cx - dx/2
_xmax = cx + dx/2
subPlot.set_xlim(... | [
"def mouse_scroll(event):\n fig = event.canvas.figure\n ax1 = fig.axes[0]\n ax2 = fig.axes[1]\n if event.button == 'down':\n previous_slice(ax1, ax2)\n elif event.button == 'up':\n next_slice(ax1, ax2)\n fig.canvas.draw()",
"def on_mouse_scroll(self, evt):\n \n pass",... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Test that NearestMeanResponseImputer has fit and transform methods. | def test_class_methods(self):
x = NearestMeanResponseImputer(
response_column="c", use_median_if_no_nulls=False, columns=None
)
h.test_object_method(obj=x, expected_method="fit", msg="fit")
h.test_object_method(obj=x, expected_method="transform", msg="transform") | [
"def test_learnt_values_not_modified(self):\n\n df = d.create_NearestMeanResponseImputer_test_df()\n\n x = NearestMeanResponseImputer(response_column=\"c\", columns=[\"a\", \"b\"])\n\n x.fit(df)\n\n x2 = NearestMeanResponseImputer(response_column=\"c\", columns=[\"a\", \"b\"])\n\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Test that NearestMeanResponseImputer inherits from BaseImputer. | def test_inheritance(self):
x = NearestMeanResponseImputer(
response_column="c", use_median_if_no_nulls=False, columns=None
)
h.assert_inheritance(x, tubular.imputers.BaseImputer) | [
"def test_class_methods(self):\n\n x = NearestMeanResponseImputer(\n response_column=\"c\", use_median_if_no_nulls=False, columns=None\n )\n\n h.test_object_method(obj=x, expected_method=\"fit\", msg=\"fit\")\n\n h.test_object_method(obj=x, expected_method=\"transform\", msg=\... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Test that an exception is raised if response_column is not str | def test_response_column_not_str_error(self):
with pytest.raises(TypeError, match="response_column must be a str"):
NearestMeanResponseImputer(response_column=0) | [
"def test_extract_column_8(self):\n with self.assertRaises(TypeError):\n querying.extract_column(self.column, check=str)",
"def test_get_column_enforce_type_typeerror(self):\n row = {\"col1\": 1, \"col2\": 2}\n with self.assertRaises(TypeError):\n get_column(row, \"col1\... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Test that an exception is raised if use_median_if_no_nulls is not bool | def test_use_median_if_no_nulls_not_bool_error(self):
with pytest.raises(TypeError, match="use_median_if_no_nulls must be a bool"):
NearestMeanResponseImputer(
response_column="a", use_median_if_no_nulls="abc"
) | [
"def test_use_median_if_no_nulls_false_and_columns_with_no_nulls_error(self):\n\n df = pd.DataFrame(\n {\"a\": [1, 2, 3, 4, 5], \"b\": [5, 4, 3, 2, 1], \"c\": [3, 2, 1, 4, 5]}\n )\n\n x = NearestMeanResponseImputer(response_column=\"c\", columns=[\"a\", \"b\"])\n\n with pytest... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Test that fit has expected arguments. | def test_arguments(self):
h.test_function_arguments(
func=NearestMeanResponseImputer.fit,
expected_arguments=["self", "X", "y"],
expected_default_values=(None,),
) | [
"def test_fit(self):\n self._fit()",
"def requires_fit(self) -> bool:\n pass",
"def test_pipeline_fit_params():\n pipe = Pipeline([('transf', TransfT()), ('clf', FitParamT())])\n pipe.fit(X=None, y=None, clf__should_succeed=True)\n # classifier should return True\n assert pipe.predict(... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Test an error is raised if response_column is nonnumeric | def test_non_numeric_response_column_error(self):
df = pd.DataFrame(
{"a": [1, 2, 3, 4, 5], "b": [5, 4, 3, 2, 1], "c": ["a", "b", "c", "d", "e"]}
)
x = NearestMeanResponseImputer(response_column="c", columns=["a", "b"])
with pytest.raises(
ValueError, match="dt... | [
"def test_response_column_not_str_error(self):\n\n with pytest.raises(TypeError, match=\"response_column must be a str\"):\n\n NearestMeanResponseImputer(response_column=0)",
"def test_check_valid_values_raises_valueerror_if_not_numeric(self):\n # Setup\n X = np.array([\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Test an error is raised if the response column contains null entries. | def test_null_values_in_response_error(self):
df = d.create_df_3()
x = NearestMeanResponseImputer(response_column="c", columns=["a", "b"])
with pytest.raises(ValueError, match=r"Response column \(c\) has null values."):
x.fit(df) | [
"def test_no_missing_data(self):\n self.assertFalse(self.data_processor.agg_data_frame.isnull().\n values.any())",
"def test_ref_data_validation_null_fail(self):\n df = pd.DataFrame(data=(1, 2, 3, None), columns=['test'])\n\n try:\n val = Validator().validat... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Test an error is raised if a nonresponse column contains no nulls and use_median_if_no_nulls is false. | def test_use_median_if_no_nulls_false_and_columns_with_no_nulls_error(self):
df = pd.DataFrame(
{"a": [1, 2, 3, 4, 5], "b": [5, 4, 3, 2, 1], "c": [3, 2, 1, 4, 5]}
)
x = NearestMeanResponseImputer(response_column="c", columns=["a", "b"])
with pytest.raises(
Valu... | [
"def test_use_median_if_no_nulls_not_bool_error(self):\n\n with pytest.raises(TypeError, match=\"use_median_if_no_nulls must be a bool\"):\n\n NearestMeanResponseImputer(\n response_column=\"a\", use_median_if_no_nulls=\"abc\"\n )",
"def test_null_values_in_response_err... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Test that BaseTransformer.transform called. | def test_super_transform_called(self, mocker):
df = d.create_NearestMeanResponseImputer_test_df()
x = NearestMeanResponseImputer(response_column="c", columns=["a", "b"])
x.fit(df)
expected_call_args = {
0: {"args": (d.create_NearestMeanResponseImputer_test_df(),), "kwargs... | [
"def test_super_transform_call(self, mocker):\n\n df = d.create_df_1()\n\n mapping = {\"b\": {\"a\": 1.1, \"b\": 1.2, \"c\": 1.3, \"d\": 1.4, \"e\": 1.5, \"f\": 1.6}}\n\n x = CrossColumnAddTransformer(mappings=mapping, adjust_column=\"a\")\n\n expected_call_args = {0: {\"args\": (d.creat... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Test that the impute_values_ from fit are not changed in transform. | def test_learnt_values_not_modified(self):
df = d.create_NearestMeanResponseImputer_test_df()
x = NearestMeanResponseImputer(response_column="c", columns=["a", "b"])
x.fit(df)
x2 = NearestMeanResponseImputer(response_column="c", columns=["a", "b"])
x2.fit(df)
x2.tra... | [
"def impute(X_train, X_test, strategy):\n imp = Imputer(missing_values=np.nan, strategy=strategy).fit(X_train)\n X_train_imputed = imp.transform(X_train)\n X_train_imputed = pd.DataFrame(\n X_train_imputed, columns=X_train.columns)\n X_test_imputed = imp.transform(X_test)\n X_test_imputed = pd... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Parse the filename of the match PDB to determine IDs and positions of match residues | def determine_matched_residue_positions(match_pdb_path):
positions_block = os.path.basename(os.path.normpath(match_pdb_path)).split('_')[2]
resnames = [a for a in re.split("[0-9]*", positions_block) if a]
resnums = [int(a) for a in re.split("[a-zA-Z]*", positions_block) if a]
return [(a, b) for a, b in... | [
"def parse_pdb(pdb_file):\n\n dict_coord = {}\n # Id for residu because in some pdb files the num residu\n # dosen't start to 1\n resID = 0\n\n for line in pdb_file:\n resName = line[17:20].strip()\n resID_pdb = line[22:26]\n\n if (line[0:4] == \"ATOM\") or ((line[0:6] == \"HETAT... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Loging the text in the log file | def Log(self, text):
self.__file.write("\n"+ str(datetime.now()) + ": " + text) | [
"def log(text: str) -> None:\n now = datetime.now()\n ts = now.timestamp()\n f = open(f\"Logs/{now.strftime('%d-%m-%Y')}.log\", \"a\")\n\n text = str(ts)+\"\\t\"+text+\"\\n\"\n print(text.strip(\"\\n\"))\n\n f.write(text)\n f.close()",
"def log(self, message):\n timestamp = datetime.da... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Chooses a valid journal location or returns a corresponding error. | def _check_journal_location(journal_location, stor, action):
if journal_location:
if not uuidutils.is_uuid_like(journal_location):
raise exception.InvalidUUID(uuid=journal_location)
# If a journal location is provided by the user.
if journal_location:
# Check that the journal l... | [
"def getLocation():\n location=input(\"please input the location you want to look at : \")\n if not location:\n location = LOCATION\n return location",
"def lookup_location(record,format=None):\n location_list = locations = record.getVariableFields('994')\n for location in location_list:\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Open a file, find the closing tag and insert the google analytics text in there. | def insert_g_analytics(fname):
try:
ff = file(fname, 'r')
except:
ff = open(fname, 'r')
# Get the text in there:
ll = ff.readlines()
ff.close()
this_idx = None
for idx, l in enumerate(ll):
if '</head>' in l:
this_idx = idx
# Only if this is ... | [
"def finish(self):\r\n with open(self.c_file, 'w') as f:\r\n # checking tag availability\r\n if self.file_opened:\r\n content_instance = self.file_str.format(content = doc.content)\r\n else:\r\n content_instance = self.file_st... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
sets properties defaults for the instrument with Name | def __init__(self,instrumentName,web_var=None):
self.iliad_prop = PropertyManager(instrumentName)
# the variables which are set up from the main properties
self._main_properties=[]
# the variables which are set up from the advanced properties.
self._advanced_properties=[]
# The varia... | [
"def _init_default_properties(self):\n for property_name in type(self).default_properties:\n if self.properties.get(property_name) is None:\n self.properties[property_name] = type(self).default_properties[property_name]",
"def defaults(cls):\n msg = \"\"\"\\\n== Instrument ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Define properties which considered to be main properties changeable by user Should be overwritten by special reduction and decorated with decorator. Should return dictionary with key are the properties names and values the default values these properties should have. | def def_main_properties(self):
raise NotImplementedError('def_main_properties has to be implemented') | [
"def MainProperties(main_prop_definition): \n def main_prop_wrapper(*args):\n properties = main_prop_definition(*args)\n #print \"in decorator: \",properties\n host = args[0]\n host._main_properties=properties\n host.iliad_prop.set_input_parameters(**properties)\n return... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Define properties which considered to be advanced but still changeable by instrument scientist or advanced user Should be overwritten by special reduction and decorated with decorator. Should return dictionary with key are the properties names and values the default values these properties should have. | def def_advanced_properties(self):
raise NotImplementedError('def_advanced_properties has to be implemented') | [
"def get_extended_properties_dict(self):\n properties = {}\n for prop in self.extended_properties:\n if prop.delete is False:\n properties[prop.name] = prop.value\n return properties",
"def AdvancedProperties(adv_prop_definition): \n def advanced_prop_wrapper(*arg... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Decorator stores properties dedicated as main and sets these properties as input to reduction parameters. | def MainProperties(main_prop_definition):
def main_prop_wrapper(*args):
properties = main_prop_definition(*args)
#print "in decorator: ",properties
host = args[0]
host._main_properties=properties
host.iliad_prop.set_input_parameters(**properties)
return properties
... | [
"def AdvancedProperties(adv_prop_definition): \n def advanced_prop_wrapper(*args):\n properties = adv_prop_definition(*args)\n #print \"in decorator: \",properties\n host = args[0]\n host._advanced_properties=properties\n host.iliad_prop.set_input_parameters(**properties)\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Decorator stores properties decided to be advanced and sets these properties as input for reduction parameters | def AdvancedProperties(adv_prop_definition):
def advanced_prop_wrapper(*args):
properties = adv_prop_definition(*args)
#print "in decorator: ",properties
host = args[0]
host._advanced_properties=properties
host.iliad_prop.set_input_parameters(**properties)
return pro... | [
"def params(self, **params):\n for param in params:\n setattr(self.steps[self.current_step], param, params[param])\n return self.common_decorator",
"def kwargs_decorator(deco):\n return update_wrapper(curry(deco), deco)",
"def MainProperties(main_prop_definition): \n def main_prop... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Return normalized sublattice site ratio. E.g. [[0.25, 0.25], [0.1666, 0.1666, 0.1666]] | def normalized_sublattice_site_ratios(self):
subl_model = self.sublattice_model
subl_names = self._sublattice_names
comp_dict = self.composition.as_dict()
site_ratios = [[comp_dict['X'+name+e+'0+']/self.num_sites for e in subl] for subl, name in zip(subl_model, subl_names)]
retur... | [
"def _site_ratio_normalization(self):\n site_ratio_normalization = S.Zero\n # Calculate normalization factor\n for idx, sublattice in enumerate(self.constituents):\n active = set(sublattice).intersection(self.components)\n subl_content = sum(spec.number_of_atoms * v.SiteFr... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Modify self to be a concrete SQS based on the sublattice model. | def get_concrete_sqs(self, subl_model, scale_volume=True):
def _subl_error():
raise ValueError('Concrete sublattice model {} does not match size of abstract sublattice model {}'.format(subl_model, self.sublattice_model))
if len(subl_model) != len(self.sublattice_model):
_subl_err... | [
"def test_abstract_sqs_scales_volume_when_made_concrete():\r\n\r\n structure = lat_in_to_sqs(ATAT_FCC_L12_LATTICE_IN)\r\n concrete_structure = structure.get_concrete_sqs([['Fe', 'Ni'], ['Al']])\r\n assert np.isclose(concrete_structure.volume, 445.35213050176463)\r\n assert np.isclose(concrete_structure.... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Return endmember space group info.. | def get_endmember_space_group_info(self, symprec=1e-2, angle_tolerance=5.0):
endmember_subl = [['X' + subl_name for _ in subl] for subl, subl_name in
zip(self.sublattice_model, self._sublattice_names)]
# we need to replace the abstract names with real names of species.
... | [
"def get_group(self): # real signature unknown; restored from __doc__\n return \"\"",
"def retr_spacegroup_number(struct,ini):\n ini[\"spacegroup\"] = struct.get_space_group_number()\n return ini",
"def McGroupCountEnd(self):\n return self._McGroupCountEnd",
"def _get_space_group(s: Struct... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Calcule the charge in an coordinate influed by atoms in dists distance with charges charge. Inputs dists and charges are array 1D of same range of floats. >>> from numpy import allclose >>> dists = array(range(5)) + 0.1 >>> charges = array(range(5)) >>> vdws = array([ 1 ] 5) >>> c = charge_1(dists, charges) >>> allclos... | def charge_1(dists, charges):
charge = charges / ( map(epsilon, dists) * dists )
return sum(charge) | [
"def charge_2(dists, charges):\n d6 = dists <= 6.0\n d8 = dists <= 8.0\n d6_8 = logical_and(logical_not(d6), d8)\n epsilons = (d6*4.0) + \\\n d6_8*(38.0*dists-224.0) + \\\n logical_not(d8)*80.0\n charge = (charges / ( epsilons * dists ))\n return sum(charge)",
"def charges(... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Calcule the charge in an coordinate influed by atoms in dists distance with charges charge. Inputs dists and charges are array 1D of same range of floats. >>> from numpy import allclose >>> dists = array(range(5)) + 0.1 >>> charges = array(range(5)) >>> vdws = array([ 1 ] 5) >>> c = charge_2(dists, charges) >>> allclos... | def charge_2(dists, charges):
d6 = dists <= 6.0
d8 = dists <= 8.0
d6_8 = logical_and(logical_not(d6), d8)
epsilons = (d6*4.0) + \
d6_8*(38.0*dists-224.0) + \
logical_not(d8)*80.0
charge = (charges / ( epsilons * dists ))
return sum(charge) | [
"def charge_1(dists, charges):\n charge = charges / ( map(epsilon, dists) * dists )\n return sum(charge)",
"def update_charge(self):\n for atom in self.atoms:\n if (len(atom.charge) == 1) and (len(atom.lone_pairs) == 1) and (len(atom.radical_electrons) == 1):\n # if the char... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Performs entity linking for the query. | def link(self, query):
q = Query(query)
linker = self.__get_linker(q)
linked_ens = linker.link()
res = {"query": q.raw_query,
"processed_query": q.query,
"results": linked_ens}
return res | [
"def bind_to_graph(self, entity):",
"def _add_related_link_to_entity(self, entity: wdi_core.WDItemEngine, uri: str):\n rel_link = wdi_core.WDUrl(value=uri, prop_nr=self._related_link_prop)\n entity.update([rel_link], append_value=[self._related_link_prop])",
"def link(self):\r\n arg_str = p... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
verification of the response after the update on user rate in timesheet by timeadmin entity for the given timesheet row on a specific day and specific task | def verify_update(self, response):
self.status = True
self.step_desc = 'Timeadmin updation of user rate in timesheet - verification'
self.remarks = '\n Inside class: %s method: %s \n' % utils.get_method_class_names()
self.step_input = '\n Response \n{}\n'.format(response.text)
i... | [
"def task_updated(cls, task):\n if task.job is None or task.job.booking is None:\n return\n if task.job.is_fulfilled():\n if task.job.booking.end < timezone.now():\n if Emailed.objects.filter(end_booking=task.job.booking).exists():\n return\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Create new instance licenses from template licenses | def _init_instance_licenses(self):
for template_license in self.template.template_licenses.all():
InstanceLicense.objects.create(
instance=self,
template_license=template_license,
setup_fee=template_license.setup_fee,
monthly_fee=templa... | [
"def test_create_iceberg_add_license_from_file(self):\n pass",
"def _add_licenses(crate, crate_entity, file_object, registry_url):\n license_entities = []\n try:\n licenses = file_object.licences.all()\n except AttributeError:\n licenses = []\n\n for license_ in licenses:\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Builds box predictor based on the configuration. Builds box predictor based on the configuration. See box_predictor.proto for configurable options. Also, see box_predictor.py for more details. | def build(argscope_fn, box_predictor_config, is_training, num_classes):
if not isinstance(box_predictor_config, box_predictor_pb2.BoxPredictor):
raise ValueError('box_predictor_config not of type '
'box_predictor_pb2.BoxPredictor.')
box_predictor_oneof = box_predictor_config.WhichOneof('bo... | [
"def __init__(self,\n model_path,\n predictor_mode=\"Analysis\",\n config_type=\"cpu\",\n batch_size=1,\n min_subgraph_size=1,\n trt_dynamic_shape_info=None):\n configs = DeployConfig(\n model_path=mode... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Check magic bytes to figure out the filetype | def check_filetype(filename):
max_len = max(len(x) for x in magic_dict2)
with open(filename) as f:
file_start = f.read(max_len)
for magic, filetype in magic_dict2.items():
if file_start.startswith(magic):
return filetype(filename)
return filename | [
"def _get_magic_type(self):\n\n try:\n with io.open(self.disk.get_fs_path(), \"rb\") as file:\n file.seek(self.offset)\n fheader = file.read(min(self.size, 4096) if self.size else 4096)\n except IOError:\n logger.exception(\"Failed reading first 4K b... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Procedure for reading both sequences and stitching them together Unless specified, it will read 10^8 sequences from the supplied read | def single_read(read1, direction = 5, nbrofitems = 10**8, fileout = None):
seqFreqs = Counter()
# TODO: Enfore trimming parameters (or rather YAML config file)
if cfg is not None:
trim5 = cfg["Trim"]["fwdread"]
trim3 = cfg["Trim"]["revread"]
else:
trim5 = [27,None]
trim3... | [
"def paired_read(read1, read2, nbrofitems = 10**8, fileout = None):\n seqFreqs = Counter()\n\n # TODO: Enfore trimming parameters (or rather YAML config file)\n if args.config is not None:\n trim5 = cfg[\"Trim\"][\"fwdread\"]\n trim3 = cfg[\"Trim\"][\"revread\"]\n else:\n trim5 = [2... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Procedure for reading both sequences and stitching them together Unless specified, it will read 10^8 sequences from the supplied reads | def paired_read(read1, read2, nbrofitems = 10**8, fileout = None):
seqFreqs = Counter()
# TODO: Enfore trimming parameters (or rather YAML config file)
if args.config is not None:
trim5 = cfg["Trim"]["fwdread"]
trim3 = cfg["Trim"]["revread"]
else:
trim5 = [27,None]
trim3... | [
"def single_read(read1, direction = 5, nbrofitems = 10**8, fileout = None):\n seqFreqs = Counter()\n\n # TODO: Enfore trimming parameters (or rather YAML config file)\n if cfg is not None:\n trim5 = cfg[\"Trim\"][\"fwdread\"]\n trim3 = cfg[\"Trim\"][\"revread\"]\n else:\n trim5 = [2... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Build an error message from a response. | def build_errmsg(
cls,
response,
msg: t.Optional[str] = None,
exc: t.Optional[Exception] = None,
) -> str:
from .tools import json_log
url = response.url
method = response.request.method
code = response.status_code
reason = response.reason
... | [
"def get_error_message(response) -> str:\n if not ErrorHelper.is_error(response):\n return None\n \n message = f\"{response.message} {response.message_detail}\"\n return message",
"def _parse_response_error(self, response):\n message = response.text or \"no_content_on... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Initialize a new instance of the FormatError exception. | def __init__(
self,
template: str,
error: Exception,
args: t.Any = None,
kwargs: t.Dict[str, t.Any] = None,
) -> None:
self.template: str = template
self.error: Exception = error
self.args: t.Any = args
self.kwargs: t.Dict[str, t.Any] = kwargs
... | [
"def __init__(self, message):\n if isinstance(message, list):\n self.error_list = []\n for message in message:\n if not isinstance(message, FormatError):\n message = FormatError(message)\n self.error_list.extend(message.error_list)\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns 'True' if all entries of the relation are binary (0 or 1), otherwise it returns 'False'. | def isBinary(self):
for i in range(0,self.m):
for j in range(i+1,self.m):
if self.Q[i,j] != 0 and self.Q[i,j] != 1:
return(False)
return(True) | [
"def is_binary(self):\n return np.logical_or(self.cmap == 1, self.cmap == 0).all()",
"def is_binary(assoc):\n return len(assoc) == 2",
"def is_binary(t):\n if t == zero or t == one:\n return True\n elif t.ty != Term.COMB:\n return False\n elif t.head == bit0 or t.head == bit1:\n... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Changes all entries (Not on the diagonal) >=0.5 to '1' and the others to '0'. | def makeBinary(self):
for i in range(0,self.m):
for j in range(i+1,self.m):
if self.Q[i,j]>=0.5:
self.setEntry([i,j],1)
else:
self.setEntry([i,j],0)
return(True) | [
"def apply_bin_labels(X):\n\tA = np.copy(X)\n\tlabel_i = A.shape[1] - 1\n\tA[A[:,label_i]==0,label_i] = -1\n\tA[A[:,label_i]>0,label_i] = 1\n\treturn A",
"def _labels_to_plus_minus(*args):\n for x in args:\n x[x <= 0.] = -1\n x[x > 0.] = 1",
"def test_to_labels_1q_array(self):\n with sel... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns a deep copy of this ReciprocalRelation. EXAMPLE >> Q=ReciprocalRelation(np.array([[0.5,0.3,0.4],[0.7,0.5,0.9],[0.6,0.1,0.5]])) >> newQ = Q.copy() >> Q.setEntry([0,1],0.99) >> Q.show() >> newQ.show() | def copy(self):
return(ReciprocalRelation(self.Q.copy(),self.precision)) | [
"def copy(self):\n r = Relation(cardinality=self.cardinality, ordered=self.isordered())\n r.forward.update(self.forward)\n r.inverse.update(self.inverse)\n return r",
"def copy(self):\n return Quadrant(\n list(self.min_coordinates), list(self.max_coordinates))",
"de... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns a list of exactly those integers x in 0,1,...,2binom(m,2)1, for which 'getBinaryReciprocalRelation(m,x)' is a WST reciprocal relation. | def getAllWSTIndices(m):
assert type(m) is int and m>=1, "`m` has to be a positive integer."
AllWSTIndices = list()
for idx in range(0,2**(scipy.special.binom(m,2)).astype(int)):
if isWST(getBinaryReciprocalRelation(m,idx)) is True:
AllWSTIndices.append(idx)
return(AllWSTIndice... | [
"def _generate_relations(self, n, base, num_relations):\n relations = []\n floor_sqrt_n = int(math.ceil(math.sqrt(n)))\n\n for x in xrange(floor_sqrt_n, n):\n if len(relations) >= num_relations:\n break\n\n exponents = is_b_smooth((x ** 2) % n, base)\n\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns the corresponding index 'idx' of a binary reciprocal relation R, such that getBinaryReciprocalRelation(R.m,idx) and R have the same entries everywhere | def getIndexOfBinaryRelation(R):
assert type(R) is ReciprocalRelation and R.isBinary(), "'R' has to be a binary relation"
index_str = ""
for i in range(0,R.m):
for j in range(i+1,R.m):
index_str = str(int(R.Q[i,j])) + index_str
return(int(index_str, base=2)) | [
"def reciprocal_rank(rels):\n\n nonzero_indices = np.asarray(rels).nonzero()[0]\n if has_no_relevant_items(nonzero_indices):\n # RR equals 0.0 if there is no relevant items\n return 0.0\n\n return 1.0 / (1.0 + nonzero_indices[0])",
"def _indices(self, r):\n bits = (2 * (r - self.r0[n... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns True if Q has a Condorcet winner, otherwise it returns False | def has_CW(Q):
assert type(Q) is ReciprocalRelation
for i in range(0,Q.m):
i_is_CW = True
for j in range(0,Q.m):
if i != j and Q.Q[i,j]<0.5:
i_is_CW = False
if i_is_CW is True:
return(True)
return(False) | [
"def collision(q):\r\n \r\n\r\n return False",
"def check_for_winner(players) -> bool:\n return sum(map(lambda x: not x.is_bankrupt(), players)) == 1",
"def is_first_winner(self):\r\n return self.first_winner",
"def _check_winner(self):\n for combo in self._winning_combos:\n wi... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns i if i is the CW of Q. If Q has no CW, it returns False | def get_CW(Q):
assert type(Q) is ReciprocalRelation
for i in range(0,Q.m):
i_is_CW = True
for j in range(0,Q.m):
if i != j and Q.Q[i,j]<0.5:
i_is_CW = False
if i_is_CW is True:
return(i)
return(False) | [
"def has_CW(Q):\r\n assert type(Q) is ReciprocalRelation\r\n for i in range(0,Q.m):\r\n i_is_CW = True\r\n for j in range(0,Q.m):\r\n if i != j and Q.Q[i,j]<0.5:\r\n i_is_CW = False\r\n if i_is_CW is True:\r\n return(True)\r\n return(False)",
"def... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Samples uniformly at random a reciprocal relation Q with m alternatives, which has a CW | def sampleCW(m,decimal_precision=10):
Q = sampleReciprocal(m,decimal_precision)
cw = np.random.randint(0,m) # cw is chosen to be the CW
for j in range(0,m):
if Q.Q[cw,j]<0.5:
buf = Q.Q[j,cw]
Q.setEntry([cw,j],buf)
return(Q), cw | [
"def sample_mniw(nu, L, M, S):\n # Sample from inverse wishart\n Q = invwishart.rvs(nu, L)\n # Sample from Matrix Normal\n A = npr.multivariate_normal(M.flatten(order='F'), np.kron(S, Q)).reshape(M.shape, order='F')\n return A, Q",
"def random_sequence_qmc(size_mv, i, n=1, randomized=True):\n si... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Samples a reciprocal relation in Q_m^{h}(\not CW), where all nondiagonal entries are in {0.5h , 0.5+h}. EXAMPLE >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> Q = sampleRecRel_exactly_h(5,0.1) Q.show() print(has_CW(Q)) <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<... | def sampleRecRel_exactly_h(m,h,decimal_precision=10):
Q = sampleReciprocal(m,decimal_precision)
Q = __EnforceBoundedFromOneHalf__(Q,0.4)
for i in range(0,Q.m):
for j in range(0,Q.m):
if Q.Q[i,j]>0.5:
Q.Q[i,j] = 0.5+h
if Q.Q[i,j]<0.5:
Q... | [
"def has_CW(Q):\r\n assert type(Q) is ReciprocalRelation\r\n for i in range(0,Q.m):\r\n i_is_CW = True\r\n for j in range(0,Q.m):\r\n if i != j and Q.Q[i,j]<0.5:\r\n i_is_CW = False\r\n if i_is_CW is True:\r\n return(True)\r\n return(False)",
"def... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Samples a reciprocal relation in Q_m^{h}(CW), where all nondiagonal entries are in {0.5h , 0.5+h}. EXAMPLE >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> Q, buf = sampleCW_exactly_h(5,0.1) Q.show() | def sampleCW_exactly_h(m,h,decimal_precision=10):
assert type(h) is float and 0<h<1/2, "The parameter `h` has to be a `float` in the interval :math:`(0,0.5)`"
Q, buf = sampleCW_boundedFromOneHalf(m,0.4,decimal_precision)
for i in range(0,Q.m):
for j in range(0,Q.m):
if Q.Q[i,j]>0.5... | [
"def sampleNotCW_exactly_h(m,h,max_tries=1000,decimal_precision=10): \r\n assert type(h) is float and 0<h<1/2, \"The parameter `h` has to be a `float` in the interval :math:`(0,0.5)`\"\r\n Q = sampleNotCW_boundedFromOneHalf(m=m,h=0.4,max_tries=1000,decimal_precision=decimal_precision)\r\n for i in range(0,... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Samples a reciprocal relation in Q_m^{h}(\not CW), where all nondiagonal entries are in {0.5h , 0.5+h}. EXAMPLE >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> Q = sampleNotCW_exactly_h(5,0.1) Q.show() print(has_CW(Q)) <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<... | def sampleNotCW_exactly_h(m,h,max_tries=1000,decimal_precision=10):
assert type(h) is float and 0<h<1/2, "The parameter `h` has to be a `float` in the interval :math:`(0,0.5)`"
Q = sampleNotCW_boundedFromOneHalf(m=m,h=0.4,max_tries=1000,decimal_precision=decimal_precision)
for i in range(0,Q.m):
... | [
"def has_CW(Q):\r\n assert type(Q) is ReciprocalRelation\r\n for i in range(0,Q.m):\r\n i_is_CW = True\r\n for j in range(0,Q.m):\r\n if i != j and Q.Q[i,j]<0.5:\r\n i_is_CW = False\r\n if i_is_CW is True:\r\n return(True)\r\n return(False)",
"def... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
this is the sort function for the keys (i.e. columns) of the csv file | def sort_colums_for_csv(column_name):
if column_name in column_sort_dict:
return column_sort_dict[column_name]
else:
return ord(column_name[0]) + 99 | [
"def re_sort(in_file, out_file):\n # First, read all the rows into a list\n with open(in_file, mode='r', newline='') as csv_file:\n reader = csv.DictReader(csv_file)\n rows = [row for row in reader]\n # Or, rows = list(reader)\n # Get the key of the second column\n second_column = r... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
this is the sort function that is used to determine the order of the lines of the csv | def sort_rows_for_csv(part):
if (part['NAME'].find(',')):
stri = part['NAME'].split(',')[0]
else:
stri = part['NAME']
if 'DO_NOT_PLACE' in part:
return '0'
if 'PROVIDED_BY' in part:
return '1'
return ''.join(c for c in stri if not c.isdigit()) | [
"def sort(self):",
"def csvsort(inputfile: str, outputfile: str, columnchoice: str) -> None:\n fileread = readfile(inputfile)\n sorteddata = sortdata(fileread, columnchoice)\n writefile(sorteddata, outputfile)",
"def re_sort(in_file, out_file):\n # First, read all the rows into a list\n with open... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
find all used keys that are used in a list of dictionaries | def get_keys_from_dict_list(elements):
keys = []
for element in elements:
element_keys = element.keys()
for key in element_keys:
if (not key in keys):
keys.append(key)
return keys | [
"def find_same_dict_from_dictlist(list_of_dict):\n common_items = reduce(operator.__and__, \n (d.viewitems() for d in list_of_dict))\n print common_items\n common_keys = [item[0] for item in common_items]\n print common_keys",
"def get_all_keys(ds):\n keys = []\n for d in ds:\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
group elements by value if they have the same attributes otherwise and write to 'filename' as csv file | def write_value_list(elements, filename, set_delimiter, settings):
elements.sort(key=sort_dict_by_all_but_name)
groups = []
uniquekeys = []
for key, group in groupby(elements, key=sort_dict_by_all_but_name):
groups.append(list(group)) # Store group iterator as a list
uniquekeys.a... | [
"def csv(self):\n output = io.StringIO()\n writer = csv.writer(output)\n labels = sorted(self.records.keys())\n\n # x labels.\n writer.writerow([''] + labels)\n\n # y labels and data.\n for y, y_label in enumerate(labels):\n row = [labels[y]]\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
get the library part from input parameters drawing, library and deviceset | def get_librarypart(drawing, library, deviceset):
for library_tree in drawing.iterfind('schematic/libraries/library'):
if (library_tree.attrib['name'] == library):
for deviceset_tree in library_tree.iterfind('devicesets/deviceset'):
if (deviceset_tree.attrib['name'] == deviceset)... | [
"def _convert_library(self, design):\n\n for _cc in design.components.components:\n _libid = 'default'\n _compname = _cc\n _tech = []\n _attrs = []\n if -1 != _cc.find(':'):\n _libid, _compname = _cc.split(':')\n\n _lib = None\n... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
get the package name of a device from input parameters drawing, library, deviceset and device | def get_package(drawing, library, deviceset, device):
deviceset_tree = get_librarypart(drawing, library, deviceset)
for device_tree in deviceset_tree.iterfind('devices/device'):
if device_tree.attrib['name'] == device:
if "package" in device_tree.attrib:
return device_tree.at... | [
"def get_device_name_and_platform(self, device):\r\n # Lowercase the device name\r\n if device is not None:\r\n device = device.lower()\r\n device = device.strip().replace(\" \",\"\")\r\n # If given vague iphone/ipad/android then set the default device\r\n if re.mat... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
get the description of a deviceset from input parameters drawing, library and deviceset | def get_description(drawing, library, deviceset):
deviceset_tree = get_librarypart(drawing, library, deviceset)
for description in deviceset_tree.iterfind('description'):
return description.text | [
"def get_librarypart(drawing, library, deviceset):\n for library_tree in drawing.iterfind('schematic/libraries/library'):\n if (library_tree.attrib['name'] == library):\n for deviceset_tree in library_tree.iterfind('devicesets/deviceset'):\n if (deviceset_tree.attrib['name'] == d... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
check weather a part is a schematic only part or if it is also on the PCB | def is_part_on_pcb(drawing, library, deviceset):
deviceset_tree = get_librarypart(drawing, library, deviceset)
if deviceset_tree.find('devices/device/connects'):
return True | [
"def check_Part_policing_operation(observation):\n \n part_oper = observation.get(\"Part of a policing operation\")\n \n if isinstance(part_oper, str):\n error = \"Field 'Part of a policing operation' is not a boolean\"\n return False, error \n \n return True, \"\"",
"def _c... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
find out if the element has different settings for the selected variant and change it accordingly | def change_part_by_variant(part_tree, part, selected_variant):
if 'populate' in part_tree.attrib and part_tree.attrib['populate'] == "no":
part['DO_NOT_PLACE'] = "yes"
return
for variant in part_tree.iterfind('variant'):
if (variant.attrib['name'] == selected_variant):
if (... | [
"def select_variant(drawing, variant_find_string, settings):\n \n ##stores the actual used variant\n selected_variant = \"\"\n ##stores the default variant if available\n default_variant = \"\"\n ##stores the number of defined variants in the board file\n number_variant = 0 \n\n #find all ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
find all variants that are defined in the drawing select the most appropriate one based on settings and default variant | def select_variant(drawing, variant_find_string, settings):
##stores the actual used variant
selected_variant = ""
##stores the default variant if available
default_variant = ""
##stores the number of defined variants in the board file
number_variant = 0
#find all variants that are ... | [
"def test_default_variant_is_most_common_or_control(self):\n s = Swab(self.datadir)\n s.add_experiment('foo', ['v1', 'v2'], 'goal')\n assert s.experiments['foo'].default_variant == 'v1'\n\n s.add_experiment('bar', ['v1', 'v2', 'v2'], 'goal')\n assert s.experiments['bar'].default_v... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
this function reads the eagle XML and processes it to produce the bill of material | def bom_creation(settings):
#prepare differences for brd and sch files
if ('in_filename_brd' in settings):
tree = ET.ElementTree(file=settings['in_filename_brd'])
variant_find_string = "board/variantdefs/variantdef"
part_find_string = "board/elements/element"
elif (... | [
"def _readMoreXML(self,xmlNode):\n Dummy._readMoreXML(self, xmlNode)\n self.initializationOptionDict['name'] = self.name\n paramInput = ROM.getInputSpecification()()\n paramInput.parseNode(xmlNode)\n def tryStrParse(s):\n \"\"\"\n Trys to parse if it is stringish\n @ In, s, string,... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Unupvote this post (this is different from other downvoting systems). | async def downvote(self) -> None:
await self._state.http.vote_on_user_post(self.author.id64, self.id, 0) | [
"def downvote(self):\n self._authenticated_action_click(NinegagXPaths.Post.DOWNVOTE_BUTTON, 'Downvoting')",
"def unvote(self, obj):\n obj._set_vote(self, 0)",
"def upvote(self):\n self._authenticated_action_click(NinegagXPaths.Post.UPVOTE_BUTTON, 'Upvoting')",
"def upvotePost(self):\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Random split data and save mindrecord | def random_split_trans2mindrecord(input_file_path, output_file_path, recommendation_dataset_stats_dict,
part_rows=100000, line_per_sample=1000, train_line_count=None,
test_size=0.1, seed=2020, dense_dim=13, slot_dim=26):
if train_line_count is None... | [
"def segment_test_train():\n lookup = get_default_lookup()\n\n\n # Lets randomize all possible fic ids\n all_ids = lookup.keys()\n shuffle(all_ids)\n\n #now define 1/5 of the dataset as train\n num_ids = len(all_ids)\n test = int(num_ids/5)\n\n testdata = all_ids[0:test]\n traindata = all... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Turn competition mode on or off. | def competition_mode(self, on):
raise NotImplementedError | [
"def toggle_gamemode(self):\n # todo: remove this check\n if self != shared.world.get_active_player():\n return\n\n if self.gamemode == 1:\n self.set_gamemode(3)\n elif self.gamemode == 3:\n self.set_gamemode(1)",
"def pet_mode(self) -> bool:\n r... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Commons out the code checking function settings for randomness Interesting to see that the rates go up with increasing width of word. No doubt because it is spending proportionately time in highly optimized math routines. Lots of patterns in that data, not a waste of time, but insight/hour is low, I think. 24 June 2018... | def check_function( self, the_function, the_rnt ) :
print( the_function )
print( "vec_size int_width statesize p_lvl difficulty " +
"duplicates zeros all ff's elapsed time byterate" )
sys.stdout.flush()
function_return = True
n_samples = self.difficulty * 64 * 1024
random_table = [ 0... | [
"def entropy_whole_process(lang, wordlength, fixations, nreps, knownwords, targetwords, mcconkie_drop, control=\"\"):\n\n\n\n #STEP 1: Compute entropy per trial\n pertrial_files=compute_entropy_pertrial(knownwords, knownwords, lang, wordlength, nreps, mcconkie_drop, fixations, control )\n #(outputs in file... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |