query
stringlengths
9
9.05k
document
stringlengths
10
222k
negatives
listlengths
19
20
metadata
dict
Gets the current explain_level
def _get_explain_level(self): self._validate_explain_level() if self.explain_level == "auto": if self._get_mode() == "Explain": return 2 if self._get_mode() == "Perform": return 1 if self._get_mode() == "Compete": return 0 if self._get_mode() == "Optuna": return 0 else: return deepcopy(self.explain_level)
[ "def help_explain(self):\n print(EXPLAIN)", "def expert_level(self) -> int:\n return self._expert_level", "def getLevel(self):\n return _libsbml.ASTBasePlugin_getLevel(self)", "def verbose_level(self):\n return self._verbose_level", "def ColorfulPyPrint_current_verbose_level():\r...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Gets the current features_selection
def _get_features_selection(self): self._validate_features_selection() if self.features_selection == "auto": if self._get_mode() == "Explain": return False if self._get_mode() == "Perform": return True if self._get_mode() == "Compete": return True if self._get_mode() == "Optuna": return False else: return deepcopy(self.features_selection)
[ "def selected_feature(self):\n return self._selected_feature", "def GetSelection(self):\r\n\r\n return self._current", "def getSelection(self): # real signature unknown; restored from __doc__\r\n pass", "def get_selection(self):\r\n return self.value", "def active_selection():\r\...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Gets the current start_random_models
def _get_start_random_models(self): self._validate_start_random_models() if self.start_random_models == "auto": if self._get_mode() == "Explain": return 1 if self._get_mode() == "Perform": return 5 if self._get_mode() == "Compete": return 10 if self._get_mode() == "Optuna": return 1 # just 1, because it will be tuned by Optuna else: return deepcopy(self.start_random_models)
[ "def get_start_maybe_randomised(self):\n if self.randomise:\n return random.uniform(0, self.start)\n else:\n return self.start\n # return (random.uniform(0, self.start) if self.random else self.start)", "def generate_nnmodels(self):\n return []", "def get_random...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Gets the current hill_climbing_steps
def _get_hill_climbing_steps(self): self._validate_hill_climbing_steps() if self.hill_climbing_steps == "auto": if self._get_mode() == "Explain": return 0 if self._get_mode() == "Perform": return 2 if self._get_mode() == "Compete": return 2 if self._get_mode() == "Optuna": return 0 # all tuning is done in Optuna else: return deepcopy(self.hill_climbing_steps)
[ "def getSteps( self ):\n\n return self.adb.get( 'steps' )", "def start_steps(self):\n return self._start_steps[:]", "def bootstrap_steps(self):\n return self._bootstrap_steps", "def get_workflow_steps(self):\n return self._data_dict[self.KEY_WF_ST...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Gets the current top_models_to_improve
def _get_top_models_to_improve(self): self._validate_top_models_to_improve() if self.top_models_to_improve == "auto": if self._get_mode() == "Explain": return 0 if self._get_mode() == "Perform": return 2 if self._get_mode() == "Compete": return 3 if self._get_mode() == "Optuna": return 0 else: return deepcopy(self.top_models_to_improve)
[ "def getTopModel(self):\n top = self.model\n while top.parent is not None:\n top = top.parent\n return top", "def best_model(self):\n return self.best_model_wts", "def top(self):", "def get_best_known_model(self) -> Tuple[Optional[Path], int]:\n return self._get_f...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Gets the current boost_on_errors
def _get_boost_on_errors(self): self._validate_boost_on_errors() if self.boost_on_errors == "auto": val = self._get_validation_strategy() if val.get("validation_type", "") == "custom": return False if self._get_mode() == "Explain": return False if self._get_mode() == "Perform": return False if self._get_mode() == "Compete": return True if self._get_mode() == "Optuna": return False else: return deepcopy(self.boost_on_errors)
[ "def on_errors(self):\n return self._on_errors", "def get_errors(self):\n return {'loss': self.loss.data[0]}", "def import_errors(self):\n return self._import_errors", "def get_script_errors(self):\r\n return self._script_errors", "def error(self):\n try:\n retu...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Gets the current kmeans_features
def _get_kmeans_features(self): self._validate_kmeans_features() if self.kmeans_features == "auto": if self._get_mode() == "Explain": return False if self._get_mode() == "Perform": return False if self._get_mode() == "Compete": return True if self._get_mode() == "Optuna": return False else: return deepcopy(self.kmeans_features)
[ "def k_means(self):\n raise NotImplementedError()", "def get_features(self):\n return self.features", "def get_features(self):\n if self.strokes is False:\n print('Isolating strokes')\n self.isolate_strokes()\n # List of features to use (sm1 omitted because alwa...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Gets the current max_single_prediction_time
def _get_max_single_prediction_time(self): self._validate_max_single_prediction_time() if self.max_single_prediction_time is None: if self._get_mode() == "Perform": return 0.5 # prediction time should be under 0.5 second return None else: return deepcopy(self.max_single_prediction_time)
[ "def max_time(self):\n #{{{ function to return time of last sample\n\n if self.maxtime == -1:\n return stock.now()\n\n return self.maxtime", "def max_time(self):\n return self.time[np.argmax(self.flux)]", "def max_time(self) -> float:\r\n if(len(self.operations_by_name)...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Gets the current optuna_time_budget
def _get_optuna_time_budget(self): self._validate_optuna_time_budget() if self.optuna_time_budget is None: if self._get_mode() == "Optuna": return 3600 return None else: if self._get_mode() != "Optuna": # use only for mode Optuna return None return deepcopy(self.optuna_time_budget)
[ "def budget(self):\n return self._budget", "def get_current_goal(self):\n if self.agenda is None or len(self.agenda) == 0:\n return None\n return self.agenda[0]", "def get_best_time():\n return best_reaction_time", "def lagtime(self):\n return self._tau", "def getSe...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Gets the current optuna_init_params
def _get_optuna_init_params(self): self._validate_optuna_init_params() if self._get_mode() != "Optuna": # use only for mode Optuna return {} return deepcopy(self.optuna_init_params)
[ "def getInitParams(self):\n paramDict = Distribution.getInitParams(self)\n paramDict['mapping'] = self.mapping\n paramDict['values'] = self.values\n return paramDict", "def init_params(self):\n self.params = {p.title: p for p in\n chain(self.session.shared_params.values(),...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Gets the current optuna_verbose
def _get_optuna_verbose(self): self._validate_optuna_verbose() # use only for mode Optuna if self._get_mode() != "Optuna": return True return deepcopy(self.optuna_verbose)
[ "def isVerbose(self):\n return self.opts.verbose", "def is_verbose(self):\n return self._verbose", "def verbose():\n return Verbose.level()", "def getVerboseLevel(self):\n return self.__verboseLevel", "def verbose_level(self):\n return self._verbose_level", "def ColorfulPyPr...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Gets the current n_jobs
def _get_n_jobs(self): self._validate_n_jobs() return deepcopy(self.n_jobs)
[ "def get_n_jobs(self):\n return self.n_jobs", "def get_num_jobs(self):\n return self._config.get_num_jobs()", "def effective_n_jobs(n_jobs=-1):\n if n_jobs == 1:\n return 1\n\n backend, backend_n_jobs = get_active_backend()\n if n_jobs is None:\n n_jobs = backend_n_jobs\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Gets the current random_state
def _get_random_state(self): self._validate_random_state() return deepcopy(self.random_state)
[ "def random_state(self):\n return self._random.get_state()", "def random_state(self):\n return self.__random_state", "def random_state(self):\n return self._distribution.random_state", "def get_state():\n return torch.get_rng_state(), random.getstate(), np.random.get_state()", "def r...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Gets the fairness metric
def _get_fairness_metric(self): self._validate_fairness_metric() if self.fairness_metric == "auto": if self._get_ml_task() == BINARY_CLASSIFICATION: return "demographic_parity_ratio" if self._get_ml_task() == REGRESSION: return "group_loss_ratio" if self._get_ml_task() == MULTICLASS_CLASSIFICATION: return "demographic_parity_ratio" else: return deepcopy(self.fairness_metric)
[ "def _get_fairness_threshold(self):\n if self.fairness_threshold == \"auto\":\n if self._get_ml_task() in [\n BINARY_CLASSIFICATION,\n MULTICLASS_CLASSIFICATION,\n ]:\n thresholds = {\n \"demographic_parity_difference\": 0....
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Gets the fairness threshold
def _get_fairness_threshold(self): if self.fairness_threshold == "auto": if self._get_ml_task() in [ BINARY_CLASSIFICATION, MULTICLASS_CLASSIFICATION, ]: thresholds = { "demographic_parity_difference": 0.1, "demographic_parity_ratio": 0.8, "equalized_odds_difference": 0.1, "equalized_odds_ratio": 0.8, } return thresholds.get(self._fairness_metric, 0.8) elif self._get_ml_task() == REGRESSION: thresholds = { "group_loss_ratio": 0.8, } if self._fairness_metric == "group_loss_difference": raise AutoMLException( "We can't set default fairness threshold value. Please set `fairness_threshold` value in AutoML constructor." ) return thresholds.get(self._fairness_metric, 0.8) else: return deepcopy(self.fairness_threshold)
[ "def threshold(self) -> float:\n return pulumi.get(self, \"threshold\")", "def get_best_threshold(ensemble_model):\n train_gen, val_gen = get_generators()\n\n # Add metrics\n ensemble_model.compile(loss='binary_crossentropy', optimizer=get_optimizer(), metrics=get_metric(scan=True))\n preds_tes...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Gets privileged groups for fair training
def _get_privileged_groups(self): if self.privileged_groups == "auto": return [] else: return deepcopy(self.privileged_groups)
[ "def _get_underprivileged_groups(self):\n if self.underprivileged_groups == \"auto\":\n return []\n else:\n return deepcopy(self.underprivileged_groups)", "def test_aws_service_api_security_groups_get(self):\n pass", "def test_get_groups(self):\n pass", "def g...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Gets underprivileged groups for fair training
def _get_underprivileged_groups(self): if self.underprivileged_groups == "auto": return [] else: return deepcopy(self.underprivileged_groups)
[ "def _get_privileged_groups(self):\n if self.privileged_groups == \"auto\":\n return []\n else:\n return deepcopy(self.privileged_groups)", "def test_aws_service_api_security_groups_get(self):\n pass", "def test_get_groups(self):\n pass", "def _identify_groups...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Download log files from remote machines on local machine via ssh
def __download_via_ssh(cls, request, local_path): hosts = request.POST.getlist('hosts[]') logs = request.POST.getlist('logs[]') if not os.path.exists(local_path): os.makedirs(local_path) for host_name in hosts: host_object = Host.objects.get(host_name=host_name) host_path = os.path.join(local_path, host_name) if not os.path.exists(host_path): os.makedirs(host_path) for log_name in logs: log_object = Log.objects.get(log_name=log_name) help_methods.get_file_via_ssh( getattr(log_object, 'log_path'), host_path, getattr(host_object, 'host_name'), getattr(host_object, 'host_root_user'), getattr(host_object, 'host_root_password') )
[ "def get_logs():\n get(remote_path=\"/tmp/log_extracts.tar.gz\",\n local_path=\"/logs/new_log.tar.gz\")", "def PullLogs(ssh, log_files, download_folder):\n for log_file in log_files:\n target_file = os.path.join(download_folder, os.path.basename(log_file))\n ssh.ScpPullFile(log_file, ta...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Make an hashable representation of an object for hashlib
def hashable(obj): return bytes(str(obj), "utf-8")
[ "def hashable(obj):\n if not obj.__hash__:\n return str(obj)\n return obj", "def hash(obj):\n \n import hashlib\n import pickle\n \n sha = hashlib.sha256()\n sha.update(pickle.dumps(obj))\n \n return sha.hexdigest()", "def hash_object(cls, serialized_obj):\n hash_byte...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Ensure row data is valid This currently just checks that 2D arrays match the variable components.
def validate_row(row): subkeys = [INDEP, DEP] for subkey in subkeys: for k, v in row[subkey].items(): if v is None: continue if np.ndim(v) > 1: assert np.ndim(v) == 2 if 1 not in np.shape(v): assert isinstance(k, variable.Variable) assert k.components is not None assert len(k.components) in np.shape(v)
[ "def valid_data(self):\n return len(self.input_row_positions) > 1", "def validate(self, row):\n raise NotImplementedError", "def _check_input_data(self, data):\n\n if not isinstance(data, np.ndarray):\n raise TypeError('Input data must be a numpy array.')", "def validate_matrix...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Add a dictionary of dependent data
def add_dict(self, indep, dep): dfull = {IND: len(self), INDEP: indep.copy(), DEP: dep} validate_row(dfull) check_objects(dfull) if settings.CONVERT_SCALAR_ARRAYS: scalarise(dfull) if settings.PRINT_UPDATES: print(self.show([dfull])) self.append(dfull) self._combine(dfull)
[ "def add_dict(dictionary, context_name):", "def addDependent(location):", "def __add__(self, dt:DictTensor)->DictTensor:\n assert dt.device()==self.device()\n for k in dt.keys():\n assert not k in self.variables, (\n \"variable \" + k + \" already exists in the DictTensor...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Return a list of dictionaries that only contain values for keys
def exclusively(self, keys, lst=None): minimal = self.minimal() if lst is None else lst def make_exclusive(d, keys): dct = {} for k in keys: if k in d: dct[k] = d[k] else: dct[k] = -999 return dct lst = [] for d in minimal: dct = make_exclusive(d, keys) if len(dct) > 0: lst.append(dct) return lst
[ "def filter_dictionary(dictionary, keys):\n return {key: dictionary[key] for key in dictionary if key in keys}", "def minidict(self):\n return {k: v for k, v in self.dict().items() if v is not None}", "def filter_keys_out(items, keys):\n for key, value in items.items():\n if key in keys:\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Merge this Box with one or more other Box instances
def merge(self, box, in_place=True): if in_place: self._merge(box) else: base = self.copy() base._merge(box) return base
[ "def merge(self, other_box_list):\n self.boxes.append(other_box_list.boxes)\n self.filter()", "def merge(self, other):\n # merge containers with the same name\n for container in self._container_child_containers:\n lookup = {obj.name: obj for obj in getattr(self, container)}\...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Return unique key values
def unique(self, key, lst=None): d = self.find(key, lst) vals = set(d.values()) return sorted(list(vals))
[ "def unique_values(self):\n for key in self.metadb.unique_values():\n yield key, self.datadb[key]", "def distinct(self, key):\n return self.database.command({'distinct': self.name,\n 'key': key})['values']", "def unique_keys(self) -> List[str]:\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
The set methods must raise a ComponentsErrorEx in case of wrong mode
def test_wrong_mode(self): self.assertRaises(ComponentErrorsEx, self.dp.setRewindingMode, 'FOO')
[ "def setControlMode(self,mode,*args,**kwargs):\n raise NotImplementedError()", "def magic_xmode(self,parameter_s = ''):\n\n new_mode = parameter_s.strip().capitalize()\n try:\n self.InteractiveTB.set_mode(mode = new_mode)\n print 'Exception reporting mode:',self.Interact...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
collect docker logs from servers $ command is $ log_collector.py
def main(): global tar_file_descr help_msg = 'Usage: log_collector.py <all | host1[,host2,host3...]>' hosts = [] if len(sys.argv) == 2: if '-h' == sys.argv[1] or '--help' == sys.argv[1]: print(help_msg) sys.exit(0) elif 'all' == sys.argv[1]: # get logs from all hosts hosts = [] host_objs = CLIENT.host_get_all() for host_obj in host_objs: hosts.append(host_obj.name) else: # get logs from specified hosts hostnames = sys.argv[1].split(',') for host in hostnames: if host not in hosts: hosts.append(host) else: print(help_msg) sys.exit(1) # open tar file for storing logs fd, tar_path = tempfile.mkstemp(prefix='kolla_support_logs_', suffix='.tgz') os.close(fd) # avoid fd leak with tarfile.open(tar_path, 'w:gz') as tar_file_descr: # clear out old logs if os.path.exists(LOGDIR): shutil.rmtree(LOGDIR) os.mkdir(LOGDIR) # gather logs from selected hosts try: for host in hosts: get_logs_from_host(host) # tar up all the container logs tar_file_descr.add(LOGDIR, arcname='container_logs') finally: # remove uncompressed logs if os.path.exists(LOGDIR): shutil.rmtree(LOGDIR) # gather dump output from kolla-cli dump_kolla_info() print('Log collection complete. Logs are at %s' % tar_path)
[ "def collect():\n try:\n return subprocess.check_output([\n 'sudo', '/opt/tinypilot-privileged/scripts/collect-debug-logs', '-q'\n ])\n except subprocess.CalledProcessError as e:\n raise LogCollectionScriptFailedError(str(e)) from e", "def __get_docker_logs(self, containers):...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Read in labels from digitStruct.mat file to create a dict of image file name and corresponding labels
def read_labels(digitstruct_file): labels = dict() for dsObj in tdqm(yieldNextDigitStruct(digitstruct_file), ncols=50): image_labels = [] for bbox in dsObj.bboxList: image_labels.append(bbox.label) labels[dsObj.name] = image_labels return labels
[ "def _get_imagenet_as_dict(self):\n real_file_path = os.path.realpath(self.map_file)\n if not os.path.exists(real_file_path):\n raise IOError(\"map file {} not exists\".format(self.map_file))\n\n label_dict = {}\n with open(real_file_path) as fp:\n line = fp.readlin...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Construct a heap from a list of elements with priorities. Each element of the list must be in the form (Item, Priority).
def construct_heap(self, elems): for e in elems: self.n += 1 self.A.append(e) self.pos[e[0]] = self.n for i in range(self.n // 2, 0, -1): self.combine(i)
[ "def priority_queue():\n class PriorityElement:\n def __init__(self, value, weight):\n self.value = value\n self.weight = weight\n\n def __lt__(self, other):\n return self.weight < other.weight\n\n # The following will produce the exact same results\n priority...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Inserts the element elem with priority prio.
def insert(self, elem, prio): self.n += 1 self.A.append( (e,w) ) self.pos[e] = self.n i = self.n p = i // 2 self.insert_loop(i, p)
[ "def change_priority(self, elem, prio):\n pos = self.pos[elem]\n currPrio = self.A[pos][1]\n self.A[pos] = (elem, prio)\n if self.cmpFn(prio, currPrio):\n self.insert_loop(pos, pos // 2) # Up heapify\n else:\n self.combine(pos) # Down heapify", "def inser...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Changes the priority of the element elem to prio.
def change_priority(self, elem, prio): pos = self.pos[elem] currPrio = self.A[pos][1] self.A[pos] = (elem, prio) if self.cmpFn(prio, currPrio): self.insert_loop(pos, pos // 2) # Up heapify else: self.combine(pos) # Down heapify
[ "def reprioritize(self, priority, element):\r\n if element not in self.element_finder:\r\n raise ValueError(\"No such element in the priority queue.\")\r\n entry = self.element_finder[element]\r\n self.add_element(priority, element, entry[1])\r\n entry[1] = self.INVALID", "d...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Gets the priority of an element.
def get_priority(self, elem): pos = self.pos[elem] return self.A[pos][1]
[ "def getpriority(self, name):\n\t\tif name not in self:\n\t\t\treturn None\n\t\treturn self.attributes[name].priority", "def priority(node):\n return node.priority", "def get_priority(self, item):\n try:\n return self.set[item][0]\n except KeyError:\n print(\"Can't get...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Transcodes a file src to a file dest.
def transcode(self, src: Path, dest: Path) -> None: pass
[ "def copyFile( src, dest ):\n\tinFile = open( src, 'r' )\n\toutFile = open( dest, 'w' )\n\tfor line in inFile:\n\t\toutFile.write( line )\n\toutFile.close()\n\tinFile.close()", "def compressFile(source, target):\n data = cake.filesys.readFile(source)\n try:\n data = zlib.compress(data, 1)\n except zlib.erro...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Takes an integer below 1001 and converts it into english text. Ignore spaces and hyphens as the instructions require.
def int2text(integer): # Numbers 1-99 are handled by simply looking up words in the special_case # dictionary. if integer < 100: return digit2text(integer) elif integer < 1000: # If exactly some hundred, then just return the word for the hundred's # place and the word 'hundred' if integer%100 == 0: return digit2text(integer/100)+'hundred' # Otherwise return the word for the hundred's place, the word # 'hundredand' and do some composition to make the rest of the words. else: return digit2text(integer/100)+'hundredand'+\ digit2text(integer%100) # Special case for 1000. elif integer == 1000: return "onethousand"
[ "def english(number):\r\n if number == 0:\r\n return 'zero'\r\n word = ''\r\n for step in itertools.count():\r\n number, rest = divmod(number, 1000)\r\n word = format_num(en3(rest), step) + word\r\n if number == 0:\r\n return word.strip()", "def num_to_thaiword(numb...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Solves [a]{b} = {x} by Gauss elimination.
def gaussElimin(a,b): a=float64(a) b=float64(b) n=len(b) x=zeros((n,1),dtype=float) for k in range(n-1): for i in range(k+1,n): l=float(a[i][k])/a[k][k] a[i][k]=0 for j in range(k+1,n): a[i][j]=a[i][j]-l*a[k][j] b[i]=b[i]-l*b[k] x[n-1]=float(b[n-1])/a[n-1][n-1] for i in range(n-2,-1,-1): sum=b[i] for j in range(i+1,n): sum=sum-a[i][j]*x[j] x[i]=float(sum)/a[i][i] return x
[ "def gauss(A, b):\n n = len(A)\n\n A, b = forward_elimination(A, b, n)\n return back_substitution(A, b, n)", "def gaussian_elimination(A, b):\n n = len(b)\n # Join A and b\n ab = np.c_[A,b]\n # Gaussian Elimination\n for i in range(n-1):\n if ab[i,i] == 0:\n raise ZeroDiv...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Solves [L][U]{x} = b, where [a] = [L\U] is the matrix returned from LUdecomp.
def LUsolve(a,b): b=float64(b) n=len(b) LU=LUdecomp(a) y=zeros((n,1)) x=zeros((n,1)) y[0]=b[0] for i in range(1,n): sum=b[i] for j in range(i): sum=sum-LU[i][j]*y[j] y[i]=sum x[n-1]=float(y[n-1])/LU[n-1][n-1] for i in range(n-2,-1,-1): sum=y[i] for j in range(i+1,n): sum=sum-LU[i][j]*x[j] x[i]=float(sum)/LU[i][i] return x
[ "def LUsolve(B, Y):\n\n n = len(B)\n U = np.zeros_like(B)\n L = np.identity(n)\n\n for i in range(n):\n for j in range(i):\n L[i,j] = B[i,j]\n \n for k in range(i, n):\n U[i,k] = B[i,k]\n\n LL = np.concatenate((L, Y), axis=1)\n Z = forward_substitute(LL)\...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Constructs a Octave ResNet26 model.
def pre_act_oct_resnet26(pretrained=False, **kwargs): model = PreActOctResNet(Bottleneck, [2, 2, 2, 2], **kwargs) return model
[ "def create_embedding_net():\n # This is a resnet50 base model\n resnet_model = models.resnet50(pretrained=True)\n\n # Now modify the network layers\n resnet_model.fc = Identity()\n resnet_model.avgpool = Identity() \n #print(resnet_model)\n\n return resnet_model", "def resnet10(shortcut_t...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Constructs a Octave ResNet200 model.
def pre_act_oct_resnet200(pretrained=False, **kwargs): model = PreActOctResNet(Bottleneck, [3, 24, 36, 3], **kwargs) return model
[ "def resnet10(**kwargs):\n model = ResNet(BasicBlock, [1, 1, 1, 1], **kwargs)\n return model", "def create_embedding_net():\n # This is a resnet50 base model\n resnet_model = models.resnet50(pretrained=True)\n\n # Now modify the network layers\n resnet_model.fc = Identity()\n resnet_model.avg...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
The standard size of a tile sprite in 2D screen space.
def tile_size_2d(self): return 32.0, 32.0
[ "def tile_size(self):\n return self._tile_size", "def tile_size(self) -> int:\n return self._tile_size", "def get_tile_size(self) -> int:\n return self.tile_size.spin.value()", "def _get_tile_size() -> int:\n return octree_config['octree']['tile_size'] if octree_config else 256", "de...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Using the Command_Handler from command module to handle command.
def usingHandler(self, cmd): self.command_handler.handle_command(cmd) while msg_queue.empty() is False: self.writeresponse(msg_queue.get())
[ "def mod_command_handler(self, cmd, args):\n self.command_handler_params = (cmd, args) # for inspection\n return bundy.config.create_answer(0)", "def handle(self, command):\n fn = \"handle_{}\".format(command)\n try:\n self.commands[fn](self)\n except KeyError:\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Target method used by monitor thread, which polls vbmc status every 3s. If vbmc stops, ipmiconsole will stop.
def monitor(instance="default"): global logger_ic while True: try: with open("{}/{}/.{}-bmc.pid".format( config.infrasim_home, instance, instance), "r") as f: pid = f.readline().strip() if not os.path.exists("/proc/{}".format(pid)): logger_ic.warning("Node {} vBMC {} is not running, " "ipmi-console is ready to quit". format(instance, pid)) break time.sleep(3) except IOError: logger_ic.warning("Node {} workspace is possibly destroyed, " "ipmi-console is ready to quit".format(instance)) break stop(instance)
[ "def bitmessage_monitor(self):\n while True:\n now = time.time()\n if self.timer_check_bm_alive < now:\n while self.timer_check_bm_alive < now:\n self.timer_check_bm_alive += 10\n lf = LF()\n if (not self.is_restarting_bitm...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Stop ipmiconsole of target instance specified by its name
def stop(instance="default"): global logger_ic logger_ic = infrasim_log.get_logger(LoggerType.ipmi_console.value, instance) try: file_ipmi_console_pid = "{}/{}/.ipmi_console.pid".\ format(config.infrasim_home, instance) with open(file_ipmi_console_pid, "r") as f: pid = f.readline().strip() os.kill(int(pid), signal.SIGTERM) logger_ic.info("SIGTERM is sent to pid: {}".format(pid)) os.remove(file_ipmi_console_pid) except IOError: # When pid file is missing, by e.g., node destroy, # find process id by instance name if instance == "default": process_name = "ipmi-console start$" else: process_name = "ipmi-console start {}".format(instance) ps_cmd = r"ps ax | grep '{}' | grep Sl | awk '{{print $1}}' | head -n1".format(process_name) logger_ic.warning("Fail to find ipmi console pid file, check by:") logger_ic.warning("> {}".format(ps_cmd)) _, pid = run_command(cmd=ps_cmd) logger_ic.warning("ipmi console pid got: {}".format(pid)) if not pid: logger_ic.warning("ipmi console for instance {} is not running".format(instance)) return os.kill(int(pid), signal.SIGTERM) logger_ic.info("SIGTERM is sent to pid: {}".format(pid)) except Exception: logger_ic.warning(traceback.format_exc()) pass
[ "def stop(self):\n self.scion_sh('stop')", "def stop_single(self, name):\n logger.debug('Stopping module \"%s\"', name)\n self.modules[name].stop()\n logger.debug('Module \"%s\" stopped', name)", "def stop_notebook_instance(NotebookInstanceName=None):\n pass", "def _stop_instanc...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Creates a handle to the Ceph Cluster.
def connect(ceph_config_file, timeout = CEPH_TIMEOUT): handle = rados.Rados(conffile = ceph_config_file) LOGGER.info("librados version: " + str(handle.version())) LOGGER.info("Attempting to connect to: " + str(handle.conf_get('mon initial members'))) handle.connect() #timeout shoudl be specified LOGGER.info("Cluster ID" + handle.get_fsid()) return handle
[ "def host_cluster_create(context, values):\n return IMPL.host_cluster_create(context, values)", "def create_cluster():\n config = get_kube_config()\n command = CLUSTER_CREATE_COMMAND.replace('\\n','').format(cluster_name=config['cluster_name'],\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Gather ceph monitor information
def get_monitor_info(handle, timeout): mon_info = dict() mon_info['stat'] = ceph_mon_command(handle, 'mon stat' , timeout) mon_info['dump'] = ceph_mon_command(handle, 'mon dump' , timeout) mon_info['map'] = ceph_mon_command(handle, 'mon getmap' , timeout) mon_info['metadata'] = ceph_mon_command(handle, 'mon metadata', timeout) return mon_info
[ "async def get_monitor_data(self):\n json = await self._api_call(\"app/monitors/%s/overview\" % self.sense_monitor_id)\n if \"monitor_overview\" in json and \"monitor\" in json[\"monitor_overview\"]:\n self._monitor = json[\"monitor_overview\"][\"monitor\"]\n return self._monitor", ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
GAther ceph device information
def get_device_info(handle, timeout): device_info = dict() device_info['ls'] = ceph_mon_command(handle, 'device ls', timeout) return device_info
[ "def device_info(self) -> dict[str, any]:\n return system_info(self.hacs)", "def device_info(self) -> dict:\n return self._device_info", "def DeviceInfo(self): \n \n self.is_attached = self.spatial.isAttached()\n self.device_name = self.spatial.getDeviceName()\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Gather ceph manager information
def get_manager_info(handle, timeout): mgr_info = dict() mgr_info['ls-modules'] = ceph_mon_command(handle, 'mgr module ls', timeout) mgr_info['dump'] = ceph_mon_command(handle, 'mgr dump' , timeout) mgr_info['metadata'] = ceph_mon_command(handle, 'mgr metadata' , timeout) return mgr_info
[ "def manager_info(self, manager):\n _, body = self.request('/v1.1/managers/active/%s' % manager, 'GET')\n return body", "def get_monitor_info(handle, timeout):\n mon_info = dict()\n mon_info['stat'] = ceph_mon_command(handle, 'mon stat' , timeout)\n mon_info['dump'] = ceph_mon_co...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Ensure that graveyard_removal.py correctly removes the graveyard from an h5m file.
def test_default_graveyard_removal(): os.system("python svalinn_tools/graveyard_removal.py " + test_file_path + test_file) size = os.path.getsize(test_file[:-4] + "_no_grave.h5m") assert size == 5748780
[ "def remove_group(self):\n try:\n with open_hdf5(self.file_name, mode=\"a\") as hdf_file:\n del hdf_file[self.h5_path]\n except KeyError:\n pass", "def test_print_graveyard_removal(capfd):\n os.system(\"python svalinn_tools/graveyard_removal.py \" + test_file_...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Ensure that graveyard_removal.py prints the correct entity handle for the graveyard volume.
def test_print_graveyard_removal(capfd): os.system("python svalinn_tools/graveyard_removal.py " + test_file_path + test_file + " -p") out, err = capfd.readouterr() assert ("12682136550675318127" in out) == True
[ "def test_delete_volume(self):\n ctxt = context.get_admin_context()\n extra_specs = {}\n type_ref = volume_types.create(ctxt, 'hgst-1', extra_specs)\n volume = {'id': '1', 'name': 'volume1',\n 'display_name': '',\n 'volume_type_id': type_ref['id'],\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Validate the regex patterns, but only partially while the user is still typing. Because the 'from' pattern will be where the user specifies captures, changing it also requires revalidating the substitution pattern. However if the user is still typing (as opposed to hitting enter to complete the input) we do the minimal amount of work necessary, i.e we just set the colors back to neutral and disable the Apply button.
def validateRegexFields(self, complete=False): # Assume the patterns aren't valid. self.m_validFromRe = False self.m_validPatterns = False ### Validate the 'from' pattern # regexCtl = self.m_reFromCtl subsCtl = self.m_reToCtl regex, subs = regexCtl.Value, subsCtl.Value regColor, subColor = wx.NullColour, wx.NullColour if complete and regex: regColor = subColor = wx.BLUE try: re.sub(regex, subs, '') except re.error as e: subColor = wx.RED try: re.compile(regex) except re.error as e: regColor = wx.RED else: self.m_validFromRe = True else: self.m_validFromRe = True self.m_validPatterns = bool(subs) self.setTextColor(regexCtl, regColor) self.setTextColor(subsCtl, subColor) if complete: self.populateFileList() else: self.m_applyBtn.Enabled = False
[ "def onTextChange(self, event):\n\n self.validateRegexFields(complete=False)\n event.Skip()", "def onHitEnterInFrom(self, event):\n\n self.validateRegexFields(complete=True)\n if self.m_validFromRe:\n self.m_reToCtl.SetFocus()", "def validate_data(self):\n for patte...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Uses the list of filesondisk and the regex patterns to build a list of what the directory will look like if we renamed the files. Because we're justusing a simple text list, we use symbols to show the user which filenames would change and whether they would produce any duplicates, substituting "." with "\1.txt".
def populateFileList(self): self.m_fileList.SetForegroundColour(wx.NullColour) # We'll need to track which file names are modified and which # file names duped. applicable, dupes = set(), set() if not self.m_validPatterns: # Regex's don't compile yet, just use the raw filename list. newNames = self.m_diskNames else: # Apply the substitution to the filename list to produce a # destination-name list, and identify whether the patterns # actually affect anything. # newNames, modifiedIndexes = [], [] matcher = re.compile(self.m_reFromCtl.Value).subn subs = self.m_reToCtl.Value for filename in self.m_diskNames: # Perform the sub (filename, numChanges) = matcher(subs, filename) # Was there a modification? if numChanges: # Record the affected name. applicable.add(filename) if filename in newNames: dupes.add(filename) # Add to the primary list newNames.append(filename) # Does this produce a different list than we already had? If so, # clear the file list and replace it with the new one. # if newNames != self.m_newNames: self.m_fileList.Clear() # Figure out the longest name so we can create a cleanly-formatted # set of prefix/suffix characters for the modified/duped annotation. # maxLen = max(map(len, newNames)) decorate = '{m} {fn:<{ml}} {m}'.format # Now build a list of display elements. for filename in newNames: mark = ' ' if filename not in applicable else '|' if filename in dupes: mark = '*' self.m_fileList.Append(decorate(m=mark, fn=filename, ml=maxLen)) # Keep the list. self.m_newNames[:] = newNames # Update the apply button, we only want it enabled when the user # has a valid set of patterns that affect any files and have no # dupes produced as a result. # self.m_applyBtn.Enabled = bool(applicable) and not dupes if dupes: # Emphasize the presence of dupes. self.m_fileList.SetForegroundColour(wx.RED) # Draw the list. self.m_fileList.Refresh()
[ "def mark_files(self,postfix):\n dk = self.cand.keys()\n dk.sort() # sort by date...\n dk.reverse() # .. and reverse so latest comes first\n res = \"\"\n for k in dk:\n fn = self.cand[k].name\n pfn = os.path.join(self.dir,fn)\n fnnew = fn + postfix\n pfnnew = os....
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
When the user hits 'enter' in the 'from' field.
def onHitEnterInFrom(self, event): self.validateRegexFields(complete=True) if self.m_validFromRe: self.m_reToCtl.SetFocus()
[ "def pressed_enter(self):\n pass", "def hit_enter():\n keyboard.press_and_release('Enter')", "def enter(self):\n\t\tself.actionObject().key_down(Keys.ENTER).key_up(Keys.ENTER).perform()", "def enterKey_cb(widget, dialog):\n dialog.response(gtk.RESPONSE_ACCEPT)", "def enter_press_log_watcher(sel...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
When the user modifies the content of either regex field.
def onTextChange(self, event): self.validateRegexFields(complete=False) event.Skip()
[ "def to_field(self, **kwargs):\n if self.regex:\n if not 'regex' in self.field_args:\n self.field_args = self.field_args + ('regex', )\n self.field_klass = forms.RegexField\n return super(StringSetting, self).to_field(**kwargs)", "def get_regex_mismatch_error_tex...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns the updated log_conf, taking into account new log files present on the instance as well as modifications made to the corresponding logentries host.
def update_instance_conf(log_paths, log_conf): log_client = LogClient.Client(account_key) instance_id, config = get_ssh_config(env.host) if log_conf is None and len(log_paths)>0: print 'log_conf is None' log_conf = create_host_logs(log_client,instance_id,log_paths) elif log_conf is not None: print 'log_conf is not None' conf_host = log_conf.get_host() if conf_host is None: print 'Error. This instance configuration is missing the corresponding model!! instance_id=%s'%instance_id logger.error('Error. This instance configuration is missing the corresponding model!! instance_id=%s',instance_id) log_conf = create_host_logs(log_client,instance_id,log_paths) return log_conf if conf_host.get_key() is None: print 'Host %s has an logentries-rsyslog config file but no account key!!'%host.get_name() logger.warning('Host %s has an logentries-rsyslog config file but no account key!!',host.get_name()) log_conf = create_host_logs(log_client,instance_id,log_paths) return log_conf account = log_client.get_account() matching_host = None for host in account.get_hosts(): if host.get_key() == conf_host.get_key(): matching_host = host break # If there is no matching host, then it is assumed that it was deleted from Logentries and that no configuration should be associated to this instance. if matching_host is None: log_conf = create_host_logs(log_client,instance_id,log_paths) return log_conf for new_log in get_new_logs(log_paths, log_conf): # Update matching host so that each new log becomes part of it. matching_host = log_client.create_log_token(host=matching_host,log_name=new_log) log_conf.set_host(matching_host) return log_conf
[ "def update_config(update):\n global _config\n new_config = copy.deepcopy(_config)\n _update_dict_recursive(new_config, update)\n logging.config.dictConfig(new_config)\n _configure_ulog_bridge()\n _config = new_config", "def update_log_config(self, monitor_name, log_config):\n pass", "d...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Given a distribution, given by the list p_list, returns the entropy of the distribution.
def entropy(p_list): assert len(p_list) > 0 E = 0.0 for p in p_list: if p == 0.0: continue E += p*math.log(p) return E
[ "def entropy(p):\n h = 0\n\n # TODO -- Calculate entropy value in nats for probability distribution `p`\n for x in p:\n h -= p[x] * math.log(p[x])\n\n return h", "def entropy_of_a_list(values):\n counts = Counter(values).values()\n total = float(sum(counts))\n probabilities = [val / to...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
For a list of dictionaries mapping values to counts, returns a cost used for DT splitting that is optimal at 0. Currently uses the negative of information gain.
def split_cost(label_count_list): return -split_information_gain(label_count_list) #this cost value is the misclassification error. return split_misclassification_error(label_count_list)
[ "def cost(foods, foods_used):\n cost = 0.00\n for i, count in foods_used.items():\n cost += (foods[i]['serving_cost'] * count)\n return cost", "def cost_fun(self, specs_dict: Dict[str, float]) -> float:\n cost = 0\n for spec in self.spec_range.keys():\n penalty = self.comp...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Given a list of values and associated labels, optimizes the best split threshold z where dividing the values into z has the lowest split cost. Returns a pair (z,cost) where cost is the split_cost of the threshold z. If nonelabels is given, this indicates the labels of missing values that must be passed down to both subtrees. This does not affect the output z but it does affect the output cost value.
def best_split(values,labels,nonelabels=None): assert len(values) >= 2 assert len(values) == len(labels) N = len(values) ilist = sorted((v,l) for (v,l) in zip(values,labels)) leftcount = defaultdict(int) rightcount = defaultdict(int) for v,l in ilist: rightcount[l] += 1 bestindex = -1 bestcost = split_cost([leftcount,rightcount]) cost = bestcost #costs = [cost] #print "Split costs:" for i in xrange(len(ilist)): v,l = ilist[i] rightcount[l] -= 1 leftcount[l] += 1 if i+1 >= len(ilist) or v == ilist[i+1][0]: #no splits when v is equal to the next value continue cost = split_cost([leftcount,rightcount]) #print " ",v,leftcount.values(),rightcount.values(),cost #costs.append(cost) if cost < bestcost: bestcost = cost bestindex = i #raw_input() if bestindex < 0: #no split found... try splitting in half splitval = (ilist[0][0]+ilist[-1][0])*0.5 else: splitval = (ilist[bestindex][0] + ilist[bestindex+1][0])*0.5 if nonelabels is None: return (splitval,bestcost) #reevaluate counts leftcount = defaultdict(int) rightcount = defaultdict(int) for l in nonelabels: leftcount[l] += 1 rightcount[l] += 1 for v,l in ilist: if v <= splitval: leftcount[l] += 1 else: rightcount[l] += 1 return splitval,split_cost([leftcount,rightcount])
[ "def split_cost(label_count_list):\n return -split_information_gain(label_count_list)\n #this cost value is the misclassification error.\n return split_misclassification_error(label_count_list)", "def pick_best_split(self,db,labels,ids,features=None):\n idlabels = [labels[id] for id in ids]\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Looks up the leaf node corresponding to the given entry. Does not handle missing values.
def lookup(self,entry): if self.type == 'v': return self v = entry[self.feature] assert v != None if self.type == 's': c = None try: c = self.children[v] except KeyError: #print "Unseen value for feature",self.feature,": ",v best = None bestDist = float('inf') for (val,c) in self.children.iteritems(): if abs(val - v) < bestDist: bestDist = abs(val - v) best = c c = best return c.lookup(entry) elif self.type == 'i': if v <= self.value: return self.children[0].lookup(entry) else: return self.children[1].lookup(entry) raise RuntimeError("Invalid DecisionTreeNode type?")
[ "def build_node_from_entry(self, entry):\n if entry is None:\n mess = \"Object browser entry expected, %s found\" % entry\n raise ValueError(mess)\n node = Node(self.sstd, self.sbld, entry)\n sobj = node.get_sobj()\n if sobj.GetID() == sobj.GetFatherComponent().GetI...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Given a indexed database db, a list of labels (one for each id), and a list of ids to test, sets this node to the best label.
def pick_best_label(self,db,labels,ids): self.type = 'v' if len(labels) > 0: self.value = vote([labels[id] for id in ids]) else: self.value = None return
[ "def learn(self,db,labels):\n self.keys = db.keys[:]\n labelindex = -1\n if isinstance(labels,str):\n labelindex = db.keys.index(labels)\n assert labelindex >= 0,\"label does not exist in database keys\"\n labels = db.get_column(labelindex)\n elif isinsta...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Given an index database db, a list of labels (one for each id), and a list of ids to train on, computes the optimal split value. It modifies this node to have the optimal split type and value, and then returns the quality of the split as computed by the split_cost function. If features != None, it is a list of available feature indices to use in this split, or a function of 0 arguments that can be called to get a list of features.
def pick_best_split(self,db,labels,ids,features=None): idlabels = [labels[id] for id in ids] if misclassification_error(idlabels) == 0: #base case: no misclassifications self.type = 'v' self.value = idlabels[0] return 0 best = None bestCost = 0 splitval = None discrete = True if features == None: if len(ids) < db.numFeatures(): #look at all present features in the training set features = db.getPresentFeatures(ids) #print len(features),"of",db.numFeatures(),"features selected" else: features = range(db.numFeatures()) elif callable(features): features = features() for i in features: if len(db.entryLists[i]) == 0: continue idiscrete = db.discreteFeature[i] if idiscrete: #count number of labels of a certain value splitter = defaultdict(lambda:defaultdict(int)) #count of labels for missing values nmissing = defaultdict(int) for id in ids: val = db[i,id] if val is None: #missing values go down to all splits nmissing[labels[id]] += 1 continue splitter[val][labels[id]] += 1 if len(splitter) > continuous_variable_threshold: #print "Determined to be a continuous variable" idiscrete = False break if idiscrete: if len(splitter) <= 1: #only a single value continue #count number of missing values in all splits cmax = 0 for k in splitter: for l,v in nmissing.iteritems(): splitter[k][l] += v cmax = max(cmax,sum(splitter[k].values())) #shrink by fraction of (# of ids - largest child)/(# of ids) scale = (1.0-float(cmax)/float(len(ids)))*len(splitter) #evaluate cost cost = split_cost(splitter.values())*scale #print "Split on",i,"information gain",-cost,splitter.values() else: #continuous, need to learn the best split vals = [] presentlabels = [] nonelabels = [] for id in ids: val = db[i,id] if val is None: nonelabels.append(labels[id]) continue vals.append(val) presentlabels.append(labels[id]) if len(vals) <= 1: print "No values for feature",i,"?" print vals continue #print "Considering continuous split on",i s,cost = best_split(vals,presentlabels,nonelabels) scale = (1.0-float(len(presentlabels)/2+len(nonelabels))/float(len(ids)))*2 cost *= scale #print "Result",s,"Information gain",-cost if cost < bestCost: best = i bestCost = cost discrete = idiscrete if not idiscrete: splitval = s if best is None: self.type = 'v' if len(ids) > 0: self.value = vote(idlabels) return misclassification_error(idlabels) else: self.value = None return 0 else: self.feature = best #discrete or inequality split if discrete: self.type = 's' else: self.type = 'i' self.value = splitval return bestCost
[ "def __get_split_feature(self, data_set, target_feature, tree_features):\n\n if self.__criterion == 'entropy':\n feature_gains = {feature: self.__gain(data_set, feature, target_feature) for (feature) in tree_features}\n split_feature = max(feature_gains, key=feature_gains.get)\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Learns from a Database instance. Each entry is given a label.
def learn(self,db,labels): self.keys = db.keys[:] labelindex = -1 if isinstance(labels,str): labelindex = db.keys.index(labels) assert labelindex >= 0,"label does not exist in database keys" labels = db.get_column(labelindex) elif isinstance(labels,int): labelindex = labels labels = db.get_column(labelindex) else: assert len(labels) == len(db.entries) self.root = DecisionTreeNode() if labelindex >= 0: raise NotImplementedError("Ooops, taking out indexed label broken") entries = np.delete(entries,labelindex,1) db = IndexedDatabase(db) if self.maxnodes != None: return self.greedy_learn_search(db,labels) else: self.deepest = 0 return self.greedy_learn(self.root,db,labels,range(len(labels)))
[ "def save_data_to_db(labelled):\n add_query = sqlite3.connect(DB_PATH).cursor()\n add_query.execute(\n \"CREATE TABLE IF NOT EXISTS labels(text TEXT, label TEXT, score FLOAT)\")\n for entry in labelled:\n add_query.execute(\"\"\"INSERT INTO labels(text,label,score) VALUES(?,?,?)\"\"\",\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Given a indexed database, greedily and recursively learns the split value for the subtree of the indicated node. Return value is the number of mistakes made by the decision tree. Missing values are handled properly as indicating a 'don't care' value that gets passed down to both sides of the tree.
def greedy_learn(self,node,db,labels,ids): if node.depth >= self.maxdepth or len(ids) <= self.minexamples: #terminate recursion node.pick_best_label(db,labels,ids) err = misclassification_error([labels[id] for id in ids]) if err > 0: print "Reached a leaf and had to make some sacrifices, cost",err print " depth",node.depth print " labels",[labels[id] for id in ids] return err features = self.feature_subset(node,db,labels,ids) cost = node.pick_best_split(db,labels,ids,features) #do a split if node.type == 'v': #base case: no misclassifications """ if cost>0: print "greedy_learn: Warning, pick_best_split indicates a leaf but the cost is nonzero" print "cost=",cost,"misclassification=",misclassification_error([labels[id] for id in ids]) print "# of ids:",len(ids) for i in ids: print "id",i,",", for k in range(db.numFeatures()): if db[k,i] != None: print k,"=",db[k,i],",", print "label",labels[i] raw_input() """ return 0 elif node.type == 's': #print "Picked feature",node.feature,"split" #do a discrete split node.children = dict() #select sub-indices Eids = defaultdict(list) noneids = [] for id in ids: v = db[node.feature,id] if v is None: #item doesn't exist, it's a missing value noneids.append(id) else: Eids[v].append(id) #print " split sizes:",[len(x) for x in Eids.values()] #print " None ids:",len(noneids) ids = None errors = 0 for v,vids in Eids.iteritems(): #recurse c = DecisionTreeNode(node) #print "Recursing on value",v #print " ids:",vids errors += self.greedy_learn(c,db,labels,vids+noneids) node.children[v] = c if c.depth > self.deepest: self.deepest = c.depth print "Decision tree learner: Reached node with depth",self.deepest return errors else: #do an inequality split assert node.type == 'i' #print "Picked feature",node.feature,"inequality value",node.value,"cost",cost leftids = [] rightids = [] for id in ids: if db[node.feature,id] is not None: if db[node.feature,id] <= node.value: leftids.append(id) else: rightids.append(id) else: leftids.append(id) rightids.append(id) if len(rightids) == len(ids) or len(leftids) == len(ids): #due to missing values, this split is useless errors = misclassification_error([labels[id] for id in ids]) print "useless split on feature",node.feature,"value",node.value,"misclassification error",errors print "Left size",len(leftids),"right size",len(rightids) raw_input() node.pick_best_label(db,labels,ids) return errors #clear memory associated with ids list del ids[:] ids = None #print "Left size",len(leftids),"right size",len(rightids) c1 = DecisionTreeNode(node) c2 = DecisionTreeNode(node) #left side errors = self.greedy_learn(c1,db,labels,leftids) #right side errors += self.greedy_learn(c2,db,labels,rightids) #restore index node.children = {0:c1,1:c2} if c1.depth > self.deepest: self.deepest = c1.depth print "Decision tree learner: Reached node with depth",self.deepest return errors
[ "def count_splits_on_tree(self, tree):\n if self.taxon_set is None:\n self.taxon_set = tree.taxon_set\n else:\n assert tree.taxon_set is self.taxon_set\n self.total_trees_counted += 1\n if not self.ignore_node_ages:\n tree.calc_node_ages()\n for sp...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Identifies the list of example indices that would follow the decision tree to node.
def identify_examples(self,db,labels,node): path = [] while node.parent != None: nkey = None for (k,c) in node.parent().children.iteritems(): if c is node: nkey = k break assert nkey != None path.append((node.parent(),nkey)) node = node.parent() path = path[::-1] nids = len(labels) ids = [] for id in xrange(nids): valid = True for n,ckey in path: f = n.feature val = featureMatrix[f,id] if val is None: #it's a None value, just continue on continue else: key = None if n.type == 'i': key = (0 if val <= n.value else 1) else: key = val if key != ckey: valid = False break if valid: ids.append(id) return ids
[ "def indices(self):", "def list_indices(self):", "def target_nodes_indexes(self) -> _TargetNodes:\n return self.__target_nodes_indexes", "def reference_nodes_idx(self) -> Dict[str, torch.Tensor]:\n return self.node_idx_references", "def getResultIdx(self):\n return [ element.idx for ele...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Same as greedy learn, but with a maximum number of nodes. Rather than a DFS, this uses a priority queue that at each step splits the node with the maximum improvement in misclassification error. At most maxnodes are in the resulting tree, and the depth is limited to maxdepth. Returns the total number of misclassifications of the training set. There is a lowmemory mode when self.lowmem == True or self.lowmem == 'auto' and the number of saved ids at a node grows beyond a certain number (self.lowmem_threshold, 10m by default). In lowmemory mode, the subset of of examples at a given node is determined dynamically, which incurs a O(|D|d) cost per node, where d is the depth of the node. Overall this raises running time by a factor of approximately O(|D| log_2 |D|).
def greedy_learn_search(self,db,labels): queue = PriorityQueue() dolowmem = (self.lowmem == True) numidsets = 0 root_ids = range(len(labels)) queue.push((self.root,root_ids),len(labels)) numnodes = 1 deepest = 0 err = 0 while len(queue) > 0 and numnodes+2 <= self.maxnodes: #print "%d nodes, priority %d"%(numnodes,queue.nextkey()) nerr = queue.nextkey() (node,trainingset) = queue.pop() #print "Greedy learn",len(trainingset) if trainingset is None: trainingset = self.identify_examples(db,labels,node) if node.depth >= self.maxdepth or len(trainingset) <= self.minexamples: #print " Hit depth or training set limit" node.pick_best_label(db,labels,trainingset) err += misclassification_error([labels[id] for id in trainingset]) continue features = self.feature_subset(node,db,labels,trainingset) cost = node.pick_best_split(db,labels,trainingset,features) numidsets -= len(trainingset) #do a split if node.type == 'v': continue elif node.type == 's': #discrete split node.children = dict() #select sub-indices Eids = defaultdict(list) noneids = [] for id in trainingset: v = db[node.feature,id] if v is None: #item doesn't exist, it's a missing value noneids.append(id) else: Eids[v].append(id) #determine whether to switch to low-memory mode if not dolowmem and self.lowmem=='auto': for v,vids in Eids.iteritems(): numidsets += len(vids)+len(noneids) if numidsets > self.lowmem_threshold: print "Decision tree learner switching to low-memory mode" dolowmem = True trainingset = None numnodes += len(Eids) #print "Split sizes",[len(v) for v in Eids.itervalues()] #print "None size",len(noneids) for v,vids in Eids.iteritems(): #print "->",len(vids),"+",len(noneids) #recurse c = DecisionTreeNode(node) node.children[v] = c err = misclassification_error([labels[id] for id in vids+noneids]) cids = (None if dolowmem else vids+noneids) queue.push((c,cids),err) if c.depth > deepest: deepest = c.depth print "Decision tree learner: Reached node with depth",deepest else: #do an inequality split assert node.type == 'i',"Got a weird type? "+str(node.type) leftids = [] rightids = [] for id in trainingset: val = db[node.feature,id] if val is not None: if val <= node.value: leftids.append(id) else: rightids.append(id) else: leftids.append(id) rightids.append(id) if len(leftids)==0 or len(rightids)==0: print "node feature "+str(node.feature)+" doesn't have a valid split value "+str(node.value) vals = [db[node.feature,id] for id in trainingset if db[node.feature,id]!=None] print "min,max of training set:",min(vals),max(vals) print "cost is",cost raw_input() assert len(leftids) > 0 and len(rightids) > 0 if not dolowmem and self.lowmem=='auto': numidsets += len(leftids) + len(rightids) if numidsets > self.lowmem_threshold: print "Decision tree learner switching to low-memory mode" dolowmem = True trainingset = None numnodes += 2 c1 = DecisionTreeNode(node) c2 = DecisionTreeNode(node) node.children = {0:c1,1:c2} #print "->",len(leftids) #print "->",len(rightids) err1 = misclassification_error([labels[id] for id in leftids]) err2 = misclassification_error([labels[id] for id in rightids]) if dolowmem: leftids = None rightids = None queue.push((c1,leftids),err1) queue.push((c2,rightids),err2) if c1.depth > deepest: deepest = c1.depth print "Decision tree learner: Reached node with depth",deepest #end of recursion. for the rest of the nodes still in the queue, make them leaf nodes if len(queue) > 0: print "%d nodes remaining in queue, setting to leaves"%(len(queue),) for (node,trainingset) in queue: node.pick_best_label(db,labels,trainingset) err += misclassification_error([labels[id] for id in trainingset]) return err
[ "def max_node_count(self) -> int:\n return pulumi.get(self, \"max_node_count\")", "def node_count_max(self) -> int:\n return int(self.graph_tuple_stats.node_count_max or 0)", "def max_nodes(self):\n return self._max_nodes", "def max_nodes(self) -> int:\n return pulumi.get(self, \"max_n...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Initializes the list. If entries is given, this initializes the entries of the list. If memoized = True, any lazy evaluated entries are saved after their first evaluation.
def __init__(self,entries=None,memoized=False): if entries is not None: self.entries = entries[:] else: self.entries = [] self.memoized = memoized
[ "def __init__(self, contents=()):\n self._data = [self._Item(k, v) for k, v in contents]\n if self._data:\n self._heapify()", "def __init__(self, entries=None):\n ## Mark the start timestamp:\n self._started_at = datetime.datetime.now()\n self._finished_at = None\n\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Test the template tag js_settings
def test_js_settings(mocker, rf): mocker.patch( "mitxpro.templatetags.js_interop.get_js_settings", return_value={"data": "value"}, ) request = rf.get("/") context = Context({"request": request}) template = Template(("{% load js_interop %}" "{% js_settings %}")) rendered_template = template.render(context) assert ( rendered_template == """<script type="text/javascript"> var SETTINGS = {"data": "value"}; </script>""" )
[ "def jssettings(self):\n self.update()\n return \"var %s = %s\" % (self.js_var_settings_name,\n json.dumps(self.settings))", "def test_jssettings(self):\n settings_fullpath = os.path.join(dirs.get_main_js_dir(), \"mediabrute-settings.js\")\n \n i...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
This function computes the fundamental matrix by computing the SVD of Ax = 0 ; 8point algorithm
def computeFundamentalMatrix(pts1, pts2): A = np.empty((8, 9)) for i in range(len(pts1)-1): x1 = pts1[i][0] x2 = pts2[i][0] y1 = pts1[i][1] y2 = pts2[i][1] A[i] = np.array([x1 * x2, x2 * y1, x2, y2 * x1, y2 * y1, y2, x1, y1, 1]) # Compute F matrix by evaluating SVD U, S, V = np.linalg.svd(A) F = V[-1].reshape(3, 3) # Constrain the F matrix to rank 2 U1, S1, V1 = np.linalg.svd(F) # print('Old S', S) # S[2] = 0 S2 = np.array([[S1[0], 0, 0], [0, S1[1], 0], [0, 0, 0]]) # print('New S', S) F = np.dot(np.dot(U1, S2), V1) return F
[ "def svd0(A):\n M,N = A.shape\n if M>N: return sla.svd(A, full_matrices=True)\n else: return sla.svd(A, full_matrices=False)", "def _nullSpaceBasis(A):\n if A.any():\n U, s, Vh = la.svd(A)\n vecs = np.array([])\n toAppend = A.shape[1] - s.size\n s = np.append(s, zeros((1, toApp...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Leverages the 8point algorithm and implement RANSAC algorithm to find the inliers and the best fundamental matrix
def getInlierRANSAC(pts1, pts2): # global finalFundamentalMatrix iterations = 50 threshold = 0.01 max_count = 0 n = len(pts1) finalFundamentalMatrix = np.zeros((3, 3)) for i in range(iterations): count = 0 idx = random.sample(range(n - 1), 8) left_pts = pts1[idx] right_pts = pts2[idx] F = computeFundamentalMatrix(left_pts, right_pts) left_feature_inlier = [] right_feature_inlier = [] # print("Sample index: ", len(idx)) for j in range(0, n): homogeneous_right = np.array([pts2[j, 0], pts2[j, 1], 1]) homogeneous_left = np.array([pts1[j, 0], pts1[j, 1], 1]) fit = np.dot(homogeneous_right.T, np.dot(F, homogeneous_left)) # print("Fit for iteration ", i," ", np.abs(fit)) if np.abs(fit) < threshold: left_feature_inlier.append(pts1[j]) right_feature_inlier.append(pts2[j]) count = count + 1 # print('Inlier count', count) inlier_Left = np.array(left_feature_inlier) inlier_Right = np.array(right_feature_inlier) if count > max_count: max_count = count finalFundamentalMatrix = F final_inlier_Left = inlier_Left final_inlier_Right = inlier_Right return finalFundamentalMatrix, final_inlier_Left, final_inlier_Right
[ "def evaluation(result, reference, verbose=0):\n # get column signals\n Ar = reference[0].copy()\n Sr = reference[1].T.copy()\n noise = reference[2].T.copy()\n Ae = result[0]\n Se = result[1].T\n r = Sr.shape[1]\n # set nan values to 0\n Ar[np.isnan(Ar)] = 0\n Sr[np.isnan(Sr)] = 0\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
This function computes the essential matrix from the fundamental matrix. The E matrix is defined in normalized image coordinates
def getEssentialMatrix(K, F): E = np.dot(K.T, np.dot(F, K)) u, s, v = np.linalg.svd(E) # We correct the singular values of the E matrix s_new = np.array([[1, 0, 0], [0, 1, 0], [0, 0, 0]]).reshape(3, 3) final_E = np.dot(u, np.dot(s_new, v)) return final_E
[ "def calc_eigendecomp(self):\n self.evals, self.evecs = np.linalg.eigh(self.sub_matrix)", "def energyMatrix(image):\n gray = cv.cvtColor(image, cv.COLOR_BGR2GRAY)\n sobelX = cv.Sobel(gray, cv.CV_64F,1,0)\n sobelY = cv.Sobel(gray, cv.CV_64F,0,1)\n engMatrix = np.abs(sobelX) + np.abs(sobelY)\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Given the essential matrix, we derive the camera position and orientation
def ExtractCameraPose(E): u, s, v = np.linalg.svd(E, full_matrices=True) w = np.array([[0, -1, 0], [1, 0, 0], [0, 0, 1]]).reshape(3, 3) c1 = u[:, 2].reshape(3, 1) r1 = np.dot(np.dot(u, w), v).reshape(3, 3) c2 = -u[:, 2].reshape(3, 1) r2 = np.dot(np.dot(u, w), v).reshape(3, 3) c3 = u[:, 2].reshape(3, 1) r3 = np.dot(np.dot(u, w.T), v).reshape(3, 3) c4 = -u[:, 2].reshape(3, 1) r4 = np.dot(np.dot(u, w.T), v).reshape(3, 3) if np.linalg.det(r1) < 0: c1 = -c1 r1 = -r1 if np.linalg.det(r2) < 0: c2 = -c2 r2 = -r2 if np.linalg.det(r3) < 0: c3 = -c3 r3 = -r3 if np.linalg.det(r4) < 0: c4 = -c4 r4 = -r4 cam_center = np.array([c1, c2, c3, c4]) cam_rotation = np.array([r1, r2, r3, r4]) return cam_center, cam_rotation
[ "def get_camera_orientation(self):\n\n # Create the vector from the camera to the robot\n vector_x = self.robot_x - self.camera_x\n vector_y = self.robot_y - self.camera_y\n vector_z = self.robot_z - self.camera_z\n\n # Calculate yaw and pitch from this vector\n yaw = math....
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
This function returns the extrinsic parameter matrix
def getExtrinsicParameter(K, R, C): t = np.dot(-R, C) homogeneous_matrix = np.hstack((R.reshape(3, 3), t)) extrinsic_parameter = np.dot(K, homogeneous_matrix) return extrinsic_parameter
[ "def get_extM(self):\n ext_mat = np.array([\n [0, 1, 0],\n [0, 0, 1],\n [1, 0, 0]]) @ np.hstack((self.R.T, -self.R.T @ self.T)) # extrinsic matrix (rows re-aligned)\n return ext_mat", "def get_model_parameters(self):\n return np.atleast_2d(self.cost_model.get_...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
removes all Hydrogen atoms from instance
def remove_hydrogens(self) -> None: for cid, c in self: for rid, r in c: for aid, a in r: if a.element == 'H': print('removing H at %s' % aid) r.remove_atom(a)
[ "def delete(self):\n del self.shx.atoms[self.index]", "def strip(self):\n types = [type(self.strip),\n type(self.values),\n type(self.__ne__),\n type(self.__class__)]\n\n for attr in dir(self):\n if not type(getattr(self, attr)) in ty...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
collect a set of residues with memb_z within [15, 15]
def memb_residues(pdb: MyPDB) -> list(): result = [] for ch in pdb.chains.values(): for res in ch.values(): if res.memb_z is not None: result.append(res) return result
[ "def residues(atoms):\n residues = dict([ [j,[]] for j in set([i['resid'] for i in atoms]) ])\n for i in range(len(atoms)):\n residues[atoms[i]['resid']].append(i)\n return residues", "def getLigandNbrs(resids: List[Residue], struct:Structure)->List[ResidueDict]:\n\n ns = NeighborSearch(list...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Initializes indicating root Python module. The application will look for all `Resource` classes defined in the given root module.
def __init__(self, root): self._root = root if not self.get_resources(): raise Exception('Your application has no Resource.')
[ "def initAll(cls):\n for dir in os.environ['MODULEPATH'].split(':'):\n if not os.path.exists(dir):\n continue\n for subdir in os.listdir(dir):\n subdirPath = \"%s/%s\" % (dir, subdir)\n if not os.path.isdir(subdirPath):\n continue\n for file in os.listdir(subdirPath...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Unnormalize a given image.
def unnormalize(self, image, transpose=False): return unnormalize(image, self.mean, self.std, transpose)
[ "def normalise(image):", "def reverse_normalize(image):\n\n reverse = transforms.Normalize(mean=[-0.485 / 0.229, -0.456 / 0.224, -0.406 / 0.255],\n std=[1 / 0.229, 1 / 0.224, 1 / 0.255])\n return reverse(image)", "def inverse_normalize(img):\n if opt.caffe_pretrain:\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Handle imbalanced dataset through sampler.
def create_class_imbalance_sampler(self): count = [0] * len(self.classes) for item in self.train_data.imgs: count[item[1]] += 1 weight_per_class = [0.] * len(self.classes) for i in range(len(self.classes)): weight_per_class[i] = float(sum(count)) / float(count[i]) weights = [0] * len(self.train_data.imgs) for idx, val in enumerate(self.train_data.imgs): weights[idx] = weight_per_class[val[1]] weights = torch.DoubleTensor(weights) self.sampler = torch.utils.data.sampler.WeightedRandomSampler( weights, len(weights) )
[ "def balanced_sampling(dat: pd.DataFrame, logger=None):\n if logger == None:\n logging.basicConfig(\n level=logging.INFO, format='%(asctime)s - %(name)s - %(levelname)s - %(message)s')\n logger = logging.getLogger(__name__)\n \n \n # upsampling\n logger.info('Start balanced s...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Get the selected locale from user settings.
def get_locale(): setting = Setting.query.filter(Setting.name == 'default_language').first() if setting is not None: return setting.value # Return default language when none found return 'en'
[ "def _get_locale(self):\n context = self.context\n locales = {\n 'en': 'en_GB',\n 'de': 'de_DE'\n }\n language = context.language if context.language else 'en'\n return locales.get(language)", "def _get_user_locale():\n if 'Windows' in platform.system():...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Decodes a Base58Check encoded key.
def from_b58check(key): return HDKey.from_bytes(base58.b58decode_check(key))[0]
[ "def base58_decode(v: bytes) -> bytes:\n try:\n prefix_len = next(\n len(encoding[2])\n for encoding in base58_encodings\n if len(v) == encoding[1] and v.startswith(encoding[0])\n )\n except StopIteration:\n raise ValueError('Invalid encoding, prefix or le...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Generates either a HDPrivateKey or HDPublicKey from the underlying bytes.
def from_bytes(b): if len(b) < 78: raise ValueError("b must be at least 78 bytes long.") version = int.from_bytes(b[:4], 'big') depth = b[4] parent_fingerprint = b[5:9] index = int.from_bytes(b[9:13], 'big') chain_code = b[13:45] key_bytes = b[45:78] rv = None if version == HDPrivateKey.MAINNET_VERSION or version == HDPrivateKey.TESTNET_VERSION: if key_bytes[0] != 0: raise ValueError("First byte of private key must be 0x00!") private_key = int.from_bytes(key_bytes[1:], 'big') rv = HDPrivateKey(key=private_key, chain_code=chain_code, index=index, depth=depth, parent_fingerprint=parent_fingerprint) elif version == HDPublicKey.MAINNET_VERSION or version == HDPublicKey.TESTNET_VERSION: if key_bytes[0] != 0x02 and key_bytes[0] != 0x03: raise ValueError("First byte of public key must be 0x02 or 0x03!") public_key = PublicKey.from_bytes(key_bytes) rv = HDPublicKey(x=public_key.point.x, y=public_key.point.y, chain_code=chain_code, index=index, depth=depth, parent_fingerprint=parent_fingerprint) else: raise ValueError("incorrect encoding.") return (rv, b[78:])
[ "def generate_ecdh_key_pair() -> tuple[X25519PrivateKey, bytes]:\n private_key = X25519PrivateKey.generate()\n public_key_raw = private_key.public_key().public_bytes(\n serialization.Encoding.Raw, serialization.PublicFormat.Raw\n )\n return private_key, public_key_raw", "def decode_public_key(b...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Whether or not this is a hardened node. Hardened nodes are those with indices >= 0x80000000.
def hardened(self): # A hardened key is a key with index >= 2 ** 31, so # we check that the MSB of a uint32 is set. return self.index & 0x80000000
[ "def isItFreeNode(self):\n for c in self.children:\n if c:\n return False\n return True", "def is_dedicated_node(self):\n return self.is_node() and not self.is_master()", "def has_extra_nodes(self):\n return (self.n_edge_nod + self.n_face_nod + self.n_bu...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns the key's fingerprint, which is the first 4 bytes of its identifier.
def fingerprint(self): return self.identifier[:4]
[ "def key_fingerprint(self):\n return self._key_fingerprint", "def fingerprint(public_key):\r\n\r\n return hashlib.new('ripemd160', hashlib.sha256(public_key).digest()).digest()[:4]", "def fingerprint(self, key):\n base64_pub = self.base64_pub_encode(key)\n return SHA256.new(base64_pub.en...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Get inventory list from config files builds a NetworkRunner inventory object and a mac_map dictionary according to ansible inventory file yaml definition
def __init__(self): self.inventory = {} self.mac_map = {} for conffile in CONF.config_file: # parse each config file sections = {} parser = cfg.ConfigParser(conffile, sections) try: parser.parse() except IOError as e: LOG.error(str(e)) # filter out sections that begin with the driver's tag hosts = {k: v for k, v in sections.items() if k.startswith(c.DRIVER_TAG)} # munge the oslo_config data removing the device tag and # turning lists with single item strings into strings for host in hosts: dev_id = host.partition(c.DRIVER_TAG)[2] dev_cfg = {k: v[0] for k, v in hosts[host].items()} for b in c.BOOLEANS: if b in dev_cfg: dev_cfg[b] = types.Boolean()(dev_cfg[b]) self.inventory[dev_id] = dev_cfg # If mac is defined add it to the mac_map if 'mac' in dev_cfg: self.mac_map[dev_cfg['mac'].upper()] = dev_id LOG.info('Ansible Host List: %s', ', '.join(self.inventory))
[ "def main():\n with open('group_vars/all.yaml', 'r') as file:\n config = yaml.safe_load(file)\n\n if not os.path.exists('host_vars'):\n os.makedirs('host_vars')\n\n nso_ip = config['nso']['ip']\n username = config['nso']['username']\n password = config['nso']['password']\n nso = NSO(...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Test case for get_liveness Get job service liveness
def test_get_liveness(self): response = self.client.open('/api/v1//liveness', method='GET', content_type='application/json') self.assert200(response, "Response body is : " + response.data.decode('utf-8'))
[ "def test_liveness(client):\n response = client.get(api_route_for(\"liveness\"))\n assert response.status_code == 200\n json_data = get_json_from_response(response)\n assert json_data == {}", "def test_get_refresh_job_status(self):\n pass", "def liveness():\n return jsonify({}), 200", "d...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Test case for get_readiness Get job service readiness
def test_get_readiness(self): response = self.client.open('/api/v1//readiness', method='GET', content_type='application/json') self.assert200(response, "Response body is : " + response.data.decode('utf-8'))
[ "def test_get_refresh_job_status(self):\n pass", "def readiness():\n return run_health_check()", "def test_readiness(client):\n response = client.get(api_route_for(\"readiness\"))\n assert response.status_code == 200\n json_data = get_json_from_response(response)\n assert json_data == {}",...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
=============================================================== save_obj(obj, saved_name ) =============================================================== this function is used to save any python object to your hard desk
def save_obj(obj, saved_name ): with open( saved_name + '.pkl', 'wb') as f: pickle.dump(obj, f, pickle.HIGHEST_PROTOCOL)
[ "def saveObject(obj):\r\n\r\n name = QtWidgets.QFileDialog.getSaveFileName(mw,'Save File','New SDE.sde',\r\n 'SDE-file *.sde')\r\n name = name[0]\r\n name = name.split('/')[-1]\r\n print(\"Save, name: \",name)\r\n with open(name,'wb') as output:\r\n pickle.dump(obj, output, -1)", "def...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
=============================================================== load_obj(saved_name) =============================================================== this function is used to save any python object to your hard desk
def load_obj(saved_name): with open( saved_name + '.pkl', 'rb') as f: return pickle.load(f)
[ "def save_obj(obj, saved_name ):\n with open( saved_name + '.pkl', 'wb') as f:\n pickle.dump(obj, f, pickle.HIGHEST_PROTOCOL)", "def pickle_object(obj, name):\n with open(name+\".pkl\", 'wb') as f:\n pickle.dump(obj, f)", "def load_obj(name):\n with open('../../data/' + name + '.pkl', 'rb...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
=========================================================== DateFormatedSQL(x) =========================================================== this function converts the the date read from a list to a datetime format
def DateFormatedSQL(x): x=[i[0] for i in x] x1=[] for i in x: if len(i)==19: x1.append(datetime.datetime(int(i[:4]),int(i[5:7]),int(i[8:10]),int(i[11:13]),int(i[14:16]),int(i[17:18]) )) # elif len(i)==13: # x1.append(datetime.datetime(int(i[:4]),int(i[5:7]),int(i[8:10]),int(i[11:13]),int(0),int(0) )) # else: # x1.append(datetime.datetime(int(i[:4]),int(i[5:7]),int(i[8:10]),int(0),int(0),int(0) )) # del i,x return x1
[ "def mapillary_to_sql_date(date):\r\n date_sql = date[:10] + \" \" + date[11:13] + \":\" + date[14:16] + \":\" + date[17:]\r\n return date_sql", "def change_format_from_input_to_datetime(list_d_t_t):\n data_output = []\n\n for row in list_d_t_t:\n data_output.append([datetime.datetime.strptime(...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
=========================================================== dateformated(x) =========================================================== this function converts the the date read from a list to a datetime format
def DateFormated(x): x1=[] for i in x: if len(i)==19: x1.append(datetime.datetime(int(i[:4]),int(i[5:7]),int(i[8:10]),int(i[11:13]),int(i[14:16]),int(i[17:18]) )) # elif len(i)==13: # x1.append(datetime.datetime(int(i[:4]),int(i[5:7]),int(i[8:10]),int(i[11:13]),int(0),int(0) )) # else: # x1.append(datetime.datetime(int(i[:4]),int(i[5:7]),int(i[8:10]),int(0),int(0),int(0) )) # del i,x return x1
[ "def change_format_from_input_to_datetime(list_d_t_t):\n data_output = []\n\n for row in list_d_t_t:\n data_output.append([datetime.datetime.strptime(row[0] + \" \" + row[1], \"%Y-%m-%d %H:%M:%S\"),\n datetime.datetime.strptime(row[0] + \" \" + row[2], \"%Y-%m-%d %H:%M:%S\")]...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Check if a record exists matching the service pattern with the current host's ip
def record_exists(route53_zone, service_name, ip): # Match records belonging to the service for particular service and # environment. match_regex = "{}\d+\.{}\.?".format(service_name, route53_zone.name) for record in route53_zone.get_records(): match = re.match(match_regex, record.name) if match and ip in record.resource_records: return True return False
[ "def _record_exists(self, cusip, dt):\n where_str = \"(cusip == '{}') & (as_of_date == {})\"\n if not isinstance(dt,int):\n dt = time.mktime(dt.timetuple())\n p_data = self.pools_table.read_where(where_str.format(cusip, dt))\n return p_data.shape[0] > 0", "def check_if_ip_ex...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Creates record with record_name and ip; updates record if it already exists with different ip does nothing if record already exists with same ip
def upsert_record(route53_zone, record_name, ip): # Only upsert the dns record if it doesn't resolve to us. try: record_ip = socket.gethostbyname(record_name) except socket.error: # Ignore if we can't connect to the host pass else: if ip == record_ip: return print str(dt.now()), "Registering host as", record_name record = route53_zone.get_a(record_name) if record and ip not in record.resource_records: route53_zone.update_a(record_name, ip) elif not record: route53_zone.add_a(record_name, ip)
[ "def _update_record(self, record_name, ip):\n if ((not hasattr(self, '_current_zone')) or (not self._current_zone)) or ((not hasattr(self, '_new_zone_version_number')) or (not self._new_zone_version_number)):\n raise GandiApiException(\"Can't update record, no cloned zone available.\")\n \n...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Create a new EC2 instance with specific parameters SecurityGroup (sg) and KeyPair (key) have to be previously created (see cassandgo initSG and cassandgo initKP)
def createInstance(ec2,ami,nb_nodes,placement,instance_type,key,sg,user_data=None): reservation = ec2.run_instances(ami,min_count=nb_nodes,max_count=nb_nodes,placement = placement,key_name=key,security_groups=[sg],instance_type=instance_type,user_data=user_data) instance = reservation.instances[0] return instance
[ "def create_instance(ami, sg_name):\n instance = None\n ec2 = boto3.resource('ec2',region_name=\"us-east-1\")\n # TODO: Create an EC2 instance\n # Wait for the instance to enter the running state\n # Reload the instance attributes\n\n try:\n instance = ec2.create_instances(\n ImageId...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
List all instances for a specific region and zone
def listInstancesRegionZone(region,zone): print "-"*80 print "# Region :",region," Zone", zone print "-"*80 instances = getInstancesRegionZone(region,zone) if instances: for instance in instances: print "[",instance.ami_launch_index,"]",instance.ip_address," (",instance.private_ip_address,") ",instance.instance_type," key=",instance.key_name
[ "def instances_by_region(aws_region=config.AWS_AWS_REGION):\n instances = _get_instances(aws_region)\n formatter = InstanceFormatter(instances)\n formatter.display()", "def get_instances(self, region):\n try:\n conn = ec2.connect_to_region(region, **self.credentials)\n region...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Create all Cassandra security groups in all regions
def createAllSG(): for info in conf_HVM: ec2 = boto.ec2.connect_to_region(info['region']+'-'+info['zone']) createSG(ec2,'SG-Cassandra-'+info['region']+'-'+info['zone'],CASSANDRA_RULES)
[ "def _create_allow_all_security_group(self):\n pass", "def create_auth_groups ():\n auth_group_list = ['Cores', 'Coords', 'Vols', 'Super-Coords']\n for auth_group_name in auth_group_list:\n create_auth_group (auth_group_name)\n print 'Group %s created' %(auth_group_name)", "def create...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Create all key pairs in all regions
def createAllKP(): if not os.path.exists(keysDir): os.makedirs(keysDir) for info in conf_HVM: keyName = 'Key-'+info['region']+'-'+info['zone'] try: os.remove(keysDir+'/'+keyName+'.pem') except OSError: pass print "Key creation :",keyName ec2 = boto.ec2.connect_to_region(info['region']+'-'+info['zone']) # check if the key pair exists kps = [kp for kp in ec2.get_all_key_pairs() if kp.name == keyName] if kps: ec2.delete_key_pair(keyName) key = ec2.create_key_pair(keyName) key.save(keysDir)
[ "def createAllSG():\n\tfor info in conf_HVM:\n\t\tec2 = boto.ec2.connect_to_region(info['region']+'-'+info['zone'])\n\t\tcreateSG(ec2,'SG-Cassandra-'+info['region']+'-'+info['zone'],CASSANDRA_RULES)", "def setup_space_keys(cls):\n if cls.KEYS:\n return\n\n from pkg_resources import iter_e...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Interpret for left != right
def _op_ne(self, left: Any, right: Any) -> BoolOrIter: out = self._op_eq(left, right) if isinstance(out, (numpy.ndarray, Series)): neout = ~out # neout[pandas.isna(out)] = numpy.nan return neout # out is always a numpy.ndarray return not out # pragma: no cover
[ "def nexact(cls, lhs, rhs):\n return lhs != rhs", "def match_LR(left,right):\n\n if left[1] == right[3][::-1]:\n return True\n\n return False", "def __ne__(self, other):\n return tf.math.not_equal(self._ordinals, other.ordinal())", "def same_level(left, right):\n for i in range(min(l...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Recycle left right operands to each other
def _recycle_left_right(left: Any, right: Any) -> Tuple: try: left = recycle_value(left, length_of(right)) except DataUnrecyclable: right = recycle_value(right, length_of(left)) return left, right
[ "def right_func(self, left):\n if self.right is None:\n if self.left is None:\n new = copy(self)\n new.left = left\n return new\n else:\n raise SyntaxError(\"Infix operator already has its \"\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
returns the sparsity penalty on network activations combined as a sum
def get_sparsity_penalty(nnet, inputs, sparsity, mode="mean", deterministic=False): assert mode in ("mean", "l1") rho = sparsity penalty = 0 eps = 0.0001 # for numerical stability for layer in nnet.all_layers: if layer.isactivation: activation = lasagne.layers.get_output(layer, inputs=inputs, deterministic=deterministic) if mode == "mean": if layer.isrelu: avg_activation = T.mean(T.gt(activation, T.zeros_like(activation)), axis=0, dtype='floatX') if layer.issigmoid: avg_activation = T.mean(activation, axis=0, dtype='floatX') KL_div = T.sum((rho+eps) * (T.log(rho+eps) - T.log(avg_activation+eps)) + (1-rho+eps) * (T.log(1-rho+eps) - T.log(1-avg_activation+eps)), dtype='floatX') penalty = penalty + KL_div if mode == "l1": penalty = penalty + T.sum(abs(activation), dtype='floatX') return T.cast(penalty, dtype='floatX')
[ "def sparsity_penalty(rbm, hidden_units, v0_vmap, target):\n # complete units lists\n hidden_units = rbm.complete_units_list(hidden_units)\n \n # complete the supplied vmap\n v0_vmap = rbm.complete_vmap(v0_vmap)\n \n hidden_vmap = rbm.mean_field(hidden_units, v0_vmap)\n\n penalty_terms = []\...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
returns the offset to balance the polynomial parameters possible by the bias terms of the network.
def get_bias_offset(nnet): offset = 0 L = len(nnet.trainable_layers) for l in range(L-1): layer = nnet.trainable_layers[l] if layer.b is not None: W_prod = T.eye(int(layer.b.shape.eval()[0])) for k in range(1, L-1): W_prod = T.dot(nnet.trainable_layers[k].W.T, W_prod) offset = offset + T.dot(W_prod, layer.b) offset = T.dot(nnet.ocsvm_layer.W.T, offset) return T.sum(offset)
[ "def _get_bias(self) -> JTensor:\n p = self.params\n b = self.local_theta().b\n if p.forget_gate_bias != 0.0:\n b = b + self.get_adjustment()\n\n return b", "def get_bias(self):", "def getbias(x, bias):\n return x / ((1.0 / bias - 2.0) * (1.0 - x) + 1.0 + 1e-6)", "def GetBiasVector(self):\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
create a OCSVM loss for network given in argument with rho=1 fixed
def compile_update_ocsvm_rho_fixed(nnet, inputs, targets): floatX = Cfg.floatX C = Cfg.C nu = Cfg.nu if len(nnet.all_layers) > 1: feature_layer = nnet.all_layers[-2] else: feature_layer = nnet.input_layer final_layer = nnet.ocsvm_layer trainable_params = lasagne.layers.get_all_params(final_layer, trainable=True) # Regularization Wsvm_penalty = T.sum(abs(final_layer.W) ** Cfg.pow) l2_penalty = get_l2_penalty(nnet, include_bias=Cfg.include_bias, pow=Cfg.pow) l2_penalty += Wsvm_penalty l2_penalty *= (1/C) # Backpropagation prediction = lasagne.layers.get_output(final_layer, inputs=inputs, deterministic=False) scores = T.ones_like(prediction) - prediction objective, train_acc = final_layer.objective(-scores, targets) # OC-SVM loss train_loss = T.cast(objective / (targets.shape[0] * nu), dtype='floatX') train_acc = T.cast(train_acc * 1. / targets.shape[0], dtype='floatX') train_obj = T.cast(floatX(0.5) * l2_penalty + train_loss, dtype='floatX') updates = get_updates(nnet, train_obj, trainable_params, solver=nnet.solver) nnet.backprop = theano.function([inputs, targets], [train_obj, train_acc], updates=updates) # Forwardpropagation test_prediction = lasagne.layers.get_output(final_layer, inputs=inputs, deterministic=True) test_scores = T.ones_like(prediction) - test_prediction objective, test_acc = final_layer.objective(-test_scores, targets) # Get network feature representation test_rep = lasagne.layers.get_output(feature_layer, inputs=inputs, deterministic=True) test_rep_norm = test_rep.norm(L=2, axis=1) test_ball_penalty = T.cast(0, dtype='floatX') test_l2_output = T.cast(0, dtype='floatX') # OC-SVM test loss test_loss = T.cast(objective / (targets.shape[0] * nu), dtype='floatX') test_acc = T.cast(test_acc * 1. / targets.shape[0], dtype='floatX') test_obj = T.cast(floatX(0.5) * l2_penalty + test_loss, dtype='floatX') nnet.forward = theano.function([inputs, targets], [test_obj, test_acc, -test_scores, floatX(0.5) * l2_penalty, floatX(0.5) * test_l2_output, test_rep, test_rep_norm, test_loss, floatX(0.5) * test_ball_penalty])
[ "def loss_creator(config):\n return torch.nn.BCELoss()", "def heteroscedastic_loss(network, params, x):\n\n pred_mean, pred_var = network(x)\n logvar = tf.reduce_sum(0.5 * tf.math.log(pred_var), axis=-1)\n squared_error = tf.reduce_sum(0.5 * tf.math.square(params - pred_mean) / pred_var, axis=-1)\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
create a SVDD loss for network given in argument
def compile_update_svdd(nnet, inputs, targets): floatX = Cfg.floatX B = Cfg.B C = Cfg.C nu = Cfg.nu # initialize R if nnet.R_init > 0: nnet.Rvar = shared(floatX(nnet.R_init), name="R") else: nnet.Rvar = shared(floatX(1), name="R") # initialization with R=1 # Loss feature_layer = nnet.all_layers[-1] rep = lasagne.layers.get_output(feature_layer, inputs=inputs, deterministic=False) # initialize c (0.5 in every feature representation dimension) rep_dim = feature_layer.num_units # nnet.cvar = shared(floatX(np.ones(rep_dim) * (1. / (rep_dim ** 0.5))), # name="c") nnet.cvar = shared(floatX(np.ones(rep_dim) * 0.5), name="c") dist = T.sum(((rep - nnet.cvar.dimshuffle('x', 0)) ** 2), axis=1, dtype='floatX') scores = dist - nnet.Rvar stack = T.stack([T.zeros_like(scores), scores], axis=1) loss = T.cast(T.sum(T.max(stack, axis=1)) / (inputs.shape[0] * nu), dtype='floatX') y_pred = T.argmax(stack, axis=1) acc = T.cast((T.sum(T.eq(y_pred.flatten(), targets), dtype='int32') * 1. / targets.shape[0]), 'floatX') # Network weight decay if Cfg.weight_decay: l2_penalty = (1/C) * get_l2_penalty(nnet, include_bias=Cfg.include_bias, pow=Cfg.pow) else: l2_penalty = T.cast(0, dtype='floatX') # Network activation sparsity regularization if Cfg.sparsity_penalty: sparsity_penalty = (1/B) * get_sparsity_penalty(nnet, inputs, Cfg.sparsity, mode=Cfg.sparsity_mode, deterministic=False) else: sparsity_penalty = T.cast(0, dtype='floatX') # Backpropagation (hard-margin: only minimizing everything to a ball # centered at c) trainable_params = lasagne.layers.get_all_params(feature_layer, trainable=True) if Cfg.gaussian_blob: avg_dist = T.mean(1-T.exp(-dist), dtype="floatX") else: avg_dist = T.mean(dist, dtype="floatX") obj_ball = T.cast(floatX(0.5) * l2_penalty + avg_dist + sparsity_penalty, dtype='floatX') updates_ball = get_updates(nnet, obj_ball, trainable_params, solver=nnet.solver) nnet.backprop_ball = theano.function([inputs, targets], [obj_ball, acc], updates=updates_ball) # Backpropagation (without training R) obj = T.cast(floatX(0.5) * l2_penalty + nnet.Rvar + loss + sparsity_penalty, dtype='floatX') updates = get_updates(nnet, obj, trainable_params, solver=nnet.solver) nnet.backprop_without_R = theano.function([inputs, targets], [obj, acc], updates=updates) # Backpropagation (with training R) trainable_params.append(nnet.Rvar) # add radius R to trainable parameters updates = get_updates(nnet, obj, trainable_params, solver=nnet.solver) nnet.backprop = theano.function([inputs, targets], [obj, acc], updates=updates) # Forwardpropagation test_rep = lasagne.layers.get_output(feature_layer, inputs=inputs, deterministic=True) test_rep_norm = test_rep.norm(L=2, axis=1) test_dist = T.sum(((test_rep - nnet.cvar.dimshuffle('x', 0)) ** 2), axis=1, dtype='floatX') test_scores = test_dist - nnet.Rvar test_stack = T.stack([T.zeros_like(test_scores), test_scores], axis=1) test_loss = T.cast(T.sum(T.max(test_stack, axis=1)) / (inputs.shape[0]*nu), dtype='floatX') test_y_pred = T.argmax(test_stack, axis=1) test_acc = T.cast((T.sum(T.eq(test_y_pred.flatten(), targets), dtype='int32') * 1. / targets.shape[0]), dtype='floatX') # Network activation sparsity regularization (with determinisitc=True) if Cfg.sparsity_penalty: test_sparsity_penalty = ((1 / B) * get_sparsity_penalty(nnet, inputs, Cfg.sparsity, mode=Cfg.sparsity_mode, deterministic=True)) else: test_sparsity_penalty = T.cast(0, dtype='floatX') test_obj = T.cast(floatX(0.5) * l2_penalty + nnet.Rvar + test_loss + test_sparsity_penalty, dtype='floatX') nnet.forward = theano.function([inputs, targets], [test_obj, test_acc, test_scores, floatX(0.5) * l2_penalty, test_sparsity_penalty, test_rep, test_rep_norm, test_loss, nnet.Rvar])
[ "def tv_loss(x, name='tv_loss'):\n raise NotImplementedError(\"Please use tensorflow total_variation loss.\")", "def loss_der(network_y, real_y):\n return (network_y - real_y)", "def train_loss(wb_vect, unflattener):\n wb_struct = unflattener(wb_vect)\n n_graphs = 100\n\n samp_graphs, samp_inputs...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
create autoencoder Theano update for network given in argument
def create_autoencoder(nnet): floatX = Cfg.floatX B = Cfg.ae_B C = Cfg.ae_C ndim = nnet.data._X_train.ndim if ndim == 2: inputs = T.matrix('inputs') elif ndim == 4: inputs = T.tensor4('inputs') final_layer = nnet.all_layers[-1] # Backpropagation trainable_params = lasagne.layers.get_all_params(final_layer, trainable=True) prediction = lasagne.layers.get_output(final_layer, inputs=inputs, deterministic=False) # use l2 or binary crossentropy loss (features are scaled to [0,1]) if Cfg.ae_loss == "l2": loss = lasagne.objectives.squared_error(prediction, inputs) if Cfg.ae_loss == "ce": loss = lasagne.objectives.binary_crossentropy(prediction, inputs) scores = T.sum(loss, axis=range(1, ndim), dtype='floatX') loss = T.mean(scores) # Regularization if Cfg.ae_weight_decay: l2_penalty = (floatX(0.5) / C) * regularize_network_params(final_layer, l2) else: l2_penalty = T.cast(0, dtype='floatX') # Network activation sparsity regularization if Cfg.ae_sparsity_penalty: sparsity_penalty = ((1 / B) * get_sparsity_penalty(nnet, inputs, Cfg.ae_sparsity, mode=Cfg.ae_sparsity_mode, deterministic=False)) else: sparsity_penalty = T.cast(0, dtype='floatX') train_obj = loss + l2_penalty + sparsity_penalty updates = get_updates(nnet, train_obj, trainable_params, solver=nnet.ae_solver) nnet.ae_backprop = theano.function([inputs], [loss, l2_penalty, sparsity_penalty, scores], updates=updates) # Forwardpropagation test_prediction = lasagne.layers.get_output(final_layer, inputs=inputs, deterministic=True) # use l2 or binary crossentropy loss (features are scaled to [0,1]) if Cfg.ae_loss == "l2": test_loss = lasagne.objectives.squared_error(test_prediction, inputs) if Cfg.ae_loss == "ce": test_loss = lasagne.objectives.binary_crossentropy(test_prediction, inputs) test_scores = T.sum(test_loss, axis=range(1, ndim), dtype='floatX') test_loss = T.mean(test_scores) # Network activation sparsity regularization (with determinisitc=True) if Cfg.ae_sparsity_penalty: test_sparsity_penalty = ((1 / B) * get_sparsity_penalty(nnet, inputs, Cfg.ae_sparsity, mode=Cfg.ae_sparsity_mode, deterministic=True)) else: test_sparsity_penalty = T.cast(0, dtype='floatX') nnet.ae_forward = theano.function([inputs], [test_loss, l2_penalty, test_sparsity_penalty, test_scores, test_prediction])
[ "def build_full_conv_autoencoder():\n input_img = Input(shape=(84, 84, 3))\n\n x = Convolution2D(48, 8, 8, activation='relu', border_mode='same', name='c1')(input_img)\n x = MaxPooling2D((2, 2), border_mode='same')(x)\n x = Convolution2D(32, 4, 4, activation='relu', border_mode='same', name='c2')(x)\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Tests gotoField if there is a mismatch between MCP and guider.
def test_goto_field_cartridge_mismatch(self): sopTester.updateModel('guider', TestHelper.guiderState['bossLoaded']) mcpState = TestHelper.mcpState['boss_science'] mcpState.update({'instrumentNum': [15]}) sopTester.updateModel('mcp', mcpState) cmdState = self.actorState.gotoField cmdState.reinitialize(self.cmd) masterThread.goto_field(self.cmd, cmdState, myGlobals.actorState) self._check_cmd(0, 14, 0, 0, finish=True, didFail=True)
[ "def field_reached(self):\r\n try:\r\n if abs(self.actual_field - self.goto_field) < 0.0001:\r\n return True\r\n else:\r\n return False\r\n except Exception,e:\r\n log(\"Couldn't determine if field reached!\",e)\r\n return False...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }