query
stringlengths
9
9.05k
document
stringlengths
10
222k
negatives
listlengths
19
20
metadata
dict
Unhexlify raw text, return unhexlified text.
def unhexlify(text): unhexlified = binascii.unhexlify(text) if six.PY3: unhexlified = unhexlified.decode('utf-8') return unhexlified
[ "def hexlify(text):\n if six.PY3:\n text = text.encode('utf-8')\n\n hexlified = binascii.hexlify(text)\n\n if six.PY3:\n hexlified = hexlified.decode('utf-8')\n\n return hexlified", "def unhexlify(data) -> bytes:", "def test_unhexlify():\n hexlified = uflash.hexlify(TEST_SCRIPT)\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Obtains the record in the set with the time closest to the given $unix_time. If this record with not $within the correct number of seconds, an exception is raised.
def get_record(self, unix_time, within): if len(self.records) <= 0: raise Exception("No records in this set") r = self.records[0] closest_record = r closest_delta = abs(r.unix_time - unix_time) for r in self.records[1:]: delta = abs(r.unix_time - unix_time) if delta < closest_delta: closest_reco...
[ "def get_closest_record(self, time):\n dist = 10000000\n record = -1\n # TODO: optimise a bit\n for i, itime in enumerate(self.times):\n if (abs(time-itime)) < dist:\n dist = abs(time-itime)\n record = i\n\n return record", "def nearest (...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Pulls in the records from other into self with the other, but since the timestamps won't match up perfectly, the output will only have a record per $period number of seconds.
def merge_with(self, other, period=60): new_list = [] last_timestamp = 0 for r in self.records: if abs(r.unix_time - last_timestamp) > period: # Accept this record last_timestamp = r.unix_time other_r = other.get_record(r.unix_time, period/2) r.merge_with(other_r) new_list.append(r) self....
[ "def merge_usage_periods(periods, new_period):\n outlist = []\n for period in periods:\n if new_period[0] > period[1]:\n # No overlap - past the end\n outlist.append(period)\n continue\n if new_period[1] < period[0]:\n # No overlap - before the beginni...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Given a UC480 camera object (instrumental module) and a number indicating the number of trap objects, applies an iterative image analysis to individual trap adjustment in order to achieve a nearly homogeneous intensity profile across traps.
def stabilize_intensity(which_cam, cam, verbose=False): L = 0.5 # Correction Rate mags = np.ones(12) ### ! ntraps = len(mags) iteration = 0 while iteration < 5: iteration += 1 print("Iteration ", iteration) im = cam.latest_frame() try: trap_po...
[ "def analyze_image(which_cam, image, ntraps, iteration=0, verbose=False):\n threshes = [0.5, 0.6]\n margin = 10\n threshold = np.max(image) * threshes[which_cam]\n im = image.transpose()\n\n x_len = len(im)\n peak_locs = np.zeros(x_len)\n peak_vals = np.zeros(x_len)\n\n ## Trap Peak Detectio...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Scans the given image for the 'ntraps' number of trap intensity peaks. Then extracts the 1dimensional gaussian profiles across the traps and returns a list of the amplitudes.
def analyze_image(which_cam, image, ntraps, iteration=0, verbose=False): threshes = [0.5, 0.6] margin = 10 threshold = np.max(image) * threshes[which_cam] im = image.transpose() x_len = len(im) peak_locs = np.zeros(x_len) peak_vals = np.zeros(x_len) ## Trap Peak Detection ## for i ...
[ "def analyze_image(image, ntraps, iteration=0, verbose=False):\n ## Image Conditioning ##\n margin = 10\n threshold = np.max(image)*0.5\n im = image.transpose()\n plt.imshow(im)\n plt.show(block=False)\n\n x_len = len(im)\n peak_locs = np.zeros(x_len)\n peak_vals = np.zeros(x_len)\n\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Given the opened camera object and the Slider object connected to the camera's exposure, adjusts the exposure to just below clipping. Binary Search
def fix_exposure(cam, slider, verbose=False): margin = 10 exp_t = MAX_EXP / 2 cam._set_exposure(exp_t * u.milliseconds) time.sleep(0.5) print("Fetching Frame") im = cam.latest_frame() x_len = len(im) right, left = MAX_EXP, 0 inc = right / 10 for _ in range(10): ## Determ...
[ "def fix_exposure(cam, slider, verbose=False):\n margin = 10\n print(\"Fetching Frame\")\n im = cam.latest_frame()\n x_len = len(im)\n print(\"Fetching Exposure\")\n exp_t = cam._get_exposure()\n\n right, left = exp_t*2, 0\n inc = right / 10\n for _ in range(10):\n ## Determine if ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Fetches prediction field from prediction byte array. After TensorRT inference, prediction data is saved in byte array and returned by object detection network. This byte array contains several pieces of data about prediction we call one such piece a prediction field. The prediction fields layout is described in TRT_PRE...
def fetch_prediction_field(field_name, detection_out, pred_start_idx): return detection_out[pred_start_idx + TRT_PREDICTION_LAYOUT[field_name]]
[ "def load_predict(path=MODEL_PATH, version=VERSION, namePredictor=DEFAULT_PREDICTOR):\n logging.info(\"trying to load {}\".format(path + namePredictor + version + '.npz'))\n return np.load(path + namePredictor + version + '.npz')['pred']", "def get_fvlm_predict_fn(serving_batch_size):\n num_classes, text_d...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Web GET or POST request를 호출 후 그 결과를 dict형으로 반환
def web_request(method_name, url, dict_data, is_urlencoded=True): method_name = method_name.upper() # 메소드이름을 대문자로 바꾼다 if method_name not in ('GET', 'POST'): raise Exception('method_name is GET or POST plz...') if method_name == 'GET': # GET방식인 경우 response = requests.get(url=url, params=di...
[ "def GET(self):\n pass", "def request_vars(self):", "def get_dict_from_request(request):\n if request.method == 'GET':\n return request.GET\n elif request.method == 'POST':\n return request.POST\n else:\n raise NotImplemented", "def do_POST(self):\r\n self.do_GET()"...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Get a dictionary with the important tags for DAGMC geometries inputs
def get_dagmc_tags(my_core): dagmc_tags = {} dagmc_tags['geom_dim'] = my_core.tag_get_handle('GEOM_DIMENSION', size=1, tag_type=types.MB_TYPE_INTEGER, storage_type=types.MB_TAG_SPARSE, create_if_missing=True) # geometric dimension dagmc_tags['category'...
[ "def getTag(self, inputs, tag):\n result = {}\n for into in inputs:\n for i in into:\n if i in self.sim.agents:\n agentTags = self.sim.agents[i].access[\"tags\"]\n if tag in agentTags:\n result[i] = agentTags[tag]\n...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Get a dictionary with MOAB ranges for each of the requested entity types inputs
def get_native_ranges(my_core, meshset, entity_types): native_ranges = {} for entity_type in entity_types: native_ranges[entity_type] = my_core.get_entities_by_type( meshset, entity_type) return native_ranges
[ "def get_entityset_ranges(my_core, meshset, geom_dim):\n\n entityset_ranges = {}\n entityset_types = ['Nodes', 'Curves', 'Surfaces', 'Volumes']\n for dimension, set_type in enumerate(entityset_types):\n entityset_ranges[set_type] = my_core.get_entities_by_type_and_tag(meshset, types.MBENTITYSET, geo...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Get a dictionary with MOAB Ranges that are specific to the types.MBENTITYSET type inputs
def get_entityset_ranges(my_core, meshset, geom_dim): entityset_ranges = {} entityset_types = ['Nodes', 'Curves', 'Surfaces', 'Volumes'] for dimension, set_type in enumerate(entityset_types): entityset_ranges[set_type] = my_core.get_entities_by_type_and_tag(meshset, types.MBENTITYSET, geom_dim, ...
[ "def getRangeMM(self) -> float:\n ...", "def _get_range_data(list_of_numbers, set_max=None):\n\n labels = []\n if set_max:\n for i in range(set_max):\n labels.append(float(i))\n else:\n for i in range(int(max(list_of_numbers) + 1)):\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Get side lengths of triangle inputs
def get_tri_side_length(my_core, tri): side_lengths = [] s = 0 coord_list = [] verts = list(my_core.get_adjacencies(tri, 0)) for vert in verts: coords = my_core.get_coords(vert) coord_list.append(coords) for side in range(3): side_lengths.append(np.linalg.norm(coord_l...
[ "def calc_side_lengths(triangles):\n first_vec = [2, 0, 1]\n second_vec = [1, 2, 0]\n sides = triangles[:, first_vec] - triangles[:, second_vec]\n lengths = np.sqrt(np.sum(sides**2, axis=2))\n return lengths", "def triangle_area():\r\n edge = float(input(\"\"))\r\n return (math.sqrt(3)/4) * e...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Cleans the line from geometrical shape characters and replaces these with space.
def clean_text_from_geometrical_shape_unicode(line): line = re.sub(r"([\u25A0-\u25FF])", " ", line) return line
[ "def clean(line):\n line = line.strip('\\n').strip()\n line = line.replace('\\xe2\\x80\\x93', '-')\n line = line.replace('\\xe2\\x80\\x99', '\\'')\n\n return line", "def _fix_line(line):\n line = line.strip(\"\\n\\r\\f\")\n # This is a hack to make the tagger work, but it loses information\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Cleans the line from private unicode characters and replaces these with space.
def clean_text_from_private_unicode(line): line = re.sub(r"([\uE000-\uF8FF]|\uD83C[\uDF00-\uDFFF]|\uD83D[\uDC00-\uDDFF])", " ", line) return line
[ "def _fix_line(line):\n line = line.strip(\"\\n\\r\\f\")\n # This is a hack to make the tagger work, but it loses information\n # TODO: could replace \"~\" with \"&tilde;\" or find the real solution\n line = line.replace('~', '')\n # backspace characters break the sdp tagger code\n line = line.rep...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
return a model as defines in model_search.yaml
def get_model_from_yaml(name): filename = pkg_resources.resource_filename('empirical_lsm', 'data/model_search.yaml') with open(filename) as f: model_dict = yaml.load(f)[name] return get_model_from_dict(model_dict)
[ "def get_model(model):\n all_models = cmd.get_object_list()\n\n if len(all_models) == 0:\n logging.parser_error('No models are opened.')\n return\n\n model = model.lower()\n\n if model and (model in all_models):\n return model\n\n if len(all_models) > 1:\n logging.parser_e...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Return a sklearn model pipeline from a model_dict
def get_model_from_dict(model_dict): pipe_list = [] if 'transforms' in model_dict: # For basic scikit-learn transforms transforms = model_dict['transforms'].copy() if 'scaler' in transforms: scaler = transforms.pop('scaler') pipe_list.append(get_scaler(scaler)) ...
[ "def get_pipeline(model):\n \n cat=['workclass', 'education','marital-status','relationship', 'occupation', 'native-country' ]\n num=['age', 'education-num','capital-gain', 'capital-loss','hours-per-week' ]\n \n pipeline = Pipeline([\n ('features', FeatureUnion([\n ('categor...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Return a Lag wrapper for a pipeline.
def get_lagger(pipe, kwargs): from .transforms import LagWrapper return LagWrapper(pipe, **kwargs)
[ "def pipeline(self) -> Pipeline:\n if self._to_pipeline is None:\n raise AttributeError(\n \"pipeline not available because `to_pipeline` was not set on __init__.\"\n )\n return self._to_pipeline(self)", "def make_pipeline():\n pipeline = Pipeline(\n co...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Return a markov wrapper for a pipeline.
def get_markov_wrapper(pipe, kwargs): from .transforms import MarkovWrapper return MarkovWrapper(pipe, **kwargs)
[ "def create_pipelines_lingspam():\n stop = ('stop', StopWordRemovalTransformer())\n lemma = ('lemma', LemmatizeTransformer())\n binz = ('binarizer', CountVectorizer())\n we = ('document embedding', DocEmbeddingVectorizer())\n sel = ('fsel', SelectKBest(score_func=mutual_info_classif, k=100))\n clf...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Return a scikitlearn clusterer from name and args.
def get_clusterer(name, kwargs): if name == 'KMeans': from sklearn.cluster import KMeans return KMeans(**kwargs) if name == 'MiniBatchKMeans': from sklearn.cluster import MiniBatchKMeans return MiniBatchKMeans(**kwargs)
[ "def get_cluster(self, name):\n return clusters.get_cluster(self, name)", "def show_cluster(name: str) -> Cluster:\n environment = EnvironmentProvider().environment\n return environment.clusters[name]", "def get_cluster(name: str) -> dict:\n return ECS.get_clusters([name])[0]", "def get(resour...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
get a sklearn scaler from a scaler name
def get_scaler(scaler): if scaler == 'standard': from sklearn.preprocessing import StandardScaler return StandardScaler() if scaler == 'minmax': from sklearn.preprocessing import MinMaxScaler return MinMaxScaler()
[ "def get_scaler(name):\n return _autoscaling_components[SCALER_KEY][name]", "def load_scaler(fname):\n return Scaler(joblib.load(fname))", "def __create_scaler_type(self):\n\n if self.scalertype == \"standard\":\n return StandardScaler()\n if self.scalertype == \"minmax\":\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
get a PCA decomposition
def get_pca(): from sklearn.decomposition import PCA return PCA()
[ "def principalComponents(self):\n\n\t\tpca = PCA()\n\t\tpca.fit(self.training_set)\n\t\treturn pca", "def pca(X = Math.array([]), no_dims = 50):\n\n\tprint (\"Preprocessing the data using PCA...\")\n\t(n, d) = X.shape;\n\tX = X - Math.tile(Math.mean(X, 0), (n, 1));\n\t(l, M) = Math.linalg.eig(Math.dot(X.T, X));\n...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
get a PolynomialFeatures transform
def get_poly(kwargs): from sklearn.preprocessing import PolynomialFeatures return PolynomialFeatures(**kwargs)
[ "def make_poly_features(x):\n poly = PolynomialFeatures(degree=5)\n new_x = poly.fit_transform(x)\n return new_x", "def polyfeatures(X: np.ndarray, degree: int) -> np.ndarray:\n poly = PolynomialFeatures(degree=degree)\n X = poly.fit_transform(X.reshape(-1,1))\n \n return(X[:,1:...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Check GMail E.g. messages,unseen = imap.check_gmail('username.com','password')
def check_gmail(username, password): i = imaplib.IMAP4_SSL('imap.gmail.com') try: i.login(username, password) x, y = i.status('INBOX', '(MESSAGES UNSEEN)') messages = int(re.search('MESSAGES\s+(\d+)', y[0]).group(1)) unseen = int(re.search('UNSEEN\s+(\d+)', y[0]).group(1)) ...
[ "def checkEmail():\n\tpop_conn = poplib.POP3_SSL('pop.gmail.com')\n\tpop_conn.user('')\n\tpop_conn.pass_('')\n\t#Get messages from server:\n\tmessages = [pop_conn.retr(i) for i in range(1, len(pop_conn.list()[1]) + 1)]\n\t# Concat message pieces:\n\tmessages = [\"\\n\".join(mssg[1]) for mssg in messages]\n\t#Parse ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Converts a raw packet to a dpkt packet regarding of link type.
def iplayer_from_raw(raw, linktype=1): if linktype == 1: # ethernet pkt = dpkt.ethernet.Ethernet(raw) ip = pkt.data elif linktype == 101: # raw ip = dpkt.ip.IP(raw) else: raise Exception("unknown PCAP linktype") return ip
[ "def parse_packet(linktype, packet):\n link_layer = parse_Ethernet(packet) if linktype == pcapy.DLT_EN10MB else parse_Cooked(packet)\n if link_layer['payload_type'] in ['IPv4', 'IPv6']:\n network_layer = parse_IPv4(link_layer['payload']) if link_layer['payload_type'] == 'IPv4' else parse_IPv6(link_laye...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Extract all packets belonging to the same flow from a pcap packet iterator
def next_connection_packets(piter, linktype=1): first_ft = None for ts, raw in piter: ft = flowtuple_from_raw(raw, linktype) if not first_ft: first_ft = ft sip, dip, sport, dport, proto = ft if not (first_ft == ft or first_ft == (dip, sip, dport, sport, proto)): bre...
[ "def iter_packets(iterable):\n prev = None\n\n for i in sorted(iterable, key=attrgetter('seq')):\n if prev is None or prev.seq != i.seq:\n prev = i\n yield i", "def packet_filter_generator(pcap_class_gen, filter_con):\n global source_mac_add\n\n for pcapfile, device_name i...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Open a PCAP, seek to a packet offset, then get all packets belonging to the same connection
def packets_for_stream(fobj, offset): pcap = dpkt.pcap.Reader(fobj) pcapiter = iter(pcap) ts, raw = pcapiter.next() fobj.seek(offset) for p in next_connection_packets(pcapiter, linktype=pcap.datalink()): yield p
[ "def pcap():", "def read_pcap(self, filename):\n packets = rdpcap(filename)[IP]\n sessions = packets.sessions()\n for key in sessions:\n # try:\n if key not in self.session_collection:\n parts = key.split()\n protocol = parts[0]\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Use SortCap class together with batch_sort to sort a pcap
def sort_pcap(inpath, outpath): inc = SortCap(inpath) batch_sort(inc, outpath, output_class=lambda path: WriteCap(path, linktype=inc.linktype)) return 0
[ "def sort(self, cmp=ProbeMapVector.compare):\n pass", "def performance_sort(tc: \"list[TransicationRecord]\", filename: str):\n tc.sort(key=performance, reverse=True)\n with open(filename, 'w+', newline='') as f:\n writer = csv.writer(f)\n writer.writerow(['id', 'r_count', 'type', 's_me...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
test that the StrainData.fetch_open_frame works as expected
def test_fetch_open_frame(self): import requests pesummary_data = StrainData.fetch_open_frame( "GW190412", IFO="L1", duration=32, sampling_rate=4096., channel="L1:GWOSC-4KHZ_R1_STRAIN", format="hdf5" ) N = len(pesummary_data) np.testing.assert_almost_equal...
[ "def test_fetch():\n try:\n df = fetch_lingspam()\n except Exception as e:\n print(e)\n assert((2893, 2) == df.values.shape)", "def test_get_dataframe(self):\n dfr = trappy.FTrace().sched_load_avg_sg.data_frame\n\n self.assertTrue(len(dfr) == 1)\n self.assertEqual(dfr[\...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Add v to a ordered set s and return s. >>> s = Link(1, Link(3, Link(5))) >>> add(s, 0) Link(0, Link(1, Link(3, Link(5)))) >>> add(s, 4) Link(0, Link(1, Link(3, Link(4, Link(5))))) >>> add(s, 6) Link(0, Link(1, Link(3, Link(4, Link(5, Link(6)))))) >>> t = Link(1) >>> add(t, 0) Link(0, Link(1))
def add(s, v): if empty(s): return Link(v) head = s if head.first > v: # s = Link(v, s) #error: assigment, then s will rebind to a new object # s.first, s.rest = v, s # error s.rest = s s.first, s.rest = v, Link(s.first, s.rest) return s # head.first <= v ...
[ "def add(s, v):\n if empty(s):\n return Link(v)\n if s.first > v:\n s.first, s.rest = v, Link(s.first, s.rest)\n elif s.first < v and empty(s.rest):\n s.rest = Link(v, s.rest)\n elif s.first < v:\n add(s.rest, v)\n return s", "def adjoin_set(S, v):\n if S.label is Non...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns the Saved news object data in serializable format
def serialize(self): return { "id": self.id, "headline": self.headline, "url": self.url, "image": self.image, "shortDescription": self.shortDescription, "saved": True, "date": self.date, "savedDate": self.savedDate ...
[ "def serialize_news(self):\n return {\n 'category': self.category,\n 'datetime': self.datetime,\n 'headline': self.headline,\n 'image': self.image,\n 'related': self.related,\n 'source': self.source,\n 'summary': self.summary,\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
This method is responsible for getting the messages to respond with Also covers analytics events for those messages for e.g. click, view
def respond_to_message(self): MessageEventHandler(self.state, self.meta_data, self.message_data).handle_events(events=self.events) data = Converter(self.state).get_messages(meta_data=self.meta_data, message_data=self.message_data) outgoing_messages = data.get("messages", []) events_to_...
[ "def on_response_received(self, message):", "def process_messages(self):\n pass", "def receive_messages():\n\n # ensure that the signature on the request is valid\n if not verify_signature(request):\n return Response(status=403, response='invalid signature')\n\n messages = request.json['m...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Given the vm data from the API, create a dictionary that contains all of the necessary keys for the template The keys will be checked in the update method and not here, this method is only concerned with fetching the data that it can.
def _get_template_data(vm_data: Dict[str, Any], span: Span) -> Optional[Dict[str, Any]]: vm_id = vm_data['id'] Windows.logger.debug(f'Compiling template data for VM #{vm_id}') data: Dict[str, Any] = {key: None for key in Windows.template_keys} data['vm_identifier'] = f'{vm_data["project...
[ "def _get_template_data(vm_data: Dict[str, Any], span: Span) -> Optional[Dict[str, Any]]:\n vm_id = vm_data['id']\n Windows.logger.debug(f'Compiling template data for VM #{vm_id}')\n data: Dict[str, Any] = {key: None for key in Windows.template_keys}\n\n data['vm_identifier'] = f'{vm_dat...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
This runs instead of most of nextEvent when Shared_Board is True and there are ambiguous wild cards. It is looking for key strokes to designate ambiguous wild cards in runs. The mouse is ignored until you designate all the wilds (turn phase goes back to play).
def nextEventWildsOnBoard(self): if self.controller._state.rules.Shared_Board and self.num_wilds > 0: for self.event in pygame.event.get(): if self.event.type == pygame.QUIT: # The window crashed, we should handle this print("pygame crash, AAA...
[ "def nextEvent(self):\n\n if self.controller._state.rules.Shared_Board:\n self.num_wilds = len(self.controller.unassigned_wilds_dict.keys())\n if self.num_wilds > 0:\n self.nextEventWildsOnBoard()\n\n for self.event in pygame.event.get():\n if self.event...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
This submits the next user input to the controller, In games with Shared_Board = False (e.g. HandAndFoot) key strokes don't do anything unless designating values for prepared wild cards, at which time the mouse is ignored unless you want to clear the prepared cards. In games with Shared_Board = True wilds on board migh...
def nextEvent(self): if self.controller._state.rules.Shared_Board: self.num_wilds = len(self.controller.unassigned_wilds_dict.keys()) if self.num_wilds > 0: self.nextEventWildsOnBoard() for self.event in pygame.event.get(): if self.event.type == pyga...
[ "def nextEventWildsOnBoard(self):\n\n if self.controller._state.rules.Shared_Board and self.num_wilds > 0:\n for self.event in pygame.event.get():\n if self.event.type == pygame.QUIT:\n # The window crashed, we should handle this\n print(\"pygam...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Confirm a user is sure about a discard and then perform it once confirmed.
def discardConfirmation(self, confirmed, wrapped_discards): discards = [] for element in wrapped_discards: discards.append(element.card) if self.discards != discards: confirmed = False self.discards = discards if not confirmed: self.control...
[ "def confirm_with_abort() -> None:\n\n click.confirm(\n \"Are you sure you want to drop the users table?\",\n abort=True\n )\n\n click.echo(\"We have gotten to this point, so the user has confirmed.\")", "def action_confirm(self):\n self.check_txt_ids()\n self.write({'state': ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Test Category model data insertion/types/field attributes
def test_category_model_entry(self): # PRUEBA DE CARGAR LA INFORMACION EN LOS MODELOS A TESTEAR data = self.data1 self.assertTrue(isinstance(data, Category)) # REALIZA EL TESTEO
[ "def test_category_model_entry(self):\n data = self.data1\n self.assertTrue(isinstance(data, Category))", "def test_category_model_entry(self):\n data = self.data1\n self.assertTrue(isinstance(data, Category))\n self.assertEqual(str(data), 'recipe')", "def test_category_model_...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Test product model data insertion/types/field attributes
def test_products_model_entry(self): data = self.data1 self.assertTrue(isinstance(data, Product)) self.assertEqual(str(data), 'django beginners')
[ "def test_product_fields(self):\n\n prd = Product.objects.get(id=1)\n\n # test the type of name field\n prd_type = prd._meta.get_field('name').get_internal_type()\n self.assertEqual(prd_type, 'CharField')\n # label name\n max_length = prd._meta.get_field('name').max_length\...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns the total, nonblank and net loc for all the python files in a directory
def get_folder_total(path): files = os.listdir(path) pythonfiles = ['%s/%s' % (path, filename) for filename in files if filename[-3:] == '.py'] total = { 'net': 0, 'total': 0, 'nonblank': 0, 'num_inputs':0 } for filename in pythonfiles: with open(filename, 'r') as thisfile: blob = th...
[ "def count_loc(project_path: str) -> int:\n _python_files = get_python_files(project_path)\n\n _loc = 0\n\n for _file_path in _python_files:\n if os.path.isfile(_file_path):\n _loc = _loc + _single_file_loc(_file_path)\n\n return _loc", "def file_stats(file_pairs):\n loc = 0\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Get vertices dividing a 1d grid.
def get_1d_vertices(grid, cut_edges=False): if len(grid.shape) > 1: raise ValueError("grid must be 1d array.") diff = np.diff(grid) vert = np.zeros(grid.size+1) # Interior vertices: halfway between points vert[1:-1] = grid[0:-1] + diff/2 # Edge vertices: tight or reflect if cut_edge...
[ "def get_vertices(self, i, j):\n pts = []\n xgrid, ygrid = self.xgrid, self.ygrid\n pts.append([xgrid[i, j], ygrid[i, j]])\n pts.append([xgrid[i + 1, j], ygrid[i + 1, j]])\n pts.append([xgrid[i + 1, j + 1], ygrid[i + 1, j + 1]])\n pts.append([xgrid[i, j + 1], ygrid[i, j + 1...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Compute padded image limits for x and y grids.
def pad_limits(xgrid, ygrid, xpad=0., ypad=0., square=None): xmin, xmax = xgrid.min(), xgrid.max() ymin, ymax = ygrid.min(), ygrid.max() dx = xmax - xmin dy = ymax - ymin x0 = xmin - xpad*dx x1 = xmax + xpad*dx y0 = ymin - ypad*dy y1 = ymax + ypad*dy if square: axis = squar...
[ "def bounds(pixels):\n for j in range(1, len(pixels)):\n if pixels[j][0] - pixels[j-1][0] > 10:\n left, right = pixels[:j], pixels[j:]\n\n # Join split sprites\n if len(left) > len(right):\n right = [(x-160, y) for (x, y) in right]\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Generate a object formatter for links..
def link(text, link_func): def object_formatter(v, c, m, p): """Format object view link.""" return Markup('<a href="{0}">{1}</a>'.format( link_func(m), text)) return object_formatter
[ "def object_formatter(v, c, m, p):\n return Markup('<a href=\"{0}\">{1}</a>'.format(\n link_func(m), text))", "def format_link(linkfunc):\n\n def func(item):\n url, text = linkfunc(item)\n return '<a href=\"%s\">%s</a>' % (url, text)\n return func", "def linkify(obj, link_t...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Format object view link.
def object_formatter(v, c, m, p): return Markup('<a href="{0}">{1}</a>'.format( link_func(m), text))
[ "def object_link(obj, view=\"view\", attribute=\"Title\", content=\"\", target=\"\"):\n from Products.CMFPlone.utils import safe_unicode\n\n href = view and \"%s/%s\" % (obj.absolute_url(), view) or obj.absolute_url()\n if not content:\n if not hasattr(obj, attribute):\n attribute = \"Tit...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns a list of the currently connected playes (on the MC server). First tries to hit the cache to see if this has been checked recently. If there is no cache entry, queries the Minecraft server's zombiepygman API to get the list of currently connected players.
def _get_connected_player_list(self): if not zpgapi.is_zgp_api_enabled(): # API is not configured, skip this. return [] cache_key = 'api_connected_players' cache_val = cache.get(cache_key) if cache_val != None: return cache_val ap...
[ "def get_players(self):\n return self.server.status().players.online", "def getplayerlist(self):\n return self.referee.players.values()", "def get_players(self):\n return self.players", "def getplayerlist(self):\n return list(self.playerlist)", "def get_players(self):\r\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Ensure the value of 'done' is set to False when creating an item
def test_done_default_value_is_False(self): item = Item(name = "A test item") self.assertEqual(item.name, "A test item") self.assertFalse(item.done)
[ "def test_done_value_can_be_set_to_True(self):\n item = Item(name = \"A test item\", done = True)\n self.assertEqual(item.name, \"A test item\")\n self.assertTrue(item.done)", "def test_mark_post_process_complete_create(self):\n pass", "def done_item(self) -> None:\n pass", ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Ensure the value of 'done' is True when set to True when creating an item
def test_done_value_can_be_set_to_True(self): item = Item(name = "A test item", done = True) self.assertEqual(item.name, "A test item") self.assertTrue(item.done)
[ "def test_done_default_value_is_False(self):\n item = Item(name = \"A test item\")\n self.assertEqual(item.name, \"A test item\")\n self.assertFalse(item.done)", "def done_item(self) -> None:\n pass", "def test_mark_post_process_complete_create(self):\n pass", "def test_done...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Ensure the string value of the object is equal to the item name
def test_object_name_is_equal_to_item_name(self): item = Item(name = "A test item") self.assertEqual(str(item), "A test item")
[ "def _valid_object_with_name(ui_object):\n return ui_object.obj_name", "def check_name(self, check_obj, schema):\n raise NotImplementedError", "def test_name(self):\n node = self.create(ObjectNodeItem, UML.ObjectNode)\n name = node.shape.icon.children[1]\n\n node.subject.name = \"Bl...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Create a postvalidator function that makes sure the value of this item is a key in the sibling dictionary 'sib_name'. Raises a ValueError if not. This generally assumes siblings[sib_name] is a required CategoryElement.
def is_sib_key(sib_name): def is_sib_key_val(siblings, value): if value not in siblings[sib_name].keys(): raise ValueError( "Must be a key of {}, but got {}" .format(sib_name, value)) return value return is_sib_key_val
[ "def check_items_slugs(cls, slugs, registry):\n for m in registry.items():\n for i in m[1]['items'].items():\n for slug in slugs:\n try:\n item = i[1]['_class'].objects.get(slug=slug)\n raise ItemAttributeChoicesSlugsD...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
get requirements file line.
def get_line(self): # type: () -> str line = "{}=={}".format(self.name, self.version) if self.type != RequirementType.LATEST_VERSION: line += ' # ' + TEMPLATES[self.type] if self.type == RequirementType.NOT_LATEST_VERSION: line = line.replace(r'(\S*)', sel...
[ "def get_line(self, path, line):\n\t\tlines = self.find_source(path)\n\t\tif lines == None:\n\t\t\treturn None\n\t\telse:\n\t\t\ttry:\n\t\t\t\treturn lines[line - 1]\n\t\t\texcept IndexError:\n\t\t\t\treturn None", "def requirements(self):\n requirements_txt = path.join(self.directory, \"requirements.txt\"...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Calculate cosine distance between two vector
def findCosineDistance(vector1, vector2): vec1 = vector1.flatten() vec2 = vector2.flatten() a = np.dot(vec1.T, vec2) b = np.dot(vec1.T, vec1) c = np.dot(vec2.T, vec2) return 1 - (a / (np.sqrt(b) * np.sqrt(c)))
[ "def cosine_dist(v1, v2):\n n1 = np.sqrt(np.sum(v1 ** 2) + SMALL)\n n2 = np.sqrt(np.sum(v2 ** 2) + SMALL)\n return 1 - (np.dot(v1, v2) / (n1 * n2))", "def findCosineDistance(vector1, vector2):\n vec1 = vector1.flatten()\n vec2 = vector2.flatten()\n\n a = np.dot(vec1.T, vec2)\n b = np.dot(vec1...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Add index operation with name to the operations given.
def add_index_operation(self, name, operations): if name not in self._index_operations: self._add_io(name, operations) else: raise AttributeError("An index operation with the name {} was already taken".format(name))
[ "def add_index(self, name, func):\n assert name not in self.indices\n info_name = 'index:%s:%s' % (self.info['name'], name)\n info = self.store._get_info(info_name, index_for=self.info['name'])\n index = Index(self, info, func)\n self.indices[name] = index\n if IndexKeyBuil...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Return the offset of the param inside this parameterized object. This does not need to account for shaped parameters, as it basically just sums up the parameter sizes which come before param.
def _offset_for(self, param): if param.has_parent(): p = param._parent_._get_original(param) if p in self.parameters: return reduce(lambda a,b: a + b.size, self.parameters[:p._parent_index_], 0) return self._offset_for(param._parent_) + param._parent_._offset_...
[ "def offset(self):\n\n if 'offset' in self:\n return self['offset']\n else:\n return None", "def Offset(self) -> int:", "def get_position_offset_and_size(self, field):\n\n if field not in self._fields:\n return None\n\n out = 0\n for fld in sel...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
get the raveled index for a param that is an int array, containing the indexes for the flattened param inside this parameterized logic. !Warning! be sure to call this method on the highest parent of a hierarchy, as it uses the fixes to do its work
def _raveled_index_for(self, param): from ..param import ParamConcatenation if isinstance(param, ParamConcatenation): return np.hstack((self._raveled_index_for(p) for p in param.params)) return param._raveled_index() + self._offset_for(param)
[ "def _raveled_index_for(self, param):\n from .param import ParamConcatenation\n if isinstance(param, ParamConcatenation):\n return np.hstack((self._raveled_index_for(p) for p in param.params))\n return param._raveled_index() + self._offset_for(param)", "def getArrayIndices(self):\n...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Helper preventing copy code. This adds the given what (transformation, prior etc) to parameter index operations which. reconstrained are reconstrained indices. warn when reconstraining parameters if warning is True.
def _add_to_index_operations(self, which, reconstrained, what, warning): if warning and reconstrained.size > 0: # TODO: figure out which parameters have changed and only print those print("WARNING: reconstraining parameters {}".format(self.hierarchy_name() or self.name)) index = ...
[ "def ensure_default_constraints(self,warn=False):\n positive_strings = ['variance','lengthscale', 'precision']\n for s in positive_strings:\n for i in self.grep_param_names(s):\n if not (i in self.all_constrained_indices()):\n name = self._get_param_names()...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Helper preventing copy code. Remove given what (transform prior etc) from which param index ops.
def _remove_from_index_operations(self, which, transforms): if len(transforms) == 0: transforms = which.properties() removed = np.empty((0,), dtype=int) for t in list(transforms): unconstrained = which.remove(t, self._raveled_index()) removed = np.union1d(remo...
[ "def _remove_operator(self, operator):", "def remove_extra_index_from_context_actions(context_action_dict):\n keys_to_keep = {'initial_value', 'replacement_value'}\n for question in context_action_dict:\n for obj_dct in context_action_dict[question]:\n total_keys = set(obj_dct.keys())\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Emit a JSON representation of a given row
def format(self, row): return json.dumps(row.print_fields)
[ "def row_to_json(row: sqlite3.Row) -> str:\n d = {}\n for key in row.keys():\n d[key] = row[key]\n\n return json.dumps(d)", "def __data_row_to_json(self, row):\n raw_data = {}\n raw_data[\"body\"] = row.body\n raw_data[\"score_hidden\"] = row.score_hidden\n raw_data[\"a...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Creates a dictonary of nodes listed by currie id from answers 1 and 2
def make_node_dict(self): if self.input1 is None or self.input2 is None: raise Exception("Missing input: please run the populate() method first") self.node_dict1 = {} for node in self.input1['knowledge_graph']['nodes']: self.node_dict1[node['id']] = node self.node...
[ "def get_nodes_by_id(ntwrk, nodeid):\r\n return {k: v for el in ntwrk\r\n for k, v in el.items() if k == nodeid}", "def node_diff(self):\n if self.input1 is None or self.input2 is None:\n raise Exception(\"Missing input: please run the populate() method first\")\n if s...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Runs through all of the nodes in the json responses storing the intersection and set differences into a dictonary organized by tuples of node ids or the tuple (1, 1) for all nodes.
def node_diff(self): if self.input1 is None or self.input2 is None: raise Exception("Missing input: please run the populate() method first") if self.node_dict1 is None or self.node_dict2 is None: self.make_node_dict() # Initialize dictonaries to keep track of the nodes in...
[ "def get_nodes_edges(response_json):\n\n nodes = dict()\n paths = dict()\n\n for element in response_json['elements']:\n if element['type'] == \"node\":\n nodes[element['id']] = convert_node(element)\n elif element['type'] == \"way\":\n paths[element['id']] = convert_edg...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Reproducing kernel Calculate the inverse FunkRadon transform of reproducing kernel for the space of spherical harmonics of maximum degree N.
def inv_funk_radon_kernel(mu, N): # Check that -1 <= mu <= 1 mu = np.clip(mu, -1, 1) # Need Legendre polynomials legPolys = legp(mu, N) p_at_zero = legp(0, N) coefs = 2*np.arange(0, N+1, 2) + 1 ker = coefs*legPolys[::2]/p_at_zero[::2] return ker.sum() / (8*np.pi)
[ "def inv_funk_radon_even_kernel(mu, N):\n A = np.zeros_like(mu)\n\n for k in range(2, N + 1, 2):\n Pk = sp.special.legendre(k)\n A += (2 * k + 1) / (8 * np.pi**2 * Pk(0) * k * (k + 1)) * Pk(mu)\n\n return A", "def inv_funk_radon_even_kernel(mu, N):\n\n # Check that -1 <= mu <= 1\n mu ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Reproducing kernel Calculate inverse FunkRadon transform and inverse spherical Laplacian of reproducing kernel for even degree subspace of spherical harmonics of maximum degree N, i.e., calculates H(\mu) = \Delta^1 G^1 K_e(\mu), where \Delta is the spherical Laplacian and G is the FunkRadon transporm. The calculation i...
def inv_funk_radon_even_kernel(mu, N): # Check that -1 <= mu <= 1 mu = np.clip(mu, -1, 1) # Need Legendre polynomials legPolys = legp(mu, N) p_at_zero = legp(0, N) coefs_num = 2*np.arange(0, N+1) + 1 coefs_den = np.arange(2,N+1,2) * (np.arange(2,N+1,2) + 1) ker = coefs_num[2::2]*legP...
[ "def inv_funk_radon_even_kernel(mu, N):\n A = np.zeros_like(mu)\n\n for k in range(2, N + 1, 2):\n Pk = sp.special.legendre(k)\n A += (2 * k + 1) / (8 * np.pi**2 * Pk(0) * k * (k + 1)) * Pk(mu)\n\n return A", "def inv_funk_radon_kernel(mu, N):\n\n # Check that -1 <= mu <= 1\n mu = np....
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Reproducing kernel Calculate of reproducing kernel for even subspace of spherical harmonics of maximum degree N.
def even_kernel(mu, N): # Check that -1 <= mu <= 1 mu = np.clip(mu, -1, 1) # Need Legendre polynomials legPolys = legp(mu, N) coefs = 2*np.arange(0, N+1) + 1 ker = coefs[0::2]*legPolys[0::2] return ker.sum() / (4.0*np.pi)
[ "def even_kernel(mu, N):\n A = np.zeros_like(mu)\n\n for k in range(2, N + 1, 2):\n Pk = sp.special.legendre(k)\n A += (2 * k + 1) / (4 * np.pi) * Pk(mu)\n\n return A", "def inv_funk_radon_even_kernel(mu, N):\n A = np.zeros_like(mu)\n\n for k in range(2, N + 1, 2):\n Pk = sp.sp...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Derivative of reproducing kernel on even subspaces of maximum degree N.
def even_kernel_der(mu, N): # Check that -1 <= mu <= 1 mu = np.clip(mu, -1, 1) #Derivatives of Legendre polynomials DlegPolys = legp_der(mu, N) coefs = 2*np.arange(0, N+1) + 1 ker = coefs[0::2]*DlegPolys[0::2] return ker.sum() / (4.0*np.pi)
[ "def even_kernel(mu, N):\n\n # Check that -1 <= mu <= 1\n mu = np.clip(mu, -1, 1)\n\n # Need Legendre polynomials\n legPolys = legp(mu, N)\n \n\n coefs = 2*np.arange(0, N+1) + 1\n \n ker = coefs[0::2]*legPolys[0::2] \n\n return ker.sum() / (4.0*np.pi)", "def inv_funk_radon_even_kernel(mu, ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns truncated iterated logarithm y = log( log(x) ) where if x<delta, x = delta and if 1delta < x, x = 1delta.
def ilog(x,delta): if(delta < x and x < 1.0 - delta): return np.log( -np.log(x) ) elif(x < delta): return np.log( -np.log(delta) ) else: return np.log( -np.log(1.0 - delta) )
[ "def log(x):\n\treturn log1p(x-1)", "def log(x):\r\n\r\n return math.log(x)", "def safelog(x):\n #return np.log(x)\n return np.log(np.clip(x,floor,np.inf))", "def diff_log(x):\n \n return np.diff(np.log(x)),np.log(x)[0]", "def diff_log(x):\n\n return np.diff(np.log(x)),np.log(x)[0]", "def _log...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Create a 3D rotation matrix for rotation about xaxis. (1 0 0 ) R(theta) = (0 cos(x) sin(x)) (0 sin(x) cos(x))
def rotation3Dx(theta): rmat = np.zeros((3,3)) rmat[0,0], rmat[0,1], rmat[0,2] = 1.0, 0.0, 0.0 rmat[1,0], rmat[1,1], rmat[1,2] = 0.0, np.cos(theta), np.sin(theta) rmat[2,0], rmat[2,1], rmat[2,2] = 0.0, -np.sin(theta), np.cos(theta) return rmat
[ "def matrix_rotate_3d_x(deg: float) -> np.matrix:\n from numpy import cos, sin, pi\n rad_x = -deg * pi/180\n c_x = cos(rad_x)\n s_x = sin(rad_x)\n return np.matrix([[1, 0, 0], [0, c_x, -s_x], [0, s_x, c_x]])", "def rotation3D_x(angle: float) -> np.array:\n c = np.cos(angle)\n s = np.sin(angle...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Create a 3D rotation matrix for rotation about zaxis. ( cos(x) sin(x) 0) R(theta) = (sin(x) cos(x) 0) ( 0 0 1)
def rotation3Dz(theta): rmat = np.zeros((3,3)) rmat[0,0] = rmat[1,1] = np.cos(theta) rmat[0,1] = np.sin(theta) rmat[1,0] = -rmat[0,1] rmat[2,2] = 1 return rmat
[ "def matrix_rotate_3d_z(deg: float) -> np.matrix:\n from numpy import cos, sin, pi\n rad_z = -deg * pi/180\n c_z = cos(rad_z)\n s_z = sin(rad_z)\n return np.matrix([[c_z, -s_z, 0], [s_z, c_z, 0], [0, 0, 1]])", "def make_rotation_z(angle):\n return Mat4(\n [\n [math.cos(angle), ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Compute the geodesic distance on the sphere for two points. The points are assumed to lie on the surface of the same sphere.
def spherical_distances(x, y): # Compute the norms of all points, we do NOT check they actually all lie on # the same sphere (that's the caller's responsibility). xn = np.sqrt((x**2).sum(axis=1)) yn = np.sqrt((y**2).sum(axis=1)) ang_cos = np.dot(x, y.T)/(xn[:, None]*yn[None, :]) # Protect a...
[ "def spherical_distance(lat1: u.deg, lon1: u.deg, lat2: u.deg, lon2: u.deg):\n\n lat1m, lat2m = np.meshgrid(lat1, lat2)\n lon1m, lon2m = np.meshgrid(lon1, lon2)\n\n lat_dif = lat1m - lat2m\n lon_dif = lon1m - lon2m\n\n slatsq = np.sin(0.5 * lat_dif)**2\n slonsq = np.sin(0.5 * lon_dif)**2\n spsi...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Compute a similarity matrix for a set of points. The points are assumed to lie on the surface of the same sphere.
def similarity_matrix(points, sigma): distances_squared = spherical_distances(points, points)**2 return np.exp( -distances_squared / (2.0 * sigma) )
[ "def dists_on_sphere(x):\n k = x.shape[0]\n dist_mat = np.zeros((k, k))\n for i in range(k):\n for j in range(k):\n if i == j:\n dist_mat[i, j] = -1\n else:\n dist_mat[i, j] = np.arccos(np.dot(x[i], x[j]))**2\n return dist_mat", "def self_simi...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Decorator to help verify that a function was actually executed. Annotates a function with an attribute 'didrun', and only sets it to True if the function is actually called.
def checkrun(f): @functools.wraps(f) def wrapper(*args, **kwargs): wrapper.didrun = True return f(*args, **kwargs) wrapper.didrun = False return wrapper
[ "def _can_run(self, func):\n self.can_run = func", "def check_called(self, func):\n self.called[func] = False\n def _check(*args, **kwargs):\n self.called[func] = True\n return func(*args, **kwargs)\n return _check", "def expect_pass(self, func: Callable, *args,...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Users can specify environment variables in their config file which will be set in the driver and worker environments. Make sure those variables are set during the workflow, but not after.
def test_workflow_environment(): config = { "workflow-name": "workflow", "cluster-type": CLUSTER_TYPE, "environment-variables": { "FOO": "BAR", "FOO2": "BAR2" } } template_dir = tempfile.mkdtemp(suffix="test-workflow-environment-template") with...
[ "def setup_env():\n os.environ['AUTH_DOMAIN'] = \"appscale.com\"\n os.environ['USER_EMAIL'] = \"\"\n os.environ['USER_NICKNAME'] = \"\"\n os.environ['APPLICATION_ID'] = \"\"", "def env_config():\n # setup\n env = {'ELB_GCP_PROJECT': 'expected-gcp-project',\n 'ELB_GCP_REGION': 'expected-gcp-reg...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
The config can specify a resource manager server address as "driver", which means the workflow should launch the resource manager on the scheduler machine. Make sure it launches, but is also shut down after the workflow exits.
def test_resource_manager_on_driver(): config = { "workflow-name": "workflow", "cluster-type": CLUSTER_TYPE, "resource-manager": { "server": "driver", "port": 4000, "config": { "read_reqs": 123, "read_data": 456, ...
[ "def run(application_config):\n\n executor = init_executor(application_config)\n\n framework = mesos_pb2.FrameworkInfo()\n framework.user = \"\" # Have Mesos fill in the current user.\n framework.name = application_config['framework_name']\n logger = logging.getLogger(\"pisaura.scheduler\")\n sch...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
The config can specify a script to be run on each worker upon cluster initialization. This test verifies that it is launched and active while the workflow runs, and that it is launched on each worker, or just once per machine, depending on the config.
def test_worker_initialization(setup_worker_initialization_template): template_dir, _config, once_per_machine = setup_worker_initialization_template num_workers = 2 if once_per_machine or CLUSTER_TYPE in ("synchronous", "processes"): expected_script_count = 1 else: expected_script_c...
[ "def test_cluster_jobs_script(self):\r\n\r\n qiime_config = load_qiime_config()\r\n submit_script = qiime_config['cluster_jobs_fp']\r\n\r\n if (submit_script):\r\n full_path = which(submit_script)\r\n if full_path:\r\n submit_script = full_path\r\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
You can provide an initialization script for each worker to call before the workflow starts. The most common usecase for such a script is to launch a local dvid server on each worker (for posting in parallel to the cloud). We provide the necessary script for local dvid workers outofthebox, in scripts/workerdvid. This t...
def test_worker_dvid_initialization(): repo_dir = Path(flyemflows.__file__).parent.parent template_dir = tempfile.mkdtemp(suffix="test-worker-dvid") # Copy worker script/config into the template shutil.copy(f'{repo_dir}/scripts/worker-dvid/dvid.toml', f'{template_dir}/dvid.toml') ...
[ "def test_worker_initialization(setup_worker_initialization_template):\n template_dir, _config, once_per_machine = setup_worker_initialization_template\n \n num_workers = 2\n if once_per_machine or CLUSTER_TYPE in (\"synchronous\", \"processes\"):\n expected_script_count = 1\n else:\n e...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Return the next power of 10
def nextpow10(n): if n == 0: return 0 else: return math.ceil(math.log10(abs(n)))
[ "def nextpower (n, base = 2.0):\n x = base**np.ceil(np.log(n) / np.log(base))\n if type(n) == np.ndarray:\n return np.asarray (x, dtype=int)\n else:\n return int (x)", "def next_pow_two(n):\n i = 1\n while i < n:\n i = i << 1\n return i", "def _next_power_of_two(self, n):\...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Return a number that looks 'nice', with a maximum error
def magicnr(value, error): magics = [ (10 ** (nextpow10(error))), (10 ** (nextpow10(error))) / 2.0, (10 ** (nextpow10(error))) / 4.0, (10 ** (nextpow10(error))) / 10.0, (10 ** (nextpow10(error))) / 20.0, (10 ** (nextpow10(error))) / 40.0, (10 ** (nextpow10(error))) / 100.0, ] magi...
[ "def _get_precision(err):\n return max(0, int(-math.log10(2 * err)) + 1)", "def current_limit_error():\n raise ValueError(\"Current can not be higher than 0.1A\")", "def class_maximum_value(class_number):\n return (10 ** class_number - 1)", "def im_not_sleepy() -> str:\n digit_values = {0: 6, 1: 2...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Get the path to a CSV by name.
def _get_csv_path(name): return os.path.join(cwd, 'output/app_info', name)
[ "def csv_path(name):\n return \"./data/%s\" % name", "def songs_csv_file_path() -> Path:\n return data_dir_path().joinpath(\"songs.csv\")", "def __csvPath__(self):\n return \"%s/%s_%s_%s%s.csv\" % ( self.analysis_dir ,\n self.input_data.input_data.name ,\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Get the app's name.
def _get_app_name(app): return app[APP_NAME_KEY]
[ "def get_name():\n return config.APP_NAME", "def app_name(self) -> str:\n return self._app_name", "def app_name(self):\n return self._app_name", "def app_name(self):\n if getattr(self, \"_app_name\", None):\n return self._app_name\n return self.__class__.__name__.lowe...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Get the contact's first name.
def _get_contact_first_name(app): name = app.get(CONTACT_NAME_KEY) if name: return ' {}'.format(name.split(' ')[0])
[ "def first_name(self):\n return self._first_name", "def first_name(self, instance):\r\n return instance.user.first_name", "def user_first_name(self, instance):\n return instance.user.first_name", "def first_name_title(self):\n\t\tlocator = self._locator.FIRST_NAME_TITLE\n\t\treturn self.g...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Get the email template name for the first contact email.
def _get_first_contact_email_template_name(app): return app[FIRST_CONTACT_EMAIL_TEMPLATE_NAME_KEY]
[ "def get_template_name(self):\n template = None\n if self.template:\n template = self.template\n if not template:\n for p in self.get_ancestors(ascending=True):\n if p.template:\n template = p.template\n break\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Gets the tote store url for this app.
def _get_app_tote_store_url(app): return app[APP_TOTE_STORE_URL]
[ "def getNoteStoreUrl(self, authenticationToken):\r\n pass", "def getNoteStoreUrl(self, authenticationToken):\r\n self.send_getNoteStoreUrl(authenticationToken)\r\n return self.recv_getNoteStoreUrl()", "def get_store_path(cls):\n user_data_dir = cls.user_data_dir()\n store_path = os.path.j...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Check if we already sent the first contact email.
def _did_send_first_contact_email(app): first_contact = app[FIRST_CONTACT_EMAIL_SENT_KEY] if first_contact and first_contact.lower() == 'y': return True return False
[ "def is_first_message(self):\n return self._is_first_message", "def is_from_ourselves(self, email = None):\n\n\t\tif not email:\n\t\t\temail = self.get_sender()[1].lower()\n\n\t\tfor lvar in self.config.rc_mymails:\n\t\t\tif email in lvar.lower():\n\t\t\t\treturn 1\n\n\t\treturn 0", "def is_send_email(se...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Sends out emails to the apps in the provided csv.
def send(app_csv='apps.csv', verbose=True, dry_run=True): results = [] app_info = _csv_to_dict(app_csv) for app in app_info: # Get all the app info needed for this request. app_name = _get_app_name(app) contact_first_name = _get_contact_first_name(app) email_address = _get_co...
[ "def send_email(self):\n server = self.config_smtp_server()\n contacts = open('contacts.csv', 'rb')\n reader = csv.DictReader(contacts)\n for person_details in reader:\n to_email = person_details['email']\n message = self.compose_message(person_details).as_string()\...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
writes data from instream into additional allocated clusters of given file. Metadata of this file will be stored in Metadata object
def write(self, instream: typ.BinaryIO, filepath: str, filename: str = None) -> None: if filename is not None: filename = path.basename(filename) if self.fs_type == 'FAT': allocator_metadata = self.fs.write(instream, filepath) self.metadata.add_fil...
[ "def addFileToInfos(self, infos):\n with open(self.loc, 'rb') as fhandle:\n pos = 0L\n piece_length = 0\n for info in infos:\n piece_length = max(piece_length, info.hasher.pieceLength)\n info.add_file_info(self.size, self.path)\n\n whi...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
clears the slackspace of files. Information of them is stored in metadata.
def clear(self): if self.fs_type == 'FAT': for file_entry in self.metadata.get_files(): file_metadata = file_entry['metadata'] file_metadata = FATAllocatorMeta(file_metadata) self.fs.clear(file_metadata) elif self.fs_type == 'NTFS': ...
[ "def clean_files(self):\n self.filenames.clear()", "def clear(self):\n self.statistics['maxSize'].clear()\n self.statistics['minSize'].clear()\n self.statistics['avgSize'].clear()\n self.statistics['sumSize'].clear()\n self.statisti...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Sets the namespace_name of this ClairpbVulnerability.
def namespace_name(self, namespace_name): self._namespace_name = namespace_name
[ "def namespace_name(self, namespace_name):\n self._namespace_name = namespace_name", "def set_namespace(self, namespace: str) -> None:\n self._namespace = namespace", "def namespace(self, namespace: str):\n\n self._namespace = namespace", "def name_space(self, name_space: str):\n\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Sets the severity of this ClairpbVulnerability.
def severity(self, severity): self._severity = severity
[ "def severity(self, severity):\n self._severity = severity", "def severity_level(self, severity_level):\n self._severity_level = severity_level", "def issue_change_severity(self, issue, severity):", "def severity(self) -> pulumi.Input[int]:\n return pulumi.get(self, \"severity\")", "def...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Sets the fixed_by of this ClairpbVulnerability.
def fixed_by(self, fixed_by): self._fixed_by = fixed_by
[ "def caused_by(self, caused_by):\n\n self._caused_by = caused_by", "def resolved_by(self, resolved_by):\n\n self._resolved_by = resolved_by", "def fixed_fee(self, fixed_fee):\n\n self._fixed_fee = fixed_fee", "def fixed_amount(self, fixed_amount):\n\n self._fixed_amount = fixed_amo...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Sets the affected_versions of this ClairpbVulnerability.
def affected_versions(self, affected_versions): self._affected_versions = affected_versions
[ "def vulnerabilities(self, vulnerabilities):\n\n self._vulnerabilities = vulnerabilities", "def versions(self, versions):\n self.__versions = versions", "def versions(self, versions):\n\n self._versions = versions", "def set_versions(self, consumer, versions):\n for resource_type, ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Optimizes the distribution of allocations for a set of stock symbols.
def optimize_portfolio(sd=dt.datetime(2008,1,1), ed=dt.datetime(2009,1,1), \ syms=['GOOG','AAPL','GLD','XOM'], gen_plot=False): # Read in adjusted closing prices for given symbols, date range dates = pd.date_range(sd, ed) prices_all = get_data(syms, dates) # automatically adds SPY prices = prices_...
[ "def find_optimal_allocations(prices):\n new_prices = prices.copy()\n noa = len(new_prices.keys())\n global df\n df = prices.copy()\n cons =({ 'type': 'ineq', 'fun': lambda inputs: 1.0 - np.sum(abs(inputs)) })\n bnds = tuple((0,1) for x in range(noa))\n weights = np.random.random(noa)\n weig...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Given a starting value and prices of stocks in portfolio with allocations return the portfolio value over time.
def get_portfolio_value(prices, allocs, start_val): normed = prices/prices.iloc[0] alloced = np.multiply(allocs, normed) pos_vals = alloced * start_val port_val = pos_vals.sum(axis=1) return port_val
[ "def get_portfolio_value(prices, allocs, start_val=1):\n # TODO: Your code here\n normed = prices/prices.ix[0,:]\n alloced = normed * allocs\n pos_vals = alloced * start_val\n port_val = pos_vals.sum(axis=1)\n return port_val", "def compute_portvals(start_date, end_date, orders_file, start_val):...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Calculate sharpe ratio for minimizer.
def get_sharpe_ratio(allocs, prices): port_val = get_portfolio_value(prices, allocs, start_val=1.0) sharpe_ratio = get_portfolio_stats(port_val, daily_rf=0.0, samples_per_year=252)[3] return -sharpe_ratio
[ "def sharpe_ratio(returns):\n sr = annualized_returns(returns) / annualized_risk(returns)\n return sr.rename('Sharpe Ratio')", "def spRatio(spFront, spRear):\r\n spRatio = spRear / spFront\r\n return spRatio", "def foundation_shear_reduction_factor():\n # According to Millen (2016)\n r...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Creates a SnowflakeSource from a protobuf representation of a SnowflakeSource.
def from_proto(data_source: DataSourceProto): return SnowflakeSource( field_mapping=dict(data_source.field_mapping), database=data_source.snowflake_options.database, schema=data_source.snowflake_options.schema, table=data_source.snowflake_options.table, ...
[ "def FromProto(cls, proto_obj):\n source = GameSource()\n source.type = proto_obj.type\n if proto_obj.update_time_utc_str:\n source.update_date_time = datetime.strptime(\n proto_obj.update_time_utc_str, tweets.DATE_PARSE_FMT_STR)\n else:\n source.update_date_time = datetime.now()\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns the database of this snowflake source.
def database(self): return self.snowflake_options.database
[ "def source_db(self):\n return self._source_db", "def target_db(self):\n return self._target_db", "def replicate_source_db(self) -> str:\n return pulumi.get(self, \"replicate_source_db\")", "def source_db_info(self):\n return self._source_db_info", "def database_name(self) -> str...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns the schema of this snowflake source.
def schema(self): return self.snowflake_options.schema
[ "def schema(self):\n return self.table_info.schema", "def schema(self):\n if not self._schema:\n response = self.api.make_request('GET', '%s/schema' % self.path)\n self._schema = response.data\n \n return self._schema", "def schema(self):\n return sel...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns the table of this snowflake source.
def table(self): return self.snowflake_options.table
[ "def parse_source_table(self):\n name = self.control.source_name\n table = self._parse_source_table(name)\n return table", "def source_table_name(self):\n return self._source_table_name", "def source_tables(self):\n return self._source_tables", "def table(self):\n ret...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Converts a SnowflakeSource object to its protobuf representation.
def to_proto(self) -> DataSourceProto: data_source_proto = DataSourceProto( type=DataSourceProto.BATCH_SNOWFLAKE, field_mapping=self.field_mapping, snowflake_options=self.snowflake_options.to_proto(), ) data_source_proto.event_timestamp_column = self.event_ti...
[ "def from_proto(data_source: DataSourceProto):\n return SnowflakeSource(\n field_mapping=dict(data_source.field_mapping),\n database=data_source.snowflake_options.database,\n schema=data_source.snowflake_options.schema,\n table=data_source.snowflake_options.table,\...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns a string that can directly be used to reference this table in SQL.
def get_table_query_string(self) -> str: if self.database and self.table: return f'"{self.database}"."{self.schema}"."{self.table}"' elif self.table: return f'"{self.table}"' else: return f"({self.query})"
[ "def get_table_query_string(self) -> str:\n return f\"`{self.table_ref}`\"", "def get_table_query_string(self) -> str:\n if self.table_ref:\n return f\"`{self.table_ref}`\"\n else:\n return f\"({self.query})\"", "def table_name() -> str:\n pass", "def table_na...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Creates a SnowflakeOptions from a protobuf representation of a snowflake option.
def from_proto(cls, snowflake_options_proto: DataSourceProto.SnowflakeOptions): snowflake_options = cls( database=snowflake_options_proto.database, schema=snowflake_options_proto.schema, table=snowflake_options_proto.table, query=snowflake_options_proto.query, ...
[ "def to_proto(self) -> DataSourceProto.SnowflakeOptions:\n snowflake_options_proto = DataSourceProto.SnowflakeOptions(\n database=self.database,\n schema=self.schema,\n table=self.table,\n query=self.query,\n )\n\n return snowflake_options_proto", "...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Converts an SnowflakeOptionsProto object to its protobuf representation.
def to_proto(self) -> DataSourceProto.SnowflakeOptions: snowflake_options_proto = DataSourceProto.SnowflakeOptions( database=self.database, schema=self.schema, table=self.table, query=self.query, ) return snowflake_options_proto
[ "def to_proto(self) -> DataSourceProto.KafkaOptions:\n\n kafka_options_proto = DataSourceProto.KafkaOptions(\n bootstrap_servers=self.bootstrap_servers,\n message_format=self.message_format.to_proto(),\n topic=self.topic,\n )\n\n return kafka_options_proto", "...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Given a dict of lang>names, return a default one
def primary_name(names): langs = names.keys() if 'en' in langs: return names['en'] return names[langs[0]]
[ "def get_default_language():\r\n lang = getattr(settings, 'SOURCE_LANGUAGE_CODE', settings.LANGUAGE_CODE)\r\n default = [l[0] for l in settings.LANGUAGES if l[0] == lang]\r\n if len(default) == 0:\r\n # when not found, take first part ('en' instead of 'en-us')\r\n lang = lang.split('-')[0]\r\...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Initializes an instance of the InstagramBot class.
def __init__(self, username = None, password = None): self.username = config['AUTH']['USERNAME'] self.password = config['AUTH']['PASSWORD'] self.login = config['URL']['LOGIN'] self.nav_url = config['URL']['NAV'] self.tag_url = config['URL']['TAGS'] self.direct_url = confi...
[ "def start(self):\r\n self._instagram_api = InstagramAPI(mongo_api=self._mongo_api)\r\n self._inst_run()", "def __init__(self):\n self._attack_counter = 0\n self._attempt_counter = 0\n # initiliazing botnet client unique id\n self._botnet_identity = str(abs(hash(os.path....
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Method gets a list of users who like a post
def get_likes_list(self, username): api = self.api api.searchUsername(username) result = api.LastJson username_id = result['user']['pk'] #Gets the user ID user_posts = api.getUserFeed(username_id) # gets the user feed result = api.LastJson ...
[ "def get_user_likes(self, data_base):\n cursor = data_base.cursor(dictionary=True)\n cursor.execute(f\"SELECT user_id FROM user_like WHERE post_id = {self.id}\")\n user_likes = tuple(map(lambda x: str(x['user_id']), cursor.fetchall()))\n if not user_likes:\n return []\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }