query
stringlengths
9
9.05k
document
stringlengths
10
222k
negatives
listlengths
19
20
metadata
dict
Gets the notes that match the given type
def get_notes_by_type(self, typ: type) -> pd.Series: # doesn't use isinstance() to prevent subtypes from being selected return self.notes[self.notes.apply(lambda n: type(n) is typ)]
[ "def list_notes(self, type_name):\n\n notes = []\n\n for note in self.output(\"notes\", \"--ref\",\n make_ref(type_name), \"list\"):\n if not note:\n continue\n notes_obj, annotated_obj = note.split(\" \", 1)\n notes.append...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Gets ids of transactions that have been manually categorized as the given category
def manual_ids(self, cat: str) -> np.ndarray: return self.notes[ # select from notes self.notes.apply( # the ones which are both a Category type and have a matching categorization lambda n: isinstance(n, note.Category) and n.category == cat ) ...
[ "def get_transactions_by_budget(self, category: BudgetCategory) -> list:\n return [transaction\n for transaction in self.transactions\n if transaction.budget_category == category]", "def getInvolvementCategoryIds(self):\n categories = []\n for cat in self.getCate...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Gets ids of transactions that target those in the given DataFrame Example Transactions A and B are both linked to transaction C, which appears in the given DataFrame Returns a Series of ids that include the ids of A and B Returns
def linked_ids(self, df: pd.DataFrame) -> np.ndarray: return self.notes[ # select from notes self.notes.apply( # the ones which are both a Link type and have a target id in the given DataFrame lambda n: isinstance(n, note.Link) and n.target in df['id'].va...
[ "def find_same_amount(df):\n ids = list(df['id'][df.duplicated(['amount','branch_id','exchange_id'],keep= False)==True].values)\n return ids", "def _find_transactions(self, df: DataFrame, transaction_column: str, status: Optional[List[str]] = None) -> DataFrame:\n if status:\n df = df.filt...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Applies Link notes in the given DataFrame, adding the value of each linked transaction onto the one it targets The DataFrame needs to include both the original transactions and the ones linked to them. The values of the linked transactions will be set to 0 as they are added onto the target transaction
def apply_linked(self, df: pd.DataFrame) -> pd.DataFrame: link_notes = self.get_notes_by_type(note.Link) source_in_df = link_notes.apply(lambda n: n.id in df['id'].values) target_in_df = link_notes.apply(lambda n: n.target in df['id'].values) # assert (target_in_df & ~source_in_df).any(...
[ "def mergeValue(linkdf, switch = 'off'):\r\n if switch == 'on': print(\"source: \", linkdf.source.iloc[0], \"; target: \", linkdf.target.iloc[0])\r\n newdf = pd.DataFrame()\r\n newdf = newdf.append(linkdf.iloc[0,])\r\n newdf.loc[:,'value'] = sum(linkdf.value)\r\n \r\n return(newdf)", "def join_t...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Get API_KEY that is set environment variant
def get_apikey(cls) -> str: dotenv_path = Path(__file__).absolute().parents[2] / '.env' if dotenv_path.exists(): load_dotenv(dotenv_path) try: apikey: str = os.environ["API_KEY"] except KeyError: print("API_KEY doesn't exist") raise...
[ "def get(cls):\n apikey = cls.__api_key or cls.__api_key_env_var\n\n if apikey:\n return apikey\n else:\n raise APIKeyMissingError(\"API key not set\")", "def get_api_key():\n try:\n return os.environ[\"GOOGLE_APPLICATION_CREDENTIALS\"]\n except Exception:\n...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Search 60 places that are nearby specified location. Parameter
def search_nearby(self, fields: dict) -> list[dict]: results: list = [] if "location" not in fields.keys(): geolocate: dict = self.get_current_locate() fields["location"] = geolocate["location"] if "radius" not in fields.keys(): fields["radius"] = 10...
[ "def nearby(req):\r\n try:\r\n mid = req.find('near')\r\n obj = req[:9-1]\r\n pos = req[9+5:]\r\n coords = find_lc(pos)\r\n H();sprint('Searching for %s near %s' % (obj, pos))\r\n webbrowser.open('https://google.com/maps/search/%s/@%s,%s' % (obj, coords[0], coords[1]))\r...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Get photo image chunk from photo reference of google map api. The place photo will be converted to base64 to display on browser. ex) place = googlemaps.Client(key=apikey).place(place_id) photos = self.get_place_photo(place["result"]["photos"]["reference"]) Parameter
def get_place_photo(self, photo_ref: str) -> str: photo_bin = self.gmaps.places_photo(photo_ref, max_width=1000) photo = base64.b64encode(b''.join(photo_bin)).decode() return photo
[ "def _get_place_photo(photoreference, api_key, maxheight=None, maxwidth=None,\n sensor=False):\n\n params = {'photoreference': photoreference,\n 'sensor': str(sensor).lower(),\n 'key': api_key}\n\n if maxheight:\n params['maxheight'] = maxheight\n\n if...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Formats the given date in RFC 3339 format for feeds.
def rfc3339date(date): if not date: return '' date = date + datetime.timedelta(seconds=-time.timezone) if time.daylight: date += datetime.timedelta(seconds=time.altzone) return date.strftime('%Y-%m-%dT%H:%M:%SZ')
[ "def format_date(self, data):\r\n if self.datetime_formatting == 'rfc-2822':\r\n return format_date(data)\r\n\r\n return data.isoformat()", "def format_rfc3339(time: Datetime) -> str:\n if isinstance(time, (datetime.date, datetime.datetime)):\n time = time.strftime(\"%Y-%m-%dT%H...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
timer function for comparing running times of NN algorithms. Returns a tuple of runtime and predicted labels
def timer(trainX, trainY, testX, k, condensed=False): gc.disable() # disable garbage collector for uninterrupted timing initial = clock() if condensed: cnn = condenseData(trainX, trainY) testY = testknn(trainX[cnn], trainY[cnn], testX, k) else: testY = testknn(trainX, tr...
[ "def time_models(x_tr, x_te, y_tr, y_te, mod_list, mod_labels, time_obj, count=0, keep=True, show=True, cls_lab=None):\n \n durations = {}\n \n for m in mod_list:\n if show:\n time_obj.start()\n evaluate_model(m, x_tr, x_te, y_tr, y_te, cls_labels=cls_lab)\n time_...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
computes accuracy given a confusion matrix
def accuracy(confusion_matrix): return confusion_matrix.diagonal().sum() / confusion_matrix.sum()
[ "def confusion_accuracy(confusion_matrix):\n diag = tf.linalg.tensor_diag_part(confusion_matrix)\n total_per_calss = tf.reduce_sum(confusion_matrix, axis=1)\n acc_per_class = diag / tf.maximum(1, total_per_calss)\n accuracy = non_nan_average(acc_per_class)\n\n return accuracy", "def get_accuracy(co...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Thread worker function this does the actual pinging and records ping data in the ring buffers for processing into latency statistics as needed.
def run(self): rate = WallRate(self.ping_frequency) while True: # In case of failure, this call will take approx 10s try: # Send 5 pings at an interval of 0.2s output = subprocess.check_output("ping -c 1 %s" % self.ip, ...
[ "def measure_latency(self, num_pings = 10):\n self._check_server_health()\n latencies = []\n if not self.server_alive:\n return\n if self.approx_latency_ms == float('inf'):\n while True:\n delay = ping.Ping(self.host, timeout=1000).do()\n if delay:\n self.approx_latency_...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Python method for retrieving local volatility matrix to have more control over the input parameters
def GetLocalVol(volInfo, isCall, forwardArray, strikeArray, timeGrid, valuationDate, skewExpiries): if timeGrid.Size() == 0: return acm.FRealMatrix() return volInfo.LocalVolatilityMatrix(isCall, forwardArray, strikeArray, timeGrid, 0.001, valuationDate, skewExpiries)
[ "def compute_local_vol_matrix(characteristic_function,\n market_params,\n strike_selector,\n maturity_times):\n strikes, maturity_times, implied_vol_surface = \\\n compute_implied_vol_surface(characteristic_function,\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Performs the GET/POST calls to the aXAPI REST interface.
def call_api(axobjectinstance, **args): if AXAPI_LOGIN == 1: args["session_id"] = AXAPI_SESSION_ID if args.has_key("post_data"): data = args["post_data"] del args["post_data"] url_str = _get_request_url()+"?"+urllib.urlencode(args) else: data = urllib.urlencode(args...
[ "def call_api(self):\n\n request = (requests.get(self.url, headers=self.headers))\n print(f\"\\nStatus code: {request.status_code}\")\n\n # Process the request\n self._process_data(request)", "def call_rest_api(self):\n return self.api.callAPI(self.rest_path, self.rest_method, q...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Parses a JSON request string to an instance of the Request class.
def parse_request(json_data: str) -> Request: logger.debug('Type: {}'.format(type(json_data))) data = json.loads(json_data) return Request( data["text"], PatternCategory(data["previous_pattern"] ) if "previous_pattern" in data else None, data["mood"], ...
[ "def from_json(cls, json_str: str) -> CallbackRequest:\n return cls.from_dict(json.loads(json_str))", "def from_json(json_string: str) -> AnalysisRequest:\n dict_obj = json.loads(json_string)\n\n # make sure the required parameters are present\n required_fields = [\"request_id\"]\n\n for field ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Test that viewlist does not show when not signed in
def testviewlist(self): rv = self.app.get('/viewcategory') self.assertEqual(rv.status_code, 302, "viewlist page should not load unless signed in")
[ "def test_user_views_without_login(self):\n for view in ['/', '/create/', '/toggle/', '/team/add/', '/view/1/', '/edit/1/', '/perms/update/']:\n response = self.client.get('/users%s' % view)\n self.assertRedirects(response, '/login/?next=/users%s' % view, msg_prefix='Error for view:%s' ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Test that createlist does not show when not signed in
def testcreatelist(self): rv = self.app.get('/createcategory') self.assertEqual(rv.status_code, 302, "createlist page should not load unless signed in")
[ "def test_create_list(self):\n pass", "def test_authenticated_cannot_create_tags(self):\n self.client.force_login(user=self.user)\n response = self.client.post(\n reverse(self.list_view),\n {'name': 'create'}\n )\n self.assertEqual(response.status_code, sta...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Compare a numerical method with the exact values gotten from Rungekutta and refine it till it matches the exact values with the requried error tolerance.
def compare_exact_with(self, exact_details, method="", err_tolerance=0.001): exact = exact_details[self.modified_t_z_label] exact_2 = exact_details[self.modified_t_z__final_h_label] # print("\n\nExact...") # print(exact) method_dict = self.get_t_z_from_step(self.h, method)...
[ "def test_newton_rhapson_system(testFunctions, tol, printFlag): \n pass", "def test_newton_rhapson(testFunctions, tol, printFlag): \n pass", "def test_func2():\n print '=== Comparing exact and numerical solution for pure vertical motion ==='\n beta_eps = [0.1, 0.3, 0.5, 0.7, 0.9]\n for bet...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Balance tree starting from current node. Return root node of the whole tree.
def __balance(self) -> "Node": current = self while True: current.__update_height() if current.balance_factor == 2: # right subtree is higher middle = current.right if middle.balance_factor < 0: # left subtree of middle node is higher ...
[ "def balance_if_needed(self,node):\n if node is None:\n return\n height = abs(self.height(node.left) - self.height(node.right))\n if height > 1:\n isRight = self.height(node.right) > self.height(node.left)\n biggerChild = node.right if isRight else node.left\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Compute sum of all keys less than this one, sum of all keys greater than this one and then return them.
def split_sums(self, key: int) -> Tuple[int, int]: current = self less, greater = 0, 0 while key != current.key: if key < current.key: # add all greater keys greater += current.right.sum if current.right is not None else 0 greater += c...
[ "def keys_geq_threshold (Dict, threshold):\n for key, value in Dict.items ():\n if value >= threshold:\n yield key", "def items_aged(self):\n now = datetime.datetime.now()\n L1 = [ (k, v[0], v[1]) for k, v in dict.items(self) ]\n L2 = []\n for k, v, ts in L1:\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Return sum of all keys of the tree.
def sum(self) -> int: return self.root.sum
[ "def __tree_keys__(self):\n return self.keys(dynamic=1)", "def get_num_keys(self) -> int:\n return self.root.get_num_keys_total()", "def keys(self, _prec=\"\"):\n if self.isLeaf:\n yield _prec + self.ch\n\n for chld in self.children.values():\n yield from chld.k...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Insert key (create new element) in the tree and return True on success or False on failure.
def insert(self, key: int) -> bool: if self.empty(): # empty tree, so value becomes the root self.root = Node(key) return True current = self.root # start at the root while current.key != key: if key < current.key: if current.left is None:...
[ "def insert(self, key, value):\n\n if None == self.root:\n self.root = BSTNode(key,value)\n return True\n current_node = self.root\n while current_node:\n if key == current_node.key:\n print(\"The key does exist!\")\n re...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Remove element with such key if it exists in the tree (return True), or return False otherwise.
def remove(self, key: int) -> bool: current = self.root.find(key) if not self.empty() else None if current is None: # if no such key, failure return False self.root = current.remove() # update root return True
[ "def remove(self, key: object) -> None:\n if self.size > 1:\n to_remove = self._get(key, self.root)\n if to_remove:\n self._remove(to_remove)\n self.size = self.size - 1\n else:\n raise KeyError(ERR_NONEXISTING_KEY)\n elif s...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Compute sum of all tree keys in segment [left, right].
def segment_sum(self, left, right): if self.empty(): return 0 less, _ = self.root.split_sums(left) _, greater = self.root.split_sums(right) return self.sum - less - greater
[ "def split_sums(self, key: int) -> Tuple[int, int]:\n current = self\n less, greater = 0, 0\n while key != current.key:\n\n if key < current.key:\n # add all greater keys\n greater += current.right.sum if current.right is not None else 0\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
`ready` should call `can_end` if all players are ready
def test_ready_true(self): mock_player = Mock() mock_stage = Mock() mock_stage._ready_list = [] mock_stage.game.players = [mock_player] JobStage.ready(mock_stage, mock_player) mock_stage.can_end.assert_called_once_with()
[ "def set_ready(self):\n if self.game.has_started() or self.status == self.PLAYER_READY:\n return\n self.status = self.PLAYER_READY\n self.game.player_is_ready()", "def ready_new_round_players(self):\n for player in self.players:\n if player.is_playing:\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
`ready` should not call `can_end` if not all players are ready
def test_ready_false(self): mock_player = Mock() mock_stage = Mock() mock_stage._ready_list = [] mock_stage.game.players = [mock_player, Mock()] JobStage.ready(mock_stage, mock_player) self.assertFalse(mock_stage.can_end.called)
[ "def maybe_start(self):\r\n\t\tif not [p for p in self.players if not p.ready]\\\r\n\t\t and len(self.players) == self.max_players \\\r\n\t\t and not self.started:\r\n\t\t\tself.start()", "def test_ready_true(self):\n\n mock_player = Mock()\n mock_stage = Mock()\n mock_stage._ready_list...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Entry; returns the ithjth entry of this matrix (1 based) >>> x = Matrix(2,3, data = [1,2,3,4,5,6]) >>> x.entry(1,3) 3 >>> x.entry(2,2) 5
def entry(self, i, j): return self.data[self.columns * (i - 1) + j - 1]
[ "def _get_entry_number(self):\n return self.__entry_number", "def get_entry(self, index = None):\n if self.land_tiledata and index and index < 0x4000:\n return self.land_tiledata[index]\n elif self.static_tiledata and index:\n return self.static_tiledata[index]\n else...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns a new matrix that is the transpose of self >>> m = Matrix(2,3, data=[1,2,3,4,5,6]) >>> t = m.transpose() >>> t.size() (3, 2) >>> t.row(1) [1, 4] >>> t.column(1) [1, 2, 3]
def transpose(self): transposed_data = [] for i in range(1, self.columns + 1): transposed_data.extend(self.column(i)) return Matrix(rows = self.columns, columns = self.rows, data = transposed_data)
[ "def transpose(self):\n return Matrix([[self.data[r][c] for r in range(len(self.data))]\n for c in range(len(self.data[1]))])", "def transpose(self): \r\n m, n = self.n, self.m\r\n mat = Matrix(m,n)\r\n mat.rows = [list(item) for item in zip(*self.rows)]\r\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Matrix addition. Sizes must be the same >>> x = Matrix(2,2, data=[1,2,3,4]) >>> y = Matrix(2,2, data=[5,6,7,8]) >>> z = x + y >>> z.size() (2, 2) >>> z.row(1) [6, 8] >>> z.row(2) [10, 12]
def __add__(self, other): if not issubclass(type(other), Matrix): raise TypeError(type(other)) if self.rows != other.rows or self.columns != other.columns: raise ValueError("Sizes should be equivalent") result = [ x + y for x, y in zip(self.data, other.data)] re...
[ "def __add__(self, OtherMatrix):\n\n assert self.size() == OtherMatrix.size(), \\\n \"\"\"Error: The two matrices are of different dimensions.\"\"\"\n matric_new = []\n matrix_other = OtherMatrix.show()\n\n for row in range(len(self.matrix)):\n matric_new.append([su...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Matrix multiplication. If self.size() = (m, n), then other.size()[0] == n >>> x = Matrix(2,3, data=[1,2,3,4,5,6]) >>> y = Matrix(3,1, data=[7, 8, 9]) >>> z = x y >>> z.size() (2, 1) >>> z.row(1) [50] >>> z.row(2) [122] >>> z = 10 x >>> z.size() (2, 3) >>> z.row(1) [10, 20, 30]
def __mul__(self, other): # Scalar multiplication if isinstance(other, (int, long, float, complex)): return Matrix(self.rows, self.columns, [other * x for x in self.data]) if not issubclass(type(other), Matrix): raise TypeError(type(other)) if self.columns != o...
[ "def __mul__(self, other):\n if isinstance(other, Matrix): # Checks if other is a matrix object.\n if self.can_be_multiplied_by(other): # Checks if the matrices are compatible for multiplication.\n answer = Matrix()\n for i in range(self.__rows):\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Matrix equality. >>> m = Matrix(2,3, data=[1,2,3,4,5,6]) >>> n = Matrix(2,3, data=[1,2,3,4,5,6]) >>> m == n True >>> m = Matrix(2,3, data=[1,2,3,4,5,6]) >>> n = Matrix(3,2, data=[1,2,3,4,5,6]) >>> m == n False >>> m = Matrix(2,3, data=[1,2,3,4,5,6]) >>> n = Matrix(2,3, data=[1,5,3,4,2,1]) >>> m == n False
def __eq__(self, other): if not issubclass(type(other), Matrix): return False if self.rows != other.rows or self.columns != other.columns: return False return self.data == other.data
[ "def matrix_equals(a, b):\n if type(a) != type(b):\n return False\n if isinstance(a, numpy.ndarray) and a.shape != b.shape:\n return False\n equal = (a == b)\n if isinstance(equal, numpy.ndarray):\n # numpy comparison returns a boolean matrix\n return equal.all()\n else:\n...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns true iff other is the inverse of self. That is, if A = self, and B = other, then AB = I and BA = I. >>> A = Matrix(2,2, data = [0, 1, 1, 1]) >>> B = Matrix(2,2, data = [1, 1, 1, 0]) >>> A.is_inverse(B) True >>> A = Matrix(2,2, data = [0, 1, 1, 1]) >>> B = Matrix(2,2, data = [10, 5, 1, 0]) >>> A.is_inverse(B) Fa...
def is_inverse(self, other): return (self * other).is_identity() and (other * self).is_identity()
[ "def has_true_inverse(self):\n return True", "def is_involution(self):\n return self == self.inverse()", "def invertible(self):\n a = self._data\n return a.shape[0] == a.shape[1] and np.linalg.matrix_rank(a) == a.shape[0]", "def GetInverse(self, inverse: 'itkMultiTransformD33') -> ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns true iff this matrix is in row echelon format. >>> x = Matrix(2, 3, data=[1, 4, 5, 0, 0, 1]) >>> x.is_row_echelon() True >>> x = Matrix(2, 3, data=[1, 4, 5, 1, 0, 1]) >>> x.is_row_echelon() False
def is_row_echelon(self): return self._is_row_echelon(False)
[ "def is_reduced_row_echelon(self):\n return self._is_row_echelon(True)", "def is_row_echelon(a):\n n = len(a)\n p = -1\n for i in range(n):\n j = 0\n while j <= n:\n if j == n:\n p = n\n break\n elif a[i][j] == 0:\n j...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns true iff this matrix is in row echelon format. >>> x = Matrix(2, 3, data=[1, 4, 5, 0, 0, 1]) >>> x.is_reduced_row_echelon() False >>> x = Matrix(2, 3, data=[1, 4, 0, 0, 0, 1]) >>> x.is_reduced_row_echelon() True >>> x = IdentityMatrix(10) >>> x.is_reduced_row_echelon() True >>> x.is_row_echelon() True
def is_reduced_row_echelon(self): return self._is_row_echelon(True)
[ "def is_row_echelon(self):\n return self._is_row_echelon(False)", "def is_row_echelon(a):\n n = len(a)\n p = -1\n for i in range(n):\n j = 0\n while j <= n:\n if j == n:\n p = n\n break\n elif a[i][j] == 0:\n j += 1\n...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Apply the Gaussian Algorithm to produce a matrix in row echelon form. Returns the resulting matrix and a list of the elementary operations applied. >>> x = Matrix(4, 6, data = [0, 0, 0, 2, 1, 9, 0, 2, 6, 2, 0, 2, 0, 2, 6, 2, 2, 0, 0, 3, 9, 2, 2, 19]) >>> x.is_row_echelon() False >>> x.is_reduced_row_echelon() False >>>...
def to_reduced_row_echelon(self): return self._to_row_echelon(fully_reduce = True)
[ "def rowReduce(self):\n myMatrix = Matrix(self.Matrix)\n print(\"This is the row reduced echelon form of your matrix: \\n\", myMatrix.rref())", "def reduced_echelon_form(matrix):\n M = echelon_form(Matrix(matrix))\n i = M.shape[0] - 1\n while i >= 0:\n row_bool = [bool(e) for e in M[...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Apply the Gaussian Algorithm to produce a matrix in row echelon form. Returns the resulting matrix and a list of the elementary operations applied. >>> x = Matrix(4, 6, data = [0, 0, 0, 2, 1, 9, 0, 2, 6, 2, 0, 2, 0, 2, 6, 2, 2, 0, 0, 3, 9, 2, 2, 19]) >>> x.is_row_echelon() False >>> y, ops = x.to_row_echelon() >>> y.is...
def to_row_echelon(self): return self._to_row_echelon(fully_reduce = False)
[ "def _row_echelon_form(A,starting_pivots=[(0,0)],do_nothing=False):\n spx,spy=starting_pivots[-1]\n nrows,ncols=A.shape\n if spx >= nrows or spy >= ncols:\n return starting_pivots[:-1]\n # find the first x for which A[x,0] != 0 \n done=False\n for y in range(spy,ncols):\n if not done...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Matrix Inversion; attempt to find the inverted matrix, or 0 if self is not invertible. >>> A = Matrix(3, 3, data = [2, 7, 1, 1, 4, 1, 1, 3, 0]) >>> B = A.invert() >>> B.row(1) [1.5, 1.5, 5.5] >>> B.row(2) [0.5, 0.5, 1.5] >>> B.row(3) [0.5, 0.5, 0.5] >>> C = A B >>> C.is_identity() True >>> C = B A >>> C.is_identity() T...
def invert(self): if self.rows != self.columns: raise ValueError("Matrix must be square to invert") A, operations = self.to_reduced_row_echelon() if not A.is_identity(): return 0 # If A was reduced to the identity matrix, then the same set of operations will ta...
[ "def inverse(self) -> \"Matrix\":\n new_mtx = Matrix(self._nrows, self._ncols)\n # step 1. Create a matrix of minors, taking the determinants of the submatrices\n for row in range(self._nrows):\n for col in range(self._ncols):\n val = self.get_sub_matrix(row, col).get_determinant()\n # s...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns the adjoint of A; that is, the transpose of the coefficient matrix of A. >>> A = Matrix(3, 3, data = [1, 3, 2, 0, 1, 5, 2, 6, 7]) >>> adj = A.adjoint() >>> adj.row(1) [37, 9, 17] >>> adj.row(2) [10, 3, 5] >>> adj.row(3) [2, 0, 1]
def adjoint(self): data = [] for i in range(1, self.rows + 1): for j in range(1, self.columns + 1): data.append(self._cofactor(i, j)) mat = Matrix(self.rows, self.columns, data) return mat.transpose()
[ "def adjoint(self):\n return self.cofactorMatrix().transpose()", "def adjoint(self):\n rotmat = self.rot.as_matrix()\n return np.vstack(\n [np.hstack([rotmat,\n self.RotationType.wedge(self.trans).dot(rotmat)]),\n np.hstack([np.zeros((3, 3)), rotm...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Matrix rank; returns the number of leading 1's for the row echelon form of this matrix >>> a = Matrix(2,2, data = [1,0,0,1]) >>> a.rank() 2 >>> x = Matrix(4, 6, data = [0, 0, 0, 2, 1, 9, 0, 2, 6, 2, 0, 2, 0, 2, 6, 2, 2, 0, 0, 3, 9, 2, 2, 19]) >>> x.rank() 3
def rank(self): if self._rank >= 0: return self._rank reduced, operations = self.to_row_echelon() non_leading_rows = 0 for i in range(self.rows, 0, -1): if not reduce(lambda x,y: x or y, reduced.row(i)): non_leading_rows += 1 else: ...
[ "def rank(self):\n return self.matrix().rank()", "def Rank(matrix):\n\treturn len(Basis(matrix)) # Compute a basis for the matrix, and return its length", "def rank(self):\n return matrix_rank(self.wdesign)", "def rank(self):\n return 0", "def rank(self, simplified=False, with_last_col=...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Use the Eggleton formula for the given mass ratio.
def eggleton_formula(mass_ratio): two_third = mass_ratio**(2.0/3.0) one_third = mass_ratio**(1.0/3.0) return 0.49 * two_third / ( 0.6 * two_third + numpy.log(1.0 + one_third))
[ "def calculate_fuel(mass):\r\n return mass // 3 - 2", "def mass_handling_gear(\n design_mass_TOGW: float,\n):\n return 3e-4 * design_mass_TOGW", "def cal_mass(self):\n\n if not self.check_def(['E','px','py','pz']):\n sys.exit('Particle error: Quadri impulsion not define (error for...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Return the orbital separation in the same units as the semimajor axis
def separation(semimajor_axis, eccentricity, true_anomaly): numerator = semimajor_axis * (1.0-eccentricity**2) denominator = 1.0 + eccentricity * numpy.cos(true_anomaly) return numerator / denominator
[ "def separation(z):\n return round((1 - MU * z) * EYE_SEP / (2 - MU * z))", "def semiminor_axis(self):\n return self.semimajor_axis * (1 - self.flattening)", "def _get_semimajor_axis(self):\n t0 = jd.t_zero(self._julianDay)\n switcher = {\n 1: 0.387099270 + t0 * 0.00000037...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
The Roche radius assumes a curcular orbit with the current separation. Note that this is not really correct for noncircular orbits.
def eggleton_roche_radius(self): return self.eggleton_roche_over_separation() * self.separation()
[ "def rotor_radius(self):\n return self.rotor_diameter / 2.0", "def polar_radius(self):\n return self.r * (1 - self.f)", "def get_radius(self):\n if self.no_dist is False:\n dist = self.distance\n radius = (dist * self.ang_size / 60. *\n np.pi/180. ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Sets the current_page of this CampaignResults.
def current_page(self, current_page): self._current_page = current_page
[ "def current_page(self, current_page: int):\n\n self._current_page = current_page", "def update_current_page() -> None:\n st.session_state[\"set_page\"] = st.session_state[\"current_page\"]", "def set_current_page(page: str) -> None:\n st.session_state[\"current_page\"] = page", "def go_to_next_p...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Sets the last_page of this CampaignResults.
def last_page(self, last_page): self._last_page = last_page
[ "def set_last_page(self, page):\n self.last_page = page\n if self.get_page() > page:\n self.set_page(page)", "def last_page(self):\n if self.is_last_disabled:\n raise PaginationNavDisabled(\"last\")\n self._last.click()", "def max_results(self, max_results):\n\n...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Sets the next_page_url of this CampaignResults.
def next_page_url(self, next_page_url): self._next_page_url = next_page_url
[ "def next_page(self, next_page):\n\n self._next_page = next_page", "def next_page_token(self, next_page_token):\n\n self._next_page_token = next_page_token", "def next_url(self):\n\n return self.make_link(self.page + 1, 'next')", "def setNext(self, nextNode):\n self.__next = nextNo...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Sets the per_page of this CampaignResults.
def per_page(self, per_page): self._per_page = per_page
[ "def set_per_page(self, per_page):\n\n\t\tif per_page is not None and not isinstance(per_page, int):\n\t\t\traise SDKException(Constants.DATA_TYPE_ERROR, 'KEY: per_page EXPECTED TYPE: int', None, None)\n\t\t\n\t\tself.__per_page = per_page\n\t\tself.__key_modified['per_page'] = 1", "def set_per_page(self, entries...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Sets the prev_page_url of this CampaignResults.
def prev_page_url(self, prev_page_url): self._prev_page_url = prev_page_url
[ "def prev_url(self):\n\n return self.make_link(self.page - 1, 'prev')", "def prevPage(self):\n self.setIndex(self.prevPageIndex)", "def setPrev(self, prev):\n\t\t\tself.prev = prev", "def previous_page(self):\n \n return self._api.copy(url=URLObject.parse(self.paging.next))", "de...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Download and parse carbanak report Add facts for md5, sha256, c2 and campaigns
def carbanak_report(client, md5_lookup): for row in get_xlsx_report( "https://www.fireeye.com/content/dam/fireeye-www/blog/pdfs/carbanak-report.xlsx", "Sheet1")[1:]: # First row is header md5 = row[0] campaign = row[3] c2_list = row[4:] sha256 = md5_lookup.g...
[ "def handle_report(\n actapi: act.api.Act, report: Dict[Text, Any]\n) -> List[act.api.fact.Fact]:\n\n feeds_facts: List[act.api.fact.Fact] = []\n\n content = report[\"sha256\"]\n for hash_type in [\"md5\", \"sha1\", \"sha256\", \"ssdeep\", \"imphash\", \"sha512\"]:\n if (\n hash_type n...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Load the test application.
def load_app(name=application_name): return TestApp( loadapp( 'config:test.ini#%s' % name, relative_to=getcwd(), global_conf={ 'test': 'true', }, ) )
[ "def loadapp(self, app, params=None):\n if not TESTMODE:\n app = 'snakewm.' + app\n\n _app = importlib.import_module(app)\n _app.load(self.MANAGER, params)", "def test_apps(self):\n import main.apps", "def testCreateApplication(self):\n main.create_application()", "de...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
guess ext from http header contentdisposition if have
def guess_ext_from_content_disposition(self): # may be bug, Content-Disposition attachment; filename="MyspacePasswordDecryptor.zip"; if self.content_disposition: file_name = self.content_disposition.split('filename=')[1] # "MyspacePasswordDecryptor.zip"; maybe like this,so rstrip...
[ "def auto_get_file_extension(self):\n self.resolve_what_url()\n self.guess_ext_from_content_disposition()\n # guess ext from content_disposition success\n if None != self.save_file_ext:\n return\n else:\n self.guess_ext_from_url()", "def parse_content_dispo...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
auto guess file ext if can not guess,self.save_file_ext is None self.save_file_ext always contain .
def auto_get_file_extension(self): self.resolve_what_url() self.guess_ext_from_content_disposition() # guess ext from content_disposition success if None != self.save_file_ext: return else: self.guess_ext_from_url()
[ "def get_file_extension(self) -> str:\n ...", "def _get_file_type(self, ext: str) -> str:\n return self.FILE_TYPE.get(ext, 'Unknown')", "def guess_ext_from_content_disposition(self):\n # may be bug, Content-Disposition attachment; filename=\"MyspacePasswordDecryptor.zip\";\n if self....
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
if down success,no Exception else, DenyMimes,CanNotGuessExtension,DownError will raise
def down(self): try: self.do_request() info = self.response.info() self.mime_type = info.gettype() if self.mime_type in self.deny_mimes: raise DenyMimes('Wrong Mime type: ' + self.mime_type) self.header_file_bytes = int(info.getheader("...
[ "def down(self, url, save_dir, save_file_without_ext, downing_callback, max_try):\n i = 1\n while i <= max_try:\n try:\n down_file = DownFile(url, save_dir, save_file_without_ext, downing_callback)\n down_file.down()\n except DenyMimes, e:\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
download file,do retry,if failed after retry,raise DownError(last error) if success, return DownFile object
def down(self, url, save_dir, save_file_without_ext, downing_callback, max_try): i = 1 while i <= max_try: try: down_file = DownFile(url, save_dir, save_file_without_ext, downing_callback) down_file.down() except DenyMimes, e: self....
[ "def _UrlRetrieveWithRetry(url, dest):\n return urlretrieve.urlretrieve(url, dest)", "def download_with_retries(url, destination, retries=5):\n for attempt in range(1, retries + 1):\n urlcleanup() # Seems important with FTP on Python 2.7\n try:\n return urlretrieve(url, destination)\...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns the exact numerical values for the simplest linear case. angle_0 and omega_0 are defined at t[0].
def LinSolution(t, angle_0, omega_0, a = 1): if angle_0 == 0: A = omega_0/np.sqrt(a) phi = np.pi/2 - np.sqrt(a)*t[0] else: A = angle_0 phi = -(np.sqrt(a)*t[0]) angle = A*np.cos(np.sqrt(a)*t + phi) omega = -A*np.sqrt(a)*np.sin(np.sqrt(a)*t + phi) ret...
[ "def test_linear():\n import nose.tools as nt\n A = -0.11; B = -0.13; g = 9.81; m = 50.; T = 10.; dt = 0.01;\n Cd = 1.2; rho = 1.0; A = 0.5;\n a = Cd*rho*A/(2.*m)\n def exact(t):\n return A*t+B\n\n def src(t):\n return m*g + m*a*abs(exact(t-dt/2.))*exact(t+dt/2.) + m*A\n \n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Solves the system defined by NonLinPendulum. 'angle_0' and 'omega_0' are defined at t[0]. The 'pendParas' tuple = (a, q, F, drivAngFreq). Returns an array of arrays of t, angle, and omega respectively
def Response(time, angle_0, omega_0, pendParas = (1,0,0,0)): initCondition = [angle_0, omega_0] solution = integrate.odeint(NonLinPendulum, y0 = initCondition, t = time, args = pendParas) return np.array([time, solution[:,0], solution[:,1]])
[ "def nonlinear_pendulum(t, X, **kwargs):\n theta = X[0]\n omega = X[1]\n\n if len(kwargs) == 0:\n theta_dot = omega\n omega_dot = (-(const.g / NONLINPEND_L)\n * math.sin(theta))\n elif len(kwargs) != 1:\n raise ValueError(\"Bad kwargs; please provide all of the \...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Estimates the time period from the roots of the angle
def EstimatePeriod(response): #is a bit shoddy, requires long time periods to produce consistent results roots = np.array([]) for i in range(len(response[1])): try: if response[1][i] == 0: roots = np.append(roots, response[0][i]) #te...
[ "def start_solar_time_angle(omega, period):\r\n return omega - (pi*period)/24", "def _period( self ):\r\n\treturn 2 * pi * sqrt( self.orbital_elements[0]**3 / self.mu_central_body )\r\n\t# http://en.wikipedia.org/wiki/Orbital_period#Calculation\r", "def end_solar_time_angle(omega, period):\r\n return omeg...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
build language models for each label each line in in_file contains a label and an URL separated by a tab(\t)
def build_LM(in_file): print 'building language models...' file_contents = open(in_file).readlines() #for each line in the file, split the language type away from the text line #split the text line into n grams and add it to the correct language type #apply smoothing to the final dictionary for line in file_conte...
[ "def build_LM(in_file):\n print(\"building language models...\")\n\n #Language model and counts\n LM = {'malaysian':{},'indonesian':{},'tamil':{}} \n LM_counts = {'malaysian':0,'indonesian':0,'tamil':0} \n\n input_text = open(in_file,encoding='utf8')\n\n #Format of line of text: [label][space][sen...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
test the language models on new URLs each line of in_file contains an URL you should print the most probable label for each URL into out_file
def test_LM(in_file, out_file, LM): print "testing language models..." # for each input line, break string into ngrams, then check it against each probability model test_contents = open(in_file).readlines() writer = open(out_file, 'w') for line in test_contents: fourgrams = ngram_from_line(line) label = cal...
[ "def test_LM(in_file, out_file, LM):\n print(\"testing language models...\")\n\n #Input test, output predictions, model files\n input_test = open(in_file,encoding='utf8')\n output_pred = open(out_file,'w')\n model = LM\n\n for line in input_test:\n sentence = line.strip()\n grams = [...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Computes the sum of two complex numbers
def complex_sum(c_1,c_2): return c_1 + c_2
[ "def __add__(self,other):\n\t\treal = self.realPart + other.realPart\n\t\timaginary = self.imaginaryPart + other.imaginaryPart\n\n\t\t#create and return new complexnumber\n\t\treturn real,imaginary", "def __add__(self, other):\n self.sum_complex_num = Complex((self.real + other.real), (self.imaginary + oth...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Computes the difference of two complex numbers
def complex_difference(c_1,c_2): return c_1 - c_2
[ "def __sub__(self,other):\n\t\treal = self.realPart - other.realPart\n\t\timaginary = self.imaginaryPart - other.imaginaryPart\n\n\t\t#create and return complexNumber\n\t\treturn real,imaginary", "def complex_multiplication(c1,c2,cr):\n cr[0] = c1[0]*c2[0] - c1[1]*c2[1]\n cr[1] = c1[0]*c2[1] + c1[1]*c2[0]\n...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Computes the multiplication of two complex numbers
def complex_multiplication(c1,c2,cr): cr[0] = c1[0]*c2[0] - c1[1]*c2[1] cr[1] = c1[0]*c2[1] + c1[1]*c2[0] return cr
[ "def __mul__(self,other):\n\t\treal = (self.realPart * other.realPart) - (self.imaginaryPart * other.imaginaryPart)\n\t\timaginary = (self.realPart*other.imaginaryPart) + (self.imaginaryPart * other.realPart)\n\n\t\t# create and return complexNumber\n\t\treturn real,imaginary", "def __mul__(self, other):\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Reads a string and extracts complex numbers. Return, values of list each list per index and operation
def complex_reader(operation,input): input = input[1:len(input)-1] #extracts the first complex number and arranges the real part and imaginary part in list complex_1 = input[: input.find(')')].split('+') #Creates a list with the imaginary and real part of the first complex number complex_1[1] = complex...
[ "def _read_complex(self, card):\n #msg = 'complex matrices not supported in the DMI reader...'\n #raise NotImplementedError(msg)\n # column number\n j = integer(card, 2, 'icol')\n # counter\n i = 0\n fields = [interpret_value(field, card) for field in card[3:]]\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Gives the inverse of a complex number
def complex_inverse(c1,cr):
[ "def complex(real, imag):", "def imag(z):", "def __neg__(self):\n return Complex(-self._reNum, -self._imNum)", "def __complex__(self): \n return complex(self.real, self.imag)", "def __complex__(self):\n return complex(self._reNum, self._imNum)", "def conjugate(self):\n r...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
returns an example java class with the given content_to_add contained within a method.
def setup_java_class(content_to_add): template = """ public class Lambda { public static void main(String args[]) { %s } } """ return template % content_to_add
[ "def add_example(self, example):\n raise NotImplementedError", "def _add(self, example: Dict[str, Any]) -> Dict[str, Any]:\n raise NotImplementedError", "def get_addable(content_type):", "def create_article_with_code(self):\n code_content = \"\"\"\n```python\nprint(\"Hello CodeCollect! I am Artic...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
yields the result of filtering the given class for the given type inside the given method identified by its name.
def filter_type_in_method(clazz, the_type, method_name): for path, node in clazz.filter(the_type): for p in reversed(path): if isinstance(p, tree.MethodDeclaration): if p.name == method_name: yield path, node
[ "def filterMethod(key, name):\n return filter(lambda c: c[\"Method\"][\"Name\"] == name, am.Query(key=key).map())", "def filter_by(self, *klass: Type[_ElementT]) -> Iterator[_ElementT]:\n yield from (el for el in self if isinstance(el, klass)) # noqa Bug in pycharm.", "def scan_methods(obj, filter_f)...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
asserts that the given tree contains a method with the supplied method name containing a lambda expression.
def assert_contains_lambda_expression_in_m( self, clazz, method_name='main'): matches = list(filter_type_in_method( clazz, tree.LambdaExpression, method_name)) if not matches: self.fail('No matching lambda expression found.') return matches
[ "def islambda(func):\n return getattr(func, 'func_name', False) == '<lambda>'", "def test_call_private_method_via_nested_lambda(self):\n self.assertEqual(\n \"Class.public_method -> Class.private_method\", self.Class().public_method_using_nested_lambdas())", "def assert_contains_method_refe...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
tests support for lambda with no parameters and no body.
def test_lambda_support_no_parameters_no_body(self): self.assert_contains_lambda_expression_in_m( parse.parse(setup_java_class("() -> {};")))
[ "def test_lambda_support_no_parameters_expression_body(self):\n test_classes = [\n setup_java_class(\"() -> 3;\"),\n setup_java_class(\"() -> null;\"),\n setup_java_class(\"() -> { return 21; };\"),\n setup_java_class(\"() -> { System.exit(1); };\"),\n ]\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
tests support for lambda with no parameters and an expression body.
def test_lambda_support_no_parameters_expression_body(self): test_classes = [ setup_java_class("() -> 3;"), setup_java_class("() -> null;"), setup_java_class("() -> { return 21; };"), setup_java_class("() -> { System.exit(1); };"), ] for test_class...
[ "def test_lambda_support_no_parameters_no_body(self):\n self.assert_contains_lambda_expression_in_m(\n parse.parse(setup_java_class(\"() -> {};\")))", "def test_lambda_support_no_parameters_complex_expression(self):\n code = \"\"\"\n () -> {\n if (true) return 21...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
tests support for lambda with no parameters and a complex expression body.
def test_lambda_support_no_parameters_complex_expression(self): code = """ () -> { if (true) return 21; else { int result = 21; return result / 2; } };""" self.assert_contains_lambda_expression_in_m( ...
[ "def test_lambda_support_no_parameters_expression_body(self):\n test_classes = [\n setup_java_class(\"() -> 3;\"),\n setup_java_class(\"() -> null;\"),\n setup_java_class(\"() -> { return 21; };\"),\n setup_java_class(\"() -> { System.exit(1); };\"),\n ]\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
tests support for lambda with parameters with inferred types.
def test_parameter_no_type_expression_body(self): test_classes = [ setup_java_class("(bar) -> bar + 1;"), setup_java_class("bar -> bar + 1;"), setup_java_class("x -> x.length();"), setup_java_class("y -> { y.boom(); };"), ] for test_class in test_c...
[ "def test_parameter_with_type_expression_body(self):\n test_classes = [\n setup_java_class(\"(int foo) -> { return foo + 2; };\"),\n setup_java_class(\"(String s) -> s.length();\"),\n setup_java_class(\"(int foo) -> foo + 1;\"),\n setup_java_class(\"(Thread th) -> ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
tests support for lambda with parameters with formal types.
def test_parameter_with_type_expression_body(self): test_classes = [ setup_java_class("(int foo) -> { return foo + 2; };"), setup_java_class("(String s) -> s.length();"), setup_java_class("(int foo) -> foo + 1;"), setup_java_class("(Thread th) -> { th.start(); };"...
[ "def test_parameter_no_type_expression_body(self):\n test_classes = [\n setup_java_class(\"(bar) -> bar + 1;\"),\n setup_java_class(\"bar -> bar + 1;\"),\n setup_java_class(\"x -> x.length();\"),\n setup_java_class(\"y -> { y.boom(); };\"),\n ]\n for ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
this tests that lambda inferred type parameters with modifiers are considered invalid as per the specifications.
def test_parameters_inferred_types_with_modifiers(self): with self.assertRaises(parser.JavaSyntaxError): parse.parse(setup_java_class("(x, final y) -> x+y;"))
[ "def test_validate_late_contextual_fparam_raises(self):\n fsig = FSignature(\n [forge.arg('a'), forge.ctx('self')],\n __validate_parameters__=False,\n )\n with pytest.raises(TypeError) as excinfo:\n fsig.validate()\n assert excinfo.value.args[0] == \\\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
asserts that the given class contains a method with the supplied method name containing a method reference.
def assert_contains_method_reference_expression_in_m( self, clazz, method_name='main'): matches = list(filter_type_in_method( clazz, tree.MethodReference, method_name)) if not matches: self.fail('No matching method reference found.') return matches
[ "def test_method_reference(self):\n self.assert_contains_method_reference_expression_in_m(\n parse.parse(setup_java_class(\"String::length;\")))", "def test_method_reference_to_the_new_method(self):\n self.assert_contains_method_reference_expression_in_m(\n parse.parse(setup_ja...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
tests that method references are supported.
def test_method_reference(self): self.assert_contains_method_reference_expression_in_m( parse.parse(setup_java_class("String::length;")))
[ "def test_method_reference_to_the_new_method(self):\n self.assert_contains_method_reference_expression_in_m(\n parse.parse(setup_java_class(\"String::new;\")))", "def test_method_signatures(self):\n pass", "def assert_contains_method_reference_expression_in_m(\n self, clazz, ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
test support for method references to 'new'.
def test_method_reference_to_the_new_method(self): self.assert_contains_method_reference_expression_in_m( parse.parse(setup_java_class("String::new;")))
[ "def test_method_reference_to_the_new_method_with_explict_type(self):\n self.assert_contains_method_reference_expression_in_m(\n parse.parse(setup_java_class(\"String::<String> new;\")))", "def __new__(S, *more): # real signature unknown; restored from __doc__\n pass", "def __new__(S, *...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
test support for method references to 'new' with an explicit type.
def test_method_reference_to_the_new_method_with_explict_type(self): self.assert_contains_method_reference_expression_in_m( parse.parse(setup_java_class("String::<String> new;")))
[ "def test_constructor_signature_init_and_new(systemcls: Type[model.System]) -> None:\n\n src = '''\\\n class Animal(object):\n # both __init__ and __new__ are defined, pydoctor only looks at the __new__ method\n # pydoctor infers the constructor to be: \"Animal(*args, **kw)\"\n def __new_...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
test support for method references from 'super'.
def test_method_reference_from_super(self): self.assert_contains_method_reference_expression_in_m( parse.parse(setup_java_class("super::toString;")))
[ "def test_method_reference_from_super_with_identifier(self):\n self.assert_contains_method_reference_expression_in_m(\n parse.parse(setup_java_class(\"String.super::toString;\")))", "def become_method(self):", "def test_mixin_super(self):\n # pylint: disable=g-wrong-blank-lines,undefined-va...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
test support for method references from Identifier.super.
def test_method_reference_from_super_with_identifier(self): self.assert_contains_method_reference_expression_in_m( parse.parse(setup_java_class("String.super::toString;")))
[ "def test_method_reference_from_super(self):\n self.assert_contains_method_reference_expression_in_m(\n parse.parse(setup_java_class(\"super::toString;\")))", "def test_method_reference_to_the_new_method_with_explict_type(self):\n self.assert_contains_method_reference_expression_in_m(\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
currently there is no support for method references for an explicit type.
def test_method_reference_explicit_type_arguments_for_generic_type(self): self.assert_contains_method_reference_expression_in_m( parse.parse(setup_java_class("List<String>::size;")))
[ "def test_method_reference_to_the_new_method_with_explict_type(self):\n self.assert_contains_method_reference_expression_in_m(\n parse.parse(setup_java_class(\"String::<String> new;\")))", "def test_method_reference_explicit_type_arguments(self):\n self.assert_contains_method_reference_ex...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
test support for method references with an explicit type.
def test_method_reference_explicit_type_arguments(self): self.assert_contains_method_reference_expression_in_m( parse.parse(setup_java_class("Arrays::<String> sort;")))
[ "def test_method_reference_explicit_type_arguments_for_generic_type(self):\n self.assert_contains_method_reference_expression_in_m(\n parse.parse(setup_java_class(\"List<String>::size;\")))", "def test_method_reference_to_the_new_method_with_explict_type(self):\n self.assert_contains_meth...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Saves network architecture and parameters to network path
def save(self): self.save_network_architecture( network_path=self.network_path ) self.save_network_parameters( file_name='net_parameters', file_path=self.network_path )
[ "def save_network(self, **kwargs):\n raise NotImplementedError", "def save_network(network, fpath):\n with open(fpath, \"wb\") as f:\n pickle.dump(network, f)", "def save_network(network, fpath):\n\twith open(fpath, \"wb\") as f:\n\t\tpickle.dump(network, f)", "def save_utility_network(self,p...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Restores network parameters to last saved values
def restore(self): if os.path.isfile( \ os.path.join(self.network_path,'net_parameters.nnprm.index')): self.load_network_parameters( file_name='net_parameters', file_path=self.network_path) else: self.log("Could not load previous network parameters fro...
[ "def reset(self):\n print('Network reset to its original copy')\n self.net = self.copy.copy()\n self.current_threshold = None\n self.method = None", "def reset_parameters(self):\n self.lin.reset_parameters()\n self.att.reset_parameters()\n self.gnn_score.reset_para...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Loads the network architecture from the network path
def load_network_architecture(self,network_path): net_architecture = np.load( os.path.join(network_path,'net_architecture.npy')).item() self.log("Network architecture loaded from file:\n{}".format( os.path.join(network_path,'net_architecture.npy'))) re...
[ "def load_network(fpath):\n with open(fpath, \"rb\") as f:\n network = pickle.load(f)\n return network", "def load_network(fpath):\n\twith open(fpath, \"rb\") as f:\n\t\tnetwork = pickle.load(f)\n\treturn network", "def load_net(self, path):\n generator_state_dict = torch.load(path + \"/biga...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Trains the network on a training set for a specified number of epochs. It loads a random training set from the annotated_image_set on every epoch
def train_epochs(self, annotated_image_set, n_epochs=100, report_every=10, annotation_type='Bodies', m_samples=100, sample_ratio=None, normalize_samples=False, annotation_border_ratio=None, morph_annotations=False, rotation_list=None, scale_list_x=None, scale_...
[ "def train_batch(self, annotated_image_set, n_batches=10, n_epochs=100,\n annotation_type='Bodies', batch_size=1000, m_samples=100,\n sample_ratio=None, annotation_border_ratio=None,\n normalize_samples=False, morph_annotations=False,\n rotation_list=None, scale_list_x=No...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Trains the network on a training set for a specified number of batches of size batch_size. Every batch iteration it loads a random training batch from the annotated_image_set. Per batch, training is done for n_epochs on a random sample of size m_samples that is selected from the current batch.
def train_batch(self, annotated_image_set, n_batches=10, n_epochs=100, annotation_type='Bodies', batch_size=1000, m_samples=100, sample_ratio=None, annotation_border_ratio=None, normalize_samples=False, morph_annotations=False, rotation_list=None, scale_list_x=None, ...
[ "def train_epochs(self, annotated_image_set, n_epochs=100, report_every=10,\n annotation_type='Bodies', m_samples=100,\n sample_ratio=None, normalize_samples=False,\n annotation_border_ratio=None,\n morph_annotations=False, rotation_list=None,\n scale_list_x=No...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Displays the network architecture
def display_network_architecture(self): self.log("\n-------- Network architecture --------") self.log("y_res: {}".format(self.y_res)) self.log("x_res: {}".format(self.x_res)) self.log("n_input_channels: {}".format(self.n_input_channels)) self.log("n_output_classes: {}".format(sel...
[ "def display_network_architecture(self):\n self.log(\"\\n-------- Network architecture --------\")\n self.log(\"y_res: {}\".format(self.y_res))\n self.log(\"x_res: {}\".format(self.x_res))\n self.log(\"n_input_channels: {}\".format(self.n_input_channels))\n self.log(\"n_output_cla...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Displays the network architecture
def display_network_architecture(self): self.log("\n-------- Network architecture --------") self.log("y_res: {}".format(self.y_res)) self.log("x_res: {}".format(self.x_res)) self.log("n_input_channels: {}".format(self.n_input_channels)) self.log("n_output_classes: {}".format(sel...
[ "def display_network_architecture(self):\n self.log(\"\\n-------- Network architecture --------\")\n self.log(\"y_res: {}\".format(self.y_res))\n self.log(\"x_res: {}\".format(self.x_res))\n self.log(\"n_input_channels: {}\".format(self.n_input_channels))\n self.log(\"n_output_cla...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
This is a helper method to convert a string into a list with the string only Or if the input is already list, simply return itself Meanwhile if the email address is invalid, remove it from the list
def list_or_str_to_valid_list(self, list_or_string): if isinstance(list_or_string, list): for email in list_or_string: if not self.validate_email_address(email): list_or_string.remove(email) return list_or_string ...
[ "def _check_email_list(email_list_string: str) -> List[str]:\n if email_list_string is None:\n return []\n\n email_list = email_list_string.split()\n if incorrect_email := get_incorrect_email(email_list):\n raise Exception(_('Invalid email address \"{0}\".').format(\n incorrect_ema...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
This is to send email by the email sender class and failover. It will also validate the from, to email address. Validate the subject and email content text. It will return an status code and message The to_list, cc_list and bcc_list could be None or an empty list [] or a string representing one email address, or a list...
def send_email(self, from_email, to_list, cc_list, bcc_list, subject, text): if from_email is None or len(from_email) == 0 or not self.validate_email_address(from_email): return 1, 'from email address invalid' if to_list is None or len(to_list) == 0: to_...
[ "def _send_email(recipients_list,\n sender,\n subject,\n body,\n attachments_list = [],\n cc_recipients_list = [],\n verbose = 0):\n \n if verbose>50:\n msgb('email 0.0')\n all_recipients = recipients_list + cc_...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Print crossword assignment to the terminal.
def print(self, assignment): letters = self.letter_grid(assignment) for i in range(self.crossword.height): for j in range(self.crossword.width): if self.crossword.structure[i][j]: print(letters[i][j] or " ", end="") else: ...
[ "def printSolvedCrossword(self):\n\t\t\n\t\tif len(self.cellData) == 0:\n\t\t\tself.__findClueAnswers()\n\t\t\t\n\t\trow = \"\"\n\t\thyphenRow = \"\\t %s\" % (\"-\" * ((self.noOfCells * 2) + 1))\n\t\tprint hyphenRow\n\t\t\n\t\tfor cellNo, value in self.cellData.items():\n\t\t\trow = row + ' ' + value\n\t\t\tif cell...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Save crossword assignment to an image file.
def save(self, assignment, filename): from PIL import Image, ImageDraw, ImageFont cell_size = 100 cell_border = 2 interior_size = cell_size - 2 * cell_border letters = self.letter_grid(assignment) # Create a blank canvas img = Image.new( "RGBA", ...
[ "def save(self, filename):\n print(\"Saving...\", end=\"\\r\")\n canvas = self.canvas[self.N:self.S,self.W:self.E]\n cv2.imwrite(\"./Output/\"+filename, canvas)\n print(\"Saved:\",filename)", "def save_image_to_classify(self,fileName):\r\n widget = self.canvas\r\n widget....
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Make variable `x` arc consistent with variable `y`. To do so, remove values from `self.domains[x]` for which there is no possible corresponding value for `y` in `self.domains[y]`. Return True if a revision was made to the domain of `x`; return False if no revision was made.
def revise(self, x, y): revision= False #creates a list of words in the domain of node x to remove since we cannot remove the elements in a set while it is iterating words_to_remove= [] #function which returns data of where the two nodes intersect/overlap overlap= self.crossword....
[ "def revise(self, x, y):\n\n # Sets revision to false, as we have not revised the domains of either variable yet\n revision = False\n\n # A set of all values in domain of x that are not consistent and will be removed\n inconsistent = set()\n\n # Finds the overlap between x and y\n...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Update `self.domains` such that each variable is arc consistent. If `arcs` is None, begin with initial list of all arcs in the problem. Otherwise, use `arcs` as the initial list of arcs to make consistent. Return True if arc consistency is enforced and no domains are empty; return False if one or more domains end up em...
def ac3(self, arcs=None): if arcs == None: #creates a queue of arcs to update arcs= [] for node1 in self.domains: for node2 in self.domains: if node1 != node2: #for each pair of nodes that intersect, add them as a tu...
[ "def ac3(self, arcs=None):\n \n all_arcs = []\n\n for va in self.domains.keys():\n for vb in self.domains.keys():\n if va != vb:\n all_arcs.append(tuple((va, vb)))\n \n for arc in all_arcs:\n #if revise updated a domain, add this...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Return an unassigned variable not already part of `assignment`. Choose the variable with the minimum number of remaining values in its domain. If there is a tie, choose the variable with the highest degree. If there is a tie, any of the tied variables are acceptable return values.
def select_unassigned_variable(self, assignment): var_list= [] #add unassigned variabled to a list along with the number of words left in its domain for var in self.domains: if var not in assignment: var_list.append((var, len(self.domains[var]))) #sort this li...
[ "def get_unassigned_variable(self, assignment):\n\n if not self.mcv:\n # Select a variable without any heuristics.\n for var in self.csp.variables:\n if var not in assignment: return var\n else:\n min_variable = None\n min_count = sys.maxint\n...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Get all dirs for all patients
def get_patient_dirs(base_folder): patient_dirs = sorted([x for x in base_folder.iterdir() if x.is_dir()]) return patient_dirs
[ "def list_dirs(self):\n return self.list_groups()", "def listdirs(self):\n return self.list_groups()", "def dirs(self) -> list:\n dirs = [tic + \"/\" for tic in sorted(self._dirs, key=str.casefold)]\n return dirs", "def getImmediateSubdirectories(dir):", "def get_dicoms(data_dir,...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Print a success message. The message is colourized with the preset 'success' mode.
def print_success(msg): colour.cprint(msg, 'success') sys.stdout.flush()
[ "def success(self, message=''):\n print(colored(message, 'green'))", "def print_success(message: str) -> None:\n __print_highlight(message, '✔', 'green')", "def print_success(msg):\n print_message(color_string('SUCCESS', 'OKGREEN'), '[%s], completed successfully.' % msg)", "def print_success(msg)...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Verifies that is_url adequately discovers a url
def test_is_url(self): url = "https://shadowrun.needs.management" self.assertTrue(run(verification.is_url(url))) url = "https:// www.google.com" self.assertFalse(run(verification.is_url(url)))
[ "def test_is_not_url(self):\r\n self.assertFalse(self.urls.is_url(\"1234567\"))", "def _check_url(url):\n if 'youtube.com' in url:\n raise IsYoutubeLink(url)\n\n if 'prezi.com' in url:\n raise IsPreziLink(url)", "def _validate_url(self, url):\n return", "def check_url_invalid...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Return the best fit line for an array of corners. This function returns an tuple of (m, b), where the best fit line is represented by y = mx + b.
def get_corner_line(corners): corner_xs = [c[0] for c in corners] corner_ys = [c[1] for c in corners] return tuple(np.polyfit(x=corner_xs, y=corner_ys, deg=1))
[ "def get_two_corner_line(corners):\n x1, y1 = corners[0]\n x2, y2 = corners[1]\n\n m = (y1 - y2) / (x1 - x2)\n # Since y - y1 = m(x - x1)\n # y = m(x - x1) + y1\n # y = mx - mx1 + y1\n b = -m * x1 + y1\n return (m, b)", "def getBestLine(lines, model):\n\ttmpmodel = normalizeLin...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Return the line that contains the two given corners. This function returns an tuple of (m, b), where the best fit line is represented by y = mx + b.
def get_two_corner_line(corners): x1, y1 = corners[0] x2, y2 = corners[1] m = (y1 - y2) / (x1 - x2) # Since y - y1 = m(x - x1) # y = m(x - x1) + y1 # y = mx - mx1 + y1 b = -m * x1 + y1 return (m, b)
[ "def get_corner_line(corners):\n corner_xs = [c[0] for c in corners]\n corner_ys = [c[1] for c in corners]\n return tuple(np.polyfit(x=corner_xs, y=corner_ys, deg=1))", "def line_mx_plus_b(\n line: shapely.geometry.LineString,\n) -> Tuple[float, float]:\n y2, y1 = line.coords[1][1], line.coords[0][...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Return the top corners for the given rectangles, sorted by their x positions in ascending order.
def get_top_corners(corners): top_corners = np.concatenate( [sorted(rect, key=getY)[:2] for rect in corners]) return sorted(top_corners, key=getX)
[ "def get_bottom_corners(corners):\n bottom_corners = np.concatenate(\n [sorted(rect, key=getY)[2:] for rect in corners])\n return sorted(bottom_corners, key=getX)", "def get_customer_code_rect(rectangles):\n index = 0\n center_y = 0\n for i, rect in enumerate(rectangles):\n if center_...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Return the bottom corners for the given rectangles, sorted by their x positions in ascending order.
def get_bottom_corners(corners): bottom_corners = np.concatenate( [sorted(rect, key=getY)[2:] for rect in corners]) return sorted(bottom_corners, key=getX)
[ "def get_top_corners(corners):\n top_corners = np.concatenate(\n [sorted(rect, key=getY)[:2] for rect in corners])\n return sorted(top_corners, key=getX)", "def _find_bboxes_in_rect(bboxes, left, bottom, right, top):\n result = (bboxes[:, 0] <= right) & (bboxes[:, 2] >= left) & \\\n (b...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }