code
stringlengths
10
2.58M
original_code
stringlengths
3
3.18M
original_language
stringclasses
1 value
source
stringclasses
7 values
function _get_cmap_data data kwargs begin string Get normalized values to be used with a colormap. Parameters ---------- data : array_like cmap_min : Optional[float] or "min" By default 0. If "min", minimum value of the data. cmap_max : Optional[float] By default, maximum value of the data cmap_normalize : str or color...
def _get_cmap_data(data, kwargs) -> Tuple[colors.Normalize, np.ndarray]: """Get normalized values to be used with a colormap. Parameters ---------- data : array_like cmap_min : Optional[float] or "min" By default 0. If "min", minimum value of the data. cmap_max : Optional[float] ...
Python
jtatman_500k
function get_conn self begin string Retrieves connection to Google Compute Engine. :return: Google Compute Engine services object :rtype: dict if not _conn begin set http_authorized = call _authorize set _conn = call build string compute api_version http=http_authorized cache_discovery=false end return _conn end functi...
def get_conn(self): """ Retrieves connection to Google Compute Engine. :return: Google Compute Engine services object :rtype: dict """ if not self._conn: http_authorized = self._authorize() self._conn = build('compute', self.api_version, ...
Python
jtatman_500k
function do_unthrottle self *args begin string Remove the throughput limits for DQL that were set with 'throttle' # Remove all limits > unthrottle # Remove the limit on total allowed throughput > unthrottle total # Remove the default limit > unthrottle default # Remove the limit on a table > unthrottle mytable # Remove...
def do_unthrottle(self, *args): """ Remove the throughput limits for DQL that were set with 'throttle' # Remove all limits > unthrottle # Remove the limit on total allowed throughput > unthrottle total # Remove the default limit > unthrottle default ...
Python
jtatman_500k
comment exercise set mydict = dict string window dict string title string Sample Konfabulator Widget ; string name string main_window ; string width 500 ; string height 500 ; string image dict string src string Images/Sun.png ; string name string sun1 ; string hOffset 250 ; string vOffset 250 ; string alignment string ...
#exercise mydict = { "window": { "title": "Sample Konfabulator Widget", "name": "main_window", "width": 500, "height": 500 }, "image": { "src": "Images/Sun.png", "name": "sun1", "hOffset": 250, "vOffset": 250, "alignment"...
Python
zaydzuhri_stack_edu_python
function getProduct self begin return product call Product_getProduct _obj end function
def getProduct(self): return Product(Product_getProduct(self._obj))
Python
nomic_cornstack_python_v1
comment Your task is to prepare a simple code able to evaluate the end time of a period of time, comment given as a number of minutes (it could be arbitrarily large). comment The start time is given as a pair of hours (0..23) and minutes (0..59). comment The result has to be printed to the console. set hour = integer i...
#Your task is to prepare a simple code able to evaluate the end time of a period of time, #given as a number of minutes (it could be arbitrarily large). #The start time is given as a pair of hours (0..23) and minutes (0..59). #The result has to be printed to the console. hour = int(input("Starting time (hours): "))...
Python
zaydzuhri_stack_edu_python
comment 482. License Key Formatting class Solution extends object begin function licenseKeyFormatting self S K begin string :type S: str :type K: int :rtype: str set S = replace S string - string set l = length S if l == 0 begin return string end set result = string set begin = 0 set end = 0 if l % K > 0 begin set en...
# 482. License Key Formatting class Solution(object): def licenseKeyFormatting(self, S, K): """ :type S: str :type K: int :rtype: str """ S = S.replace('-', '') l = len(S) if l == 0: return '' result = '' begin = end = 0 ...
Python
zaydzuhri_stack_edu_python
function agrupar self indiceA indiceB begin set agrupA = agrupaciones at indiceA set agrupB = agrupaciones at indiceB set inicio_corrimiento = indiceB + 1 for i in range inicio_corrimiento length agrupaciones begin call actualizar_indice_agrupamiento agrupaciones at i i - 1 end call actualizar_indice_agrupamiento agrup...
def agrupar(self,indiceA,indiceB): agrupA = self.agrupaciones[indiceA] agrupB = self.agrupaciones[indiceB] inicio_corrimiento = indiceB+1 for i in range(inicio_corrimiento,len(self.agrupaciones)): self.actualizar_indice_agrupamiento(self.agrupaciones[i],i-1) ...
Python
nomic_cornstack_python_v1
function check_url_format self begin set m = match string ^http://www.tesco.com/direct/[0-9a-zA-Z-]+/[0-9-]+\.prd$ product_page_url set n = match string ^http://www.tesco.com/.*$ product_page_url return not not m or not not n end function
def check_url_format(self): m = re.match("^http://www.tesco.com/direct/[0-9a-zA-Z-]+/[0-9-]+\.prd$", self.product_page_url) n = re.match("^http://www.tesco.com/.*$", self.product_page_url) return (not not m) or (not not n)
Python
nomic_cornstack_python_v1
from math import inf from sys import stdout , stdin set P_BIG = 9369319 set A_BIG = 451543 set P_SMALL = 31 set A_SMALL = 26 class MultiMap begin function __init__ self begin set hash_p = P_BIG set a = list none * hash_p set size = 0 set hash_a = A_BIG set ripcnt = 0 end function function insert self x y begin if size ...
from math import inf from sys import stdout, stdin P_BIG = 9369319 A_BIG = 451543 P_SMALL = 31 A_SMALL = 26 class MultiMap: def __init__(self): self.hash_p = P_BIG self.a = [None] * self.hash_p self.size = 0 self.hash_a = A_BIG self.ripcnt = 0 d...
Python
zaydzuhri_stack_edu_python
function GetEntitiesCount self begin return call InvokeTypes 5 LCID 1 tuple 3 0 tuple end function
def GetEntitiesCount(self): return self._oleobj_.InvokeTypes(5, LCID, 1, (3, 0), (),)
Python
nomic_cornstack_python_v1
import numpy as np import pickle function unpickle file begin set infile = open file string rb set data = load pickle infile close infile return data end function function dopickle obj file begin with open file string wb as f begin dump obj f end end function function stride_axis arr window begin string Takes a numpy a...
import numpy as np import pickle def unpickle(file): infile = open(file, 'rb') data = pickle.load(infile) infile.close() return data def dopickle(obj, file): with open(file, 'wb') as f: pickle.dump(obj, f) def stride_axis(arr, window): """ Takes a numpy array and creates multipl...
Python
zaydzuhri_stack_edu_python
function nitems_written self *args **kwargs begin return call repeater_sptr_nitems_written self *args keyword kwargs end function
def nitems_written(self, *args, **kwargs): return _my_lte_swig.repeater_sptr_nitems_written(self, *args, **kwargs)
Python
nomic_cornstack_python_v1
from sklearn.tree import DecisionTreeClassifier from sklearn import tree from sklearn import datasets import matplotlib.pyplot as plt from sklearn.model_selection import cross_val_score set iris = call load_iris print iris set X = data set y = target print X print y set tree_model = call DecisionTreeClassifier max_dept...
from sklearn.tree import DecisionTreeClassifier from sklearn import tree from sklearn import datasets import matplotlib.pyplot as plt from sklearn.model_selection import cross_val_score iris = datasets.load_iris() print(iris) X = iris.data y = iris.target print(X) print(y) tree_model = DecisionTreeClassifier(max_de...
Python
zaydzuhri_stack_edu_python
function add_random_alpha_variation self image begin comment skip mask images if mode == string L begin return image end set img_array = array call convert string RGBA set center_y = random integer 0 shape at 0 set center_x = random integer 0 shape at 1 set alpha_array = call full_like img_array at tuple slice : : s...
def add_random_alpha_variation(self, image: Image.Image) -> Image.Image: if image.mode == "L": # skip mask images return image img_array = np.array(image.convert('RGBA')) center_y = np.random.randint(0, img_array.shape[0]) center_x = np.random.ran...
Python
nomic_cornstack_python_v1
function ad_create template replacements fallback max_len=30 capitalize=true begin if length format template fallback > max_len begin raise call ValueError string template + fallback should be <= + string max_len + string chars end set final_ad = list for rep in replacements begin if length format template rep <= max_...
def ad_create(template, replacements, fallback, max_len=30, capitalize=True): if len(template.format(fallback)) > max_len: raise ValueError('template + fallback should be <= ' + str(max_len) + ' chars') final_ad = [] for rep in replacements: if len(template.format(re...
Python
nomic_cornstack_python_v1
comment real signature unknown; restored from __doc__ function bit_length self begin pass end function
def bit_length(self): # real signature unknown; restored from __doc__ pass
Python
nomic_cornstack_python_v1
function wait_for_connection timeout begin global connected set total_time = 0 while not connected and total_time < timeout begin sleep 1 set total_time = total_time + 1 end if not connected begin raise call RuntimeError string Could not connect to MQTT bridge. end end function
def wait_for_connection(timeout): global connected total_time = 0 while not connected and total_time < timeout: time.sleep(1) total_time += 1 if not connected: raise RuntimeError('Could not connect to MQTT bridge.')
Python
nomic_cornstack_python_v1
function convert self out_path begin set tape_data_hdf5 = call createTapeHDF5Dict call deleteFile out_path call to_hdf5 tape_data_hdf5 out_path print format string HDF5 file has been successfully saved at {} out_path end function
def convert(self, out_path: str)->None: tape_data_hdf5 = self.createTapeHDF5Dict() self.deleteFile(out_path) self.to_hdf5(tape_data_hdf5, out_path) print("HDF5 file has been successfully saved at {}".format(out_path))
Python
nomic_cornstack_python_v1
class TrieNode begin function __init__ self label terminal begin set label = label set terminal = terminal set next_nodes = dict end function end class class Trie begin function __init__ self build_lexi=none begin set Root = call TrieNode string false if build_lexi is not none begin call construct build_lexi end end ...
class TrieNode: def __init__(self, label, terminal): self.label = label self.terminal = terminal self.next_nodes = {} class Trie: def __init__(self, build_lexi=None): self.Root = TrieNode('', False) if build_lexi is not None: self.construct(build_lexi) ...
Python
zaydzuhri_stack_edu_python
comment !/usr/bin/env python comment preamble, line start, line end, post-amble set c = tuple string fizzbuzz.c string #include<stdio.h> int main(){ string printf(" string "); string } set cplusplus = tuple string fizzbuzz.cpp string #include <iostream> int main(){ string std::cout << " string "; string } set java = tu...
#!/usr/bin/env python # preamble, line start, line end, post-amble c = ("fizzbuzz.c", "#include<stdio.h>\n\nint main(){\n", " printf(\"", "\");\n", "}") cplusplus = ("fizzbuzz.cpp", "#include <iostream>\n\nint main(){\n", " std::cout << \"", "\";\n", "}") java = ("FizzBuzz.java", "public class fizzbuzz {\n pub...
Python
zaydzuhri_stack_edu_python
import matplotlib.pyplot as plt import numpy as np import os import tensorflow as tf import tensorflow.keras.layers as tfl from tensorflow.keras.preprocessing import image_dataset_from_directory from tensorflow.keras.layers.experimental.preprocessing import RandomFlip , RandomRotation comment Data Preparation : Create ...
import matplotlib.pyplot as plt import numpy as np import os import tensorflow as tf import tensorflow.keras.layers as tfl from tensorflow.keras.preprocessing import image_dataset_from_directory from tensorflow.keras.layers.experimental.preprocessing import RandomFlip, RandomRotation # Data Preparation : Create a Dat...
Python
zaydzuhri_stack_edu_python
import numpy as np class InitConfig begin string This class holds everything intended to be configurable by the user in one location. I'm doing this instead of a run script with global variables. function __init__ self begin comment Related to generations and breeding comment Total population per generation set generat...
import numpy as np class InitConfig: """ This class holds everything intended to be configurable by the user in one location. I'm doing this instead of a run script with global variables. """ def __init__(self) -> None: # Related to generations and breeding # Total population pe...
Python
zaydzuhri_stack_edu_python
function traffic_generator_connectivity testbed get_configuration begin if get_configuration at string traffic_generator at string name == string lanforge begin set lanforge_ip = get_configuration at string traffic_generator at string details at string ip set lanforge_port = get_configuration at string traffic_generato...
def traffic_generator_connectivity(testbed, get_configuration): if get_configuration['traffic_generator']['name'] == "lanforge": lanforge_ip = get_configuration['traffic_generator']['details']['ip'] lanforge_port = get_configuration['traffic_generator']['details']['port'] # Condition : ...
Python
nomic_cornstack_python_v1
import matplotlib.pyplot as plt import environment from q_learning_agent import QLearningAgent import utils if __name__ == string __main__ begin comment Initializing Environment set env = call Env comment Initializing Graphic Display set display = call GraphicDisplay env comment Initializing Q-Learning Agent set q_lear...
import matplotlib.pyplot as plt import environment from q_learning_agent import QLearningAgent import utils if __name__ == "__main__": env = environment.Env() # Initializing Environment display = utils.GraphicDisplay(env) # Initializing Graphic Display q_learning_agent = QLearningAgent(env.actions) # In...
Python
zaydzuhri_stack_edu_python
comment your code goes here set tuple a b = map str split input set c = integer b set d = length a set s = a for i in range c begin set s = s at - 1 + s at slice : d - 1 : end print s
# your code goes here a,b=map(str,input().split()) c=int(b) d=len(a) s=a for i in range(c): s=s[-1]+s[:d-1] print(s)
Python
zaydzuhri_stack_edu_python
function get_sample self begin if c_heatmap_3 begin set tuple sample_images sample_conditions = call get_image_condition_pose_mpii_big sample_files condition_dir channel_num=3 set images_visual = merge call denorm_image sample_images list manifold_h_sample manifold_w_sample end else if c_heatmap_all begin set tuple sam...
def get_sample(self): if self.c_heatmap_3: sample_images, sample_conditions = get_image_condition_pose_mpii_big( self.sample_files, self.condition_dir, channel_num=3) images_visual = merge(denorm_image(sample_images), [self.manifold_h_sample, self.manifold_w_sample]) ...
Python
nomic_cornstack_python_v1
for ch in st at slice : : - 1 begin if ch == string ( begin set st_out = st_out + string ) end else begin set st_out = st_out + string ( end end
for ch in st[::-1]: if ch == '(': st_out += ')' else: st_out += '('
Python
zaydzuhri_stack_edu_python
function get_search_coords bank_folder=string quad_bank/ begin if not exists path bank_folder begin make directory os bank_folder end set s_coords = list comprehension split split split fil string / at 1 string _ at 1 string . at 0 for fil in glob glob bank_folder + string *.txt if length s_coords == 0 begin print stri...
def get_search_coords(bank_folder="quad_bank/"): if not os.path.exists(bank_folder): os.mkdir(bank_folder) s_coords = [fil.split("/")[1].split("_")[1].split(".")[0] for fil in glob.glob(bank_folder + "*.txt")] if len(s_coords) == 0: print( f"Error: no seed files f...
Python
nomic_cornstack_python_v1
function setInput self begin setup gpio bcm_id IN pull_up_down=pull set mode = IN end function
def setInput(self): gpio.setup(self.bcm_id, gpio.IN, pull_up_down=self.pull) self.mode = gpio.IN
Python
nomic_cornstack_python_v1
function main begin run use_reloader=true end function
def main(): app.handler.run(use_reloader=True)
Python
nomic_cornstack_python_v1
import sys import itertools from io import StringIO from tikz import * from pospopcnt import * function popcnt bytes mask begin set res = 0 for b in bytes begin if b ? mask begin set res = res + 1 end end return res end function function draw_picture f begin set x = 0.0 set y = 0.0 set w_bit = 0.25 set h = 0.45 set inp...
import sys import itertools from io import StringIO from tikz import * from pospopcnt import * def popcnt(bytes, mask): res = 0 for b in bytes: if b & mask: res += 1 return res def draw_picture(f): x = 0.0 y = 0.0 w_bit = 0.25 h = 0.45 input = QWORD(x, y, 64...
Python
zaydzuhri_stack_edu_python
function test_get_target self begin pass end function
def test_get_target(self): pass
Python
nomic_cornstack_python_v1
function process_settings settings begin function build_passive_voice_regex linking_verbs irregulars begin return string (?<!\w)( + join string | linking_verbs + string )\s+(\w+ed| + join string | irregulars + string )(?!\w) end function function build_regex_from_wordlist words begin set word_to_expr = lambda w -> stri...
def process_settings(settings): def build_passive_voice_regex(linking_verbs, irregulars): return r'(?<!\w)(' + '|'.join(linking_verbs) + r')\s+(\w+ed|' + '|'.join(irregulars) + r')(?!\w)' def build_regex_from_wordlist(words): word_to_expr = lambda w: r'(?<!\w)' + w + r'(?!\w)' ...
Python
nomic_cornstack_python_v1
for i in a begin if i not in a1 begin append a1 i end else begin set n1 = n1 + 1 end end print *a1 print n1
for i in a: if i not in a1: a1.append(i) else: n1 += 1 print(*a1) print(n1)
Python
zaydzuhri_stack_edu_python
for value in range 1 6 begin print value end set digits = list range 1 10 print digits print max digits print min digits print sum digits print digits at slice 1 : 6 : for digit in digits at slice : 6 : begin print digit end
for value in range(1, 6): print(value) digits = list(range(1, 10)) print(digits) print(max(digits)) print(min(digits)) print(sum(digits)) print(digits[1:6]) for digit in digits[:6]: print(digit)
Python
zaydzuhri_stack_edu_python
function test_save_and_load self tmpdir create_configuration begin global example_data set tmp_file = join tmpdir string configuration.ini comment create the configuration set tuple configuration load_args save_args = call create_configuration tmp_file comment set the values for tuple group key value args in example_da...
def test_save_and_load(self, tmpdir, create_configuration): global example_data tmp_file = tmpdir.join("configuration.ini") # create the configuration configuration, load_args, save_args = create_configuration(tmp_file) # set the values for group, key, value, args in ...
Python
nomic_cornstack_python_v1
function drag_data_received self widget context x y sel_data info time begin if sel_data and call get_data begin set data = loads call get_data if is instance data list begin set data = list comprehension loads x for x in data end else begin set data = list data end for value in data begin set tuple mytype selfid obj r...
def drag_data_received(self, widget, context, x, y, sel_data, info, time): if sel_data and sel_data.get_data(): data = pickle.loads(sel_data.get_data()) if isinstance(data, list): data = [pickle.loads(x) for x in data] else: data = [data] ...
Python
nomic_cornstack_python_v1
function get_properties zos_obj begin string Returns a lists of properties bound to the object `zos_obj` @param zos_obj: ZOS API Python COM object @return prop_get: list of properties that are only getters @return prop_set: list of properties that are both getters and setters set prop_get = set keys _prop_map_get_ set ...
def get_properties(zos_obj): """Returns a lists of properties bound to the object `zos_obj` @param zos_obj: ZOS API Python COM object @return prop_get: list of properties that are only getters @return prop_set: list of properties that are both getters and setters """ prop_get = set(zos_obj._pro...
Python
jtatman_500k
function SelectByName self Flags=defaultNamedNotOptArg IdStr=defaultNamedNotOptArg begin return call InvokeTypes 65575 LCID 1 tuple 24 0 tuple tuple 3 1 tuple 8 1 Flags IdStr end function
def SelectByName(self, Flags=defaultNamedNotOptArg, IdStr=defaultNamedNotOptArg): return self._oleobj_.InvokeTypes(65575, LCID, 1, (24, 0), ((3, 1), (8, 1)),Flags , IdStr)
Python
nomic_cornstack_python_v1
function build_detection_graph config checkpoint batch_size=1 score_threshold=none iou_threshold=none force_nms_cpu=true replace_relu6=true remove_assert=true input_shape=none output_dir=string .generated_model begin set config_path = config set checkpoint_path = checkpoint comment parse config from file set config = c...
def build_detection_graph(config, checkpoint, batch_size=1, score_threshold=None, iou_threshold=None, force_nms_cpu=True, replace_relu6=True, remove_assert=Tr...
Python
nomic_cornstack_python_v1
comment !/usr/bin/env python3 from pandas import read_csv class IMPORT_CEX begin function __init__ self path begin set path = path set df = call import_els path set df = call propre_df df end function comment mettre les methode a lancer function import_els self path begin try begin set df = read csv path end except Typ...
#!/usr/bin/env python3 from pandas import read_csv class IMPORT_CEX: def __init__(self, path): self.path = path self.df = self.import_els(self.path) self.df = self.propre_df(self.df) # mettre les methode a lancer def import_els(self, path): try: df = read_...
Python
zaydzuhri_stack_edu_python
function FaceInSurfaceSense self begin return call InvokeTypes 10 LCID 1 tuple 11 0 tuple end function
def FaceInSurfaceSense(self): return self._oleobj_.InvokeTypes(10, LCID, 1, (11, 0), (),)
Python
nomic_cornstack_python_v1
comment В файлике train.csv содержится информация о числе ридов с каждым из 4-ёх нуклеотидов по разным позициям (колонки A, T, G, C)). comment Постройте гистограмму распределения этих чисел import pandas as pd import numpy as np import matplotlib.pyplot as plt comment когда вставляла ссылску на гитхаб, он ругался set d...
#В файлике train.csv содержится информация о числе ридов с каждым из 4-ёх нуклеотидов по разным позициям (колонки A, T, G, C)). # Постройте гистограмму распределения этих чисел import pandas as pd import numpy as np import matplotlib.pyplot as plt df = pd.read_csv('/Users/lolitiy/Documents/inst_bioinf_19_20/python/t...
Python
zaydzuhri_stack_edu_python
function problem1_space_test begin set ll = call gen_test_ll 10 print string Before: + string ll set ll = call problem1_space ll print string After: + string ll end function
def problem1_space_test(): ll = gen_test_ll(10) print('Before: ' + str(ll)) ll = problem1_space(ll) print('After: ' + str(ll))
Python
nomic_cornstack_python_v1
from pymongo import MongoClient set client = call MongoClient string localhost 27017 set dict_database = call get_database string dictionary set teencode_collection = call get_collection string teencodes set teencode = call find_one del teencode at string _id comment teencode_collection.insert_one(teencode) while true ...
from pymongo import MongoClient client = MongoClient('localhost', 27017) dict_database = client.get_database('dictionary') teencode_collection = dict_database.get_collection('teencodes') teencode = teencode_collection.find_one() del teencode["_id"] # teencode_collection.insert_one(teencode) while True: for key i...
Python
zaydzuhri_stack_edu_python
function verify_neighbor_count device protocol neighbor value neighbor_count begin info format string verify the neighbor count on device for protocol {protocol} neighbor {neighbor} value {value} protocol=protocol neighbor=neighbor value=value set cmd = string show { protocol } { neighbor } | count { value } try begin ...
def verify_neighbor_count(device, protocol, neighbor, value, neighbor_count): log.info( "verify the neighbor count on device for protocol {protocol} neighbor {neighbor} value {value}".format( protocol=protocol, neighbor=neighbor, value=value ) ) cmd = f'show {protocol} {ne...
Python
nomic_cornstack_python_v1
function bit_count int_type begin set count = 0 while int_type begin set int_type = int_type ? int_type - 1 set count = count + 1 end return count end function
def bit_count(int_type): count = 0 while int_type: int_type &= int_type - 1 count += 1 return count
Python
nomic_cornstack_python_v1
function finish self closed=false cont=false begin call removeTemporaryObject if oldWP begin set DraftWorkingPlane = oldWP if has attribute Gui string Snapper begin call setGrid call restack end end set oldWP = none if length node > 1 begin if true begin call addModule string Draft comment The command to run is built a...
def finish(self, closed=False, cont=False): self.removeTemporaryObject() if self.oldWP: App.DraftWorkingPlane = self.oldWP if hasattr(Gui, "Snapper"): Gui.Snapper.setGrid() Gui.Snapper.restack() self.oldWP = None if len(self.node) ...
Python
nomic_cornstack_python_v1
import pandas as pd import requests import time comment Search npi registry for specific taxonomy and return bulk - Sample call: https://npiregistry.cms.hhs.gov/api/?number=&enumeration_type=&taxonomy_description=&first_name=&use_first_name_alias=&last_name=&organization_name=&address_purpose=&city=&state=&postal_code=...
import pandas as pd import requests import time #Search npi registry for specific taxonomy and return bulk - Sample call: https://npiregistry.cms.hhs.gov/api/?number=&enumeration_type=&taxonomy_description=&first_name=&use_first_name_alias=&last_name=&organization_name=&address_purpose=&city=&state=&postal_code=&c...
Python
zaydzuhri_stack_edu_python
function max_subarray_sum arr begin set current_sum = 0 set max_sum = 0 for x in arr begin set current_sum = current_sum + x if current_sum < 0 begin set current_sum = 0 end if current_sum > max_sum begin set max_sum = current_sum end end return max_sum end function set result = call max_subarray_sum list - 2 4 - 1 5 6...
def max_subarray_sum(arr): current_sum = 0 max_sum = 0 for x in arr: current_sum += x if current_sum < 0: current_sum = 0 if current_sum > max_sum: max_sum = current_sum return max_sum result = max_subarray_sum([-2, 4, -1, 5, 6]) print(result)
Python
iamtarun_python_18k_alpaca
comment Library to play Go. import copy import logging set BLACK = 1 set WHITE = 2 set PASS = 0 set SURRENDER = 1 class PlayLog begin function __init__ self board ko turn action winner begin string Defines play log. board: [0/1/2] * 81 ko: 1~81, 0 means no Ko. turn: black:1, white:2 action: 0: pass, 11~99: play, 1: sur...
# Library to play Go. import copy import logging BLACK = 1 WHITE = 2 PASS = 0 SURRENDER = 1 class PlayLog: def __init__(self, board, ko, turn, action, winner): """ Defines play log. board: [0/1/2] * 81 ko: 1~81, 0 means no Ko. turn: black:1, white:2 action: 0: pass, 11~99: play, 1: surrender ...
Python
zaydzuhri_stack_edu_python
function report_failure self out test example got begin call out call _failure_header test example + call output_difference example got optionflags end function
def report_failure(self, out, test, example, got): out(self._failure_header(test, example) + self._checker.output_difference(example, got, self.optionflags))
Python
nomic_cornstack_python_v1
import pygame import os from space_invaders import * function setup_graphics begin call init set screen = call set_mode tuple 1200 800 call set_caption string Space Invaders set images = dict with call scandir string .\images as it begin for entry in it begin if call is_dir begin set imagelist = list with call scandi...
import pygame import os from space_invaders import * def setup_graphics(): pygame.init() screen = pygame.display.set_mode((1200, 800)) pygame.display.set_caption("Space Invaders") images = {} with os.scandir(".\images") as it: for entry in it: if entry.is_dir(): ...
Python
zaydzuhri_stack_edu_python
comment https://en.wikipedia.org/wiki/Methods_of_computing_square_roots#Babylonian_method function square_root value abs_err=1e-09 iters=10000 begin set current = value + 1 / 2 set err = 1 set count = 0 while count < iters and err > abs_err begin set new = current + value / current / 2 set err = absolute current ^ 2 - ...
# https://en.wikipedia.org/wiki/Methods_of_computing_square_roots#Babylonian_method def square_root(value, abs_err=1e-9, iters=10000): current = (value + 1) / 2 err = 1 count = 0 while count < iters and err > abs_err: new = (current + value / current) / 2 err = abs(current ** 2 - value) ...
Python
zaydzuhri_stack_edu_python
function labelSlider begin global count sliderwords set text = string welcome to typing speed increaser game if count >= length text begin set count = 0 set sliderwords = string end set sliderwords = sliderwords + text at count set count = count + 1 call configure text=sliderwords call after 150 labelSlider end functi...
def labelSlider(): global count,sliderwords text='welcome to typing speed increaser game' if(count>=len(text)): count=0 sliderwords ='' sliderwords=sliderwords+text[count] count+=1 fontLabel.configure(text=sliderwords) fontLabel.after(150,labelSlider) def time...
Python
zaydzuhri_stack_edu_python
from enum import Enum from collections import deque class ModelAction extends Enum begin string An action that occurs in the game. These are the actions that the model publishes, and which views may subscribe to. set tuple player_added player_removed board_created game_started next_player try_again color_played game_wo...
from enum import Enum from collections import deque class ModelAction(Enum): """An action that occurs in the game. These are the actions that the model publishes, and which views may subscribe to. """ ( player_added, player_removed, board_created, game_started, next_player, try_ag...
Python
zaydzuhri_stack_edu_python
import numpy from collections import Counter set n = array list 1 1 2 3 3 3 0 print string original n print string most common: call most_common set res = list comprehension x at 1 for x in call most_common if x at 0 > 1 print string Duplicates: res
import numpy from collections import Counter n = numpy.array([1, 1, 2, 3, 3, 3, 0]) print("original", n) print("most common:", Counter(n).most_common()) res = [x[1] for x in Counter(n).most_common() if x[0] > 1] print("Duplicates: ", res)
Python
zaydzuhri_stack_edu_python
function max_prime_factor number begin set max_factor = 0 set current_factor = 2 while number > 1 begin while call is_factor number current_factor begin set number = number / current_factor set max_factor = current_factor end set current_factor = current_factor + 1 end return max_factor end function
def max_prime_factor(number): max_factor = 0 current_factor = 2 while number > 1: while is_factor(number, current_factor): number /= current_factor max_factor = current_factor current_factor += 1 return max_factor
Python
zaydzuhri_stack_edu_python
comment !/usr/bin/env python comment -*- coding: utf-8 -*- comment count sort comment k means the max integer(value scope) in list function countSort alist k begin set b = list set c = list comprehension 0 for i in call xrange k + 1 for i in alist begin comment count the value i of alist to c[i] set c at i = c at i + ...
#!/usr/bin/env python # -*- coding: utf-8 -*- #count sort #k means the max integer(value scope) in list def countSort(alist, k): b = [] c = [0 for i in xrange(k+1)] for i in alist: c[i] += 1 #count the value i of alist to c[i] c_index = 0 #current index of c for i in c: for dup in range(0, i): #dup m...
Python
zaydzuhri_stack_edu_python
function _match_smaller self begin return get size path path < args at string n end function
def _match_smaller(self): return os.path.getsize(self.ctx.path) < self.args["n"]
Python
nomic_cornstack_python_v1
function bb_temp_watts obs_wavelength pixel_deltalambda source_temp=270 * K begin set frequency = to c / obs_wavelength Hz set bt = call brightness_temperature frequency set brightness_temp = to source_temp string Jy/steradian equivalencies=bt set spectral_stuff = call spectral_density obs_wavelength set zeus_beam_radi...
def bb_temp_watts(obs_wavelength, pixel_deltalambda, source_temp=270*units.K ): frequency = (const.c/obs_wavelength).to(units.Hz) bt = units.brightness_temperature(frequency) brightness_temp = source_temp.to("Jy/steradian", equivalencies=bt) spectral...
Python
nomic_cornstack_python_v1
function test_rekey_non_encrypted self begin with raises EncryptionError begin call rekey string message old_key=b'0' * 32 new_key=b'1' * 32 end end function
def test_rekey_non_encrypted(self): with pytest.raises(EncryptionError): rekey('message', old_key=b'0' * 32, new_key=b'1' * 32)
Python
nomic_cornstack_python_v1
function test_no_sites_framework self begin delete del SITE_ID set response = get client reverse string django-admindocs-views-index call assertContains response string View documentation end function
def test_no_sites_framework(self): Site.objects.all().delete() del settings.SITE_ID response = self.client.get(reverse('django-admindocs-views-index')) self.assertContains(response, 'View documentation')
Python
nomic_cornstack_python_v1
from lib.molecule import molecule import lib.handle_file as hf comment 单例 class toplogy begin comment 分子及其个数 set molecules_list = list comment 分子种类 set molecules_set = set comment 按出现的顺序, 分子名——分子拓扑 set molname2molobj = dict function __init__ self in_file sys_ff begin set file = in_file set ffield = sys_ff call _extra...
from lib.molecule import molecule import lib.handle_file as hf # 单例 class toplogy: molecules_list = [] # 分子及其个数 molecules_set = set() # 分子种类 molname2molobj = {} # 按出现的顺序, 分子名——分子拓扑 def __init__(self, in_file, sys_ff): self.file = in_file self.ffield = sys_ff se...
Python
zaydzuhri_stack_edu_python
function spider_booster game_queue args begin set dolphin = call get_dolphin args while not call empty begin comment Try to get a game ID non-blocking. try begin set game_id = get game_queue false end except Empty begin close dolphin return end set spider = call GameSpider game_id dolphin call crawl end close dolphin e...
def spider_booster(game_queue, args): dolphin = get_dolphin(args) while not game_queue.empty(): # Try to get a game ID non-blocking. try: game_id = game_queue.get(False) except queue.Empty: dolphin.close() return spider = GameSpider(game_id, do...
Python
nomic_cornstack_python_v1
function parse_contents contents filename date begin comment length=len(contents) set sign = call detect_sign contents return call Div list call Img src=contents style=dict string width string 30% ; string height string 30% ; string margin string 10px call H4 sign end function comment HTML images accept base64 encoded ...
def parse_contents(contents, filename, date): # length=len(contents) sign=detect_sign(contents) return html.Div([ # HTML images accept base64 encoded strings in the same format # that is supplied by the upload html.Img(src=contents, style={"width":'30%',"height":"30%",'margin': '10px...
Python
nomic_cornstack_python_v1
function read_data_block_size s begin set size = call unpack string !I call read_n_bytes s 4 set size = size at 0 debug format string read command block size {} size return size end function
def read_data_block_size(s): size = struct.unpack('!I', read_n_bytes(s, 4)) size = size[0] logging.debug("read command block size {}".format(size)) return size
Python
nomic_cornstack_python_v1
string Python Version: python3.6 OS: OS X El Capitan Version: 10.11.6 Usage: python 3.6 Assembler_Symbol.py filename.asm from sys import argv import os.path import re string Class Assembler class Assembler extends object begin function __init__ self filename begin set filename = filename set parse = parse set intermedi...
''' Python Version: python3.6 OS: OS X El Capitan Version: 10.11.6 Usage: python 3.6 Assembler_Symbol.py filename.asm ''' from sys import argv import os.path import re '''Class Assembler''' class Assembler(object): def __init__(self, filename): self.filename = filename self.parse...
Python
zaydzuhri_stack_edu_python
function _second_heuristicA self j non_bounds begin if E at j > 0 begin set i = argument minimum E at non_bounds end else begin set i = argument maximum E at non_bounds end if call _take_step i j begin return true end return false end function
def _second_heuristicA(self, j, non_bounds): if self.E[j] > 0: i = cp.argmin(self.E[non_bounds]) else: i = cp.argmax(self.E[non_bounds]) if self._take_step(i, j): return True return False
Python
nomic_cornstack_python_v1
function onBlock self data begin pass end function
def onBlock(self, data) : pass
Python
nomic_cornstack_python_v1
import django import os set default environ string DJANGO_SETTINGS_MODULE string portfolio.settings setup django import base64 import tempfile from django.test import TestCase , override_settings from portfolio.portfolio_projects.forms import CommentForm , ProjectForm from django.core.files.uploadedfile import InMemory...
import django import os os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'portfolio.settings') django.setup() import base64 import tempfile from django.test import TestCase, override_settings from portfolio.portfolio_projects.forms import CommentForm, ProjectForm from django.core.files.uploadedfile import ...
Python
jtatman_500k
for i in list 1 3 5 begin set product = product * i print product end
for i in [1, 3, 5]: product=product*i print(product)
Python
zaydzuhri_stack_edu_python
function _calculate_momentum self mass vel begin comment p = m*v return mass * vel end function
def _calculate_momentum(self, mass, vel): # p = m*v return mass * vel
Python
nomic_cornstack_python_v1
comment !/usr/bin/env python comment coding: utf-8 comment In[1]: import sys import pymysql class Database begin string Database connection class. function __init__ self config begin set host = db_host set username = db_user set password = db_password set port = db_port set dbname = db_name set conn = none end function...
#!/usr/bin/env python # coding: utf-8 # In[1]: import sys import pymysql class Database: """Database connection class.""" def __init__(self, config): self.host = config.db_host self.username = config.db_user self.password = config.db_password self.port = config.db_port ...
Python
zaydzuhri_stack_edu_python
comment -*-coding: utf-8 -*- comment 移除有序数列中重复的元素,并返回剩余数组的长度 comment 用一个tail记录当前的最大长度 function removeDup nums begin if not nums begin return 0 end set tail = 0 for i in range 1 length nums begin if nums at i != nums at tail begin set tail = tail + 1 set nums at tail = nums at i end end return tail + 1 end function comm...
# -*-coding: utf-8 -*- #移除有序数列中重复的元素,并返回剩余数组的长度 #用一个tail记录当前的最大长度 def removeDup(nums): if not nums: return 0 tail =0 for i in range(1,len(nums)): if nums[i]!=nums[tail]: tail+=1 nums[tail]= nums[i] return tail+1 # 数组中每个元素可以最多出现两次,求删除多余元素后数组的长度。 def remove...
Python
zaydzuhri_stack_edu_python
comment Permuted multiples comment Problem 52 comment It can be seen that the number, 125874, and its double, 251748, contain comment exactly the same digits, but in a different order. comment Find the smallest positive integer, x, such that 2x, 3x, 4x, 5x, and 6x, comment contain the same digits. import time function ...
# Permuted multiples # Problem 52 # It can be seen that the number, 125874, and its double, 251748, contain # exactly the same digits, but in a different order. # Find the smallest positive integer, x, such that 2x, 3x, 4x, 5x, and 6x, # contain the same digits. import time def permuted_multiples(i): digits = lis...
Python
zaydzuhri_stack_edu_python
if a > b begin set t = a set a = b set b = t end print a b
if a>b: t=a a=b b=t print(a,b)
Python
zaydzuhri_stack_edu_python
from PIL import Image import numpy as np from scipy.ndimage import filters import matplotlib.pyplot as plt set im = array call convert string L comment sobel导数滤波器 set imx = zeros shape call sobel im 1 imx set imy = zeros shape call sobel im 0 imy comment This is my trick with axis: just add the operation in your mind t...
from PIL import Image import numpy as np from scipy.ndimage import filters import matplotlib.pyplot as plt im = np.array(Image.open('../data/empire.jpg').convert('L')) # sobel导数滤波器 imx = np.zeros(im.shape) filters.sobel(im, 1, imx) imy = np.zeros(im.shape) filters.sobel(im, 0, imy) # This is my trick with axis: just...
Python
zaydzuhri_stack_edu_python
function get_object self begin return user end function
def get_object(self): return self.request.user
Python
nomic_cornstack_python_v1
comment -*- coding: utf-8 -* import scipy.stats as st import tensorflow as tf import numpy as np import sys from functools import reduce function log10 x begin set numerator = log x set denominator = log call constant 10 dtype=dtype return numerator / denominator end function function _tensor_size tensor begin from ope...
# -*- coding: utf-8 -* import scipy.stats as st import tensorflow as tf import numpy as np import sys from functools import reduce def log10(x): numerator = tf.log(x) denominator = tf.log(tf.constant(10, dtype=numerator.dtype)) return numerator / denominator def _tensor_size(tensor): from operator import mu...
Python
zaydzuhri_stack_edu_python
function get_default_language begin set lang = get attribute settings string SOURCE_LANGUAGE_CODE LANGUAGE_CODE set default = list comprehension l at 0 for l in LANGUAGES if l at 0 == lang if length default == 0 begin comment when not found, take first part ('en' instead of 'en-us') set lang = split lang string - at 0 ...
def get_default_language(): lang = getattr(settings, 'SOURCE_LANGUAGE_CODE', settings.LANGUAGE_CODE) default = [l[0] for l in settings.LANGUAGES if l[0] == lang] if len(default) == 0: # when not found, take first part ('en' instead of 'en-us') lang = lang.split('-')[0] default ...
Python
nomic_cornstack_python_v1
function test_compute_rewards_closest_reward begin set device = string cuda set float_dtype = call get_float device set flock_size = 1 set n_frequent_seqs = 3 set n_cluster_centers = 5 set seq_length = 4 set seq_lookahead = 3 set context_size = 3 set n_providers = 1 comment region Setup set buffer = call create_tp_buff...
def test_compute_rewards_closest_reward(): device = 'cuda' float_dtype = get_float(device) flock_size = 1 n_frequent_seqs = 3 n_cluster_centers = 5 seq_length = 4 seq_lookahead = 3 context_size = 3 n_providers = 1 # region Setup buffer = create_tp_buffer(flock_size=flock_s...
Python
nomic_cornstack_python_v1
comment tuples are like lists can be used to store multiple values comment tuples cannot be modified set numbers = tuple 1 2 3 4 5
# tuples are like lists can be used to store multiple values # tuples cannot be modified numbers = (1, 2, 3, 4, 5)
Python
zaydzuhri_stack_edu_python
comment ! /usr/bin/env python function seem_world_up_day str_arg begin call important_place_or_group str_arg print string take_life_for_group end function function important_place_or_group str_arg begin print str_arg end function if __name__ == string __main__ begin call seem_world_up_day string child_or_point end
#! /usr/bin/env python def seem_world_up_day(str_arg): important_place_or_group(str_arg) print('take_life_for_group') def important_place_or_group(str_arg): print(str_arg) if __name__ == '__main__': seem_world_up_day('child_or_point')
Python
zaydzuhri_stack_edu_python
function broadcast_inputs tensor_a tensor_b name=string broadcast_inputs begin from smaug.python.ops.array_ops import repeat if length dims != length dims begin raise call ValueError string Cannot broadcast: tensor_a has % dimensions but tensor_b has %. % tuple length dims length dims end set multiples_a = ones length ...
def broadcast_inputs(tensor_a, tensor_b, name="broadcast_inputs"): from smaug.python.ops.array_ops import repeat if len(tensor_a.shape.dims) != len(tensor_b.shape.dims): raise ValueError( "Cannot broadcast: tensor_a has % dimensions but tensor_b has %." % (len(tensor_a.shape.dims), len(tensor_b....
Python
nomic_cornstack_python_v1
function get_clusters board col loose=false begin set clusters = list set remaining_cells = list comprehension tuple i j for i in range s for j in range s while remaining_cells begin set curr = remaining_cells at 0 if board at curr != col begin pop remaining_cells 0 continue end comment ._get_connections(*curr,loose=l...
def get_clusters(board,col,loose=False): clusters = [] remaining_cells = [(i,j) for i in range(board.s) for j in range(board.s)] while remaining_cells: curr = remaining_cells[0] if board[curr] != col: remaining_cells.pop(0) continue conn = board._get_conn_rec(curr[0],curr[1],col,loose=loose) #._get_conne...
Python
zaydzuhri_stack_edu_python
function is_ready_update self begin raise call UnityTrainerException string The is_ready_update method was not implemented. end function
def is_ready_update(self): raise UnityTrainerException("The is_ready_update method was not implemented.")
Python
nomic_cornstack_python_v1
import math as m import random comment Combinations of k events in a total of n events comment Calculates n! / (k! * (n - k)!) function combinations k n begin set tuple num den = tuple 1 1 for i in range k begin set num = n - i * num set den = k - i * den end return num / den end function function permutations n k begi...
import math as m import random # Combinations of k events in a total of n events # Calculates n! / (k! * (n - k)!) def combinations(k, n): num, den = 1, 1 for i in range(k): num = (n - i) * num den = (k - i) * den return num / den def permutations(n, k): num = 1 for i in range(k):...
Python
zaydzuhri_stack_edu_python
function mime_form self begin return __mime_form end function
def mime_form(self): return self.__mime_form
Python
nomic_cornstack_python_v1
function load_Particle_From_mrcFileDir trainInputDir particle_size model_input_size coordinate_symbol mrc_number produce_negative=true negative_distance_ratio=0.5 begin set mrc_file_all = list set mrc_file_coordinate = list set file_coordinate = list if not is directory path trainInputDir begin print string Invalide...
def load_Particle_From_mrcFileDir(trainInputDir, particle_size, model_input_size, coordinate_symbol, mrc_number, produce_negative = True, negative_distance_ratio = 0.5): mrc_file_all = [] mrc_file_coordinate = [] file_coordinate = [] if not os.path.isdir(trainInputDir): prin...
Python
nomic_cornstack_python_v1
string Generate some data with open string data1.bin string wb as f begin for _ in range 5 begin for a in range 200 begin write f bytes list a 1 a end end end with open string data2.bin string wb as f begin write f bytes list 255 for _ in range 10 begin for a in range 200 begin write f bytes list a 1 a end end end
""" Generate some data """ with open('data1.bin', 'wb') as f: for _ in range(5): for a in range(200): f.write(bytes([a, 1, a])) with open('data2.bin', 'wb') as f: f.write(bytes([0xff])) for _ in range(10): for a in range(200): f.write(bytes([a, 1, a]))
Python
zaydzuhri_stack_edu_python
import requests from flask import Flask , request , jsonify , send_from_directory set app = call Flask __name__ import pandas as pd import quandl import math import random import os import numpy as np from sklearn import preprocessing , cross_validation , svm from sklearn.linear_model import LinearRegression decorator ...
import requests from flask import Flask, request, jsonify, send_from_directory app = Flask(__name__) import pandas as pd import quandl import math import random import os import numpy as np from sklearn import preprocessing, cross_validation, svm from sklearn.linear_model import LinearRegression @app.route('getstockd...
Python
zaydzuhri_stack_edu_python
function job_output_type self begin return get pulumi self string job_output_type end function
def job_output_type(self) -> str: return pulumi.get(self, "job_output_type")
Python
nomic_cornstack_python_v1
function select_bill_and_audit_submenu self begin call select_submenu home_menu_locator bill_and_audit_submenu_locator end function
def select_bill_and_audit_submenu(self): self.select_submenu(self.home_menu_locator, self.bill_and_audit_submenu_locator)
Python
nomic_cornstack_python_v1
function print_datapoint parts begin set t = call fromtimestamp parts at 0 set humid = parts at 1 set temp_c = parts at 2 set temp_f = parts at 3 set heat_c = parts at 4 set heat_f = parts at 5 end function
def print_datapoint(parts): t = datetime.fromtimestamp(parts[0]) humid = parts[1] temp_c = parts[2] temp_f = parts[3] heat_c = parts[4] heat_f = parts[5]
Python
nomic_cornstack_python_v1
function sample_observations self begin set sample_dict = dict for obs in observations begin set domain = properties at string domain comment If probabilistic, sample from the true distribution if type == string probabilistic begin set probabilities = properties at string probability end else begin comment If uncontro...
def sample_observations(self): sample_dict={} for obs in self.observations: domain = obs.properties['domain'] #If probabilistic, sample from the true distribution if obs.type=='probabilistic': probabilities = obs.properties['probability'] #...
Python
nomic_cornstack_python_v1
function url self begin return get pulumi self string url end function
def url(self) -> Optional[pulumi.Input[str]]: return pulumi.get(self, "url")
Python
nomic_cornstack_python_v1
function _filter_for_similar_ligands_2d ligand structures begin import pandas as pd from openeye import oechem from rdkit import Chem , RDLogger from rdkit.Chem import AllChem , DataStructs comment disable RDKit logging call DisableLog string rdApp.* debug string Converting OpenEye molecule to RDKit molecule ... set li...
def _filter_for_similar_ligands_2d( ligand: oechem.OEGraphMol, structures: pd.DataFrame ) -> pd.DataFrame: import pandas as pd from openeye import oechem from rdkit import Chem, RDLogger from rdkit.Chem import AllChem, DataStructs RDLogger.DisableLog("rdApp.*") # di...
Python
nomic_cornstack_python_v1
function _handle_PacketIn self event begin comment This is the parsed packet data. set packet = parsed if not parsed begin warning string Ignoring incomplete packet return end comment The actual ofp_packet_in message. set packet_in = ofp call act_like_switch packet packet_in end function
def _handle_PacketIn(self, event): packet = event.parsed # This is the parsed packet data. if not packet.parsed: log.warning("Ignoring incomplete packet") return packet_in = event.ofp # The actual ofp_packet_in message. self.act_like_switch(packet, packet_in)
Python
nomic_cornstack_python_v1