code
stringlengths
10
2.58M
original_code
stringlengths
3
3.18M
original_language
stringclasses
1 value
source
stringclasses
7 values
function idcs_grid_to_idcs_flatten idcs grid_shape begin for tuple i size in enumerate grid_shape begin set idcs at tuple slice : : slice : : i = idcs at tuple slice : : slice : : i * call prod grid_shape at slice i + 1 : : end return sum - 1 end function
def idcs_grid_to_idcs_flatten(idcs, grid_shape): for i, size in enumerate(grid_shape): idcs[:, :, i] *= prod(grid_shape[i + 1 :]) return idcs.sum(-1)
Python
nomic_cornstack_python_v1
function rate_match_conv_make *args **kwargs begin return call rate_match_conv_make *args keyword kwargs end function
def rate_match_conv_make(*args, **kwargs): return _my_lte_swig.rate_match_conv_make(*args, **kwargs)
Python
nomic_cornstack_python_v1
function credentials self begin return _credentials end function
def credentials(self) -> WorkspaceConnectionCredentials: return self._credentials
Python
nomic_cornstack_python_v1
function apply_cm over_im cm begin comment Check input colormap - if it is a list create a custom map if type cm == list begin from matplotlib.colors import LinearSegmentedColormap set cm = call from_list string mycmap cm end else if type cm == str begin set cm = call get_cmap cm end comment Normalize comment if not (o...
def apply_cm(over_im, cm): # Check input colormap - if it is a list create a custom map if type(cm) == list: from matplotlib.colors import LinearSegmentedColormap cm = LinearSegmentedColormap.from_list('mycmap', cm) elif type(cm) == str: cm = get_cmap(cm) # Normalize # if n...
Python
nomic_cornstack_python_v1
from component import COMPONENT_LIST class ComponentMaster begin function __init__ self begin set __components = list comprehension c for c in COMPONENT_LIST end function function getid self component_type begin return index __components component_type end function function get_component self uid begin return __compone...
from component import COMPONENT_LIST class ComponentMaster: def __init__(self): self.__components = [c for c in COMPONENT_LIST] def getid (self, component_type): return self.__components.index (component_type) def get_component (self, uid): return self.__components[uid] def components (self): ...
Python
zaydzuhri_stack_edu_python
function predict_dist self booster start_values data pred_type=string parameters n_samples=1000 quantiles=list 0.1 0.5 0.9 seed=123 begin comment Set base_margin as starting point for each distributional parameter. Requires base_score=0 in parameters. set base_margin_predt = ones shape=tuple call num_row 1 * start_valu...
def predict_dist(self, booster: xgb.Booster, start_values: np.ndarray, data: xgb.DMatrix, pred_type: str = "parameters", n_samples: int = 1000, quantiles: list = [0.1, 0.5, 0.9], ...
Python
nomic_cornstack_python_v1
function find_point_depth x y point_cloud begin if length point_cloud == 0 begin return none end comment Select only points that are in front. set point_cloud = point_cloud at where point_cloud at tuple slice : : 2 > 0.0 comment Select x and y. set pc_xy = point_cloud at tuple slice : : slice 0 : 2 : comment Sel...
def find_point_depth(x, y, point_cloud): if len(point_cloud) == 0: return None # Select only points that are in front. point_cloud = point_cloud[np.where(point_cloud[:, 2] > 0.0)] # Select x and y. pc_xy = point_cloud[:, 0:2] # Select z pc_z = point_cloud[:, 2] # Divize x, y by z...
Python
nomic_cornstack_python_v1
function set self id object begin set id = lower id set cache at id = object end function
def set(self, id, object): id = id.lower() self.cache[id] = object
Python
nomic_cornstack_python_v1
comment -*- coding:utf-8 -*- import pygame from pygame.locals import * import time function main begin comment 1.创建一个窗口,用来显示内容 set screen = call set_mode tuple 480 600 0 32 comment 2. 创建一个和窗口大小的图片,用来充当背景 set background = load image string ./feiji/background.png comment 创建一个飞机图片 set hero = load image string ./feiji/hero...
# -*- coding:utf-8 -*- import pygame from pygame.locals import * import time def main(): #1.创建一个窗口,用来显示内容 screen = pygame.display.set_mode((480,600),0,32) #2. 创建一个和窗口大小的图片,用来充当背景 background = pygame.image.load("./feiji/background.png") #创建一个飞机图片 hero = pygame.image.load("./feiji/hero1.png") ...
Python
zaydzuhri_stack_edu_python
function with_values self values begin raise call NotImplementedError self end function
def with_values(self, values): raise NotImplementedError(self)
Python
nomic_cornstack_python_v1
function proc self image begin comment Get the image dimensions set height = length image set width = length image at 0 comment Get the random zoom factor set zoom_factor = call random_sample 1 at 0 * max_zoom_factor - min_zoom_factor + min_zoom_factor comment Get the cropping size w.r.t. the image set crop_height = in...
def proc(self, image): # Get the image dimensions height = len(image) width = len(image[0]) # Get the random zoom factor zoom_factor = np.random.random_sample(1)[0]*(self.max_zoom_factor-self.min_zoom_factor)+self.min_zoom_factor # Get the cropping size w.r.t....
Python
nomic_cornstack_python_v1
function mat2vec M column=0 begin try begin M at 0 at column return list comprehension m at column for m in M end except any begin return M end end function
def mat2vec(M, column=0): try: M[0][column] return [m[column] for m in M] except: return M
Python
nomic_cornstack_python_v1
function getLast alist begin return alist at - 1 end function set my_list = list 1 3 7 14 print call getLast my_list
def getLast(alist): return alist[-1] my_list = [1, 3, 7, 14] print(getLast(my_list))
Python
zaydzuhri_stack_edu_python
comment import로 모듈 가져오기 import math comment static method pi comment math 모듈을 가져오면서 이름을 m으로 지정 import math as m square root 4.0 from math import pi pi comment math 모듈에서 sqrt 함수만 가져옴 from math import sqrt comment sqrt 함수를 바로 사용 square root 4.0 comment sqrt 함수를 바로 사용 square root 2.0 comment 다 가져오기 from math import * pi c...
# import로 모듈 가져오기 import math math.pi #static method import math as m # math 모듈을 가져오면서 이름을 m으로 지정 m.sqrt(4.0) from math import pi pi from math import sqrt # math 모듈에서 sqrt 함수만 가져옴 sqrt(4.0) # sqrt 함수를 바로 사용 sqrt(2.0) # sqrt 함수를 바로 사용 # 다 가져오기 from math import * pi # from import로 ...
Python
zaydzuhri_stack_edu_python
import sys set input = readline set N = integer input set P = list map int split input set Q = list map int split input comment Segment treeの台の要素数 set seg_el = 1 ? call bit_length comment 1-indexedなので、要素数2*seg_el.Segment treeの初期値で初期化 set SEG = list 0 * 2 * seg_el comment 1-indexedなので、要素数2*seg_el.Segment treeの初期値で初期化 se...
import sys input = sys.stdin.readline N=int(input()) P=list(map(int,input().split())) Q=list(map(int,input().split())) seg_el=1<<(N.bit_length()) # Segment treeの台の要素数 SEG=[0]*(2*seg_el) # 1-indexedなので、要素数2*seg_el.Segment treeの初期値で初期化 LAZY=[0]*(2*seg_el) # 1-indexedなので、要素数2*seg_el.Segment treeの初期値で初期化 def indexes(L,R...
Python
jtatman_500k
string approach: Bit Manipulation(left shift) Time: O(log(dividend / divisor)) Space: O(1) You are here! Your runtime beats 98.70 % of python submissions. You are here! Your memory usage beats 69.11 % of python submissions. class Solution extends object begin function divide self dividend divisor begin string :type div...
''' approach: Bit Manipulation(left shift) Time: O(log(dividend / divisor)) Space: O(1) You are here! Your runtime beats 98.70 % of python submissions. You are here! Your memory usage beats 69.11 % of python submissions. ''' class Solution(object): def divide(self, dividend, divisor): """ :type d...
Python
zaydzuhri_stack_edu_python
comment Homework 18 comment Programmer Lauren Cox comment Date of last revision 11-02-2016 set lower_dict = dict string a string * ; string b string * * ; string c string ** ; string d string ** * ; string e string * * ; string f string ** * ; string g string ** ** ; string h string * ** ; string i string * * ; string ...
# Homework 18 # Programmer Lauren Cox # Date of last revision 11-02-2016 lower_dict={'a':'*\n\n','b':'*\n*','c':'**\n' \ ,'d':'**\n *','e':'*\n *','f':'**\n*' \ ,'g':'**\n**','h':'*\n**','i':' *\n*' \ ,'j':' *\n**','k':'*\n*','l':'*\n*\n*' \ ,'m':'**\n*','n':'**\n *\n*',...
Python
zaydzuhri_stack_edu_python
function api_response_error_printer self begin set error_string = string for tuple key value in items errors begin set error_string = error_string + format string {} {} errors value key end print error_string end function
def api_response_error_printer(self): error_string = '' for key, value in self.errors.items(): error_string += '{} {} errors '.format(value, key) print(error_string)
Python
nomic_cornstack_python_v1
function read_json_url json_url begin comment get url data response set url_data = url open json_url comment return loaded json return loads read url_data end function
def read_json_url(json_url): #get url data response url_data = urlopen(json_url) #return loaded json return json.loads(url_data.read())
Python
nomic_cornstack_python_v1
function test_list_g_month_day_pattern_nistxml_sv_iv_list_g_month_day_pattern_1_1 mode save_output output_format begin call assert_bindings schema=string nistData/list/gMonthDay/Schema+Instance/NISTSchema-SV-IV-list-gMonthDay-pattern-1.xsd instance=string nistData/list/gMonthDay/Schema+Instance/NISTXML-SV-IV-list-gMont...
def test_list_g_month_day_pattern_nistxml_sv_iv_list_g_month_day_pattern_1_1(mode, save_output, output_format): assert_bindings( schema="nistData/list/gMonthDay/Schema+Instance/NISTSchema-SV-IV-list-gMonthDay-pattern-1.xsd", instance="nistData/list/gMonthDay/Schema+Instance/NISTXML-SV-IV-list-gMonth...
Python
nomic_cornstack_python_v1
comment !/usr/bin/env python comment -*- coding: utf-8 -*- string https://adventofcode.com/2019/day/1 This is the code for Advent day 1 puzzle. Basically it will take in a list of values, the mass, and calculates the fuel required for each one, then spits out the total compbined fuel requirement set module_list = list ...
#!/usr/bin/env python # -*- coding: utf-8 -*- """ https://adventofcode.com/2019/day/1 This is the code for Advent day 1 puzzle. Basically it will take in a list of values, the mass, and calculates the fuel required for each one, then spits out the total compbined fuel requirement """ module_list = [103450,107815,5377...
Python
zaydzuhri_stack_edu_python
from selenium import webdriver import time from bs4 import BeautifulSoup import multiprocessing comment 새로 refresh해서 얻어온 값과 전에 얻어온 값을 비교하기 위해 선언한 변수 set new_user = string set last_user = string function crawl hashtag option=false begin set count = 0 global new_user last_user comment 크롤링을 할 url 설정 set url = string htt...
from selenium import webdriver import time from bs4 import BeautifulSoup import multiprocessing # 새로 refresh해서 얻어온 값과 전에 얻어온 값을 비교하기 위해 선언한 변수 new_user = '' last_user = '' def crawl(hashtag, option = False): count = 0 global new_user, last_user # 크롤링을 할 url 설정 url = 'https://www.instagram.com/explor...
Python
zaydzuhri_stack_edu_python
function getControls self begin string Calculates consumption for the representative agent using the consumption functions. Takes the weighted average of cLvl across perceived Markov states. Parameters ---------- None Returns ------- None set StateCount = shape at 0 set t = t_cycle at 0 comment Array of chosen cNrm by ...
def getControls(self): ''' Calculates consumption for the representative agent using the consumption functions. Takes the weighted average of cLvl across perceived Markov states. Parameters ---------- None Returns ------- None ''' ...
Python
jtatman_500k
function help request begin call help request end function
def help (request): pydoc.help(request)
Python
nomic_cornstack_python_v1
from math import pow , sin , pi , fabs import numpy as np class MultiGridRelaxation begin function __init__ self begin set delta = 0.2 set nx = 128 set ny = 128 set xMax = delta * nx set yMax = delta * ny set TOL = power 10 - 8 comment self.V = np.zeros((self.nx + 1, self.ny + 1)) set k = list 16 8 4 2 1 end function f...
from math import pow,sin,pi,fabs import numpy as np class MultiGridRelaxation(): def __init__(self): self.delta = 0.2 self.nx = 128 self.ny = 128 self.xMax = self.delta * self.nx self.yMax = self.delta * self.ny self.TOL = pow(10, -8) #self.V = np.zeros((self...
Python
zaydzuhri_stack_edu_python
function Dict_with_default_values begin from collections import defaultdict set d = default dictionary int comment d['key'] == 1 set d at string key = d at string key + 1 set d = default dictionary list comment d['key'] == [1] append d at string key 1 end function function rewrite_file src dest begin with open src stri...
def Dict_with_default_values(): from collections import defaultdict d = defaultdict(int) d['key'] += 1 # d['key'] == 1 d = defaultdict(list) d['key'].append(1) # d['key'] == [1] def rewrite_file(src, dest): with open(src, 'r') as s, open(dest, 'w') as d: for line in s: d.wri...
Python
zaydzuhri_stack_edu_python
comment !/usr/bin/env python from __future__ import division function process line modules begin set module = split split line string : at 0 string ( at 0 set time = split split line string : at 2 at 2 comment print module set times = list append times time comment print times if call has_key module begin append modul...
#!/usr/bin/env python from __future__ import division def process(line,modules): module=line.split(":")[0].split("(")[0] time=line.split(":")[2].split()[2] #print module times=[] times.append(time) #print times if modules.has_key(module): modules[module].append(time) else: ...
Python
zaydzuhri_stack_edu_python
function test_festivals_urls_case_4 self begin set response = get client call get_absolute_url call assertTemplateUsed response name assert equal status_code 200 end function
def test_festivals_urls_case_4(self): response = self.client.get(self.festival_4.get_absolute_url()) self.assertTemplateUsed(response, self.festival_4.custom_html.name) self.assertEqual(response.status_code, 200)
Python
nomic_cornstack_python_v1
import pandas as pd import matplotlib.pyplot as plt from sklearn.cross_validation import train_test_split from sklearn.linear_model import LinearRegression import numpy as np from sklearn.metrics import mean_squared_error if __name__ == string __main__ begin set path = string E:\python program\ML code\linear regression...
import pandas as pd import matplotlib.pyplot as plt from sklearn.cross_validation import train_test_split from sklearn.linear_model import LinearRegression import numpy as np from sklearn.metrics import mean_squared_error if __name__ == '__main__': path = 'E:\\python program\\ML code\\linear regression\\Advertising...
Python
zaydzuhri_stack_edu_python
function write self path data offset fh=none begin comment Update the database metadata if debug == true begin debug string In the write call end return 0 end function
def write(self, path, data, offset, fh=None): #Update the database metadata if self.debug == True: logging.debug("In the write call") return 0
Python
nomic_cornstack_python_v1
function get_option_value_from_user self begin try begin set user_option = string call raw_input string Please enter an option: end except any begin set user_option = string m end end function
def get_option_value_from_user(self): try: self.menu.user_option = str(raw_input("Please enter an option:")) except: self.menu.user_option = "m"
Python
nomic_cornstack_python_v1
function get_file_versions self secure_data_path limit=none offset=none begin string Get versions of a particular file This is just a shim to get_secret_versions secure_data_path -- full path to the file in the safety deposit box limit -- Default(100), limits how many records to be returned from the api at once. offset...
def get_file_versions(self, secure_data_path, limit=None, offset=None): """ Get versions of a particular file This is just a shim to get_secret_versions secure_data_path -- full path to the file in the safety deposit box limit -- Default(100), limits how many records to be retur...
Python
jtatman_500k
comment -*- coding: utf-8 -*- string @author: Shipra set num1 = list 1 2 3 0 0 0 set num2 = list 2 5 6 set m = 3 set n = 3 class Solution begin function mergeArray self num1 num2 m n begin set tuple i j = tuple 0 0 set num3 = list while i < m and j < n begin if num1 at i < num2 at j begin append num3 num1 at i set i =...
# -*- coding: utf-8 -*- """ @author: Shipra """ num1 = [1, 2, 3, 0, 0, 0] num2 = [2, 5, 6] m = 3 n = 3 class Solution: def mergeArray(self, num1, num2, m, n): i, j = 0, 0 num3 = [] while i < m and j < n: if num1[i] < num2[j]: num3.append(num1[i])...
Python
zaydzuhri_stack_edu_python
function createWidgets self begin call createBannerFrame call createPaddingFrame call createContentFrame call createDirFrame call createOptFrame call createRunFrame call createFooterFrame end function
def createWidgets(self): self.createBannerFrame() self.createPaddingFrame() self.createContentFrame() self.createDirFrame() self.createOptFrame() self.createRunFrame() self.createFooterFrame()
Python
nomic_cornstack_python_v1
import numpy import random comment total number of bearings set N = 1500000 comment population mean set mu_x_gram = 55 comment population standard deviation set sig_x_gram = 5 function normaldistribution n begin comment Counters to determine number of times the mean falls into the confidence intervals set counter95 = 0...
import numpy import random N = 1500000 # total number of bearings mu_x_gram = 55 # population mean sig_x_gram = 5 # population standard deviation def normaldistribution(n): # Counters to determine number of times the mean falls into the confidence intervals counter95 = 0 counter99 = 0 rando = num...
Python
zaydzuhri_stack_edu_python
function _register_mecab_loc location begin string Set MeCab binary location global MECAB_LOC if not is file path location begin warning format string Provided mecab binary location does not exist {} location end info format string Mecab binary is switched to: {} location set MECAB_LOC = location end function
def _register_mecab_loc(location): ''' Set MeCab binary location ''' global MECAB_LOC if not os.path.isfile(location): logging.getLogger(__name__).warning("Provided mecab binary location does not exist {}".format(location)) logging.getLogger(__name__).info("Mecab binary is switched to: {}"....
Python
jtatman_500k
function do_count self line opts=none begin call call_attr line string count_ end function
def do_count(self, line, opts=None): self.call_attr(line, "count_")
Python
nomic_cornstack_python_v1
function test_poly_seq_scheme_handler_incon_off self begin set fh = call StringIO ASYM_ENTITY + string loop_ _pdbx_poly_seq_scheme.asym_id _pdbx_poly_seq_scheme.entity_id _pdbx_poly_seq_scheme.seq_id _pdbx_poly_seq_scheme.auth_seq_num _pdbx_poly_seq_scheme.pdb_strand_id A 1 1 6 X A 1 2 7 X A 1 3 8 X A 1 4 10 X set tupl...
def test_poly_seq_scheme_handler_incon_off(self): fh = StringIO(ASYM_ENTITY + """ loop_ _pdbx_poly_seq_scheme.asym_id _pdbx_poly_seq_scheme.entity_id _pdbx_poly_seq_scheme.seq_id _pdbx_poly_seq_scheme.auth_seq_num _pdbx_poly_seq_scheme.pdb_strand_id A 1 1 6 X A 1 2 7 X A 1 3 8 X A 1 4 10 X """) s, = ihm...
Python
nomic_cornstack_python_v1
function fetch self begin string Retrieves the remote design document content and populates the locally cached DesignDocument dictionary. View content is stored either as View or QueryIndexView objects which are extensions of the ``dict`` type. All other design document data are stored directly as ``dict`` types. call ...
def fetch(self): """ Retrieves the remote design document content and populates the locally cached DesignDocument dictionary. View content is stored either as View or QueryIndexView objects which are extensions of the ``dict`` type. All other design document data are stored dir...
Python
jtatman_500k
function copy_log_details_type self begin return get pulumi self string copy_log_details_type end function
def copy_log_details_type(self) -> str: return pulumi.get(self, "copy_log_details_type")
Python
nomic_cornstack_python_v1
import sys import pygame import random from time import sleep from bullet import Bullet from alien import Alien from button import Button from queenBee import QueenBee from queenBeeBullet import QueenBeeBullet comment sets direction of the bullet/determines movement set direction1 = string set direction2 = string com...
import sys import pygame import random from time import sleep from bullet import Bullet from alien import Alien from button import Button from queenBee import QueenBee from queenBeeBullet import QueenBeeBullet # sets direction of the bullet/determines movement direction1 = '' direction2 = '' # updates screen def upd...
Python
zaydzuhri_stack_edu_python
string Given an array of integers nums. A pair (i,j) is called good if nums[i] == nums[j] and i < j. Return the number of good pairs. set nums = list 1 2 3 1 1 3 function numIdenticalPairs nums begin set pairs = 0 for i in range length nums begin for j in range i + 1 length nums begin if nums at i == nums at j begin se...
''' Given an array of integers nums. A pair (i,j) is called good if nums[i] == nums[j] and i < j. Return the number of good pairs. ''' nums = [1,2,3,1,1,3] def numIdenticalPairs(nums): pairs = 0 for i in range(len(nums)): for j in range(i+1, len(nums)): if nums[i] == nums[j]: ...
Python
zaydzuhri_stack_edu_python
function iter_png_fp stream translate=true verify_crc=true begin set signature = call read_or_raise stream 8 if signature != png_sig begin raise call ParseError string Not a png file end if not translate begin yield tuple b'' b'' signature b'' end set iend = false while true begin set data = read stream 8 if not data b...
def iter_png_fp(stream: IO[bytes], translate: bool = True, verify_crc: bool = True) -> Iterator[tuple]: signature = read_or_raise(stream, 8) if signature != png_sig: raise ParseError("Not a png file") if not translate: yield (b"", b"", signature, b"") iend = False while True: ...
Python
nomic_cornstack_python_v1
function get_cut1_with_rejection self rejection=2.0 begin set tuple integrals ranges = call _get_integrals_and_ranges set sig = _signal set tuple flav_x flav_y = list comprehension t for t in _tags if t != sig set eff = integrals at sig at tuple slice : : 0 / max set bg_eff = integrals at flav_x at tuple slice : :...
def get_cut1_with_rejection(self, rejection=2.0): integrals, ranges = self._get_integrals_and_ranges() sig = self._signal flav_x, flav_y = [t for t in _tags if t != sig] eff = integrals[sig][:,0] / integrals[sig][:,0].max() bg_eff = integrals[flav_x][:,0] / integrals[flav_x][:...
Python
nomic_cornstack_python_v1
import make_chronological_sets from pprint import pprint from naiveBayesClassifier import tokenizer from naiveBayesClassifier.trainer import Trainer from naiveBayesClassifier.classifier import Classifier from tabulate import tabulate comment The size parameter defines how many samples will be in the training/testing se...
import make_chronological_sets from pprint import pprint from naiveBayesClassifier import tokenizer from naiveBayesClassifier.trainer import Trainer from naiveBayesClassifier.classifier import Classifier from tabulate import tabulate # The size parameter defines how many samples will be in the training/testing set ea...
Python
zaydzuhri_stack_edu_python
function get_model input_size struct_param settings is_uncertainty=false loss_core=string mse is_cuda=false begin if is_uncertainty begin set model_pred = call MLP_noise input_size=input_size struct_param=struct_param settings=settings is_cuda=is_cuda set model_logstd = call MLP_noise input_size=input_size struct_param...
def get_model(input_size, struct_param, settings, is_uncertainty = False, loss_core = "mse", is_cuda = False): if is_uncertainty: model_pred = MLP_noise(input_size = input_size, struct_param = struct_param, settings = settings, is_cu...
Python
nomic_cornstack_python_v1
comment Project: Master Thesis in Computational Statistics # comment Author: Lander Bodyn # comment Date: January 2017 # comment Email: bodyn.lander@gmail.com # import numpy as np import matplotlib.pyplot as plt import math from numpy import genfromtxt import matplotlib.patches as mpatches from collections import Count...
##################################################### #Project: Master Thesis in Computational Statistics # #Author: Lander Bodyn # #Date: January 2017 # #Email: bodyn.lander@gmail.com # ##################################################...
Python
zaydzuhri_stack_edu_python
comment Generates cost matrices based on given number of nodes and processors import os import networkx as nx import argparse from heft.heft import Task from graph import random_comp_matrix , random_comm_matrix comment nodes = 1000; comment processors = 16; comment generates comp matrices comment for x in range(0,nodes...
# Generates cost matrices based on given number of nodes and processors import os import networkx as nx import argparse from heft.heft import Task from graph import random_comp_matrix, random_comm_matrix # nodes = 1000; # processors = 16; # generates comp matrices # for x in range(0,nodes): # # for y in range(1,50...
Python
zaydzuhri_stack_edu_python
function magic_string string begin set k = length string // 2 set count_changes = 0 for tuple index char in enumerate string begin if index < k and char == string < begin set count_changes = count_changes + 1 end else if index >= k and char == string > begin set count_changes = count_changes + 1 end end return count_ch...
def magic_string(string): k = len(string) // 2 count_changes = 0 for index, char in enumerate(string): if index < k and char == "<": count_changes += 1 elif index >= k and char == ">": count_changes += 1 return count_changes def main(): print(magic_string(">...
Python
zaydzuhri_stack_edu_python
function get_temp_img_hashes soup delete_when_done=true begin set tempdir = join default_data_location string tempimgs if not exists path tempdir begin make directory os tempdir end call save_all_tableau_images soup tempdir set temp_hashes = set set onlypngs = list comprehension f for f in list directory tempdir if is ...
def get_temp_img_hashes(soup, delete_when_done = True): tempdir = join(default_data_location,"tempimgs") if not os.path.exists(tempdir): os.mkdir(tempdir) save_all_tableau_images(soup, tempdir) temp_hashes = set() onlypngs = [f for f in listdir(tempdir) if isfile(join(tempdir, f)) and f...
Python
nomic_cornstack_python_v1
from config.named_constants import Constants class MyConstants extends Constants begin set PI = 3.141592653589793 set E = 2.718281828459045 set AUTHOR = string 周小雪 end class class Colors extends Constants begin set tuple red yellow green blue white = range 5 end class class FigConstants extends Constants begin decorato...
from config.named_constants import Constants class MyConstants(Constants): PI = 3.141592653589793 E = 2.718281828459045 AUTHOR = "周小雪" class Colors(Constants): red, yellow, green, blue, white = range(5) class FigConstants(Constants): @classmethod def read(cls, i): return cls(int(i)...
Python
zaydzuhri_stack_edu_python
import matplotlib.pyplot as plt import numpy as np import seaborn as sns import pandas as pd import os if not exists path string figures begin make directories string figures end class Draw begin function draw begin set df = call DataFrame dict string data list 1 2 3 4 5 6 index=list string A string B string C string A...
import matplotlib.pyplot as plt import numpy as np import seaborn as sns import pandas as pd import os if not os.path.exists('figures'): os.makedirs('figures') class Draw(): def draw(): df = pd.DataFrame({'data': [1, 2, 3, 4, 5, 6]}, index=['A', 'B', 'C', 'A', 'B', 'C']) ...
Python
zaydzuhri_stack_edu_python
import RPi.GPIO as gpio from time import sleep , time set step_pin = 16 set dir_pin = 18 set SLEEP_TIME = 0.0001 comment T:clockwise&close, F:counter-clockwise&open set direction = false call setmode BOARD setup gpio step_pin OUT setup gpio dir_pin OUT for x in range 6 begin call output dir_pin direction set steps = 0 ...
import RPi.GPIO as gpio from time import sleep, time step_pin = 16 dir_pin = 18 SLEEP_TIME = 0.0001 direction = False # T:clockwise&close, F:counter-clockwise&open gpio.setmode(gpio.BOARD) gpio.setup(step_pin, gpio.OUT) gpio.setup(dir_pin, gpio.OUT) for x in range(6): gpio.output(dir_pin, direction) steps = 0 # s...
Python
zaydzuhri_stack_edu_python
function list_photos self begin comment Generate a "stub function" on-the-fly which will actually make comment the request. comment gRPC handles serialization and deserialization, so we just need comment to pass in the functions for each. if string list_photos not in _stubs begin set _stubs at string list_photos = call...
def list_photos(self) -> Callable[ [rpcmessages.ListPhotosRequest], rpcmessages.ListPhotosResponse]: # Generate a "stub function" on-the-fly which will actually make # the request. # gRPC handles serialization and deserialization, so we just need # to pass in the ...
Python
nomic_cornstack_python_v1
class Solution extends object begin function longestPalindrome self s begin string :type s: str :rtype: str if length s < 2 begin return s end set res = string for i in range 1 length s begin set curr = call find_Palindrome s i i if length curr > length res begin set res = curr end set curr = call find_Palindrome s i ...
class Solution(object): def longestPalindrome(self, s): """ :type s: str :rtype: str """ if len(s) < 2: return s res = '' for i in range(1, len(s)): curr = self.find_Palindrome(s, i, i) if len(curr) > len(res): ...
Python
zaydzuhri_stack_edu_python
import numpy as np import matplotlib.pyplot as plt function function x y begin comment return 1/20*(x**2) + (y**2) return x ^ 2 + y ^ 2 end function function func_grad x y begin comment return (1/10*x) + 2*y return 2 * x + 2 * y end function function grad_map function func_grad rate begin set x = array range 0 11 0.1 s...
import numpy as np import matplotlib.pyplot as plt def function(x, y): # return 1/20*(x**2) + (y**2) return (x**2) + (y**2) def func_grad(x, y): # return (1/10*x) + 2*y return 2*x + 2*y def grad_map(function, func_grad, rate): x = np.arange(0, 11, 0.1) arrowprops = dict(color='black', ...
Python
zaydzuhri_stack_edu_python
function render self begin set out = list call apply_formatting call update_size if title is not none begin set avail_space = width - length title set pad_num = avail_space // length spacer // 2 set pad = spacer * pad_num set out = out + list format string {:{fill}^{w}} title w=width fill=title_filler end if table_sty...
def render(self): out = [] self.apply_formatting() self.update_size() if self.title is not None: avail_space = (self.width - len(self.title)) pad_num = (avail_space // len(self.spacer)) // 2 pad = self.spacer * pad_num ...
Python
nomic_cornstack_python_v1
comment 使用Python实现(罗森布拉特感知器)感知器学习算法 comment 定义感知器的接口,使得我们可以初始化新的感知器对象 comment fit方法从数据中学习 comment predict对新的样本进行测试 import numpy as np class Perceptron extends object begin comment 以下是多行注释 string Perceptron Classifier Parameters ----------- eta:float 学习率(0到1之间) n_iter:int 训练数据集上迭代次数 Attributes ----------- w_:ld-array 学习...
#使用Python实现(罗森布拉特感知器)感知器学习算法 #定义感知器的接口,使得我们可以初始化新的感知器对象 #fit方法从数据中学习 #predict对新的样本进行测试 import numpy as np class Perceptron(object): #以下是多行注释 """ Perceptron Classifier Parameters ----------- eta:float 学习率(0到1之间) n_iter:int 训练数据集上迭代次数 Attributes ----------- w_:ld-arr...
Python
zaydzuhri_stack_edu_python
function sortColors self nums begin set res = dictionary comprehension x : 0 for x in range 3 for n in nums begin set res at n = res at n + 1 end comment print(res) set i = 0 for r in res begin for _ in range res at r begin set nums at i = r set i = i + 1 end end end function
def sortColors(self, nums: List[int]) -> None: res = {x: 0 for x in range (3)} for n in nums: res[n] += 1 # print(res) i = 0 for r in res: for _ in range(res[r]): nums[i] = r i += 1
Python
nomic_cornstack_python_v1
function f2p_list phrase max_word_size=15 cutoff=3 begin string Convert a phrase from Finglish to Persian. phrase: The phrase to convert. max_word_size: Maximum size of the words to consider. Words larger than this will be kept unchanged. cutoff: The cut-off point. For each word, there could be many possibilities. By d...
def f2p_list(phrase, max_word_size=15, cutoff=3): """Convert a phrase from Finglish to Persian. phrase: The phrase to convert. max_word_size: Maximum size of the words to consider. Words larger than this will be kept unchanged. cutoff: The cut-off point. For each word, there could be many pos...
Python
jtatman_500k
function deal numhands n=5 deck=list comprehension r + s for r in string 23456789TJQKA for s in string SHDC begin comment deals numhands hands with n cards each. shuffle random deck return list comprehension deck at slice n * i : n * i + 1 : for i in range numhands end function
def deal(numhands, n=5, deck=[r+s for r in '23456789TJQKA' for s in 'SHDC']): # deals numhands hands with n cards each. random.shuffle(deck) return [deck[n*i:n*(i+1)] for i in range(numhands)]
Python
nomic_cornstack_python_v1
function test_customSettingObjectIO self begin set cs = call Settings set yaml = call YAML set inp = load yaml call StringIO XS_EXAMPLE set cs at CONF_CROSS_SECTION = inp assert equal geometry string 0D set fname = string test_setting_obj_io_.yaml call writeToYamlFile fname set outText = read open fname string r assert...
def test_customSettingObjectIO(self): cs = caseSettings.Settings() yaml = YAML() inp = yaml.load(io.StringIO(XS_EXAMPLE)) cs[CONF_CROSS_SECTION] = inp self.assertEqual(cs[CONF_CROSS_SECTION]["AA"].geometry, "0D") fname = "test_setting_obj_io_.yaml" cs.writeToYamlF...
Python
nomic_cornstack_python_v1
comment - comment Frequency using Collections comment The collections is built in comment - from collections import Counter comment Initialize set ds = counter comment Add set ds at 1 = ds at 1 + 1 set ds at 2 = ds at 2 + 1 set ds at 1 = ds at 1 + 1 comment Test assert ds at 1 == 2 assert ds at 2 == 1 assert ds at 3 ==...
#- # Frequency using Collections # The collections is built in #- from collections import Counter # Initialize ds = Counter() # Add ds[1] += 1 ds[2] += 1 ds[1] += 1 # Test assert ds[1] == 2 assert ds[2] == 1 assert ds[3] == 0
Python
zaydzuhri_stack_edu_python
class Solution begin function smallestFactorization self a begin if a == 1 begin return 1 end set result = 0 set mul = 1 for i in range 9 1 - 1 begin while a % i == 0 begin set a = a // i set result = mul * i + result set mul = mul * 10 end end if result > 2 ^ 31 - 1 or a != 1 begin return 0 end else begin return resul...
class Solution: def smallestFactorization(self, a: int) -> int: if a == 1: return 1 result = 0 mul = 1 for i in range(9,1,-1): while a%i == 0: a = a//i result = mul*i + result mul *= 10 if resu...
Python
zaydzuhri_stack_edu_python
comment *_*coding:utf-8 *_* string 题目:海滩上有一堆桃子,五只猴子来分。第一只猴子把这堆桃子平均分为五份,多了一个,这只猴子把多的一个扔入海中,拿走了一份。第二只猴子把剩下的桃子又平均分成五份,又多了一个, 它同样把多的一个扔入海中,拿走了一份,第三、第四、第五只猴子都是这样做的,问海滩上原来最少有多少个桃子? function peach part monkey begin for i in range part + monkey + 1 10000 begin if i - 1 % part == 0 begin set b = i set c = 0 for j in range 1 mon...
# *_*coding:utf-8 *_* ''' 题目:海滩上有一堆桃子,五只猴子来分。第一只猴子把这堆桃子平均分为五份,多了一个,这只猴子把多的一个扔入海中,拿走了一份。第二只猴子把剩下的桃子又平均分成五份,又多了一个, 它同样把多的一个扔入海中,拿走了一份,第三、第四、第五只猴子都是这样做的,问海滩上原来最少有多少个桃子? ''' def peach(part, monkey): for i in range((part+monkey+1), 10000): if (i - 1) % part == 0: b = i c = 0 ...
Python
zaydzuhri_stack_edu_python
import re comment 城市的气候中所含的逗号和空格都去掉 set Xtrain at string Location = apply Xtrain at string Location lambda x -> sub string , string strip x
import re #城市的气候中所含的逗号和空格都去掉 Xtrain["Location"] = Xtrain["Location"].apply(lambda x:re.sub(",","",x.strip()))
Python
zaydzuhri_stack_edu_python
function print_card card begin set titles = list string Ones string Twos string Threes string Fours string Fives string Sixes string One pair string Two Pairs string Three of string Four of string Straigth string Big straight string House string Yatzy print string +---------+-----------------+-------+ print string | In...
def print_card(card): titles = ["Ones", "Twos", "Threes", "Fours", "Fives", "Sixes", "One pair", "Two Pairs", "Three of", "Four of", "Straigth", "Big straight", "House", "Yatzy"] print("+---------+-----------------+-------+") print("| Index | ...
Python
nomic_cornstack_python_v1
from datetime import date from datetime import datetime from datetime import timedelta function add_gigasecond date_input begin set dt_input = call datetime year month day set dt = dt_input + call fromtimestamp 10 ^ 9 - call datetime 1970 1 1 + time delta 1 0 0 return call date end function
from datetime import date from datetime import datetime from datetime import timedelta def add_gigasecond(date_input): dt_input = datetime(date_input.year, date_input.month, date_input.day) dt = dt_input + (datetime.fromtimestamp(10**9) - datetime(1970, 1, 1) + timedelta(1, 0, 0)) return dt.date()
Python
zaydzuhri_stack_edu_python
from ipaddress import ip_address decorator staticmethod function is_priv_revdns input begin set _ipv4 = string .in-addr.arpa set _ipv6 = string .ip6.arpa set _fqdn = lower right strip input string . if ends with _fqdn _ipv4 begin set addr_list = list comprehension i for i in reversed split _fqdn at slice : - length _i...
from ipaddress import ip_address @staticmethod def is_priv_revdns(input): _ipv4 = '.in-addr.arpa' _ipv6 = '.ip6.arpa' _fqdn = input.rstrip('.').lower() if _fqdn.endswith(_ipv4): addr_list = [i for i in reversed(_fqdn[:-len(_ipv4)].split('.'))] while len(addr_list) < 4: addr...
Python
zaydzuhri_stack_edu_python
from selenium import webdriver set driver = call Chrome call maximize_window call implicitly_wait 7 get driver string https://www.baidu.com try begin call find_element_by_link_text string 新闻 comment driver.find_element_by_xpath("//a[2][contains(@class, 'mnav')]").click() # 也可以用元素索引进行定位 就像 //a [2] comment driver.find_el...
from selenium import webdriver driver = webdriver.Chrome() driver.maximize_window() driver.implicitly_wait(7) driver.get("https://www.baidu.com") try: driver.find_element_by_link_text("新闻") #driver.find_element_by_xpath("//a[2][contains(@class, 'mnav')]").click() # 也可以用元素索引进行定位 就像 //a [2] #driver.find_ele...
Python
zaydzuhri_stack_edu_python
function renderOGRVRT vrt_filename src_datasets begin set vrt_head = string <OGRVRTDataSource> <OGRVRTUnionLayer name="merged"> <FieldStrategy>Union</FieldStrategy> set vrt_tail = string </OGRVRTUnionLayer> </OGRVRTDataSource> with open vrt_filename string w as vrt_write begin write vrt_write vrt_head for i in enumerat...
def renderOGRVRT(vrt_filename, src_datasets): vrt_head='<OGRVRTDataSource>\n <OGRVRTUnionLayer name="merged">\n <FieldStrategy>Union</FieldStrategy>\n' vrt_tail=' </OGRVRTUnionLayer>\n</OGRVRTDataSource>\n' with open(vrt_filename,'w') as vrt_write: vrt_write.write(vrt_head) for i in en...
Python
nomic_cornstack_python_v1
function GetFileSizeByPath self path begin set stat_object = call stat path return st_size end function
def GetFileSizeByPath(self, path): stat_object = os.stat(path) return stat_object.st_size
Python
nomic_cornstack_python_v1
function GetExtraFiles self extra_archive_paths source_file_name begin set extra_files_list = list set extra_path_list = split extra_archive_paths string , for path in extra_path_list begin set path = strip path set source_file = join path _src_dir path source_file_name if exists path source_file begin set new_files_l...
def GetExtraFiles(self, extra_archive_paths, source_file_name): extra_files_list = [] extra_path_list = extra_archive_paths.split(',') for path in extra_path_list: path = path.strip() source_file = os.path.join(self._src_dir, path, source_file_name) if os.path.exists(source_file): ...
Python
nomic_cornstack_python_v1
class Person begin function __init__ self name begin call __init__ set name = name print string { name } end function function talk self begin print string My name is { name } end function end class set name = input string Enter your name > set greeting = call Person string Vijay Saini call talk set bob = call Person s...
class Person: def __init__(self, name): super().__init__() self.name = name print(f'{name}') def talk(self): print(f"My name is {name}") name = input("Enter your name > ") greeting = Person("Vijay Saini") greeting.talk() bob = Person("Bob Smith") bob.talk()
Python
zaydzuhri_stack_edu_python
function state self begin try begin return _state end except AttributeError begin pass end set _state : BlynclightState = call BlynclightState return _state end function
def state(self) -> BlynclightState: try: return self._state except AttributeError: pass self._state: BlynclightState = BlynclightState() return self._state
Python
nomic_cornstack_python_v1
import numpy as np function generateRandomMatrix m n begin return randn m n end function
import numpy as np def generateRandomMatrix(m, n): return np.random.randn(m, n)
Python
jtatman_500k
import psycopg2 class Conexao begin function __init__ self begin set conexao = call connect dbname=string project4 user=string postgres password=string postgres print string Conexão estabelecida set cursor = call cursor end function function __del__ self begin close cursor close conexao print string Conexão encerrada e...
import psycopg2 class Conexao: def __init__(self): self.conexao = psycopg2.connect(dbname='project4', user="postgres", password="postgres") print('Conexão estabelecida') self.cursor = self.conexao.cursor() def __del__(self): self.cursor.close() self.conexao.close() ...
Python
zaydzuhri_stack_edu_python
function create_rcv self **kwargs begin set defaults = dict string run testrun ; string caseversion__productversion productversion ; string caseversion__case__product product ; string environments envs update defaults kwargs return call create keyword defaults end function
def create_rcv(self, **kwargs): defaults = { "run": self.testrun, "caseversion__productversion": self.testrun.productversion, "caseversion__case__product": self.testrun.productversion.product, "environments": self.envs, } defaults.update...
Python
nomic_cornstack_python_v1
function fix self begin return call Ray call fix end function
def fix(self) -> Ray: return Ray(self._contract.call().fix())
Python
nomic_cornstack_python_v1
function __init__ self figure offsets=tuple - 20 20 formatter=lambda ax x y -> string x: %0.2f y: %0.2f % tuple x y begin set format = formatter set offsets = offsets set figure = figure set annotations = dict call mpl_connect string motion_notify_event self end function
def __init__(self, figure, offsets=(-20, 20), formatter=lambda ax, x, y: 'x: %0.2f\ny: %0.2f' % (x, y)): self.format = formatter self.offsets = offsets self.figure = figure self.annotations = {} self.figure.canvas.mpl_connect('motion_notify_event', self)
Python
nomic_cornstack_python_v1
from helpers import analytics call monitor import os , itertools set dirname = directory name path __file__ set filename = join path dirname string bin string p098_words.txt set wordsFile = open filename string r function getWords begin set words = list for line in wordsFile begin set words = words + list comprehensio...
from helpers import analytics analytics.monitor() import os, itertools dirname = os.path.dirname(__file__) filename = os.path.join(dirname, "bin", "p098_words.txt") wordsFile = open(filename, "r") def getWords(): words = [] for line in wordsFile: words += [word.strip('"') for word in line.split(",") i...
Python
zaydzuhri_stack_edu_python
function cap self begin string "Caps" the construction of the pipeline, signifying that no more inputs and outputs are expected to be added and therefore the input and output nodes can be created along with the provenance. set to_cap = tuple _inputnodes _outputnodes _prov if to_cap == tuple none none none begin set _in...
def cap(self): """ "Caps" the construction of the pipeline, signifying that no more inputs and outputs are expected to be added and therefore the input and output nodes can be created along with the provenance. """ to_cap = (self._inputnodes, self._outputnodes, self._prov...
Python
jtatman_500k
comment !/usr/bin/env python import rospy from geometry_msgs.msg import Twist , Quaternion from std_msgs.msg import Float32 from nav_msgs.msg import Odometry import math import numpy as np import tf class RobotOdom begin function __init__ self begin comment rospy.init_node('robot_odom') call Subscriber string /lb_wheel...
#!/usr/bin/env python import rospy from geometry_msgs.msg import Twist, Quaternion from std_msgs.msg import Float32 from nav_msgs.msg import Odometry import math import numpy as np import tf class RobotOdom(): def __init__(self): #rospy.init_node('robot_odom') rospy.Subscriber('/lb_wheel_vel', Float32, self.lb_li...
Python
zaydzuhri_stack_edu_python
class Polygon begin function _init_ self no_of_sides begin set n = no_of_sides set sides = list for i in range no_of_sides begin append sides 0 end end function function input_sides self begin for i in range n begin set sides at i = decimal input string Enter side + string i + 1 + string : end end function end class c...
class Polygon: def _init_(self, no_of_sides): self.n = no_of_sides self.sides = [] for i in range(no_of_sides): self.sides.append(0) def input_sides(self): for i in range(self.n): self.sides[i] = float(input("Enter side"+str(i+1)+" : ")) ...
Python
zaydzuhri_stack_edu_python
function forward self input hidden=none begin comment tag = None # if hidden is none begin set hidden = call _init_hidden input end function recurrence input hidden begin string Recurrence helper. call set_dropout_masks size input 0 comment n_b x hidden_dim set tuple hx cx = hidden comment gates = self.input_weights(in...
def forward(self, input, hidden=None): # tag = None # if hidden is None: hidden = self._init_hidden(input) def recurrence(input, hidden): """Recurrence helper.""" self.set_dropout_masks(input.size(0)) hx, cx = hidden # n_b x hidden_dim ...
Python
nomic_cornstack_python_v1
import random import string class Account begin function __init__ self initial_deposit begin set identifier = call generate_identifier set balance = 0 set num_deposits = 0 set num_withdrawals = 0 set minimum_balance = 500 set maximum_balance = 50000 call deposit initial_deposit end function function generate_identifier...
import random import string class Account: def __init__(self, initial_deposit): self.identifier = self.generate_identifier() self.balance = 0 self.num_deposits = 0 self.num_withdrawals = 0 self.minimum_balance = 500 self.maximum_balance = 50000 self....
Python
jtatman_500k
import telebot import datetime import pickle import atexit class Player begin string Класс Player имеет поля: _id - неизмняемое поле - id игрока _name - неизменяемое поле - имя жабки last_feed - время последнего кормления size - размер жабки function __init__ self id name begin string Конструктор класса принимает 2 арг...
import telebot import datetime import pickle import atexit class Player: ''' Класс Player имеет поля: _id - неизмняемое поле - id игрока _name - неизменяемое поле - имя жабки last_feed - время последнего кормления size - размер жабки''' def __init__(self, id : st...
Python
zaydzuhri_stack_edu_python
comment -*- coding: utf-8 -*- string Created on Sun Apr 29 15:10:34 2018 @author: nit_n from gaussxw import gaussxwab from numpy import linspace , arange from pylab import plot , show , xlabel , ylabel from math import pi , exp , sqrt comment joules/kelvin set k = 1.38065e-23 comment joules set h = 6.626e-34 comment me...
# -*- coding: utf-8 -*- """ Created on Sun Apr 29 15:10:34 2018 @author: nit_n """ from gaussxw import gaussxwab from numpy import linspace, arange from pylab import plot, show, xlabel, ylabel from math import pi, exp, sqrt k = 1.38065e-23 # joules/kelvin h = 6.626e-34 # joules lam1 = 390e-9 # meters ...
Python
zaydzuhri_stack_edu_python
import webbrowser , sys , pyperclip import bs4 , requests from selenium import webdriver import time import os.path from pathlib import Path comment link used to implement this code : comment https://automatetheboringstuff.com/chapter11/ if length argv > 1 begin comment Get address from command line set url = join stri...
import webbrowser, sys, pyperclip import bs4, requests from selenium import webdriver import time import os.path from pathlib import Path # link used to implement this code : # https://automatetheboringstuff.com/chapter11/ if len(sys.argv) > 1 : # Get address from command line url = ' '.join(sys.argv[1:]) else : ...
Python
zaydzuhri_stack_edu_python
function main begin set name = input string What is your name? call some_method name end function function some_method name begin if lower strip name == string rob begin print string Hello old friend! end else begin print string Nice to meet you { name } . print string My name is Python! end end function if __name__ ==...
def main(): name = input("What is your name? ") some_method(name) def some_method(name: str): if name.strip().lower() == 'rob': print("Hello old friend!") else: print(f"Nice to meet you {name}.") print("My name is Python!") if __name__ == "__main__": main()
Python
zaydzuhri_stack_edu_python
from datetime import datetime from django.shortcuts import get_object_or_404 from rest_framework.generics import ListCreateAPIView , RetrieveAPIView , CreateAPIView from rest_framework.response import Response from rest_framework.views import APIView from rest_framework import status import scipy.interpolate from anima...
from datetime import datetime from django.shortcuts import get_object_or_404 from rest_framework.generics import ListCreateAPIView, RetrieveAPIView, CreateAPIView from rest_framework.response import Response from rest_framework.views import APIView from rest_framework import status import scipy.interpolate from anima...
Python
zaydzuhri_stack_edu_python
string Part 2 Optimize the previous code to reduce the runtime and memory. Pseudocode set an empty array select every object from array apply order by module element%2==0 add that element to our array return the newarray with all elementens orderd by module our new order will be something like this --> [0,0,0,0,0,0,0,0...
""" Part 2 Optimize the previous code to reduce the runtime and memory. Pseudocode set an empty array select every object from array apply order by module element%2==0 add that element to our array return the newarray with all elementens orderd by module our new order will be something like this --> [0,0,0,0,...
Python
zaydzuhri_stack_edu_python
function insert deck rightIndex value begin for i in reversed range rightIndex begin if deck at i > value begin call swap deck i rightIndex set rightIndex = rightIndex - 1 end end return deck end function
def insert(deck, rightIndex, value): for i in reversed(range(rightIndex)): if deck[i] > value: swap(deck,i,rightIndex) rightIndex-=1 return deck
Python
nomic_cornstack_python_v1
function simple_test_img_only self img img_metas proposals=none rescale=false begin comment noqa: E501 assert with_img_bbox msg string Img bbox head must be implemented. assert with_img_backbone msg string Img backbone must be implemented. assert with_img_rpn msg string Img rpn must be implemented. assert with_img_roi_...
def simple_test_img_only(self, img, img_metas, proposals=None, rescale=False): # noqa: E501 assert self.with_img_bbox, 'Img bbox head must be implemented.' assert self.with_img_backbone, ...
Python
nomic_cornstack_python_v1
function quantos_uns n begin set i = 0 set qtd_1 = 0 if length n == 1 begin if n == string 1 begin return 1 end else begin return 0 end end else begin while i != length n begin if n at i == string 1 begin set qtd_1 = qtd_1 + 1 set i = i + 1 end else begin set i = i + 1 end end end return qtd_1 end function
def quantos_uns(n): i = 0 qtd_1 = 0 if len(n) == 1: if n == '1': return 1 else: return 0 else: while i != len(n): if n[i] == '1': qtd_1 += 1 i += 1 else: i += 1 return qtd_1
Python
zaydzuhri_stack_edu_python
function __init__ self person begin comment The person to which this body belongs set person = person comment Prepare all the attributes that we'll be setting momentarily; these will comment be instantiated as Feature attributes (that extend Float) set age_of_physical_peak = none comment Left-handed set lefty = false c...
def __init__(self, person): self.person = person # The person to which this body belongs # Prepare all the attributes that we'll be setting momentarily; these will # be instantiated as Feature attributes (that extend Float) self.age_of_physical_peak = None self.lefty = False # ...
Python
nomic_cornstack_python_v1
comment coding:utf-8 import jieba set f = open string shiji.txt string r set fhand = read f set seg_list = call cut fhand set words = list seg_list set d = dict for w in words begin set count = get d w 0 set d at w = count + 1 end print d
#coding:utf-8 import jieba f = open("shiji.txt","r") fhand = f.read() seg_list = jieba.cut(fhand) words = list(seg_list) d = {} for w in words: count = d.get(w, 0) d[w] = count + 1 print(d)
Python
zaydzuhri_stack_edu_python
import os import subprocess class Report begin function __init__ self outdir begin set outdir = outdir + string /data end function function report self results begin string Generate Nocoverage.txt of regions within targets that have Zero coverage. Input: Coveragefile object, outdir set coveragefiles = results at 0 set ...
import os import subprocess class Report(): def __init__(self, outdir): self.outdir = outdir + '/data' def report(self, results): '''Generate Nocoverage.txt of regions within targets that have Zero coverage. Input: Coveragefile object, outdir ''' coveragefiles = results[0] ...
Python
zaydzuhri_stack_edu_python
function extract_enum_vals enum begin set rv_list = list set name = call group 1 set lines = join string split enum string set body = call group 1 set entries = split body string , set previous_value = - 1 for m in entries begin comment Empty line if match string *$ m begin continue end comment Parse with = first set...
def extract_enum_vals(enum): rv_list = [] name = re.search("enum +(\w+)", enum).group(1) lines = " ".join(enum.split("\n")) body = re.search("\{(.+)\}", lines).group(1) entries = body.split(",") previous_value = -1 for m in entries: if re.match(" *$", m): # Empty line co...
Python
nomic_cornstack_python_v1
function insert self word begin set level = root for char in word begin if char not in childrenNode begin set childrenNode at char = call TrieNode end set level = childrenNode at char end set isWord = true end function
def insert(self, word): level = self.root for char in word: if char not in level.childrenNode: level.childrenNode[char] = self.TrieNode() level = level.childrenNode[char] level.isWord = True
Python
nomic_cornstack_python_v1