code
stringlengths
10
2.58M
original_code
stringlengths
3
3.18M
original_language
stringclasses
1 value
source
stringclasses
7 values
function __init__ self ctx begin set available_workers = list set workflow_comms = dict set thread_exit = false set pending_workflows = queue set ctx = ctx set server_secret_file = join path zmq_private_keys_path string server.key_secret set tuple server_public server_secret = call load_certificate server_secret_file...
def __init__(self, ctx): self.available_workers = [] self.workflow_comms = {} self.thread_exit = False self.pending_workflows = Queue() self.ctx = ctx server_secret_file = os.path.join(core.config.paths.zmq_private_keys_path, "server.key_secret") server_public, s...
Python
nomic_cornstack_python_v1
function bench_compare_multiple logger *param_groups **fn_names begin set tuple title_str ans_str time_str = tuple string Testing {name}: string {name}({params}) = {ans} string Time = {time} for tuple name fn in items fn_names begin set str_params = dict string name name print format title_str keyword str_params for pg...
def bench_compare_multiple(logger, *param_groups, **fn_names): title_str, ans_str, time_str = "Testing {name}:","\t{name}({params}) = {ans}","\tTime = {time}" for name, fn in fn_names.items(): str_params = {'name': name} print(title_str.format(**str_params)) for pg in param_groups: ...
Python
nomic_cornstack_python_v1
function negative_elbo decoded_subgraphs mu logvar g begin comment First unbatch all the graphs into individual comment subgraphs set gs_unbatched = call unbatch g assert length decoded_subgraphs == length gs_unbatched set loss = 0.0 for tuple i subgraph in enumerate gs_unbatched begin comment Compute decoding loss for...
def negative_elbo(decoded_subgraphs, mu, logvar, g): # First unbatch all the graphs into individual # subgraphs gs_unbatched = dgl.unbatch(g) assert len(decoded_subgraphs) == len(gs_unbatched) loss = 0.0 for i, subgraph in enumerate(gs_unbatched): # Compute decoding loss for each indivi...
Python
nomic_cornstack_python_v1
function generate_password userName begin import random set password = string for c in range 4 begin set newChar = userName at random integer 0 length userName - 1 set capital = random integer 0 1 if capital is 0 begin set password = password + upper newChar end else begin set password = password + newChar end end for...
def generate_password(userName): import random password = "" for c in range(4): newChar = userName[random.randint(0,len(userName)-1)] capital = random.randint(0,1) if(capital is 0): password = password + newChar.upper() else: password = password + newChar for t in range(4): password = password +...
Python
zaydzuhri_stack_edu_python
function _create_tokenizer self corpus_type begin if corpus_type not in list string char string word begin set e = string Corpus type should be `char` or `word`. error e raise call RuntimeError e end if corpus_type == string char begin return pipeline lower_case valid_char tokenize_to_char end return pipeline lower_cas...
def _create_tokenizer(self, corpus_type: str) -> callable: if corpus_type not in ["char", "word"]: e = "Corpus type should be `char` or `word`." logger.error(e) raise RuntimeError(e) if corpus_type == "char": return p.pipeline(p.lower_case, p.valid_cha...
Python
nomic_cornstack_python_v1
import PE import EF import scipy.io as sio import STSpam import numpy as np comment Part One: Email Preprocessing
import PE import EF import scipy.io as sio import STSpam import numpy as np #Part One: Email Preprocessing
Python
zaydzuhri_stack_edu_python
function isTrajectory nc variable begin if call is_cf_trajectory nc variable or call is_single_trajectory nc variable begin return true end return false end function
def isTrajectory(nc, variable): if is_cf_trajectory(nc, variable) or is_single_trajectory(nc, variable): return True return False
Python
nomic_cornstack_python_v1
comment load all train and test data from the har dataset from numpy import dstack from pandas import read_csv comment load a single file as a numpy array function load_file filepath begin set dataframe = read csv filepath header=none delim_whitespace=true return values end function comment load a list of files, such a...
# load all train and test data from the har dataset from numpy import dstack from pandas import read_csv # load a single file as a numpy array def load_file(filepath): dataframe = read_csv(filepath, header=None, delim_whitespace=True) return dataframe.values # load a list of files, such as x, y, z data for ...
Python
zaydzuhri_stack_edu_python
function test_get_fails_when_getting_vendor_dependency_with_wrong_component_type self begin set result = call invoke cli list *CLI_LOG_OPTION string config string get string vendor.fetchai.component_type_not_correct.error.non_existing_attribute standalone_mode=false assert exit_code == 1 set s = string 'component_type_...
def test_get_fails_when_getting_vendor_dependency_with_wrong_component_type(self): result = self.runner.invoke( cli, [ *CLI_LOG_OPTION, "config", "get", "vendor.fetchai.component_type_not_correct.error.non_existing_attribute...
Python
nomic_cornstack_python_v1
function wrap self tag *args **kwargs begin string Returns all *args* (strings) wrapped in HTML tags like so:: >>> b = TagWrap('b') >>> print(b('bold text')) <b>bold text</b> To add attributes to the tag you can pass them as keyword arguments:: >>> a = TagWrap('a') >>> print(a('awesome software', href='http://liftoffso...
def wrap(self, tag, *args, **kwargs): """ Returns all *args* (strings) wrapped in HTML tags like so:: >>> b = TagWrap('b') >>> print(b('bold text')) <b>bold text</b> To add attributes to the tag you can pass them as keyword arguments:: >>> a = T...
Python
jtatman_500k
function attach_tool_model *args begin set sel = call ls selection=true type=string transform set robot = call get_robot_roots comment Exception handling if not sel begin warning string Nothing selected; select a valid robot control and tool controller return end if not robot begin warning string No tool controller sel...
def attach_tool_model(*args): sel = pm.ls(selection=True, type='transform') robot = get_robot_roots() # Exception handling if not sel: pm.warning('Nothing selected; ' \ 'select a valid robot control and tool controller') return if not robot: pm.warning('No...
Python
nomic_cornstack_python_v1
import math function tanh_prime x begin return 1 - tanh x ^ 2 end function function relu x begin return max 0 x end function function relu_prime x begin return if expression x > 0 then 1 else 0 end function set x = 100 set a1 = tanh x set a2 = tanh a1 set a3 = tanh a2 set y = tanh a3 print y print string w4: call tanh_...
import math def tanh_prime(x): return 1 - math.tanh(x)**2 def relu(x): return max(0, x) def relu_prime(x): return 1 if x > 0 else 0 x = 100 a1 = math.tanh(x) a2 = math.tanh(a1) a3 = math.tanh(a2) y = math.tanh(a3) print(y) print('w4: ', tanh_prime(a3) * a3) print('w3: ', tanh_prime(a3) * tanh_prime(a...
Python
zaydzuhri_stack_edu_python
import matplotlib from matplotlib import pyplot set minutes = list 1 2 3 4 5 6 7 8 9 set player1 = list 1 2 3 3 4 4 4 4 5 set player2 = list 1 1 1 1 2 2 2 3 4 set player3 = list 1 1 1 2 2 2 3 3 3 set legends = list string player1 string player2 string player3 call stackplot minutes player1 player2 player3 labels=legend...
import matplotlib from matplotlib import pyplot minutes = [1, 2, 3, 4, 5, 6, 7, 8, 9] player1 = [1, 2, 3, 3, 4, 4, 4, 4, 5] player2 = [1, 1, 1, 1, 2, 2, 2, 3, 4] player3 = [1, 1, 1, 2, 2, 2, 3, 3, 3] legends=['player1','player2','player3'] pyplot.stackplot(minutes,player1,player2,player3,labels=legends) #to change...
Python
zaydzuhri_stack_edu_python
from picamera import PiCamera from time import sleep import time set camera = call PiCamera call start_preview for i in range 3 begin comment sleep(3) set start = time call capture string /home/pi/Desktop/imageNoSleep%s.jpg % i set end = time print string taking photo time: %f % end - start end call stop_preview
from picamera import PiCamera from time import sleep import time camera = PiCamera() camera.start_preview() for i in range(3): #sleep(3) start = time.time() camera.capture('/home/pi/Desktop/imageNoSleep%s.jpg' % i) end = time.time() print("taking photo time: %f" % (end - start)) camera.stop_previe...
Python
zaydzuhri_stack_edu_python
comment Looking at Logistic Regression Classifier comment Encoding import numpy import matplotlib.pyplot as plt from sklearn.datasets import load_iris from sklearn.model_selection import train_test_split from split_data import split_dataframes_train_test from sklearn import tree from sklearn.linear_model import Logisti...
# Looking at Logistic Regression Classifier # Encoding import numpy import matplotlib.pyplot as plt from sklearn.datasets import load_iris from sklearn.model_selection import train_test_split from split_data import split_dataframes_train_test from sklearn import tree from sklearn.linear_model import LogisticRegression...
Python
zaydzuhri_stack_edu_python
function _batching_scheme batch_size max_length min_length_bucket length_bucket_step drop_long_sequences=false shard_multiplier=1 length_multiplier=1 min_length=0 begin set max_length = max_length or batch_size if max_length < min_length begin raise call ValueError string max_length must be greater or equal to min_leng...
def _batching_scheme(batch_size, max_length, min_length_bucket, length_bucket_step, drop_long_sequences=False, shard_multiplier=1, length_multiplier=1, min_length=0): max_...
Python
nomic_cornstack_python_v1
function test_rshift_basic_array_num_array_b1 self begin for testval in data2param begin with call subTest msg=string Failed with parameter testval=testval begin comment Copy the array so we don't change the original data. set datax = copy copy data1 set expected = list comprehension call pyshift x testval for x in dat...
def test_rshift_basic_array_num_array_b1(self): for testval in self.data2param: with self.subTest(msg='Failed with parameter', testval = testval): # Copy the array so we don't change the original data. datax = copy.copy(self.data1) expected = [self.pyshift(x, testval) for x in datax] arrayfunc.r...
Python
nomic_cornstack_python_v1
function watchdog_func event cmd exec_timeout begin wait event exec_timeout if returncode is none begin error string Task timed out and will be killed call kill_process_with_children pid end end function
def watchdog_func(event, cmd, exec_timeout): event.wait(exec_timeout) if cmd.returncode is None: logger.error("Task timed out and will be killed") kill_process_with_children(cmd.pid)
Python
nomic_cornstack_python_v1
function read self size=1 begin set pkt = read stdout size if DEBUG_STREAM_RX begin debug string RX Raw: + string map hexify_chr pkt end return map ord pkt at 0 end function
def read(self, size=1): pkt = self.pipe.stdout.read(size) if CONFIG.DEBUG_STREAM_RX: logging.debug("RX Raw: " + str(map(spinel.util.hexify_chr, pkt))) return map(ord, pkt)[0]
Python
nomic_cornstack_python_v1
comment 类的定义 class MyClass begin pass end class comment __init__() method 方法 function(函数) comment attribute 属性 comment method 方法 class People begin function __init__ self name age begin set name = name set age = age end function function sayhi self begin print format string Hi, my name is {}, and I'm {} name age end fu...
# 类的定义 class MyClass: pass # __init__() method 方法 function(函数) # attribute 属性 # method 方法 class People: def __init__(self, name, age): self.name = name self.age = age def sayhi(self): print("Hi, my name is {}, and I'm {}".format( self.name, self.age )) #...
Python
zaydzuhri_stack_edu_python
import os.path from flask import Flask import os import json import run_backend import time set app = call Flask __name__ function get_predictions begin set novos_videos_json = string novos_videos.json if not exists path novos_videos_json begin call update_db end set last_update = call getmtime novos_videos_json with o...
import os.path from flask import Flask import os import json import run_backend import time app = Flask(__name__) def get_predictions(): novos_videos_json = 'novos_videos.json' if not os.path.exists(novos_videos_json): run_backend.update_db() last_update = os.path.getmtime(novos_videos_json) with open(...
Python
zaydzuhri_stack_edu_python
function mousePress self widget button=none position=none state=none modifiers=none qgraphicsscene=none begin call _mouseEvent MouseButtonPress widget button position state modifiers qgraphicsscene end function
def mousePress(self, widget, button=None, position=None, state=None, modifiers=None, qgraphicsscene=None): self._mouseEvent(QEvent.MouseButtonPress, widget, button, position, state, modifiers, qgraphicsscene)
Python
nomic_cornstack_python_v1
comment IP-models for graph coloring. comment Input as an edge list. comment Output the number of colors. from pyscipopt import Model import pyscipopt comment Reads dimacs graph comment Returns: vertex set, max degree, edge list function read_dimacs filename begin with open filename string r as fin begin comment Find h...
# IP-models for graph coloring. # Input as an edge list. # Output the number of colors. from pyscipopt import Model import pyscipopt # Reads dimacs graph # Returns: vertex set, max degree, edge list def read_dimacs(filename): with open(filename, "r") as fin: # Find header while True: r...
Python
zaydzuhri_stack_edu_python
function list self limit=none begin call _validate_type limit string limit int false set href = call get_search_script_href set data = dict string query string *:* if limit is not none begin update data dict string limit limit end if not _ICP begin set response = post href params=call _params headers=call _get_headers ...
def list(self, limit=None): Script._validate_type(limit, u'limit', int, False) href = self._href_definitions.get_search_script_href() data = { "query": "*:*" } if limit is not None: data.update({"limit": limit}) if not self._ICP: ...
Python
nomic_cornstack_python_v1
string 329. Longest Increasing Path in a Matrix from typing import List class Solution begin function longestIncreasingPath self matrix begin if not matrix begin return 0 end set tuple ni nj = tuple length matrix length matrix at 0 set dp = list comprehension list - 1 * nj for _ in range ni set ret = 0 set directions =...
""" 329. Longest Increasing Path in a Matrix """ from typing import List class Solution: def longestIncreasingPath(self, matrix: List[List[int]]) -> int: if not matrix: return 0 ni, nj = len(matrix), len(matrix[0]) dp = [ [ -1 ] * nj for _ in range(ni) ] ret = 0 ...
Python
zaydzuhri_stack_edu_python
function set self data begin set ret = call _rest_call data string POST return ret at 0 == 200 end function
def set(self, data): ret = self._rest_call(data, 'POST') return ret[0] == 200
Python
nomic_cornstack_python_v1
import pandas as pd import numpy as np import os from sklearn.preprocessing import MinMaxScaler function standardize train test begin string Standardize data comment Standardize train and test set X_train = train - mean np train axis=0 at tuple none slice : : slice : : / standard deviation np train axis=0 at tupl...
import pandas as pd import numpy as np import os from sklearn.preprocessing import MinMaxScaler def standardize(train, test): """ Standardize data """ # Standardize train and test X_train = (train - np.mean(train, axis=0)[None, :, :]) / np.std(train, axis=0)[None, :, :] X_test = (test - np.mean(test, ...
Python
zaydzuhri_stack_edu_python
comment !/usr/bin/env python3 comment -*- coding: utf-8 -*- set n = integer input set yama = list for _ in range n begin comment 縦N、横2N-1 の山 append yama list input end function yamakuzushi a b begin comment aが横、bが縦 comment 入力された a,b は 'x' になっている場所で、上3箇所のいずれかに '#' があれば 'X' に置き換える comment 一個上の山が存在しなければ終わり if b - 1 < 0 b...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- n = int(input()) yama = [] for _ in range(n): # 縦N、横2N-1 の山 yama.append(list(input())) def yamakuzushi (a:int, b:int): # aが横、bが縦 # 入力された a,b は 'x' になっている場所で、上3箇所のいずれかに '#' があれば 'X' に置き換える if b-1 < 0: # 一個上の山が存在しなければ終わり return 0 if 0 <= b-1...
Python
zaydzuhri_stack_edu_python
function __init__ __self__ linked_service_name path=none begin set __self__ string linked_service_name linked_service_name if path is not none begin set __self__ string path path end end function
def __init__(__self__, *, linked_service_name: Any, path: Optional[Any] = None): pulumi.set(__self__, "linked_service_name", linked_service_name) if path is not None: pulumi.set(__self__, "path", path)
Python
nomic_cornstack_python_v1
function qst2 self begin set success = false end function
def qst2(self): self.success = False
Python
nomic_cornstack_python_v1
function align_center foregroundWidth backgroundWidth distanceTop=0 begin return tuple integer backgroundWidth / 2 - integer foregroundWidth / 2 distanceTop end function
def align_center(foregroundWidth: int, backgroundWidth: int, distanceTop: int = 0): return int(backgroundWidth / 2) - int(foregroundWidth / 2), distanceTop
Python
nomic_cornstack_python_v1
function save_backup self begin set backup = data end function
def save_backup( self): self.backup = self.data
Python
nomic_cornstack_python_v1
function _get_title self link begin set title = none with call Timeout GET_TIMEOUT begin set res = get requests link if status_code == 200 begin set tree = call fromstring content set title = call xpath string //title/text() at 0 info format string Title for {}: {} link title end else begin error format string Unable t...
def _get_title(self, link): title = None with eventlet.Timeout(GET_TIMEOUT): res = requests.get(link) if res.status_code == 200: tree = html.fromstring(res.content) title = tree.xpath('//title/text()')[0] logger.info("Title for {}:...
Python
nomic_cornstack_python_v1
function startElement self tag attrs begin if tag == string tip begin set tlist = list comment Skip all tips with xml:lang attribute, as they are comment already in the translation catalog set skip = string xml:lang in attrs end else if tag == string br begin pass end else if tag != string tips begin comment let all t...
def startElement(self, tag, attrs): if tag == "tip": self.tlist = [] # Skip all tips with xml:lang attribute, as they are # already in the translation catalog self.skip = 'xml:lang' in attrs elif tag == "br": pass elif tag != "tips": ...
Python
nomic_cornstack_python_v1
import numpy as np set x = 2 print exp x print 2.7182 * 2.7182
import numpy as np x = 2 print(np.exp(x)) print(2.7182 * 2.7182)
Python
zaydzuhri_stack_edu_python
import numpy as np import pandas as pd import time import warnings filter warnings string ignore set file_name = string ./output set f = open file_name set user_size = 212063 set buff = list comprehension string for i in range user_size set i = 0 for line in f begin set buff at i = line set i = i + 1 end close f set u...
import numpy as np import pandas as pd import time import warnings warnings.filterwarnings("ignore") file_name = "./output" f = open(file_name) user_size = 212063 buff = ["" for i in range(user_size)] i = 0 for line in f: buff[i] = line i += 1 f.close() user_chunks = pd.read_csv("/home/jason/datamining/dat...
Python
zaydzuhri_stack_edu_python
function test_base_path original_base_path args begin if skip_redirects begin return original_base_path end comment WARNING: some redirects are hardcoded to production URLs. comment Both staging and production will rate limit us. set response = head session root_url + original_base_path allow_redirects=true if 200 <= s...
def test_base_path(original_base_path, args): if args.skip_redirects: return original_base_path # WARNING: some redirects are hardcoded to production URLs. # Both staging and production will rate limit us. response = session.head(args.root_url + original_base_path, allow_redirects=True) if...
Python
nomic_cornstack_python_v1
function create_token self data options=none begin string Generates a secure authentication token. Our token format follows the JSON Web Token (JWT) standard: header.claims.signature Where: 1) 'header' is a stringified, base64-encoded JSON object containing version and algorithm information. 2) 'claims' is a stringifie...
def create_token(self, data, options=None): """ Generates a secure authentication token. Our token format follows the JSON Web Token (JWT) standard: header.claims.signature Where: 1) 'header' is a stringified, base64-encoded JSON object containing version and algorithm ...
Python
jtatman_500k
import multiprocessing function cal_sq n q begin for i in n begin put i * i end end function if __name__ == string __main__ begin set arr = list 2 3 4 set q = queue set p1 = process target=cal_sq args=tuple arr q start p1 join p1 while call empty is false begin print get q end end comment ### multiprocessing comment q ...
import multiprocessing def cal_sq(n, q): for i in n: q.put(i * i) if __name__ == "__main__": arr = [2, 3, 4] q = multiprocessing.Queue() p1 = multiprocessing.Process(target=cal_sq, args=(arr, q,)) p1.start() p1.join() while q.empty() is False: print(q.get()) ## ### mul...
Python
zaydzuhri_stack_edu_python
comment !/usr/bin/env python string CREATED:2011-11-03 10:23:22 by Brian McFee <bmcfee@cs.ucsd.edu> Generate a tag-hopper playlist Usage: ./sampleTaghopper.py model.pickle songhash.pickle N import cPickle as pickle import sys import hypergraph
#!/usr/bin/env python ''' CREATED:2011-11-03 10:23:22 by Brian McFee <bmcfee@cs.ucsd.edu> Generate a tag-hopper playlist Usage: ./sampleTaghopper.py model.pickle songhash.pickle N ''' import cPickle as pickle import sys import hypergraph
Python
zaydzuhri_stack_edu_python
comment Uses python3 import sys import math import heapq function dist p1 p2 begin return square root p2 at 0 - p1 at 0 ^ 2 + p2 at 1 - p1 at 1 ^ 2 end function function minimum_distance x y begin set visited = list false * length x set pq = list tuple 0 0 set distance = 0 set num_visited = 0 while length pq begin set ...
#Uses python3 import sys import math import heapq def dist(p1, p2): return math.sqrt((p2[0] - p1[0])**2 + (p2[1]-p1[1])**2) def minimum_distance(x, y): visited = [False] * len(x) pq = [(0,0)] distance = 0 num_visited = 0 while(len(pq)): v = heapq.heappop(pq) i = v[1] if...
Python
zaydzuhri_stack_edu_python
class Solution begin comment Find the reflection point. function findReflectPoint self point k line begin comment Calculate the b of y = k * x + b. set b = point at 1 - k * point at 0 comment If line is vertical, the reflection point should be (x, k * x + b), x = 0 or p. if line at 0 begin return tuple line at 1 k * li...
class Solution: def findReflectPoint(self, point: tuple, k: float, line: tuple) -> tuple: #Find the reflection point. b = point[1] - k * point[0] #Calculate the b of y = k * x + b. if line[0]: ...
Python
zaydzuhri_stack_edu_python
comment Definition for a binary tree node. comment class TreeNode: comment def __init__(self, val=0, left=None, right=None): comment self.val = val comment self.left = left comment self.right = right class FindElements begin function __init__ self root begin set visited = set function helper root prev begin if root beg...
# Definition for a binary tree node. # class TreeNode: # def __init__(self, val=0, left=None, right=None): # self.val = val # self.left = left # self.right = right class FindElements: def __init__(self, root: TreeNode): self.visited = set() def helper(root, prev...
Python
zaydzuhri_stack_edu_python
import requests from bs4 import BeautifulSoup class cricket begin function scoreFinder self url begin set source_code = get requests url set plain_text = text set soup = call BeautifulSoup plain_text for link in find all string div dict string class string match-information-strip begin set title = string print title en...
import requests from bs4 import BeautifulSoup class cricket(): def scoreFinder(self,url): source_code=requests.get(url) plain_text=source_code.text soup=BeautifulSoup(plain_text) for link in soup.findAll('div',{'class':'match-information-strip'}): title=link.string ...
Python
zaydzuhri_stack_edu_python
comment Given a string that contains only digits 0-9 and a target value, return all possibilities to add binary operators (not unary) +, -, or * between the digits so they evaluate to the target value. comment Examples: comment "123", 6 -> ["1+2+3", "1*2*3"] comment "232", 8 -> ["2*3+2", "2+3*2"] comment "105", 5 -> ["...
# Given a string that contains only digits 0-9 and a target value, return all possibilities to add binary operators (not unary) +, -, or * between the digits so they evaluate to the target value. # # Examples: # "123", 6 -> ["1+2+3", "1*2*3"] # "232", 8 -> ["2*3+2", "2+3*2"] # "105", 5 -> ["1*0+5","10-5"] # "00",...
Python
zaydzuhri_stack_edu_python
function choose_action self node exploit=false begin set best_val = - inf set mcts_policy = cuda zeros 1 length node at string childs device set n_children = length node at string childs comment Get back to the root node and evaluate its children. Choose the best estimated action comment and move to the next node. This...
def choose_action(self, node: dict, exploit: bool = False) -> tuple: best_val = -np.inf mcts_policy = torch.zeros(1, len(node["childs"])).cuda(self.controller.device) n_children = len(node["childs"]) # Get back to the root node and evaluate its children. Choose the best estimated action...
Python
nomic_cornstack_python_v1
function main begin set creds = none comment The file token.pickle stores the user's access and refresh tokens, and is comment created automatically when the authorization flow completes for the first comment time. if exists path string token.pickle begin with open string token.pickle string rb as token begin set creds...
def main(): creds = None # The file token.pickle stores the user's access and refresh tokens, and is # created automatically when the authorization flow completes for the first # time. if os.path.exists('token.pickle'): with open('token.pickle', 'rb') as token: creds = pickle.loa...
Python
nomic_cornstack_python_v1
class Sentences begin function __init__ self stream begin set iter = iterate stream end function function __iter__ self begin return self end function function __next__ self begin set sentence = string for c in iter begin set sentence = sentence + c if c == string . begin return sentence end end raise StopIteration en...
class Sentences: def __init__(self, stream): self.iter = iter(stream) def __iter__(self): return self def __next__(self): sentence = '' for c in self.iter: sentence += c if c == '.': return sentence raise StopIteration ...
Python
zaydzuhri_stack_edu_python
function RNA s begin set rnaTranslate = string for item in s begin set item = upper item if item == string A begin set rnaTranslate = rnaTranslate + item end if item == string C begin set rnaTranslate = rnaTranslate + item end if item == string G begin set rnaTranslate = rnaTranslate + item end if item == string T beg...
def RNA(s): rnaTranslate='' for item in s: item=item.upper() if item == 'A': rnaTranslate+=item if item == 'C': rnaTranslate+=item if item == 'G': rnaTranslate...
Python
zaydzuhri_stack_edu_python
function check_memory self n array_ptr_str offset=1 begin set data = split array_ptr_str string at 3 set bytes_from_heap = split data string set actual_start = offset for i in range 0 n * 4 4 begin set hex_str = bytes_from_heap at i + 3 at slice 2 : : set hex_str = hex_str + bytes_from_heap at i + 2 at slice 2 : : ...
def check_memory(self, n, array_ptr_str, offset=1): data = array_ptr_str.split("\n")[3] bytes_from_heap = data.split(" ") actual_start = offset for i in range(0, n * 4, 4): hex_str = bytes_from_heap[i+3][2:] hex_str += bytes_from_heap[i+2][2:] hex_str...
Python
nomic_cornstack_python_v1
comment coding=utf-8 comment 导入需要使用的模块 comment import itertools import urllib comment import sys,io comment sys.stdout=io.TextIOWrapper(sys.stdout.buffer,encoding='utf-8')#为了防止有时候输出产生中文乱码的问题 import requests from lxml import etree import json from docx import Document from docx.shared import Inches from docx.oxml.ns imp...
# coding=utf-8 #导入需要使用的模块 #import itertools import urllib #import sys,io #sys.stdout=io.TextIOWrapper(sys.stdout.buffer,encoding='utf-8')#为了防止有时候输出产生中文乱码的问题 import requests from lxml import etree import json from docx import Document from docx.shared import Inches from docx.oxml.ns import qn from docx.shared import P...
Python
zaydzuhri_stack_edu_python
function __init__ self *args **kwargs begin set org = pop kwargs string organization call __init__ *args keyword kwargs set fields at string documents = call ModelMultipleChoiceField queryset=all required=false end function
def __init__(self, *args, **kwargs): org = kwargs.pop("organization") super(LibraryDocumentAssociateForm, self).__init__(*args, **kwargs) self.fields['documents'] = forms.ModelMultipleChoiceField( queryset=org.documentasset_set.all(), required=False)
Python
nomic_cornstack_python_v1
function answer x r c begin if r * c % x != 0 begin return string RICHARD end if x == 1 or x == 2 begin return string GABRIEL end if x == 4 and r * c == 12 or r * c == 16 begin return string GABRIEL end if x == 3 and r * c > 3 begin return string GABRIEL end else begin return string RICHARD end end function set lines =...
def answer(x,r,c): if r*c % x != 0: return 'RICHARD' if x == 1 or x == 2: return 'GABRIEL' if (x == 4) and ((r*c == 12) or (r*c == 16)): return 'GABRIEL' if (x == 3) and r*c > 3: return 'GABRIEL' else: return 'RICHARD' lines = [line.strip() for line in open('in')] n = lines[0] for i in range(int(n)): ...
Python
zaydzuhri_stack_edu_python
comment !/usr/bin/env python3 function main begin set N = integer input set A = list map int split input sort A set li = list set mm1 = A at N - 1 set mm2 = A at 0 set i = 1 while i < N - 1 begin if A at i <= 0 begin append li list mm1 A at i set mm1 = mm1 - A at i end else begin append li list mm2 A at i set mm2 = mm...
#!/usr/bin/env python3 def main(): N = int(input()) A = list(map(int,input().split())) A.sort() li = [] mm1 = A[N-1] mm2 = A[0] i = 1 while(i<N-1): if A[i]<=0: li.append([mm1,A[i]]) mm1 -= A[i] else: li.append([mm2,A[i]]) ...
Python
zaydzuhri_stack_edu_python
comment -*- coding: utf-8 -*- import socket import threading from time import sleep , gmtime , strftime from tkinter import * import time set master = call Tk set ip = string localhost set port = 18039 function C begin while true begin set data = call recv 1024 if data != b'' begin print string client 2 recieved data d...
# -*- coding: utf-8 -*- import socket import threading from time import sleep,gmtime,strftime from tkinter import* import time master=Tk() ip='localhost' port=18039 def C(): while True: data=s.recv(1024) if data!=b'': print('client 2 recieved data', data) try: s=socket.so...
Python
zaydzuhri_stack_edu_python
function get_shot_angles self shot_loc begin return tuple call calc_yaw shot_loc call calc_pitch shot_loc end function
def get_shot_angles(self, shot_loc): return (self.trajectory_algo.calc_yaw(shot_loc), self.trajectory_algo.calc_pitch(shot_loc))
Python
nomic_cornstack_python_v1
comment Definition for a binary tree node. comment class TreeNode: comment def __init__(self, x): comment self.val = x comment self.left = None comment self.right = None class Solution extends object begin comment Here (a,b): a is the max value that you can rob with root= this node comment b is similar to a but without...
# Definition for a binary tree node. # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution(object): # Here (a,b): a is the max value that you can rob with root= this node # b is similar to a but without rob the node def r...
Python
zaydzuhri_stack_edu_python
comment !/usr/bin/env python3 comment -*- coding: utf-8 -*- string Created on Thu Apr 25 18:58:34 2019 @author: DRFricke comment !/usr/bin/env python3 comment -*- coding: utf-8 -*- string Created on Thu Apr 11 17:34:52 2019 @author: DRFricke import csv import numpy as np import matplotlib.pyplot as plt import scipy.sig...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Thu Apr 25 18:58:34 2019 @author: DRFricke """ #!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Thu Apr 11 17:34:52 2019 @author: DRFricke """ import csv import numpy as np import matplotlib.pyplot as plt import scipy.signal as sig from scipy...
Python
zaydzuhri_stack_edu_python
with open string code.txt as f begin set content = read lines f end set new_content = list for line in content begin append new_content strip line end set indent_level = 0 set no_bracket_for_indentation = false set fo = open string new code.txt string w for line in new_content begin if starts with line string } begin ...
with open("code.txt") as f: content = f.readlines() new_content = [] for line in content: new_content.append(line.strip()) indent_level = 0 no_bracket_for_indentation = False fo = open("new code.txt", 'w') for line in new_content: if line.startswith('}'): indent_level -= 1 inden...
Python
zaydzuhri_stack_edu_python
function compare_numbers num1 num2 begin if num1 - num2 > 0 begin return num1 end else if num1 - num2 < 0 begin return num2 end else begin return string Equal end end function set result = call compare_numbers 5 7 print result
def compare_numbers(num1, num2): if num1 - num2 > 0: return num1 elif num1 - num2 < 0: return num2 else: return "Equal" result = compare_numbers(5, 7) print(result)
Python
jtatman_500k
import numpy as np function loss_function output_activations y begin string The networks loss function. ME - Minimum Error return output_activations - y end function function sigmoid z begin string Numpy implementation of the sigmoid function return 1.0 / 1.0 + exp - z end function function sigmoid_prime z begin string...
import numpy as np def loss_function(output_activations, y): """ The networks loss function. ME - Minimum Error """ return (output_activations - y) def sigmoid(z): """ Numpy implementation of the sigmoid function """ return 1.0 / (1.0 + np.exp(-z)) def sigmoid_prime(z): """ ...
Python
zaydzuhri_stack_edu_python
function Double_Expand self one=- 1 two=- 1 begin set pre = get yscroll if one == string 0 and two == string 1 and pre at 0 != string 0 and pre at 1 != string 1 begin comment hide scroll if inactive call pack_forget end else if pre at 0 != string 0 and pre at 1 != string 1 begin comment show scroll if inactive and need...
def Double_Expand( self, one = -1, two = -1 ): pre = self.yscroll.get() if( one == '0' and two == '1' and pre[0]!='0' and pre[1]!='1' ): #hide scroll if inactive self.yscroll.pack_forget( ) elif( pre[0] != '0' and pre[1] != '1' ): #show scroll if inactiv...
Python
nomic_cornstack_python_v1
function call S K sigma r t begin set v1 = call d1 S K sigma r t set v2 = call d2 S K sigma r t return S * call erf v1 - K * exp - r * t * call erf v2 end function
def call(S,K,sigma,r,t): v1 = d1(S,K,sigma,r,t) v2 = d2(S,K,sigma,r,t) return S * erf(v1) - K * math.exp(-r*t) * erf(v2)
Python
nomic_cornstack_python_v1
import tensorflow as tf from tensorflow.python.client import device_lib set gpus = list comprehension d for d in call list_local_devices if device_type == string GPU print list comprehension name for g in gpus comment Creates a graph. with device name begin set a = call constant list 1.0 2.0 3.0 4.0 5.0 6.0 shape=list ...
import tensorflow as tf from tensorflow.python.client import device_lib gpus = [d for d in device_lib.list_local_devices() if d.device_type == 'GPU'] print([g.name for g in gpus]) # Creates a graph. with tf.device(gpus[1].name): a = tf.constant([1.0, 2.0, 3.0, 4.0, 5.0, 6.0], shape=[2, 3], name='a') ...
Python
zaydzuhri_stack_edu_python
comment 파이썬 유용한 내장함수 comment 1. 실행버튼을 클릭한 후 터미널에 '안녕하세요 파이썬'을 입력해보세요. comment k = input('<값>을 입력하세요: ') comment 아래는 출력을 위한 코드입니다. 수정하지 마세요. comment print('당신이 입력한 값은 <' + k + '>입니다.') comment 실습에 사용될 변수를 선언합니다. 수정하지 마세요. set numdata = 57 set strdata = string 파이썬 set listdata = list 1 2 3 set dictdata = dict string a 1 ...
## 파이썬 유용한 내장함수 # 1. 실행버튼을 클릭한 후 터미널에 '안녕하세요 파이썬'을 입력해보세요. #k = input('<값>을 입력하세요: ') # 아래는 출력을 위한 코드입니다. 수정하지 마세요. #print('당신이 입력한 값은 <' + k + '>입니다.') # 실습에 사용될 변수를 선언합니다. 수정하지 마세요. numdata = 57 strdata = '파이썬' listdata = [1, 2, 3] dictdata = {'a':1, 'b':2} # 실습에 사용될 함수를 선언합니다. 수정하지 마세요. def func(): print('안녕하...
Python
zaydzuhri_stack_edu_python
function generate self index begin set line = list append line string index append line string dim append line name comment num components append line string length comp append line name set comp_names = list for comp in comp begin append comp_names name end extend line comp_names append line string return join strin...
def generate(self, index): line = [] line.append(str(index)) line.append(str(self.dim)) line.append(self.name) line.append(str(len(self.comp))) # num components line.append(self.dpmf.name) comp_names = [] for comp in self.comp: comp_names.appe...
Python
nomic_cornstack_python_v1
function yresolution self begin set kw = __resolutionunitdistancekeyword set yresolution = call Fraction *self.tags['YResolution'] return distance pixels=decimal yresolution pscale=1 / distance keyword dict kw 1 pscale=1 end function
def yresolution(self): kw = self.__resolutionunitdistancekeyword yresolution = fractions.Fraction(*self.tags["YResolution"]) return units.Distance(pixels=float(yresolution), pscale=1) / units.Distance(**{kw: 1}, pscale=1)
Python
nomic_cornstack_python_v1
function _draw self begin if _total == 0 begin return end call _clear print format string {0:-<{1}}{2:3d}% ({3:{5}d}/{4:{5}d}) ETA {6} string = * round _bar_width * _current / _total _bar_width round floor _current / _total * 100 _current _total _digits _remaining_time end=string end function
def _draw(self): if self._total == 0: return self._clear() print('{0:-<{1}}{2:3d}% ({3:{5}d}/{4:{5}d}) ETA {6}'.format( "=" * round(self._bar_width * self._current / self._total), self._bar_width, round(math.floor(self._current / self._total * 100...
Python
nomic_cornstack_python_v1
string This program made by Joe set shapeSize = 60 comment Passed variables are translated to these member variables as they enter the def function draw_polygon m_sides m_color m_size begin call pendown call begin_fill call color m_color comment Function draws a circle of m_size, 360 degrees, with m_sides, making full ...
""" This program made by Joe """ shapeSize = 60 def draw_polygon(m_sides, m_color, m_size): # Passed variables are translated to these member variables as they enter the def pendown() begin_fill() color(m_color) circle(m_size, 360, m_sides) # Function draws a circle of m_size, 360 degrees, with m_sides...
Python
zaydzuhri_stack_edu_python
function compute_SCL_VGBF particle fieldset time begin comment dt has to be in years --> 86400*365 set SCL = SCL + k * SCLmax - SCL * dt / 31536000 end function
def compute_SCL_VGBF(particle, fieldset, time): particle.SCL = particle.SCL + fieldset.k * (fieldset.SCLmax - particle.SCL) * particle.dt / 31536000 #dt has to be in years --> 86400*365
Python
nomic_cornstack_python_v1
comment !/usr/bin/env python import sys import os import fileinput from array import * from math import floor , log10 from optparse import OptionParser from operator import itemgetter , attrgetter import numpy from decimal import * from HEPData.ExtractionTools.hepDataClasses import * from HEPData.ExtractionTools.hepDat...
#!/usr/bin/env python import sys import os import fileinput from array import * from math import floor, log10 from optparse import OptionParser from operator import itemgetter, attrgetter import numpy from decimal import * from HEPData.ExtractionTools.hepDataClasses import * from HEPData.ExtractionTools.hepDataUtilit...
Python
zaydzuhri_stack_edu_python
function test_list_own_user_ingredients self begin comment Create a new user set new_user = call mock_user email=string new_user password=string new_password comment Create ingredients for default user call create name=string ingredient_own_user user=user comment Create ingredients for new user call create name=string ...
def test_list_own_user_ingredients(self): # Create a new user new_user = mock_user(email='new_user', password='new_password') # Create ingredients for default user Ingredient.objects.create(name='ingredient_own_user', user=self.user) # Create ingredients for new user Ingredient.objects.create(name='ingredie...
Python
nomic_cornstack_python_v1
function anonymous_login self begin string Login as anonymous user :return: logon result, see `CMsgClientLogonResponse.eresult <https://github.com/ValvePython/steam/blob/513c68ca081dc9409df932ad86c66100164380a6/protobufs/steammessages_clientserver.proto#L95-L118>`_ :rtype: :class:`.EResult` debug string Attempting Anon...
def anonymous_login(self): """Login as anonymous user :return: logon result, see `CMsgClientLogonResponse.eresult <https://github.com/ValvePython/steam/blob/513c68ca081dc9409df932ad86c66100164380a6/protobufs/steammessages_clientserver.proto#L95-L118>`_ :rtype: :class:`.EResult` """ ...
Python
jtatman_500k
function get_iou bb1 bb2 begin assert bb1 at string x1 < bb1 at string x2 assert bb1 at string y1 < bb1 at string y2 assert bb2 at string x1 < bb2 at string x2 assert bb2 at string y1 < bb2 at string y2 comment determine the coordinates of the intersection rectangle set x_left = max bb1 at string x1 bb2 at string x1 se...
def get_iou(bb1, bb2): assert bb1['x1'] < bb1['x2'] assert bb1['y1'] < bb1['y2'] assert bb2['x1'] < bb2['x2'] assert bb2['y1'] < bb2['y2'] # determine the coordinates of the intersection rectangle x_left = max(bb1['x1'], bb2['x1']) y_top = max(bb1['y1'], bb2['y1']) x_right = min(bb1['x2...
Python
nomic_cornstack_python_v1
function task_progress_view request task_id begin if call login_required_if_login_only_mode request begin return call redirect string %s?next=%s % tuple LOGIN_URL path end set default_title = string Please wait... set redirect_default = reverse string productdb:home set meta_data = call get_meta_data_for_task task_id c...
def task_progress_view(request, task_id): if login_required_if_login_only_mode(request): return redirect('%s?next=%s' % (settings.LOGIN_URL, request.path)) default_title = "Please wait..." redirect_default = reverse("productdb:home") meta_data = get_meta_data_for_task(task_id) # title of t...
Python
nomic_cornstack_python_v1
from fastapi import FastAPI from pydantic import BaseModel from fastapi.responses import JSONResponse from deta import Deta set deta = call Deta set users = call Base string fastapi-crud set app = call FastAPI class User extends BaseModel begin set name : str set age : int set hometown : str end class class UserUpdate ...
from fastapi import FastAPI from pydantic import BaseModel from fastapi.responses import JSONResponse from deta import Deta deta = Deta() users = deta.Base("fastapi-crud") app = FastAPI() class User(BaseModel): name: str age: int hometown: str class UserUpdate(BaseModel): name: str = None age...
Python
zaydzuhri_stack_edu_python
comment Escreva um programa que obtenha um nome de um arquivo texto do usuário e crie um processo para executar o programa do sistema Windows bloco de notas (notepad) para abrir o arquivo. import psutil , time , os set nome_do_arquivo = input set diretorio = list directory if is file path nome_do_arquivo begin call sys...
#Escreva um programa que obtenha um nome de um arquivo texto do usuário e crie um processo para executar o programa do sistema Windows bloco de notas (notepad) para abrir o arquivo. import psutil, time, os nome_do_arquivo = input() diretorio = os.listdir() if os.path.isfile(nome_do_arquivo): os.system(nome_d...
Python
zaydzuhri_stack_edu_python
function climb_to_root S seq begin set stack = list while seq begin set tuple seq a = S at seq append stack a end comment print("".join(reversed(stack))) for a in reversed stack begin yield a end end function
def climb_to_root(S, seq): stack = [] while seq: seq, a = S[seq] stack.append(a) #print("".join(reversed(stack))) for a in reversed(stack): yield a
Python
nomic_cornstack_python_v1
function _delta self difference sample_weight=none begin if has attribute difference string abs begin set abs_diff = absolute end else begin set abs_diff = absolute difference end if sample_weight is none begin set delta = call percentile abs_diff alpha * 100 end else begin set delta = call _weighted_percentile abs_dif...
def _delta(self, difference: pandas_or_numpy, sample_weight=None) -> np.float64: if hasattr(difference, 'abs'): abs_diff = difference.abs() else: abs_diff = np.abs(difference) if sample_weight is None: delta = np.percentile(abs_diff, self.alpha * 100) ...
Python
nomic_cornstack_python_v1
function to_dict self begin set result = dict for tuple attr _ in call iteritems swagger_types begin set value = get attribute self attr if is instance value list begin set result at attr = list map lambda x -> if expression has attribute x string to_dict then call to_dict else x value end else if has attribute value ...
def to_dict(self): result = {} for attr, _ in six.iteritems(self.swagger_types): value = getattr(self, attr) if isinstance(value, list): result[attr] = list(map( lambda x: x.to_dict() if hasattr(x, "to_dict") else x, value ...
Python
nomic_cornstack_python_v1
function GetFacilityRequestStatusFull self request context begin call set_code UNIMPLEMENTED call set_details string Method not implemented! raise call NotImplementedError string Method not implemented! end function
def GetFacilityRequestStatusFull(self, request, context): context.set_code(grpc.StatusCode.UNIMPLEMENTED) context.set_details('Method not implemented!') raise NotImplementedError('Method not implemented!')
Python
nomic_cornstack_python_v1
string Input is as below which includes ASVs (amplicon sequence variants) and their relative abundance per sample #SampleID Subject Sample_Number 852bfcb95375282d779f638524d195fb 9327da197cd2232a4def87f314f833a9 stool.ASD.12.1 12 1 0.080176471 0.019352941 stool.ASD.12.2 12 2 0.014823529 0.011 stool.ASD.14.1 14 1 0 0.03...
""" Input is as below which includes ASVs (amplicon sequence variants) and their relative abundance per sample #SampleID Subject Sample_Number 852bfcb95375282d779f638524d195fb 9327da197cd2232a4def87f314f833a9 stool.ASD.12.1 12 1 0.080176471 0.019352941 stool.ASD.12.2 12 2 0.014823529 0.011 stool.ASD.14.1 14 1 0 0.0363...
Python
zaydzuhri_stack_edu_python
comment just for future references , how to perfom crud on tables in pyqt5 from PyQt5 import QtCore , QtGui , QtWidgets , uic from PyQt5.QtGui import QIcon from PyQt5.QtCore import QTimer , QThreadPool , QThread , pyqtSignal , QObject from PyQt5.QtWidgets import QSizePolicy , QGridLayout , QTableWidgetItem , QAction , ...
# just for future references , how to perfom crud on tables in pyqt5 from PyQt5 import QtCore, QtGui, QtWidgets , uic from PyQt5.QtGui import QIcon from PyQt5.QtCore import QTimer , QThreadPool , QThread , pyqtSignal , QObject from PyQt5.QtWidgets import QSizePolicy , QGridLayout , QTableWidgetItem , QAction , QMess...
Python
zaydzuhri_stack_edu_python
string ============== 3D scatterplot ============== Demonstration of a basic scatterplot in 3D. from mpl_toolkits.mplot3d import Axes3D import matplotlib.pyplot as plt from sklearn.manifold import TSNE import numpy as np import readfh set MAL_PATH = string C:\data\fh_mal_train set BENIGN_PATH = string C:\data\fh_benign...
''' ============== 3D scatterplot ============== Demonstration of a basic scatterplot in 3D. ''' from mpl_toolkits.mplot3d import Axes3D import matplotlib.pyplot as plt from sklearn.manifold import TSNE import numpy as np import readfh MAL_PATH = "C:\\data\\fh_mal_train" BENIGN_PATH = "C:\\data\\fh_benign_train" MAL...
Python
zaydzuhri_stack_edu_python
import requests set response = get requests string https://api.skypicker.com/flights params=dict string fly_from string JFK ; string fly_to string LAX ; string date_from string 01/01/2024 ; string date_to string 01/02/2024 set flights = json response at string data print flights at 0 at string price
import requests response = requests.get('https://api.skypicker.com/flights', params={'fly_from': 'JFK', 'fly_to': 'LAX', 'date_from': '01/01/2024', 'date_to': '01/02/2024'}) flights = response.json()['data'] print(flights[0]['price'])
Python
flytech_python_25k
string Given the coordinates of four points in 2D space, return whether the four points could construct a square. The coordinate (x,y) of a point is represented by an integer array with two integers. Example: Input: p1 = [0,0], p2 = [1,1], p3 = [1,0], p4 = [0,1] Output: True class Solution begin function dist self p q ...
""" Given the coordinates of four points in 2D space, return whether the four points could construct a square. The coordinate (x,y) of a point is represented by an integer array with two integers. Example: Input: p1 = [0,0], p2 = [1,1], p3 = [1,0], p4 = [0,1] Output: True """ class Solution: def dist(self, p,q)...
Python
zaydzuhri_stack_edu_python
string Memory Efficient Doubly Linked List based on bitwise XOR, do not store pointer to previous and next node inplace of storing pointer to next and prev node it stores xor of prev and next node Node = {data, xor} for head node it will be {data, xor(null, next)} since prev of head is null for travarsal do the xor wit...
''' Memory Efficient Doubly Linked List based on bitwise XOR, do not store pointer to previous and next node inplace of storing pointer to next and prev node it stores xor of prev and next node Node = {data, xor} for head node it will be {data, xor(null, next)} since prev of head is null for travarsal do the xor with p...
Python
zaydzuhri_stack_edu_python
comment import all the functions comment these functions will perform different web app enumeration techniques import sys import requests from funcmodule import dom_vulnerability_check from funcmodule import search_all_vulnerabilites from funcmodule import display_options from bs4 import BeautifulSoup comment we will d...
# import all the functions # these functions will perform different web app enumeration techniques import sys import requests from .funcmodule import dom_vulnerability_check from .funcmodule import search_all_vulnerabilites from .funcmodule import display_options from bs4 import BeautifulSoup # we will do the crawlin...
Python
zaydzuhri_stack_edu_python
function get_type self begin return string taxonomies end function
def get_type(self) -> str: return "taxonomies"
Python
nomic_cornstack_python_v1
function popup_empty_menu self control begin set _cur_control = control call PopupMenuXY menu 0 0 end function
def popup_empty_menu ( self, control ): self._cur_control = control control.PopupMenuXY( MakeMenu( self.empty_list_menu, self, True, control ).menu, 0, 0 )
Python
nomic_cornstack_python_v1
function expand start end tag begin if end - start == 1 begin set word = words at start for leaf in lexicon begin if tag == tag and word == word begin yield leaf end end end if tag in grammar begin for tags in grammar at tag begin for branches in call expand_all start end tags begin yield call Tree tag branches end end...
def expand(start, end, tag): if end-start == 1: word = words[start] for leaf in lexicon: if leaf.tag == tag and leaf.word == word: yield leaf if tag in grammar: for tags in grammar[tag]: for branches in expand_all(st...
Python
nomic_cornstack_python_v1
function storageFull N=10 D=1 begin return N * D ^ 2 * double / GB end function function storageDecomposition N=10 D=1 cg=false begin comment WX: DxN comment Kp: NxN comment Kpp: NxN comment W: ignored (1,DxD) if cg begin set total = 3 * D * N + 3 * N ^ 2 end else begin set total = D * N + 2 * N ^ 2 end return total * ...
def storageFull(N=10,D=1): return (N*D)**2*double/GB def storageDecomposition(N=10,D=1,cg=False): # WX: DxN # Kp: NxN # Kpp: NxN # W: ignored (1,DxD) if cg: total=3*D*N + 3*N**2 else: total=D*N +2*N**2 return total*double/GB def printStorage(N=10,D=1,cg=False): ...
Python
zaydzuhri_stack_edu_python
function make_bibtex self begin set filename = string ./ThesisClass/thesis_bibliography.txt with open filename string w errors=string backslashreplace as output begin for p_hash in parents begin set p = all_papers at p_hash set bib = call request string GET string http://dx.doi.org/ + doi headers=dict string Accept str...
def make_bibtex(self): filename = './ThesisClass/thesis_bibliography.txt' with open(filename, 'w', errors='backslashreplace') as output: for p_hash in self.parents: p = self.all_papers[p_hash] bib = requests.request('GET', 'http://dx.doi.org/' + p.doi, headers={'Accept':'application/x-bibtex'}, t...
Python
nomic_cornstack_python_v1
function _set_packagebase self variant begin call setEnabled variant is not none set variant = variant set is_package = is instance variant Package set prev_index = call currentIndex set disabled_tabs = set for d in call itervalues begin set index = d at string index if not d at string lazy or call currentIndex == inde...
def _set_packagebase(self, variant): self.setEnabled(variant is not None) self.variant = variant is_package = isinstance(variant, Package) prev_index = self.currentIndex() disabled_tabs = set() for d in self.tabs.itervalues(): index = d["index"] i...
Python
jtatman_500k
set nums = sorted split input string + print join string + nums
nums = sorted(input().split('+')) print('+'.join(nums))
Python
zaydzuhri_stack_edu_python
function main begin set N = integer input set A = list map int split input set mod = 10 ^ 9 + 7 set A_cum_sum = list A at - 1 for a in A at slice : : - 1 at slice 1 : : begin append A_cum_sum a + A_cum_sum at - 1 end set A_cum_sum = A_cum_sum at slice : : - 1 set ans = 0 for i in range N - 1 begin set sum_mod = A...
def main(): N = int(input()) A = list(map(int, input().split())) mod = 10 ** 9 + 7 A_cum_sum = [A[-1]] for a in A[::-1][1:]: A_cum_sum.append(a + A_cum_sum[-1]) A_cum_sum = A_cum_sum[::-1] ans = 0 for i in range(N-1): sum_mod = A_cum_sum[i+1] % mod mul_mod = (A[i]...
Python
zaydzuhri_stack_edu_python
function __init__ __self__ image_id type begin set __self__ string image_id image_id set __self__ string type string ManagedImage end function
def __init__(__self__, *, image_id: pulumi.Input[str], type: pulumi.Input[str]): pulumi.set(__self__, "image_id", image_id) pulumi.set(__self__, "type", 'ManagedImage')
Python
nomic_cornstack_python_v1
comment Most Common Words comment Amazon is partnering with the linguistics department at a local university to comment analyze important works of English literature and identify patterns in word comment usage across different eras. To ensure a cleaner output. the linguistics comment department has provided a list of c...
# Most Common Words # Amazon is partnering with the linguistics department at a local university to # analyze important works of English literature and identify patterns in word # usage across different eras. To ensure a cleaner output. the linguistics # department has provided a list of commonly used words # (e.g., “a...
Python
zaydzuhri_stack_edu_python
function testRemovedAddingUser self begin comment Share to second viewpoint. set tuple vp_id _ = call ShareNew _cookie2 list tuple _ep_id _photo_ids list user_id comment Now remove user #1 from first viewpoint. call RemoveFollowers _cookie _vp_id list user_id comment Merge user #2 into user #3. call MergeAccounts _cook...
def testRemovedAddingUser(self): # Share to second viewpoint. vp_id, _ = self._tester.ShareNew(self._cookie2, [(self._ep_id, self._photo_ids)], [self._user3.user_id]) # Now remove user #1 from first viewpoint. self._tester.RemoveFollowers(self._cookie, self._vp_id, [self._user.user_id]) # M...
Python
nomic_cornstack_python_v1
comment -*- coding: utf-8 -*- string Created on Sun Sep 22 02:35:18 2019 @author: ADMIN comment Import NaiveBayes.py and LogisticRegression.py import NaiveBayes as nb import LogisticRegression as lr set ans = string while ans != string 3 begin print string --------------------------------- print string | Enter your Ch...
# -*- coding: utf-8 -*- """ Created on Sun Sep 22 02:35:18 2019 @author: ADMIN """ #Import NaiveBayes.py and LogisticRegression.py import NaiveBayes as nb import LogisticRegression as lr ans = "" while(ans != "3"): print("---------------------------------") print("| Enter your Choice: |"...
Python
zaydzuhri_stack_edu_python