code
stringlengths
10
2.58M
original_code
stringlengths
3
3.18M
original_language
stringclasses
1 value
source
stringclasses
7 values
function _parse_args begin string Parse and return command line arguments. set parser = call ArgumentParser description=__doc__ formatter_class=_CliFormatter call add_argument string -v string --verbose action=string store_true help=string Enable verbose output. set fb_group = call add_argument_group string FogBugz arg...
def _parse_args(): """Parse and return command line arguments.""" parser = argparse.ArgumentParser( description=__doc__, formatter_class=_CliFormatter) parser.add_argument('-v', '--verbose', action='store_true', help='Enable verbose output.') fb_group = parser.ad...
Python
jtatman_500k
function _b_py self eSolution source_list begin return call _b_pyPrimary eSolution source_list + call _b_pySecondary eSolution source_list end function
def _b_py(self, eSolution, source_list): return self._b_pyPrimary(eSolution, source_list) + self._b_pySecondary( eSolution, source_list )
Python
nomic_cornstack_python_v1
from zonnescherm import * from tkinter import * from tkinter import _setit from tkinter import Canvas class GUI begin function __init__ self begin comment Variables set __zonneschermen = list set __selected_zonnescherm = none set __update_CB = none set __update_milliseconds = 1000 comment The root(TK) set __root = cal...
from zonnescherm import * from tkinter import * from tkinter import _setit from tkinter import Canvas class GUI: def __init__(self): # Variables self.__zonneschermen = [] self.__selected_zonnescherm = None self.__update_CB = None self.__update_milliseconds = 1000 ...
Python
zaydzuhri_stack_edu_python
comment Assignment 6 comment Problem 1b comment Hoazhe Wang import pandas as pd import csv import pylab import numpy as np import matplotlib.pyplot as plt set labeledfile = read csv string labeled_data.csv set plotdata2 = labeledfile at list string # zipcode string num_incidents set index2 = set index plotdata2 string ...
#Assignment 6 #Problem 1b #Hoazhe Wang import pandas as pd import csv import pylab import numpy as np import matplotlib.pyplot as plt labeledfile = pd.read_csv('labeled_data.csv') plotdata2 = labeledfile[['# zipcode','num_incidents']] index2 = plotdata2.set_index('# zipcode') second_plot = index2.plot(legend = True, ...
Python
zaydzuhri_stack_edu_python
from ant_updated import * from maze_classes import * from algorithms_updated import * import simpy import math import numpy as np from tower_of_hanoi import * import matplotlib.pyplot as plt set size = 2 set maze = call mirror_hanoi size set nest_name = string up + string -top * size set food_name = string down + strin...
from ant_updated import * from maze_classes import * from algorithms_updated import * import simpy import math import numpy as np from tower_of_hanoi import * import matplotlib.pyplot as plt size = 2 maze = mirror_hanoi(size) nest_name = 'up'+'-top'*size food_name = 'down'+'-bottom'*size nest = maze.get_intersection(...
Python
zaydzuhri_stack_edu_python
function __enter__ self begin if not _content begin comment type: IO[str] with call YamlFile _path as file begin append _content call YamlFromStream file end end return self end function
def __enter__(self) -> Yaml: if not self._content: with YamlFile(self._path) as file: # type: IO[str] self._content.append(YamlFromStream(file)) return self
Python
nomic_cornstack_python_v1
function removeBrackets s begin set newS = list set brackLevel = 0 for c in s begin if c == string ( begin set brackLevel = brackLevel + 1 continue end if c == string ) begin set brackLevel = brackLevel - 1 continue end if brackLevel == 0 begin append newS c end end return strip join string newS end function
def removeBrackets(s): newS = [] brackLevel = 0 for c in s: if c=="(": brackLevel+=1 continue if c==")": brackLevel-=1 continue if brackLevel==0: newS.append(c) return "".join(newS).strip()
Python
nomic_cornstack_python_v1
function reverseString s begin return s at slice : : - 1 end function set s = string Hello print call reverseString s
def reverseString(s): return s[::-1] s = "Hello" print(reverseString(s))
Python
flytech_python_25k
function _relief_square_inner_refresh self add_instruction top_color bottom_color wid_x wid_y wid_width wid_height begin set lines = integer relief_square_inner_lines set offset = integer relief_square_inner_offset for line in range 1 lines + 1 begin set alpha = 0.9 - line / lines * 0.81 set line = line + offset set li...
def _relief_square_inner_refresh(self, add_instruction: Callable, top_color: ColorRGB, bottom_color: ColorRGB, wid_x: float, wid_y: float, wid_width: float, wid_height: float): lines = int(self.relief_square_inner_lines) offset = ...
Python
nomic_cornstack_python_v1
function get_random_wilson_coeffs_start self begin if fit_wc_function is none begin comment no Wilson coefficients present return none end else if start_wc_priors is none begin if fit_wc_priors is none begin raise call ValueError string Starting values can only be generated if either fit_wc_priors or start_wc_priors is...
def get_random_wilson_coeffs_start(self): if self.fit_wc_function is None: # no Wilson coefficients present return None elif self.start_wc_priors is None: if self.fit_wc_priors is None: raise ValueError("Starting values can only be generated if" ...
Python
nomic_cornstack_python_v1
comment !/usr/bin/env python3 comment -*- coding: utf-8 -*- import math from pathlib import Path import matplotlib.pyplot as plt import numpy as np from python_inferno.inferno import sigmoid from python_inferno.plotting import use_style if __name__ == string __main__ begin call use_style set factors = list - 1 0.5 3 se...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- import math from pathlib import Path import matplotlib.pyplot as plt import numpy as np from python_inferno.inferno import sigmoid from python_inferno.plotting import use_style if __name__ == "__main__": use_style() factors = [-1, 0.5, 3] centres = [0] ...
Python
zaydzuhri_stack_edu_python
function predict self observation state=none mask=none deterministic=false begin comment TODO (GH/1): add support for RNN policies comment if state is None: comment state = self.initial_state comment if mask is None: comment mask = [False for _ in range(self.n_envs)] set vectorized_env = false if is instance observatio...
def predict( self, observation: Union[np.ndarray, Dict[str, np.ndarray]], state: Optional[np.ndarray] = None, mask: Optional[np.ndarray] = None, deterministic: bool = False, ) -> Tuple[np.ndarray, Optional[np.ndarray]]: # TODO (GH/1): add support for RNN policies ...
Python
nomic_cornstack_python_v1
function fit_to_focus x y model focus_point begin from scipy.optimize import curve_fit set tuple x1 y1 = focus_point set init_vals = list 0 + focus_point set tuple v c = curve fit model x + list x1 y + list y1 p0=init_vals return v end function
def fit_to_focus(x, y, model, focus_point): from scipy.optimize import curve_fit x1, y1 = focus_point init_vals = [0] + focus_point v, c = curve_fit(model, x + [x1], y + [y1], p0=init_vals) return v
Python
nomic_cornstack_python_v1
function balance_check_existing_oldBF_new_view request begin comment Check connected if not call has_permission request settings at string affaire_numero_edition begin raise call HTTPForbidden end set affaire_id = params at string affaire_id set oldBF = loads params at string oldBF comment Control existance of each old...
def balance_check_existing_oldBF_new_view(request): # Check connected if not Utils.has_permission(request, request.registry.settings['affaire_numero_edition']): raise exc.HTTPForbidden() affaire_id = request.params['affaire_id'] oldBF = json.loads(request.params['oldBF']) # Control exi...
Python
nomic_cornstack_python_v1
function regDebug cls word1 word2 word3 word4 begin set regs = zeros REG_PACKET_LEN dtype=string <u1 set regs at 0 = 2 set regs at 1 = 1 set regs at slice 13 : 17 : = call littleEndian word1 set regs at slice 17 : 21 : = call littleEndian word2 set regs at slice 21 : 25 : = call littleEndian word3 set regs at slice ...
def regDebug(cls, word1, word2, word3, word4): regs = np.zeros(cls.REG_PACKET_LEN, dtype='<u1') regs[0] = 2 regs[1] = 1 regs[13:17] = littleEndian(word1) regs[17:21] = littleEndian(word2) regs[21:25] = littleEndian(word3) regs[25:29] = littleEndian(word4) ...
Python
nomic_cornstack_python_v1
comment !/usr/bin/env python string _Couch_ A simple API to CouchDB that sends HTTP requests to the REST interface. Warning: There is a known issue when posting large (~800KB) JSON documents from OSX through a reverse proxy. If a timeout is set then the client will stop sending data and the request will not complete. T...
#!/usr/bin/env python """ _Couch_ A simple API to CouchDB that sends HTTP requests to the REST interface. Warning: There is a known issue when posting large (~800KB) JSON documents from OSX through a reverse proxy. If a timeout is set then the client will stop sending data and the request will not complete. This issu...
Python
zaydzuhri_stack_edu_python
function crop cnt *images begin assert images is not none comment Checking that all are in fact images if not all generator expression is instance item ndarray for item in images begin raise call TypeError string "*images" must be nust be of type: "numpy.ndarray" end comment Returning the cropped images set tuple refer...
def crop(cnt, *images): assert images is not None #Checking that all are in fact images if not all(isinstance(item, np.ndarray) for item in images): raise TypeError('"*images" must be nust be of type: "numpy.ndarray"') #Returning the cropped images reference_y, reference_x = images[0].sha...
Python
nomic_cornstack_python_v1
function do_bounding_boxes_intersect a b begin return x <= x and x >= x and y <= y and y >= y end function
def do_bounding_boxes_intersect(a: tuple[Point, Point], b: tuple[Point, Point]) -> bool: return ( a[0].x <= b[1].x and a[1].x >= b[0].x and a[0].y <= b[1].y and a[1].y >= b[0].y )
Python
nomic_cornstack_python_v1
from django.shortcuts import render from django.http import HttpResponse from django.contrib.admin.views.decorators import staff_member_required import datetime , calendar from decimal import * from models import teacher , Class , student , timetable , attendence , theorysubject , lab function home request begin set n ...
from django.shortcuts import render from django.http import HttpResponse from django.contrib.admin.views.decorators import staff_member_required import datetime , calendar from decimal import * from .models import teacher , Class , student , timetable , attendence , theorysubject , lab def home(request): n = datet...
Python
zaydzuhri_stack_edu_python
function potencia c begin if length c == 0 begin return list list end set r = call potencia c at slice : - 1 : return r + list comprehension s + list c at - 1 for s in r end function
def potencia(c): if len(c) == 0: return [[]] r = potencia(c[:-1]) return r + [s + [c[-1]] for s in r]
Python
nomic_cornstack_python_v1
from math import pow import requests set prev = json get requests string http://95.217.177.249/casino/playLcg?id=228&bet=1&number=1 at string realNumber set curr = json get requests string http://95.217.177.249/casino/playLcg?id=228&bet=1&number=1 at string realNumber set nextn = json get requests string http://95.217....
from math import pow import requests prev = requests.get("http://95.217.177.249/casino/playLcg?id=228&bet=1&number=1").json()["realNumber"] curr = requests.get("http://95.217.177.249/casino/playLcg?id=228&bet=1&number=1").json()["realNumber"] nextn = requests.get("http://95.217.177.249/casino/playLcg?id=228&bet=1&numb...
Python
zaydzuhri_stack_edu_python
function build_encoder_bi tparams options begin comment word embedding (source) set embedding = call tensor3 string embedding dtype=string float32 set embeddingr = embedding at slice : : - 1 set x_mask = call matrix string x_mask dtype=string float32 set xr_mask = x_mask at slice : : - 1 comment encoder set proj = ...
def build_encoder_bi(tparams, options): # word embedding (source) embedding = tensor.tensor3('embedding', dtype='float32') embeddingr = embedding[::-1] x_mask = tensor.matrix('x_mask', dtype='float32') xr_mask = x_mask[::-1] # encoder proj = get_layer(options['encoder'])[1](tparams, embedding, options, ...
Python
nomic_cornstack_python_v1
from rs_converter import * from lexicon_converter import * import sys comment This top level script obtains two optional arguments: comment a) input file name - the file must be a well formed lisp version of ONTO lexicon comment residing in the same directory with this script comment IF the file name is missing then 'l...
from rs_converter import * from lexicon_converter import * import sys ## This top level script obtains two optional arguments: ## a) input file name - the file must be a well formed lisp version of ONTO lexicon ## residing in the same directory with this script ## IF the file name is missing then 'lexicon....
Python
zaydzuhri_stack_edu_python
import random import unionfind import argparse import numpy as np from matplotlib import pyplot as plt import matplotlib.cm as cm import HelperFunctions as hf comment given length and width, generate maze using kruskal's minimum spanning tree algorithm function generate_maze length width begin comment generate edges se...
import random import unionfind import argparse import numpy as np from matplotlib import pyplot as plt import matplotlib.cm as cm import HelperFunctions as hf #given length and width, generate maze using kruskal's minimum spanning tree algorithm def generate_maze(length,width): #generate edges edges=hf.gene...
Python
zaydzuhri_stack_edu_python
function __setitem__ self key val begin set call self at key = val end function
def __setitem__(self, key, val): self()[key] = val
Python
nomic_cornstack_python_v1
function box begin for i in range 0 length word begin print word at slice 0 : length word : end end function call box
def box(): for i in range(0, len(word)): print(word[0:len(word)]) box()
Python
zaydzuhri_stack_edu_python
comment !/usr/bin/python string using MySQLdb import MySQLdb import re comment Open database connection set db = call connect string localhost string root string root string rcp_base comment prepare a cursor object using cursor() method set cursor = call cursor comment Drop table if it already exist using execute() met...
#!/usr/bin/python ''' using MySQLdb ''' import MySQLdb import re # Open database connection db = MySQLdb.connect("localhost","root","root","rcp_base" ) # prepare a cursor object using cursor() method cursor = db.cursor() # Drop table if it already exist using execute() method. cursor.execute("DROP TABLE IF EXISTS C...
Python
zaydzuhri_stack_edu_python
function init_params begin set p = dict comment 2040 set p at string endYear = 1940 comment 1990 set p at string statsCollectFrom = 1900 set p at string implementPoliciesFromYear = 1920 set p at string numRepeats = 4 return p end function
def init_params(): p = {} p['endYear'] = 1940 # 2040 p['statsCollectFrom'] = 1900 # 1990 p['implementPoliciesFromYear'] = 1920 p['numRepeats'] = 4 return p
Python
nomic_cornstack_python_v1
async function cookies ctx user whispers=none begin try begin if whispers is none begin await call send string * { mention } passes { mention } a 🍪* end else begin await call send string * { mention } passes { mention } a 🍪 and whispers { whispers } * end end except Exception as e begin comment if error await call se...
async def cookies(ctx, user: discord.Member, *, whispers=None): try: if whispers is None: await ctx.send(f"*{ctx.author.mention} passes {user.mention} a 🍪*") else: await ctx.send(f"*{ctx.author.mention} passes {user.mention} a 🍪 and whispers {whispers}*") except Exception as e: await ctx.send(f'There wa...
Python
nomic_cornstack_python_v1
set n = integer input set xs = list map int split input set max_x = max xs set bad = sum xs set good = n * max_x - bad print max_x + max 0 1 + bad - good // n
n = int(input()) xs = list(map(int, input().split())) max_x = max(xs) bad = sum(xs) good = n * max_x - bad print(max_x + max(0, 1 + (bad - good) // n))
Python
zaydzuhri_stack_edu_python
function countdown n begin while n > 0 begin yield n set n = n - 1 end end function set c = call countdown 3
def countdown(n): while n > 0: yield n n -= 1 c = countdown(3)
Python
zaydzuhri_stack_edu_python
function __init__ self normal_vector=none constant_term=none begin set dimension = 2 if not normal_vector begin set all_zeros = list string 0 * dimension set normal_vector = call Vector all_zeros end set normal_vector = normal_vector if not constant_term begin set constant_term = call Decimal string 0 end set constant_...
def __init__(self, normal_vector=None, constant_term=None): self.dimension = 2 if not normal_vector: all_zeros = ['0']*self.dimension normal_vector = Vector(all_zeros) self.normal_vector = normal_vector if not constant_term: constant_term = Decimal('...
Python
nomic_cornstack_python_v1
function preserve_patron_loan self data **kwargs begin set record = get context string record return call preserve_patron_loan data record end function
def preserve_patron_loan(self, data, **kwargs): record = self.context.get("record") return preserve_patron_loan(data, record)
Python
nomic_cornstack_python_v1
function get_iterator x n forced=false begin if forced begin return list x * n end if not is instance x Iterable or is instance x str begin set x = list x * n end comment Note: np.array, list are always iterable if length x != n begin set x = list x * n end return x end function
def get_iterator(x, n, forced=False): if forced: return [x] * n if not isinstance(x, collections.Iterable) or isinstance(x, str): x = [x] * n # Note: np.array, list are always iterable if len(x) != n: x = [x] * n return x
Python
nomic_cornstack_python_v1
function name self begin warn string attribute 'name' has been deprecated from provider version 1.129.0 and it will be remove in the future version. Please use the new attribute 'certificate_name' instead. DeprecationWarning warn string name is deprecated: attribute 'name' has been deprecated from provider version 1.12...
def name(self) -> Optional[pulumi.Input[str]]: warnings.warn("""attribute 'name' has been deprecated from provider version 1.129.0 and it will be remove in the future version. Please use the new attribute 'certificate_name' instead.""", DeprecationWarning) pulumi.log.warn("""name is deprecated: attribut...
Python
nomic_cornstack_python_v1
from functools import wraps function hello_decorator function begin decorator wraps function function decorator begin set result = call function return string this is + result + string decorated end function return decorator end function decorator hello_decorator function hello_world begin return string Hello World end...
from functools import wraps def hello_decorator(function): @wraps(function) def decorator(): result = function() return 'this is ' + result + ' decorated' return decorator @hello_decorator def hello_world(): return 'Hello World' print(hello_world())
Python
zaydzuhri_stack_edu_python
comment package to solve gyrokinetic equations when Apar = 0 import numpy as np from scipy.special import i0e , i1e import scipy.optimize from gk_solver.util import real_imag , list2complex , zp comment ------------------------------------- comment Terms ABCDE in the dispersion tensor comment --------------------------...
# package to solve gyrokinetic equations when Apar = 0 import numpy as np from scipy.special import i0e, i1e import scipy.optimize from gk_solver.util import real_imag, list2complex, zp #------------------------------------- # Terms ABCDE in the dispersion tensor #------------------------------------- def A(ti_te, mi...
Python
zaydzuhri_stack_edu_python
function _get_triggers settings begin try begin set triggers_list = settings at string triggers end except KeyError as e begin raise call SettingNotFound string %s setting not found % e end set triggers = list for trigger_el in triggers_list begin if is instance trigger_el dict begin for trigger_name in trigger_el begi...
def _get_triggers(settings): try: triggers_list = settings["triggers"] except KeyError as e: raise SettingNotFound("%s setting not found" % e) triggers = list() for trigger_el in triggers_list: if isinstance(trigger_el, dict): for tri...
Python
nomic_cornstack_python_v1
import tabula import camelot from pdfrw import PdfReader import pandas as pd import xlsxwriter import re comment Importing PDF set file = string Data\DBS_P3Q42020.pdf comment Get number of pages set num_pages = length pages comment Function to clean camelot table_c function split_newline df_c begin for k in range lengt...
import tabula import camelot from pdfrw import PdfReader import pandas as pd import xlsxwriter import re ## Importing PDF file = "Data\DBS_P3Q42020.pdf" ## Get number of pages num_pages = len(PdfReader(file).pages) ## Function to clean camelot table_c def split_newline(df_c): for k in range(len(df...
Python
zaydzuhri_stack_edu_python
import divination import gallows print string *********************************************************** print string *********************************************************** print string *********************************************************** print string Choose your game print string (1) Gallows (2) Divinatio...
import divination import gallows print("***********************************************************") print("***********************************************************") print("***********************************************************") print ("Choose your game") print("(1) Gallows (2) Divination") print("***...
Python
zaydzuhri_stack_edu_python
comment !/usr/bin/python3 string This is the "text_indentation" module. The "text-indentation" module provides a simple function text_indentation() that prints a text with 2 new lines after each characters: ., ? and :. function text_indentation text begin string Print a text with 2 new lines after each characters: ., ?...
#!/usr/bin/python3 """ This is the "text_indentation" module. The "text-indentation" module provides a simple function text_indentation() that prints a text with 2 new lines after each characters: ., ? and :. """ def text_indentation(text): """Print a text with 2 new lines after each characters: ., ? and :. ...
Python
zaydzuhri_stack_edu_python
import asyncio import websockets import pygame import time import json comment Starts the game, finds the joysticks on the system. Automatically includes pygame.joystick.init() call init comment print(pygame.joystick.Joystick(0).get_axis(0)) if call get_init begin print string Joystick object initialized end comment py...
import asyncio import websockets import pygame import time import json pygame.init() #Starts the game, finds the joysticks on the system. Automatically includes pygame.joystick.init() #print(pygame.joystick.Joystick(0).get_axis(0)) if pygame.joystick.get_init(): print("Joystick object initialized") #pygame.joys...
Python
zaydzuhri_stack_edu_python
function rescale_features feature variable begin set SCALER = call read_pickle parent / string data/SCALER.p if variable == string inputs begin set feature = feature * SCALER at string input_stds + SCALER at string input_means end else if variable == string output begin set feature = feature * SCALER at string output_s...
def rescale_features(feature: np.ndarray, variable: str) -> np.ndarray: SCALER = pd.read_pickle(Path(__file__).absolute().parent.parent / ("data/SCALER.p")) if variable == 'inputs': feature = feature * SCALER["input_stds"] + SCALER["input_means"] elif variable == 'output': feature ...
Python
nomic_cornstack_python_v1
from scipy.stats import rv_continuous import numpy as np class marchenko_pastur extends rv_continuous begin function _pdf self x Q var begin set lambda_min = var * 1 + 1 / Q - 2 * square root 1 / Q set lambda_max = var * 1 + 1 / Q + 2 * square root 1 / Q return where x > lambda_max ? x < lambda_min 0 Q / 2 * pi * var *...
from scipy.stats import rv_continuous import numpy as np class marchenko_pastur(rv_continuous): def _pdf(self, x, Q, var): lambda_min = var * (1 + 1/Q - 2 * np.sqrt(1/Q)) lambda_max = var * (1 + 1/Q + 2 * np.sqrt(1/Q)) return np.where((x > lambda_max) | (x < lambda_min), 0, Q/(2*np.pi*...
Python
zaydzuhri_stack_edu_python
import cv2 , os , sys import numpy as np import matplotlib.pyplot as plt from fractions import Fraction from decimal import Decimal from PIL import Image comment from untitled8 import calc function calc x begin set y = x ^ 2 comment y = 9.1*x-1 comment y = 9.1*x**4 + 2.15*x**3 + 7.1*x**2 + 7*x - 4 # 2542.png return y e...
import cv2, os, sys import numpy as np import matplotlib.pyplot as plt from fractions import Fraction from decimal import Decimal from PIL import Image # from untitled8 import calc def calc(x): y = x**2 # y = 9.1*x-1 # y = 9.1*x**4 + 2.15*x**3 + 7.1*x**2 + 7*x - 4 # 2542.png return y def process_coord...
Python
zaydzuhri_stack_edu_python
function avgsize_c self begin return _avgsize_c end function
def avgsize_c(self): return self._avgsize_c
Python
nomic_cornstack_python_v1
function evalExpressionStr expression_str context begin return flatten context call ExprTree expression_str end function
def evalExpressionStr(expression_str, context): return context.flatten(classad.ExprTree(expression_str))
Python
nomic_cornstack_python_v1
async function on_message self message begin if not bot begin set guild_info = call get_guild_info guild set warned_users = guild_info at string warnedUsers if call contains_profanity content begin await delete await call send string { mention } that is not allowed! try begin set found_user = false for user in warned_u...
async def on_message(self, message: discord.Message): if not message.author.bot: guild_info = server_setup.get_guild_info(message.guild) warned_users = guild_info["warnedUsers"] if profanity.contains_profanity(message.content): await message.delete() ...
Python
nomic_cornstack_python_v1
function compress self data_list begin set files_to_upload = list set files_to_delete = list if data_list begin set files_to_upload = data_list at 0 set files_to_delete = data_list at 1 end set data = tuple files_to_upload files_to_delete call validate data return data end function
def compress(self, data_list): files_to_upload = [] files_to_delete = [] if data_list: files_to_upload = data_list[0] files_to_delete = data_list[1] data = (files_to_upload, files_to_delete) self.validate(data) return data
Python
nomic_cornstack_python_v1
function check h w begin set count = 0 for tuple dy dx in dydx begin if 0 <= h + dy < H and 0 <= w + dx < W and S at h + dy at w + dx == string # begin set count = count + 1 end end return count end function for h in range H begin for w in range W begin if S at h at w == string . begin set S at h at w = string call che...
def check(h, w): count = 0 for dy, dx in dydx: if 0 <= h + dy < H and 0 <= w + dx < W and S[h+dy][w+dx] == '#': count += 1 return count for h in range(H): for w in range(W): if S[h][w] == '.': S[h][w] = str(check(h, w)) res = "".join(S[h]) print(res)
Python
zaydzuhri_stack_edu_python
comment just a parser demo for demostrating templite class. import re set e1 = string abc.edf.ghi print split e1 string . set buffered = list string haha string hehe if length buffered == 1 begin print string append_result(%s) % buffered at 0 end else if length buffered > 1 begin print string extend_result([%s]) % join...
# just a parser demo for demostrating templite class. import re e1 = "abc.edf.ghi" print(e1.split(".")) buffered = ["haha", "hehe"] if len(buffered) == 1: print("append_result(%s)" % buffered[0]) elif len(buffered) > 1: print("extend_result([%s])" % ", ".join(buffered)) # re对templite的解析 text = ''' <h...
Python
zaydzuhri_stack_edu_python
function get_from_snap_id self begin return from_snapshot_id end function
def get_from_snap_id(self): return self.from_snapshot_id
Python
nomic_cornstack_python_v1
function check_cached self file_name n begin try begin with open string files/ + file_name + string .txt string r as f begin set f_ = read lines f comment no data in the file if length f_ == 0 begin return false end return decimal f_ at 0 + n * 60 < time end end except FileNotFoundError begin with open string files/ + ...
def check_cached(self, file_name, n): try: with open('files/' + file_name + '.txt', 'r') as f: f_ = f.readlines() if len(f_) == 0: # no data in the file return False return float(f_[0]) + (n * 60) < time.time() except FileN...
Python
nomic_cornstack_python_v1
function velocity_embedding adata basis=none vkey=string velocity density=1 scale=1 X=none V=none color=none use_raw=none layer=none color_map=none colorbar=false palette=none size=none alpha=0.2 perc=none sort_order=true groups=none components=none projection=string 2d legend_loc=string none legend_fontsize=none legen...
def velocity_embedding(adata, basis=None, vkey='velocity', density=1, scale=1, X=None, V=None, color=None, use_raw=None, layer=None, color_map=None, colorbar=False, palette=None, size=None, alpha=.2, perc=None, sort_order=True, groups=None, components=None, projection='2d',...
Python
nomic_cornstack_python_v1
from collections import deque , defaultdict , Counter class Solution begin function countSubTrees self n edges labels begin set tree = default dictionary list for tuple u v in edges begin append tree at u v append tree at v u end set output = list comprehension 0 for _ in range n function dfs i parent begin set counter...
from collections import deque, defaultdict, Counter class Solution: def countSubTrees(self, n, edges, labels): tree = defaultdict(list) for u, v in edges: tree[u].append(v) tree[v].append(u) output = [0 for _ in range(n)] def dfs(i, parent): counte...
Python
zaydzuhri_stack_edu_python
comment WAP read the data from the file and display all the words which are starts witj comment i or I set f = open string input.txt string r set data = read f close f set words = split data comment print(words) for word in words begin comment print(word, type(word)) if word at 0 == string i or word at 0 == string I be...
# WAP read the data from the file and display all the words which are starts witj # i or I f = open('input.txt', 'r') data = f.read() f.close() words = data.split() #print(words) for word in words: #print(word, type(word)) if word[0] == 'i' or word[0] == 'I': print(word)
Python
zaydzuhri_stack_edu_python
comment encoding:utf-8 string Created on 2017年8月10日 题目:输出指定格式的日期。 知识链接: 1、re.finditer-正则取字符串中的数字(正则切片): a = re.finditer(r'\d+', str) print a.group() 2、time.localtime()、time.strftime('格式', time.localtime()) @author: wangtaoyuan import datetime import time import re set time = string format time time string %Y, %m, %d, %...
# encoding:utf-8 ''' Created on 2017年8月10日 题目:输出指定格式的日期。 知识链接: 1、re.finditer-正则取字符串中的数字(正则切片): a = re.finditer(r'\d+', str) print a.group() 2、time.localtime()、time.strftime('格式', time.localtime()) @author: wangtaoyuan ''' import datetime import time import re time = time.strftime('%Y, %m, %d, %H...
Python
zaydzuhri_stack_edu_python
function name self begin return get pulumi self string name end function
def name(self) -> str: return pulumi.get(self, "name")
Python
nomic_cornstack_python_v1
comment import youtube_dl for download the vedio comment import tkinter for GUI from __future__ import unicode_literals import youtube_dl from tkinter import * from tkinter import ttk from tkinter import filedialog comment fun for download function DownloadVideo begin comment get the type of vedio(mp4/mp3) set choice =...
#import youtube_dl for download the vedio # import tkinter for GUI from __future__ import unicode_literals import youtube_dl from tkinter import * from tkinter import ttk from tkinter import filedialog #fun for download def DownloadVideo(): #get the type of vedio(mp4/mp3) choice = ytdchoices.get() #...
Python
zaydzuhri_stack_edu_python
function _hash blob begin if blob is not none begin set m = md5 update m blob return hex digest m end end function
def _hash(blob): if blob is not None: m = hashlib.md5() m.update(blob) return m.hexdigest()
Python
nomic_cornstack_python_v1
function number_of_strongly_connected_components adj begin set result = 0 comment write your code here comment Find the reverse graph set trans_graph = call transpose_graph adj comment Find the topological order of the reverse graph, comment To find the sink vertex of the original graph. set trans_order = call toposort...
def number_of_strongly_connected_components(adj): result = 0 # write your code here # Find the reverse graph trans_graph = transpose_graph(adj) # Find the topological order of the reverse graph, # To find the sink vertex of the original graph. trans_order = toposort(trans_graph) # Creat...
Python
nomic_cornstack_python_v1
if film == string Пятница begin set date = input string ВВедите дату(сегодня или завтра) if date == string сегодня begin set time = integer input string ВВедите время сеанса(12, 16, 20) set score = integer input string ВВедите к-во билетов if time == 12 begin if score < 20 begin print 250 * score end else begin print 2...
if film=="Пятница": date=input("ВВедите дату(сегодня или завтра) ") if date=="сегодня": time=int(input("ВВедите время сеанса(12, 16, 20) ")) score=int(input("ВВедите к-во билетов ")) if time==12: if score<20: print(250*score) else: ...
Python
zaydzuhri_stack_edu_python
function test_make_qual self begin set qual_fp = join path sff_dir string test.qual set qual_gz_fp = join path gz_sff_dir string test_gz.qual call make_qual sff_fp qual_fp call make_qual sff_gz_fp qual_gz_fp assert equal read open qual_fp qual_txt assert equal read open qual_gz_fp qual_txt end function
def test_make_qual(self): qual_fp = os.path.join(self.sff_dir, 'test.qual') qual_gz_fp = os.path.join(self.gz_sff_dir, 'test_gz.qual') make_qual(self.sff_fp, qual_fp) make_qual(self.sff_gz_fp, qual_gz_fp) self.assertEqual(open(qual_fp).read(), qual_txt) self.assertE...
Python
nomic_cornstack_python_v1
set x = string 7 print x print call zfill 6
x = "7" print(x) print(x.zfill(6))
Python
zaydzuhri_stack_edu_python
comment Returns a tuple where the string is parted into three parts set x = call partition string bananas print x
# Returns a tuple where the string is parted into three parts x = txt.partition("bananas") print(x)
Python
zaydzuhri_stack_edu_python
function is_correct self question answer begin return correct_answer == call strtobool lower answer end function
def is_correct(self, question, answer): return self.get(question=question).correct_answer == strtobool(answer.lower())
Python
nomic_cornstack_python_v1
function handle_jump data begin set jumping = call unpack string ? data at slice : 1 : at 0 return tuple data at slice 1 : : if expression jumping then string Jumping else string Falling end function
def handle_jump(data: bytes) -> Tuple[bytes, str]: jumping = struct.unpack('?', data[:1])[0] return data[1:], 'Jumping' if jumping else 'Falling'
Python
nomic_cornstack_python_v1
function get_top_words file_list begin set word_dict = dict print string Getting top words... for doc in file_list begin for word in doc at string diff_text begin if word not in word_dict begin set word_dict at word = 1 end else begin set word_dict at word = word_dict at word + 1 end end end set top_200 = dictionary s...
def get_top_words(file_list): word_dict = {} print("Getting top words...") for doc in file_list: for word in doc['diff_text']: if word not in word_dict: word_dict[word] = 1 else: word_dict[word] = word_dict[word] + 1 top_200 = dict(sorted(w...
Python
nomic_cornstack_python_v1
function plot_confusion_matrix cm classes normalize=false title=string Confusion matrix cmap=Greys begin if normalize begin set cm = as type cm string float / sum axis=1 at tuple slice : : newaxis print string Normalized confusion matrix end else begin print string Confusion matrix, without normalization end comment...
def plot_confusion_matrix(cm, classes, normalize=False, title='Confusion matrix', cmap=plt.cm.Greys): if normalize: cm = cm.astype('float') / cm.sum(axis=1)[:, np.newaxis] print("Normalized confusion matrix") else: ...
Python
nomic_cornstack_python_v1
function crawl_course metadata begin comment Need to re-decode with utf-8, original is encoded with ISO-8859-1 set text : str = decode encode text string ISO-8859-1 string utf-8 set html : _Element = call HTML text set title : _Element = call xpath string //*[@id="header"]/h1/div/span at 1 set filtered = list filter la...
def crawl_course(metadata: CourseInfo) -> CourseInfo: # Need to re-decode with utf-8, original is encoded with ISO-8859-1 text: str = requests.get( "http://class-qry.acad.ncku.edu.tw/syllabus/online_display.php", params={ "syear": metadata.year.zfill(4), "sem": metadata.s...
Python
nomic_cornstack_python_v1
import json from get_data_from_csv_xls import Item from send_requests import StorageApi from PIL import Image , ImageDraw , ImageColor , ImageFont class Cell begin function __init__ self name lvl merged group_of_merge=0 merged_with=list size_width=none size_height=none size_depth=1 busy=false begin set name = name set...
import json from get_data_from_csv_xls import Item from send_requests import StorageApi from PIL import Image, ImageDraw, ImageColor, ImageFont class Cell: def __init__(self, name, lvl, merged, group_of_merge=0, merged_with=[], size_width=None, size_height=None, size_depth=1, busy=False): ...
Python
zaydzuhri_stack_edu_python
comment # comment Todo esse código será feito na extensão .py para que seja possível usá-lo nos projetos. # comment # comment Todas as anotações e explicações sobre o que está sendo usado nesse documento podem ser # comment encontradas no documento "Aula 5 - Detecção da face (Introdução).ipynb". # comment # comment Git...
################################################################################################ # # # Todo esse código será feito na extensão .py para que seja possível usá-lo nos projetos. # # ...
Python
zaydzuhri_stack_edu_python
function save_to_file data filename dir=none begin if is instance data ByteArray begin set data = data end if dir begin set filename = join path dir filename end set path = join path MEDIA_ROOT filename set file = open path string wb try begin write file data end except any begin raise end try else begin close file end...
def save_to_file(data, filename, dir=None): if isinstance(data, amf.ByteArray): data = data.data if dir: filename = os.path.join(dir, filename) path = os.path.join(settings.MEDIA_ROOT, filename) file = open(path, 'wb') try: file.write(data) except: raise...
Python
nomic_cornstack_python_v1
import timeit set sumwords = 4 set listWords = list string champions string we string are string Stepik set listErrors = list set numlines = 3 set line = list string We are the champignons string We Are The Champions string Stepic comment listWords = [input().lower() for i in range(int(input()))] comment print(*listWo...
import timeit sumwords = 4 listWords = ['champions', 'we', 'are', 'Stepik'] listErrors = [] numlines = 3 line = ['We are the champignons', 'We Are The Champions', 'Stepic'] #listWords = [input().lower() for i in range(int(input()))] #print(*listWords) #for i in line: #for i in range(int(input())): for i in line: f...
Python
zaydzuhri_stack_edu_python
function reverse_words string begin set reversed_string = string set start = 0 set end = 0 set length = length string while end < length begin comment Find the start and end of each word while start < length and not is alpha string at start begin set start = start + 1 end set end = start while end < length and is alph...
def reverse_words(string): reversed_string = "" start = 0 end = 0 length = len(string) while end < length: # Find the start and end of each word while start < length and not string[start].isalpha(): start += 1 end = start while end < length and string...
Python
jtatman_500k
import urllib.request function GetTypesOfCancer begin string Retrieves a list of all the clinical types of cancer stored on the server OUTPUT: A tab-delimited file with two columns: type_of_cancer_id: a unique text identifier used to identify the type of cancer. For example, "gbm" identifies Glioblastoma multiforme. na...
import urllib.request def GetTypesOfCancer(): """Retrieves a list of all the clinical types of cancer stored on the server OUTPUT: A tab-delimited file with two columns: type_of_cancer_id: a unique text identifier used to identify the type of cancer. For example, "gbm" identifies Glioblastom...
Python
zaydzuhri_stack_edu_python
function _DrawTextList *args **kwargs begin return call DC__DrawTextList *args keyword kwargs end function
def _DrawTextList(*args, **kwargs): return _gdi_.DC__DrawTextList(*args, **kwargs)
Python
nomic_cornstack_python_v1
comment !/usr/bin/python3 string This module contains a function called *lookup* that returns a list function lookup obj begin string Returns: The list of available attributes and methods of an object. return directory obj end function
#!/usr/bin/python3 """This module contains a function called *lookup* that returns a list""" def lookup(obj): """ Returns: The list of available attributes and methods of an object. """ return dir(obj)
Python
zaydzuhri_stack_edu_python
comment !/usr/bin/env python comment -*- coding:utf-8 -*- from repository import models from django.db.models import Count , Avg , Max , Min , Sum , Aggregate from utils.response import BaseResponse class Business extends object begin decorator staticmethod function chart begin set response = call BaseResponse try begi...
#!/usr/bin/env python # -*- coding:utf-8 -*- from repository import models from django.db.models import Count, Avg, Max, Min, Sum, Aggregate from utils.response import BaseResponse class Business(object): @staticmethod def chart(): response = BaseResponse() try: sql = """ ...
Python
zaydzuhri_stack_edu_python
from keras.utils import Sequence from skimage.io import imread from skimage.transform import resize from keras.preprocessing.image import img_to_array , load_img from keras.utils import to_categorical import numpy as np import pandas as pd class DataGenerator extends Sequence begin set __slots__ = tuple string data_dir...
from keras.utils import Sequence from skimage.io import imread from skimage.transform import resize from keras.preprocessing.image import img_to_array, load_img from keras.utils import to_categorical import numpy as np import pandas as pd class DataGenerator(Sequence): __slots__ = 'data_dir', 'seq_length', 'type', '...
Python
zaydzuhri_stack_edu_python
from turtle import * function shape k begin call pendown set l = list tuple 1 90 tuple 7 - 90 tuple 2 - 90 tuple 2 - 90 tuple 2 90 tuple 1 90 tuple 3 90 tuple 4 90 tuple 4 90 tuple 8 90 call begin_fill for tuple s a in l begin call fd s * k call rt a end call end_fill call penup end function function klucze begin call ...
from turtle import * def shape(k): pendown() l = [(1,90),(7,-90),(2,-90),(2,-90),(2,90),(1,90),(3,90),(4,90),(4,90),(8,90)] begin_fill() for s,a in l: fd(s*k) rt(a) end_fill() penup() def klucze(): pencolor("orange") fillcolor("green") k=420/(12*1.41) pensize(2)...
Python
zaydzuhri_stack_edu_python
function run self begin pass end function
def run(self): pass
Python
nomic_cornstack_python_v1
class Solution extends object begin function sumEvenGrandparent self root begin function DFS root father_even grandpa_even begin if root == none begin return 0 end set result = 0 if grandpa_even begin set result = result + val end set currrent_even = val % 2 == 0 set result = result + call DFS left currrent_even father...
class Solution(object): def sumEvenGrandparent(self, root): def DFS(root, father_even, grandpa_even): if root == None: return 0 result = 0 if grandpa_even: result += root.val currrent_even = root.val % 2 == 0 result ...
Python
zaydzuhri_stack_edu_python
function output2sphinx data mime_type metadata out_dir inline=false begin comment This only works lazily because the logger is inited by Sphinx from import logger comment If we're in `inline` mode, ensure that we don't add block-level nodes if inline begin set literal_node = literal set math_node = math end else begin...
def output2sphinx(data, mime_type, metadata, out_dir, inline=False): # This only works lazily because the logger is inited by Sphinx from . import logger # If we're in `inline` mode, ensure that we don't add block-level nodes if inline: literal_node = docutils.nodes.literal math_node = ...
Python
nomic_cornstack_python_v1
import json import sys class Coverage begin function __init__ self begin comment super().__init__() set kiap = load json open string /Users/arashsaidi/PycharmProjects/GardnerDavies2/coverage/kiap.txt set kiap_count = integer read line open string /Users/arashsaidi/PycharmProjects/GardnerDavies2/coverage/count_kiap.txt ...
import json import sys class Coverage: def __init__(self): # super().__init__() self.kiap = json.load(open('/Users/arashsaidi/PycharmProjects/GardnerDavies2/coverage/kiap.txt')) self.kiap_count = int(open('/Users/arashsaidi/PycharmProjects/GardnerDavies2/coverage/count_kiap.txt').readline(...
Python
zaydzuhri_stack_edu_python
function create_dataset file_pattern batch_size mode begin function _parse serialized_example begin string Parse serialized example and return feature_dict and label. Args: serialized_example: tf.example to parse. Returns: Parsed features dictionary and label. set feature_map = dict string dayofweek call FixedLenFeatur...
def create_dataset(file_pattern, batch_size, mode): def _parse(serialized_example): """Parse serialized example and return feature_dict and label. Args: serialized_example: tf.example to parse. Returns: Parsed features dictionary and label. """ fea...
Python
nomic_cornstack_python_v1
function _define self begin string Calculate a subcircuit that implements this unitary. if num_qubits == 1 begin set q = call QuantumRegister 1 string q set angles = call euler_angles_1q call to_matrix set definition = list tuple call U3Gate *angles list q at 0 list end if num_qubits == 2 begin set definition = call t...
def _define(self): """Calculate a subcircuit that implements this unitary.""" if self.num_qubits == 1: q = QuantumRegister(1, "q") angles = euler_angles_1q(self.to_matrix()) self.definition = [(U3Gate(*angles), [q[0]], [])] if self.num_qubits == 2: ...
Python
jtatman_500k
function render self begin pass end function
def render(self): pass
Python
nomic_cornstack_python_v1
function go_right self begin set change_x = 6 set direction = string R end function
def go_right(self): self.change_x = 6 self.direction = "R"
Python
nomic_cornstack_python_v1
import re import nltk import requests from flask import Flask , render_template , request from nltk.stem.snowball import EnglishStemmer set app = call Flask __name__ decorator call route string / function index begin return call render_template string index.html end function decorator call route string /api/ function t...
import re import nltk import requests from flask import Flask, render_template, request from nltk.stem.snowball import EnglishStemmer app = Flask(__name__) @app.route("/") def index(): return render_template('index.html') @app.route("/api/") def text_to_sign(): words = [request.args.get("word").lower(), E...
Python
zaydzuhri_stack_edu_python
from nltk.tag import UnigramTagger , BigramTagger , TrigramTagger , DefaultTagger from nltk.tokenize import sent_tokenize from nltk import StanfordNERTagger , word_tokenize from os import getcwd import re from taggers.paragraphs import tag_paragraphs from taggers.sentences import tag_sentences from taggers.time import ...
from nltk.tag import UnigramTagger, BigramTagger, TrigramTagger, DefaultTagger from nltk.tokenize import sent_tokenize from nltk import StanfordNERTagger, word_tokenize from os import getcwd import re from taggers.paragraphs import tag_paragraphs from taggers.sentences import tag_sentences from taggers.time import tag...
Python
zaydzuhri_stack_edu_python
comment Importing essential libraries from tkinter import * comment Create the root window set root = call Tk comment Defining the title of the window title root string GUI created using Tkinter comment Defining the size of the window call geometry string 500x500 comment Create the widgets set label_1 = call Label root...
# Importing essential libraries from tkinter import * # Create the root window root = Tk() # Defining the title of the window root.title("GUI created using Tkinter") # Defining the size of the window root.geometry("500x500") # Create the widgets label_1 = Label(root, text = "My First Program needs GUI") #...
Python
jtatman_500k
function indiv_email_new lab_dict sub_dict new_sub begin comment # Check if the subscription is cancelled comment if new_sub.subscription_status.lower() == CONST_SUB_CANCELLED.lower(): comment html_content = email_top(CONST_EMAIL_SUBJECT_CANCELLED) comment else: set html_content = call email_top CONST_EMAIL_SUBJECT_NEW...
def indiv_email_new(lab_dict, sub_dict, new_sub): # # Check if the subscription is cancelled # if new_sub.subscription_status.lower() == CONST_SUB_CANCELLED.lower(): # html_content = email_top(CONST_EMAIL_SUBJECT_CANCELLED) # else: html_content = email_top(CONST_EMAIL_SUBJECT_NEW) html_mid...
Python
nomic_cornstack_python_v1
function Binary arr begin for i in range length begin for j in range length begin set arr at i at j = if expression arr at i at j < 128 then 0 else 255 end end return arr end function
def Binary(arr): for i in range(length): for j in range(length): arr[i][j] = 0 if arr[i][j] < 128 else 255 return arr
Python
nomic_cornstack_python_v1
function adopt_instances self begin return call succeed 0 set instance_names = list comprehension call name for x in call listDomainsID for name in instance_names begin try begin set new_inst = call fromName _conn _pool name call update_state end except any begin pass end end return call succeed length _instances end f...
def adopt_instances(self): return defer.succeed(0) instance_names = [self._conn.lookupByID(x).name() for x in self._conn.listDomainsID()] for name in instance_names: try: new_inst = Instance.fromName(self._conn, self._pool, name) ...
Python
nomic_cornstack_python_v1
function near_max_spectra_matrix SN_df SN_spec_df begin set tuple spec_idx_list_use sn_name sn_spec_idx sn_spec_time = call near_max_spectra_idxs SN_df SN_spec_df comment nof_objects = spec_idx_list_use[spec_idx_list_use > 0].shape[0] set file_name_list = values set tuple W X dX spec_len = call get_vanilla_spectra_matr...
def near_max_spectra_matrix(SN_df, SN_spec_df): spec_idx_list_use, sn_name, sn_spec_idx, sn_spec_time = near_max_spectra_idxs(SN_df, SN_spec_df) #nof_objects = spec_idx_list_use[spec_idx_list_use > 0].shape[0] file_name_list = SN_spec_df['#Filename'].values W, X, dX, spec_len = get_vanilla_spectra_matr...
Python
nomic_cornstack_python_v1
comment real signature unknown function __setattr__ self *args **kwargs begin pass end function
def __setattr__(self, *args, **kwargs): # real signature unknown pass
Python
nomic_cornstack_python_v1
function threecycle_stimulus tau begin comment pre-pulse set y0 = list 0.99996874 0.10023398 0 set param at 3 = tau set kron = call Oscillator model null_I param y0 set intoptions at string constraints = none set dsol_pre = call int_odes 10.4 set dts_pre = ts set y0_pulse = dsol_pre at - 1 set dsol_pulses = list dsol_p...
def threecycle_stimulus(tau): # pre-pulse y0 = [ 0.99996874, 0.10023398, 0] param[3]=tau kron = lc.Oscillator(model(null_I), param, y0) kron.intoptions['constraints']=None dsol_pre = kron.int_odes(10.4) dts_pre = kron.ts y0_pulse = dsol_pre[-1] dsol_pulses = [dsol_pre] dts_pul...
Python
nomic_cornstack_python_v1
comment dit wordt hoogstwaarschijnlijk afzien comment print( voornaam, "is nogal trash,\n de", voornaam, "is vrij tot uitzonderlijk zielig") set voornaam = input string Wat is jouw voornaam? set naam = input string Wat is jouw naam? set leeftijd = integer input string Wat is jouw leeftijd? set leeftijd = leeftijd + 100...
#dit wordt hoogstwaarschijnlijk afzien #print( voornaam, "is nogal trash,\n de", voornaam, "is vrij tot uitzonderlijk zielig") voornaam = input("Wat is jouw voornaam? ") naam = input("Wat is jouw naam? ") leeftijd = int(input("Wat is jouw leeftijd? ")) leeftijd = leeftijd + 100 print( "Welkom {0}. Jouw naam is {1} e...
Python
zaydzuhri_stack_edu_python
comment type: () -> ControllerHostConfig function controller self begin return controller end function
def controller(self): # type: () -> ControllerHostConfig return self.host_settings.controller
Python
nomic_cornstack_python_v1