code
stringlengths
10
2.58M
original_code
stringlengths
3
3.18M
original_language
stringclasses
1 value
source
stringclasses
7 values
function initGlobalsFromFile filename begin set shpfile = open string argv at 1 string rb set minbounds = call ShapeFile_info shpfile at 2 set maxbounds = call ShapeFile_info shpfile at 2 set dbffile = open string argv at 1 string rb set numrecords = call DBFFile_record_count dbffile set numfields = call DBFFile_field_...
def initGlobalsFromFile(filename): shpfile = shapelibc.open(str(sys.argv[1]),"rb") minbounds = shapelibc.ShapeFile_info(shpfile)[2] maxbounds = shapelibc.ShapeFile_info(shpfile)[2] dbffile = dbflibc.open(str(sys.argv[1]),"rb") numrecords = dbflibc.DBFFile_record_count(dbffile) numfields = dbflib...
Python
nomic_cornstack_python_v1
class Solution begin comment @param {integer[]} candidates comment @param {integer} target comment @return {integer[][]} function combinationSum2 self candidates target begin set candidates = sorted candidates comment total, start, path set stack = list tuple 0 - 1 list set result = list while stack begin set tuple t...
class Solution: # @param {integer[]} candidates # @param {integer} target # @return {integer[][]} def combinationSum2(self, candidates, target): candidates = sorted(candidates) stack = [(0, -1, [])] # total, start, path result = [] while stack: total, start, p...
Python
zaydzuhri_stack_edu_python
function addBufferIndices feature begin return call buffer 35 end function
def addBufferIndices(feature): return feature.buffer(35)
Python
nomic_cornstack_python_v1
function _process_neighbor self begin call _validate_neighbor call _treat_soft_reconfiguration call _treat_community call _order_neighbor end function
def _process_neighbor(self): self._validate_neighbor() self._treat_soft_reconfiguration() self._treat_community() self._order_neighbor()
Python
nomic_cornstack_python_v1
function gen_rand_points num begin set points = call empty tuple num 3 for index in range num begin set points at tuple index slice : : = call rand 3 end return points end function
def gen_rand_points(num): points = np.empty((num, 3)) for index in range(num): points[index, :] = np.random.rand(3) return points
Python
nomic_cornstack_python_v1
import file_utils import shutil import os import http_utils import time import logging import logging.config class SiteWatcher begin call fileConfig string logging.conf set url_dir = string urls set html_dir = string htmls set old_html_dir = string old_htmls set report_dir = string report function prepare_dirs self beg...
import file_utils import shutil import os import http_utils import time import logging import logging.config class SiteWatcher(): logging.config.fileConfig('logging.conf') url_dir = "urls" html_dir = "htmls" old_html_dir = "old_htmls" report_dir = "report" def prepare_dirs(self): if o...
Python
zaydzuhri_stack_edu_python
string Markovify EconTalk transcripts. import markovify comment Get raw text as string. with open string data/corpus.txt as fin begin set text = read fin end comment Build the model. set text_model = call Text text comment Print five randomly-generated sentences comment for i in range(5): comment print(text_model.make_...
""" Markovify EconTalk transcripts. """ import markovify # Get raw text as string. with open("data/corpus.txt") as fin: text = fin.read() # Build the model. text_model = markovify.Text(text) # Print five randomly-generated sentences # for i in range(5): # print(text_model.make_sentence()) # Print three ran...
Python
zaydzuhri_stack_edu_python
comment -*- coding: utf-8 -*- comment !/usr/bin/env python string Created on Sat Oct 26 15:26:03 2019 @author: cw817615 import numpy as np import random import matplotlib.pyplot as plt import pandas as pd comment 用来正常显示中文标签 set rcParams at string font.sans-serif = list string SimHei comment 用来正常显示负号 set rcParams at str...
# -*- coding: utf-8 -*- #!/usr/bin/env python """ Created on Sat Oct 26 15:26:03 2019 @author: cw817615 """ import numpy as np import random import matplotlib.pyplot as plt import pandas as pd plt.rcParams['font.sans-serif']=['SimHei'] #用来正常显示中文标签 plt.rcParams['axes.unicode_minus']=False #用来正常显示负号 ...
Python
zaydzuhri_stack_edu_python
import requests import pymongo import os from hashlib import md5 from bs4 import BeautifulSoup import re from lxml import etree from config import * set client = call MongoClient MONGO_URL set db = client at MONGO_DB function get_onepage_url start_url begin set response = text return response end function function pars...
import requests import pymongo import os from hashlib import md5 from bs4 import BeautifulSoup import re from lxml import etree from config import * client = pymongo.MongoClient(MONGO_URL) db = client[MONGO_DB] def get_onepage_url(start_url): response = requests.get(start_url).text return response def parse...
Python
zaydzuhri_stack_edu_python
import torch import numpy as np from omniglotNShot import OmniglotNShot from model import CNN import torch.optim as optim set device = if expression call is_available then device string cuda else device string cpu set criterion = to cross entropy loss device function get_grads model op x y begin zero grad op set hypoth...
import torch import numpy as np from omniglotNShot import OmniglotNShot from model import CNN import torch.optim as optim device = torch.device('cuda') if torch.cuda.is_available() else torch.device('cpu') criterion = torch.nn.CrossEntropyLoss().to(device) def get_grads(model, op, x, y): op.zero_grad() hypoth...
Python
zaydzuhri_stack_edu_python
import pandas as pd import scipy.stats as sp from argparse import ArgumentParser , Namespace set hgb_file = string FILEPATH set idcols = list string location_id string year_id string age_group_id string sex_id function parse_args begin set parser = call ArgumentParser call add_argument string --year_id help=string year...
import pandas as pd import scipy.stats as sp from argparse import ArgumentParser, Namespace hgb_file = 'FILEPATH' idcols = ['location_id', 'year_id', 'age_group_id', 'sex_id'] def parse_args() -> Namespace: parser = ArgumentParser() parser.add_argument("--year_id", help="year to use", type=int) parser.add...
Python
zaydzuhri_stack_edu_python
string Given the mapping a = 1, b = 2, ... z = 26, and an encoded message, count the number of ways it can be decoded. For example, the message '111' would give 3, since it could be decoded as 'aaa', 'ka', and 'ak'. You can assume that the messages are decodable. For example, '001' is not allowed. function possibilitie...
''' Given the mapping a = 1, b = 2, ... z = 26, and an encoded message, count the number of ways it can be decoded. For example, the message '111' would give 3, since it could be decoded as 'aaa', 'ka', and 'ak'. You can assume that the messages are decodable. For example, '001' is not allowed. ''' def possibilities...
Python
zaydzuhri_stack_edu_python
function ping self begin call _write b'\xc0\x00' set last_ping = call ticks_ms end function
def ping(self): self._write(b"\xc0\0") self.last_ping = ticks_ms()
Python
nomic_cornstack_python_v1
import inspect import os.path class logger extends object begin function __init__ self log_to_stdout=true logger_level=0 filename=string py_log.txt append=false begin set logger_initialized = true set logger_enabled = true set log_to_stdout = log_to_stdout set log_file_name = none set logger_level = logger_level if log...
import inspect import os.path class logger(object): def __init__(self, log_to_stdout=True, logger_level=0, filename="py_log.txt", append=False): self.logger_initialized = True self.logger_enabled = True self.log_to_stdout = log_to_stdout self.log_file_name = None self.logg...
Python
zaydzuhri_stack_edu_python
import turtle function flip_and_reverse l begin return list reversed call flip l end function function flip input begin set output = list for x in input begin if x == string R begin append output string L end else begin append output string R end end return output end function function getTurns order begin if order <=...
import turtle def flip_and_reverse(l): return list(reversed(flip(l))) def flip(input): output = [] for x in input: if x == 'R': output.append('L') else: output.append('R') return output def getTurns(order): if order <= 1: return ['R'] else: lower_order_turns = getTurns(order ...
Python
zaydzuhri_stack_edu_python
import pandas as pd from scipy import stats import numpy as np import yaml comment logging import import warnings import logging import datetime import os import sys comment module logger set logger = call getLogger __name__ function start_logging log_file=string log_level=string INFO verbose=false begin string Start ...
import pandas as pd from scipy import stats import numpy as np import yaml # logging import import warnings import logging import datetime import os import sys logger = logging.getLogger(__name__) # module logger def start_logging(log_file='', log_level='INFO', verbose=False): """Start logging information into ...
Python
zaydzuhri_stack_edu_python
function create_product_shipping_class self **data begin return call _create string products/shipping_classes data end function
def create_product_shipping_class(self, **data): return self._create('products/shipping_classes', data)
Python
nomic_cornstack_python_v1
import string import copy comment Enigma I rotors: set ROTOR_I_WIRING = string EKMFLGDQVZNTOWYHXUSPAIBRCJ set ROTOR_I_NOTCH = string Q set ROTOR_II_WIRING = string AJDKSIRUXBLHWTMCQGZNPYFVOE set ROTOR_II_NOTCH = string E set ROTOR_III_WIRING = string BDFHJLCPRTXVZNYEIWGAKMUSQO set ROTOR_III_NOTCH = string V set ROTOR_I...
import string import copy # Enigma I rotors: ROTOR_I_WIRING = "EKMFLGDQVZNTOWYHXUSPAIBRCJ" ROTOR_I_NOTCH = "Q" ROTOR_II_WIRING = "AJDKSIRUXBLHWTMCQGZNPYFVOE" ROTOR_II_NOTCH = "E" ROTOR_III_WIRING = "BDFHJLCPRTXVZNYEIWGAKMUSQO" ROTOR_III_NOTCH = "V" ROTOR_IV_WIRING = "ESOVPZJAYQUIRHXLNFTGKDCMWB" ROTOR_IV_NOTCH = "J" R...
Python
zaydzuhri_stack_edu_python
function get_vertex self v_id begin pass end function
def get_vertex(self, v_id): pass
Python
nomic_cornstack_python_v1
function orbitrap file_path begin set headers = list string scan string rt string mz string drift string intensity set input_data = list set intensity_cutoff = intensity_cutoff for path_name in glob glob join path file_path string *.mzML.binary.*.txt begin set file_name = split path_name string / at - 1 set scan_numbe...
def orbitrap(file_path): headers = ["scan", "rt", "mz", "drift", "intensity"] input_data = [] intensity_cutoff = config.intensity_cutoff for path_name in glob.glob(os.path.join(file_path, "*.mzML.binary.*.txt")): file_name = path_name.split("/")[-1] scan_number = int(file_name.split("....
Python
nomic_cornstack_python_v1
from sqlalchemy import Column , String , Integer , ForeignKey , create_engine , MetaData , Table from sqlalchemy.ext.declarative import declarative_base from sqlalchemy.orm import sessionmaker , relationship set Base = call declarative_base comment OneToOne set e_f_table = call Table string e_f metadata call Column str...
from sqlalchemy import Column, String, Integer, ForeignKey, create_engine, MetaData, Table from sqlalchemy.ext.declarative import declarative_base from sqlalchemy.orm import sessionmaker, relationship Base = declarative_base() # OneToOne e_f_table = Table('e_f', Base.metadata, Column('e_id', Integer, ForeignKey('...
Python
zaydzuhri_stack_edu_python
comment Michael Patrick comment 4/4/21 comment Warhammer File Generator comment Creates a list of characters that fits the Warhammer comment Simulator format of file input, as shown below: comment [Character 1 Name] comment [Character 1 Stats] comment [Character Psychic Abilities]( if none, "None") comment Ranged[Chara...
# Michael Patrick # 4/4/21 # Warhammer File Generator # # Creates a list of characters that fits the Warhammer # Simulator format of file input, as shown below: # [Character 1 Name] # [Character 1 Stats] # [Character Psychic Abilities]( if none, "None") # Ranged[Character 1 Ranged] # . # . # . # Melee[Character 1 Melee...
Python
zaydzuhri_stack_edu_python
from selenium import webdriver from selenium.webdriver.common.by import By from selenium.webdriver.common.keys import Keys from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions as EC import pandas as pd import time comment To get the csv file which contains t...
from selenium import webdriver from selenium.webdriver.common.by import By from selenium.webdriver.common.keys import Keys from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions as EC import pandas as pd import time # To get the csv file which contains the da...
Python
zaydzuhri_stack_edu_python
function has_intersection self obj begin set obj_x = call get_x set obj_y = call get_y set distance = square root obj_x at 0 - __x at 0 ^ 2 + obj_y at 0 - __y at 0 ^ 2 if distance <= call radius + call get_radius begin return true end return false end function
def has_intersection(self, obj): obj_x = obj.get_x() obj_y = obj.get_y() distance = math.sqrt((obj_x[0]-self.__x[0])**2 + (obj_y[0] - self.__y[0])**2) if distance <= (self.radius() + obj.get_radius()): return True return False
Python
nomic_cornstack_python_v1
comment def checkpoint(soldiers): comment gun = gun-soldiers comment print("남은 총 개수: {0}".format(gun)) comment def checkpoint(soldiers): comment global gun #전역변수 gun을 쓰겠다는 의미. comment gun = gun-soldiers comment print("남은 총 개수: {0}".format(gun)) comment checkpoint(2) function checkpoint gun soldiers begin comment 이 gun은...
# def checkpoint(soldiers): # gun = gun-soldiers # print("남은 총 개수: {0}".format(gun)) # def checkpoint(soldiers): # global gun #전역변수 gun을 쓰겠다는 의미. # gun = gun-soldiers # print("남은 총 개수: {0}".format(gun)) # checkpoint(2) def checkpoint(gun, soldiers): gun = gun-soldiers #이 gun은 이제 지역변수임. 그러므로...
Python
zaydzuhri_stack_edu_python
from surt import surt from warcio.archiveiterator import ArchiveIterator import os import io import pandas as pd import csv import justext import codecs from os.path import basename import bz2 class WarcParser begin set PATH_TO_WARCS = string /home/nguyen/nn4ir/data/top1k/ decorator staticmethod function combine_urls d...
from surt import surt from warcio.archiveiterator import ArchiveIterator import os import io import pandas as pd import csv import justext import codecs from os.path import basename import bz2 class WarcParser: PATH_TO_WARCS = "/home/nguyen/nn4ir/data/top1k/" @staticmethod def combine_urls(dir): ...
Python
zaydzuhri_stack_edu_python
class Node begin function __init__ self value begin set value = value set next = none end function end class function delete_node head value begin comment Detect and break cycles using Floyd's Cycle-Finding Algorithm set slow_ptr = head set fast_ptr = head while fast_ptr and next begin set slow_ptr = next set fast_ptr ...
class Node: def __init__(self, value): self.value = value self.next = None def delete_node(head, value): # Detect and break cycles using Floyd's Cycle-Finding Algorithm slow_ptr = head fast_ptr = head while fast_ptr and fast_ptr.next: slow_ptr = slow_ptr.next fa...
Python
jtatman_500k
function _create_stream self max_buffer_size af addr **kwargs begin comment pylint: disable=unused-argument,arguments-differ comment Always connect in plaintext; we'll convert to ssl if necessary comment after one connection has completed. set sock = call _get_socket opts call _set_tcp_keepalive sock opts set stream = ...
def _create_stream( self, max_buffer_size, af, addr, **kwargs ): # pylint: disable=unused-argument,arguments-differ # Always connect in plaintext; we'll convert to ssl if necessary # after one connection has completed. sock = _get_socket(self.opts) _set_tcp_keepalive(sock, s...
Python
nomic_cornstack_python_v1
function average_losses tower_losses begin set ret = list for quantities in zip *tower_losses begin append ret call add_n quantities / length quantities end return ret end function
def average_losses(tower_losses): ret = [] for quantities in zip(*tower_losses): ret.append(tf.add_n(quantities) / len(quantities)) return ret
Python
nomic_cornstack_python_v1
function fetch_title_details srcfile source api_key1 api_key2 begin with open srcfile as json_file begin set data = load json json_file set titles = list set count = 0 for i in data begin if count <= 200 begin comment print(count) set title = call fetch_title_data i at string id count api_key1 api_key2 set title at st...
def fetch_title_details(srcfile, source, api_key1, api_key2): with open(srcfile) as json_file: data = json.load(json_file) titles = [] count = 0 for i in data: if count <= 200: # print(count) title = fetch_title_data(i['id'], count, api_key...
Python
nomic_cornstack_python_v1
import random set my_list = list 1 2 3 shuffle random my_list sort my_list print my_list
import random my_list = [1, 2, 3] random.shuffle(my_list) my_list.sort() print(my_list)
Python
jtatman_500k
import sqlite3 set con = call connect string 8Bdatabase.sqlite3 set cur = call cursor execute cur string SELECT id,name FROM data WHERE gender=? tuple string Female for row in cur begin print row end
import sqlite3 con=sqlite3.connect('8Bdatabase.sqlite3') cur=con.cursor() cur.execute('SELECT id,name FROM data WHERE gender=?',('Female',)) for row in cur: print(row)
Python
zaydzuhri_stack_edu_python
from bs4 import BeautifulSoup import urllib2 function get_genres url begin set genres = list set wiki = url comment Needed to prevent 403 error on Wikipedia set header = dict string User-Agent string Mozilla/5.0 set req = call Request wiki headers=header end function
from bs4 import BeautifulSoup import urllib2 def get_genres(url): genres = [] wiki = url header = {'User-Agent': 'Mozilla/5.0'} #Needed to prevent 403 error on Wikipedia req = urllib2.Request(wiki,headers=header)
Python
zaydzuhri_stack_edu_python
async function joined self ctx user=none begin if not user begin set user = author end if joined_at begin set user_joined = string format time joined_at string %d %b %Y %H:%M set since_joined = days set joined_on = string { user_joined } ( { since_joined } days ago) end else begin set joined_on = string a mysterious da...
async def joined(self, ctx, user: discord.Member = None): if not user: user = ctx.author if user.joined_at: user_joined = user.joined_at.strftime("%d %b %Y %H:%M") since_joined = (ctx.message.created_at - user.joined_at).days joined_on = f"{user_join...
Python
nomic_cornstack_python_v1
function input_device_validation_test self device begin try begin set mic_info = call get_device_info_by_index device comment or self.mic_info["hostApi"] != 0: if mic_info at string maxInputChannels < 1 begin return false end set stream = open format=paInt16 channels=1 input_device_index=device frames_per_buffer=chunk ...
def input_device_validation_test(self, device): try: self.mic_info = self.p.get_device_info_by_index(device) if self.mic_info["maxInputChannels"] < 1: # or self.mic_info["hostApi"] != 0: return False stream = self.p.open(format=pyaudio.paInt16, channels=1, ...
Python
nomic_cornstack_python_v1
function getLPBlob filename=string fooba.bin username=string johndoe@nowhere.org passwordIn=string nothing topt=string -1 TimeTag=false Search=false begin if passwordIn == string nothing begin set password = call getpass string Enter LP Password: end else begin set password = passwordIn end if topt == string -1 begin s...
def getLPBlob(filename="fooba.bin", username="johndoe@nowhere.org", passwordIn='nothing', topt='-1', TimeTag=False, Search=False): if passwordIn == 'nothing': password = getpass.getpass('Enter LP Password: ') else: password = passwordIn if topt == '-1': mytotpnow = raw_input('Enter O...
Python
nomic_cornstack_python_v1
function swap i j begin set tuple num at i num at j = tuple num at j num at i end function comment Bubble Sort comment for i in range (len(num)): comment for j in range (len(num)-1): comment if(num[j] > num[j+1]): comment swap(j, j+1) comment print(num[1]) comment Selection Sort comment for i in range (len(num)): comme...
def swap(i,j): num[i], num[j] = num[j], num[i] #Bubble Sort # for i in range (len(num)): # for j in range (len(num)-1): # if(num[j] > num[j+1]): # swap(j, j+1) # # print(num[1]) #Selection Sort # for i in range (len(num)): # min = i # for j in range (i+1, len(num)): ...
Python
zaydzuhri_stack_edu_python
function _check_primitive self begin if constructor in _PRIMITIVES begin if obj is UNDEFINED begin raise call DeserializeError constructor obj new_depth key end if obj is none begin raise call DeserializeError constructor obj new_depth key end if not is instance obj constructor begin if not convert_primitives begin rai...
def _check_primitive(self) -> PossibleResult[T]: if self.constructor in _PRIMITIVES: if self.obj is UNDEFINED: raise DeserializeError( self.constructor, self.obj, self.new_depth, self.key ) if self.obj is None: raise Des...
Python
nomic_cornstack_python_v1
import urllib.request import xml.dom.minidom as minidom import sqlite3 import datetime function get_data xml_url begin try begin set web_file = url open xml_url return read web_file end except any begin pass end end function function get_currencies_dictionary xml_content begin set dom = call parseString xml_content cal...
import urllib.request import xml.dom.minidom as minidom import sqlite3 import datetime def get_data(xml_url): try: web_file = urllib.request.urlopen(xml_url) return web_file.read() except: pass def get_currencies_dictionary(xml_content): dom = minidom.parseString(xml_content) ...
Python
zaydzuhri_stack_edu_python
comment 코드업 3016: 1등한 학생의 성적 문제 set n = integer input set array = list set array2 = list set array3 = list for _ in range n begin append array split input end set max_index = 0 for i in range 1 n begin if integer array at max_index at 1 < integer array at i at 1 begin set max_index = i end end for j in range n begin...
# 코드업 3016: 1등한 학생의 성적 문제 n = int(input()) array = [] array2 = [] array3 = [] for _ in range(n) : array.append(input().split()) max_index = 0 for i in range(1,n) : if int(array[max_index][1]) < int(array[i][1]) : max_index = i for j in range(n) : array2.append(int(array[j][2])) for k in ra...
Python
zaydzuhri_stack_edu_python
function get_values self n=5 begin debug string Getting "values" set zener_constant = 3 set ldr_pullup_resistance = 56.0 set rain_pull_up_resistance = 1 set rain_res_at25 = 1 set rain_beta = 3450.0 set abszero = 273.15 set internal_voltages = list set ldr_resistances = list set rain_sensor_temps = list for i in rang...
def get_values(self, n=5): logger.debug('Getting "values"') zener_constant = 3 ldr_pullup_resistance = 56. rain_pull_up_resistance = 1 rain_res_at25 = 1 rain_beta = 3450. abszero = 273.15 internal_voltages = [] ldr_resistances = [] rain_sen...
Python
nomic_cornstack_python_v1
function load_plugin_factories self begin for plugin in call get_plugins group=string enaml_native_ios_factories begin set get_factories = load plugin set PLUGIN_FACTORIES = call get_factories update IOS_FACTORIES PLUGIN_FACTORIES end end function
def load_plugin_factories(self): for plugin in self.get_plugins(group='enaml_native_ios_factories'): get_factories = plugin.load() PLUGIN_FACTORIES = get_factories() factories.IOS_FACTORIES.update(PLUGIN_FACTORIES)
Python
nomic_cornstack_python_v1
function remove_from_set A B begin for element in B begin discard A element end return A end function set A = set literal 1 2 3 4 set B = set literal 2 3 print call remove_from_set A B comment Output: {1, 4}
def remove_from_set(A, B): for element in B: A.discard(element) return A A = {1, 2, 3, 4} B = {2, 3} print(remove_from_set(A,B)) # Output: {1, 4}
Python
jtatman_500k
comment _*_ coding: utf-8 _*_ set __author__ = string wuhao set __date__ = string 2017/8/17 12:12 string 迭代器 迭代是Python最强大的功能之一,是访问集合元素的一种方式。。 迭代器是一个可以记住遍历的位置的对象。 迭代器对象从集合的第一个元素开始访问,直到所有的元素被访问完结束。迭代器只能往前不会后退。 迭代器有两个基本的方法:iter() 和 next()。 字符串,列表或元组对象都可用于创建迭代器 comment import sys comment list1 = [1, 2, 3, 4] comment it = i...
# _*_ coding: utf-8 _*_ __author__ = 'wuhao' __date__ = '2017/8/17 12:12' """ 迭代器 迭代是Python最强大的功能之一,是访问集合元素的一种方式。。 迭代器是一个可以记住遍历的位置的对象。 迭代器对象从集合的第一个元素开始访问,直到所有的元素被访问完结束。迭代器只能往前不会后退。 迭代器有两个基本的方法:iter() 和 next()。 字符串,列表或元组对象都可用于创建迭代器 """ # import sys # list1 = [1, 2, 3, 4] # it = iter(list1) # 创建迭代器对象 # # for x in it: ...
Python
zaydzuhri_stack_edu_python
class Queens begin function __init__ self boardSize count board begin string Objective: To initialize data members of object of type Queens Input Parameters: self (implicit parameter)- object of type Queens boardSize, board,board - numeric Return Value: None set boardSize = boardSize set count = count set board = board...
class Queens(): def __init__(self,boardSize,count,board): ''' Objective: To initialize data members of object of type Queens Input Parameters: self (implicit parameter)- object of type Queens boardSize, board,board - numeric Return Value: None ''...
Python
zaydzuhri_stack_edu_python
function super_punch self enemy_player begin if super_punch_state begin if time * 1000 - initial_punch < 200 begin if facing_right begin set movex = 3 end if not facing_right begin set movex = - 3 end end else begin set movex = 0 set super_punch_state = false end end if super_kick_state begin if time * 1000 - initial_p...
def super_punch(self, enemy_player): if self.super_punch_state: if time.time()*1000-self.initial_punch < 200: if self.facing_right: enemy_player.movex = 3 if not self.facing_right: enemy_player.movex = -3 else: ...
Python
nomic_cornstack_python_v1
import os import csv import shutil import argparse import pandas as pd from skimage import io comment Command line inputs set parser = call ArgumentParser call add_argument string --outputdir help=string Name of the output directory type=str default=string train_reduced call add_argument string --inputdir help=string N...
import os import csv import shutil import argparse import pandas as pd from skimage import io # Command line inputs parser = argparse.ArgumentParser() parser.add_argument("--outputdir", help='Name of the output directory', type=str, default='train_reduced') parser.add_argument("--inputdir", help='Name of the input dir...
Python
zaydzuhri_stack_edu_python
function python_type self begin return SeriesPanelEntity end function
def python_type(self) -> type: return SeriesPanelEntity
Python
nomic_cornstack_python_v1
comment Definition for a binary tree node. comment class TreeNode: comment def __init__(self, val=0, left=None, right=None): comment self.val = val comment self.left = left comment self.right = right class Solution begin comment O(n) space O(n) time function isSymmetric self root begin if root == none begin return true...
# Definition for a binary tree node. # class TreeNode: # def __init__(self, val=0, left=None, right=None): # self.val = val # self.left = left # self.right = right class Solution: # O(n) space O(n) time def isSymmetric(self, root: TreeNode) -> bool: if root == None: ...
Python
zaydzuhri_stack_edu_python
function test_get_dispatched_events self begin set msg_helper = call MessageHelper set worker_helper = call WorkerHelper set dispatched = call get_dispatched_events string fooconn assert equal dispatched list set msg = call make_ack call _add_to_dispatched broker string fooconn.event msg set dispatched = call get_dispa...
def test_get_dispatched_events(self): msg_helper = MessageHelper() worker_helper = WorkerHelper() dispatched = worker_helper.get_dispatched_events('fooconn') self.assertEqual(dispatched, []) msg = msg_helper.make_ack() self._add_to_dispatched( worker_helper.br...
Python
nomic_cornstack_python_v1
comment -*- coding: utf-8 -*- import numpy as np comment for converting voxel grids to meshes (to import objects into simulators) import trimesh comment to know how long it takes for the code to run import time comment to walk through directories, to rename files import os import sys import glob comment to manipulate b...
# -*- coding: utf-8 -*- import numpy as np import trimesh # for converting voxel grids to meshes (to import objects into simulators) import time # to know how long it takes for the code to run import os # to walk through directories, to rename files import sys import glob import binvox_rw # to manipulate binvox files ...
Python
zaydzuhri_stack_edu_python
function get_outdoor_data temp_dir site begin if site == string berk begin set files_od = glob join temp_dir string outdoor string 20*.xlsx end else if site == string bus begin set files_od = glob join temp_dir string outdoor string Busara*.csv end else begin raise call NameError site end set dfs = list for f in files...
def get_outdoor_data(temp_dir,site): if site == 'berk': files_od = glob(join(temp_dir,'outdoor','20*.xlsx')) elif site == 'bus': files_od = glob(join(temp_dir,'outdoor','Busara*.csv')) else: raise NameError(site) dfs = [] for f in files_od: if site == 'berk': ...
Python
nomic_cornstack_python_v1
function is_permitted self store begin if not call is_valid_creator store CreatorID OriginatorID begin return false end return true end function
def is_permitted(self, store): if not self.CreatorType.is_valid_creator(store, self.CreatorID, self.OriginatorID): return False return True
Python
nomic_cornstack_python_v1
function CASE207 self main begin from tests.USECASE.SegmentRouting.SRRouting.dependencies.SRRoutingTest import SRRoutingTest call runTest main test_idx=207 onosNodes=3 dhcp=1 routers=1 ipv4=1 ipv6=0 description=string Test switch failures with IPv4 hosts (including external host configured with route-add command) check...
def CASE207( self, main ): from tests.USECASE.SegmentRouting.SRRouting.dependencies.SRRoutingTest import SRRoutingTest SRRoutingTest.runTest( main, test_idx=207, onosNodes=3, dhcp=1, ...
Python
nomic_cornstack_python_v1
function get_current_user_tasks_route begin set user = current_user if call get_id is not none begin return call get_user_jobs_route id end else begin set response_object = dict string status string error end return call jsonify response_object end function
def get_current_user_tasks_route(): user = current_user if user.get_id() is not None: return get_user_jobs_route(user.id) else: response_object = {'status': 'error'} return jsonify(response_object)
Python
nomic_cornstack_python_v1
function stop self begin Ellipsis end function
def stop(self) -> None: ...
Python
nomic_cornstack_python_v1
function writeSavedDf df begin comment this will work for python 3.6 and above call to_pickle DF_FILENAME protocol=4 end function
def writeSavedDf(df): df.to_pickle(DF_FILENAME, protocol=4) # this will work for python 3.6 and above
Python
nomic_cornstack_python_v1
function seed source output_path config_path skip_image_prefix=true directories=none begin set config = call read_config config_path set engine = config at string ingestion_engine at string engine comment get dictionary that contains [name]["writer"], [name]["schema"], [name]["pandas_dataframe"] set writers_dict = call...
def seed(source, output_path, config_path, skip_image_prefix=True, directories=None): config = cytominer_database.utils.read_config(config_path) engine = config["ingestion_engine"]["engine"] # get dictionary that contains [name]["writer"], [name]["schema"], [name]["pandas_dataframe"] writers_dict = cyt...
Python
nomic_cornstack_python_v1
function insert_execution_data self execution_query_payload begin set query = string INSERT INTO test_execution (guid, execution_start, total_execution_time, username) VALUES (%(guid)s,%(execution_start_time)s, %(total_execution_time)s,%(username)s) call execute_query query call get_params return guid end function
def insert_execution_data(self, execution_query_payload): query = """INSERT INTO test_execution (guid, execution_start, total_execution_time, username) VALUES (%(guid)s,%(execution_start_time)s, %(total_execution_time)s,%(username)s)""" D...
Python
nomic_cornstack_python_v1
function interface self begin if _interface is none begin set expression = WPA_INTERFACE set name = INTERFACE_NAME set command = interface_list_command set _interface = call _match expression name command end return _interface end function
def interface(self): if self._interface is None: expression = expressions.WPA_INTERFACE name = expressions.INTERFACE_NAME command = self.interface_list_command self._interface = self._match(expression, name, ...
Python
nomic_cornstack_python_v1
function get_fixables model from_date=USE_DEFAULT to_date=USE_DEFAULT status=USE_DEFAULT nnow=none begin set nnow = nnow or now if from_date == USE_DEFAULT begin set from_date = call default_from_date nnow=nnow end if to_date == USE_DEFAULT begin set to_date = call date end set query_set = call order_by string -created...
def get_fixables( model, from_date=USE_DEFAULT, to_date=USE_DEFAULT, status=USE_DEFAULT, nnow=None): nnow = nnow or now() if from_date == USE_DEFAULT: from_date = default_from_date(nnow=nnow) if to_date == USE_DEFAULT: to_date = nnow.date() query_set = model.objects.filter( created__gte=be...
Python
nomic_cornstack_python_v1
function find self vport_name=none emulation_host=none **filters begin return find call super IxnSimInterfaceEthernetConfigEmulation self list string topology string deviceGroup string networkGroup string networkTopology string simInterface string simInterfaceEthernetConfig vport_name emulation_host filters end functio...
def find(self, vport_name=None, emulation_host=None, **filters): return super(IxnSimInterfaceEthernetConfigEmulation, self).find(["topology","deviceGroup","networkGroup","networkTopology","simInterface","simInterfaceEthernetConfig"], vport_name, emulation_host, filters)
Python
nomic_cornstack_python_v1
string Given a linked list, determine if it has a cycle in it. Follow up: Can you solve it without using extra space? comment Definition for singly-linked list. comment class ListNode(object): comment def __init__(self, x): comment self.val = x comment self.next = None from utils.utils import ListNode from utils.utils ...
""" Given a linked list, determine if it has a cycle in it. Follow up: Can you solve it without using extra space? """ # Definition for singly-linked list. # class ListNode(object): # def __init__(self, x): # self.val = x # self.next = None from utils.utils import ListNode from utils.utils impor...
Python
zaydzuhri_stack_edu_python
function run_cmd_source_env source_script lines begin with temporary directory as d begin set script = join path d string run.sh with open script string w as f begin print string #!/bin/bash file=f print string set -e file=f print string . { source_script } file=f for line in lines begin print line file=f end end call ...
def run_cmd_source_env(source_script, lines): with tempfile.TemporaryDirectory() as d: script = os.path.join(d, 'run.sh') with open(script, 'w') as f: print('#!/bin/bash', file=f) print('set -e', file=f) print(f'. {source_script}', file=f) for line in ...
Python
nomic_cornstack_python_v1
function _split_threshold self node begin comment define the score to improve upon if n_clusters >= min_leaves and size <= max_leaf_size begin comment split only if min(children scores) > node.score set force_split = false set best_score = score end else begin comment force split: just take the best (even if children a...
def _split_threshold(self, node): # define the score to improve upon if self.n_clusters >= self.min_leaves and node.size <= self.max_leaf_size: # split only if min(children scores) > node.score force_split = False best_score = node.score else: # f...
Python
nomic_cornstack_python_v1
string Ejercicio 4. Escriba un programa que pregunte la edad al usuario, la fecha actual, y si ha cumplido años en el año actual o no, y en base a esa información calcule su año de nacimiento. set edad = integer input string Cuántos años tienes? set fecha = integer input string En qué año estamos? set c = input string ...
'''Ejercicio 4. Escriba un programa que pregunte la edad al usuario, la fecha actual, y si ha cumplido años en el año actual o no, y en base a esa información calcule su año de nacimiento.''' edad=int(input("Cuántos años tienes?")) fecha=int(input("En qué año estamos?")) c=input("Has cumplido los años este año?") ...
Python
zaydzuhri_stack_edu_python
import inflect set p = call engine set allletters = string for i in range 1 1000 + 1 begin set a = call number_to_words i set a = replace a string string set a = replace a string - string set allletters = allletters + a end print length allletters
import inflect p = inflect.engine() allletters = '' for i in range(1, 1000+1): a = p.number_to_words(i) a = a.replace(' ', '') a = a.replace('-', '') allletters += a print(len(allletters))
Python
zaydzuhri_stack_edu_python
import copy from scipy.ndimage.measurements import label import numpy as np function label_3D array begin comment array lengths set tuple Lx Ly Lz = tuple integer shape at 0 integer shape at 1 integer shape at 2 comment find 2 shortest lengths set tuple dx dy dz = tuple 0 0 0 comment these 3 sections create an nx4 arra...
import copy from scipy.ndimage.measurements import label import numpy as np def label_3D(array): Lx, Ly, Lz =int(array.shape[0]) , int(array.shape[1]) , int(array.shape[2]) #array lengths dx,dy,dz = 0, 0 , 0 #find 2 shortest lengths #these 3 sections create an nx4 array of groupings ...
Python
zaydzuhri_stack_edu_python
import matplotlib.pyplot as plt import numpy as np function draw_models models X y begin set cols = list string red string green for model in models begin call draw_model model end for tuple i yi in enumerate unique y begin scatter plt X at tuple y == yi 0 X at tuple y == yi 1 color=cols at i end legend call xlim left=...
import matplotlib.pyplot as plt import numpy as np def draw_models(models, X, y): cols = ['red', 'green'] for model in models: draw_model(model) for i, yi in enumerate(np.unique(y)): plt.scatter(X[y == yi, 0], X[y == yi, 1], color=cols[i]) plt.legend() plt.xlim(left=-2, right=2) ...
Python
zaydzuhri_stack_edu_python
from bs4 import BeautifulSoup from decimal import Decimal import requests , os import tkinter as tk from tkinter import ttk class MainApplication extends Frame begin set font = tuple string arial 11 comment how many numbers after the "." set precision = 4 comment add icon and name to window function setup_apear self be...
from bs4 import BeautifulSoup from decimal import Decimal import requests,os import tkinter as tk from tkinter import ttk class MainApplication(tk.Frame): font = ('arial', 11) precision=4 #how many numbers after the "." # add icon and name to window def setup_apear(self): window.title("Currenc...
Python
zaydzuhri_stack_edu_python
function instantiate_inline_workflow_template self template project_id region request_id=none retry=DEFAULT timeout=none metadata=tuple begin if region is none begin raise call TypeError string missing 1 required keyword argument: 'region' end set metadata = metadata or tuple set client = call get_template_client regi...
def instantiate_inline_workflow_template( self, template: dict | WorkflowTemplate, project_id: str, region: str, request_id: str | None = None, retry: Retry | _MethodDefault = DEFAULT, timeout: float | None = None, metadata: Sequence[tuple[str, str]] = (),...
Python
nomic_cornstack_python_v1
comment Machine Learning Online Class - Exercise 3 | Part 1: One-vs-all comment Instructions comment ------------ comment This file contains code that helps you get started on the comment linear exercise. You will need to complete the following functions comment in this exericse: comment lrCostFunction.m (logistic regr...
## Machine Learning Online Class - Exercise 3 | Part 1: One-vs-all # Instructions # ------------ # # This file contains code that helps you get started on the # linear exercise. You will need to complete the following functions # in this exericse: # # lrCostFunction.m (logistic regression cost function) # ...
Python
zaydzuhri_stack_edu_python
function ask_diff_mode_on_launch self begin return get _data string ask_diff_mode_on_launch end function
def ask_diff_mode_on_launch(self): return self._data.get('ask_diff_mode_on_launch')
Python
nomic_cornstack_python_v1
function gen_batches_triplet data data_corrupted batch_size random=true begin assert batch_size > 0.0 for key in data begin assert shape at 0 == shape at 0 end if batch_size < 1.0 begin set batch_size = max round shape at 0 * batch_size 1 end set index = list range 0 shape at 0 if random begin shuffle random index end ...
def gen_batches_triplet(data, data_corrupted, batch_size, random=True): assert batch_size > 0. for key in data: assert data[key].shape[0] == data_corrupted[key].shape[0] if batch_size < 1.: batch_size = max(round(data[key].shape[0] * batch_size), 1) index = list(range(0, data[key].shape[0])) ...
Python
nomic_cornstack_python_v1
comment USAGE comment python detect-low-contrast-video.py comment import necessary packages from skimage.exposure import is_low_contrast import numpy as np import argparse import imutils import cv2 comment construct argument parser set ap = call ArgumentParser call add_argument string -i string --input type=str default...
# USAGE # python detect-low-contrast-video.py # import necessary packages from skimage.exposure import is_low_contrast import numpy as np import argparse import imutils import cv2 # construct argument parser ap = argparse.ArgumentParser() ap.add_argument("-i", "--input", type=str, default="", help="op...
Python
zaydzuhri_stack_edu_python
comment !/usr/bin/env python import time import sys from cryptography.fernet import Fernet set start_time = time set key = call generate_key set cryptor = call Fernet key set msg = string argv at - 1 set encryptedMsg = call encrypt msg set decryptedMsg = call decrypt encryptedMsg
#!/usr/bin/env python import time import sys from cryptography.fernet import Fernet start_time = time.time() key = Fernet.generate_key() cryptor = Fernet(key) msg = str(sys.argv[-1]) encryptedMsg = cryptor.encrypt(msg) decryptedMsg = cryptor.decrypt(encryptedMsg)
Python
zaydzuhri_stack_edu_python
comment Definition for a binary tree node. comment class TreeNode: comment def __init__(self, val=0, left=None, right=None): comment self.val = val comment self.left = left comment self.right = right class Solution begin function sumEvenGrandparent self root begin function getSum root begin set tuple s children = tuple...
# Definition for a binary tree node. # class TreeNode: # def __init__(self, val=0, left=None, right=None): # self.val = val # self.left = left # self.right = right class Solution: def sumEvenGrandparent(self, root: TreeNode) -> int: def getSum(root): s, children = 0, ...
Python
zaydzuhri_stack_edu_python
import random import sys import numpy as np from MersenneTwister import MT19937 from UniformDistribution import uniform_distribution , plot_unif_dist from BernoulliDistribution import bernoulli_distribution , plot_bern_dist from BinomialDistribution import binomial_distribution , plot_binom_dist from PoissonDistributio...
import random import sys import numpy as np from MersenneTwister import MT19937 from UniformDistribution import uniform_distribution, plot_unif_dist from BernoulliDistribution import bernoulli_distribution, plot_bern_dist from BinomialDistribution import binomial_distribution, plot_binom_dist from PoissonDistribution...
Python
zaydzuhri_stack_edu_python
import pytest class TestDict begin function test_dict_key self begin set d = dictionary comprehension a : a ^ 2 for a in range 7 with raises KeyError begin assert d at string 1 == 2 end end function function test_dict_update self begin set d = dictionary comprehension a : a for a in range 4 set other = dict string dict...
import pytest class TestDict: def test_dict_key(self): d = {a: a ** 2 for a in range(7)} with pytest.raises(KeyError): assert d['1'] == 2 def test_dict_update(self): d = {a: a for a in range(4)} other = {'dict': 1, 'd': 2} d.update(other) assert d =...
Python
zaydzuhri_stack_edu_python
from unittest import TestCase from json import JSONDecodeError from app.lib.nlp import analyzers class ComplexityAnalyzerTestCase extends TestCase begin function setUp self begin pass end function function test_analyze self begin comment Sub-Test 1 set data1 = string set data2 = string set expected = dict string yngv...
from unittest import TestCase from json import JSONDecodeError from app.lib.nlp import analyzers class ComplexityAnalyzerTestCase(TestCase): def setUp(self): pass def test_analyze(self): # Sub-Test 1 data1 = '' data2 = '' expected = {'yngve': 'null', 'frazier': 'nul...
Python
zaydzuhri_stack_edu_python
function __str__ self begin set d = dict set d at string allocation_id_csv = allocation_id_csv set d at string bandwidth = bandwidth set d at string center_frequency = center_frequency set d at string complex = complex set d at string decimation = decimation set d at string enabled = enabled set d at string gain = gai...
def __str__(self): d = {} d["allocation_id_csv"] = self.allocation_id_csv d["bandwidth"] = self.bandwidth d["center_frequency"] = self.center_frequency d["complex"] = self.complex d["decimation"] = self.decimation ...
Python
nomic_cornstack_python_v1
from sys import argv import random from random import randint import codecs import string set f = open string passwordNew.txt encoding=string utf-8 set data = read lines f set target = open string newPasses.txt string w encoding=string utf-8 set d = 0 set u = 0 set l = 0 set s = 0 set chars = string !@#$^&*()_+}{|[]:'\...
from sys import argv import random from random import randint import codecs import string f = open('passwordNew.txt',encoding='utf-8') data = f.readlines() target = open('newPasses.txt','w',encoding='utf-8') d=0 u=0 l=0 s=0 chars= "!@#$^&*()_+}{|[]:'\/\"?><,.~`" multiple = string.ascii_letters + chars for line in da...
Python
zaydzuhri_stack_edu_python
comment Given a two dimenstional array of unequal height and width containing only 0s and 1s. comment Each 0 represents land and 1 represents part of the river. A river consists of any number of 1s that are wither horizontally comment or vertically adjacent. Write a function that returns an array of size of all rivers ...
# Given a two dimenstional array of unequal height and width containing only 0s and 1s. # Each 0 represents land and 1 represents part of the river. A river consists of any number of 1s that are wither horizontally # or vertically adjacent. Write a function that returns an array of size of all rivers represneted in the...
Python
zaydzuhri_stack_edu_python
import cv2 import os import numpy as np import time from time import sleep import copy from multiprocessing.pool import ThreadPool from collections import deque print __version__ print string Esc - End comment define framerate and period of framerate set framerate = 236 set showTime = integer 1 / framerate * 1000 comme...
import cv2 import os import numpy as np import time from time import sleep import copy from multiprocessing.pool import ThreadPool from collections import deque print(cv2.__version__) print('Esc - End') # define framerate and period of framerate framerate = 236 showTime = int((1 / framerate) * 1000) ...
Python
zaydzuhri_stack_edu_python
comment 아래 코드의 의미를 알아본다. comment list1 = [4, 5, 6] comment list1[0] = 10 set list1 = list 4 5 6 set list2 = list1 print string list1==> string address= call id list1 string , value= list1 print string list2==> string address= call id list2 string , value= list2 print string ----------------- print string list1[0]==> st...
############################### # 아래 코드의 의미를 알아본다. # list1 = [4, 5, 6] # list1[0] = 10 ############################### list1 = [4, 5, 6] list2 = list1 print("list1==>", "address=", id(list1), ", value=", list1) print("list2==>", "address=", id(list2), ", value=", list2) print("-----------------") print("list1[0]==>",...
Python
zaydzuhri_stack_edu_python
function timeseries_dataframe begin set ts_index = call date_range string 1/1/2019 periods=1000 freq=string 1H set v1 = list comprehension random integer 1 2000 for i in range 1000 set test_df = call DataFrame dict string v1 v1 index=ts_index return test_df end function
def timeseries_dataframe() -> pd.DataFrame: ts_index = pd.date_range("1/1/2019", periods=1000, freq="1H") v1 = [randint(1, 2000) for i in range(1000)] test_df = pd.DataFrame({"v1": v1}, index=ts_index) return test_df
Python
nomic_cornstack_python_v1
function continuousLoop self begin comment FIXME: the i3 und i4 stuff is not clean, need to clean it up later set i4 = 0 while true begin set startTime = time end end function comment it is important that we keep running even if an error occurred, lets make sure
def continuousLoop(self): # FIXME: the i3 und i4 stuff is not clean, need to clean it up later i4 = 0 while True: startTime = time.time() # it is important that we keep running even if an error occurred, lets make sure
Python
nomic_cornstack_python_v1
function pass_breakups_per_target self pass_breakups_per_target begin set _pass_breakups_per_target = pass_breakups_per_target end function
def pass_breakups_per_target(self, pass_breakups_per_target): self._pass_breakups_per_target = pass_breakups_per_target
Python
nomic_cornstack_python_v1
function addline self line begin comment If the line begins with whitespace, assume it is a continuation of comment the previous line, and append it to the last value read. I'm not comment sure how legit this is but all examples of multi-line headers comment I've seen seem to follow this pattern. It is possible that co...
def addline(self, line): # If the line begins with whitespace, assume it is a continuation of # the previous line, and append it to the last value read. I'm not # sure how legit this is but all examples of multi-line headers # I've seen seem to follow this pattern. It is possible that ...
Python
nomic_cornstack_python_v1
function plot_mpr_topology options tags=none cursor=none begin set options at string cur_src = string topo set options at string prefix = string mpr set locs = options at string locs set colors = call linear space 0 1 101 set circ_max = 5 set line_max = 10 set floor_factor = 2 set floor_skew = - 0.25 set line_min = 1 s...
def plot_mpr_topology(options, tags=None, cursor=None): options['cur_src'] = 'topo' options['prefix'] = "mpr" ################################################################################ locs = options['locs'] colors = options['color2'](pylab.linspace(0, 1, 101)) ############################...
Python
nomic_cornstack_python_v1
function readStringWithArchive path name begin with open path READ_ARCHIVE_TYPE as tar begin for tarinfo in tar begin if name == name begin return read extract file tar name end end end return none end function
def readStringWithArchive(path, name): with tarfile.open(path, READ_ARCHIVE_TYPE) as tar: for tarinfo in tar: if tarinfo.name == name: return tar.extractfile(tarinfo.name).read() return None
Python
nomic_cornstack_python_v1
function onchange_product_tmpl_id self cr uid ids product_tmpl_id product_qty=0 context=none begin set res = dict if product_tmpl_id begin set prod = call browse cr uid product_tmpl_id context=context set res at string value = dict string product_uom id end return res end function
def onchange_product_tmpl_id(self, cr, uid, ids, product_tmpl_id, product_qty=0, context=None): res = {} if product_tmpl_id: prod = self.pool.get('product.template').browse(cr, uid, product_tmpl_id, context=context) res['value'] = { 'product_uom': prod.uom_id.id, ...
Python
nomic_cornstack_python_v1
import pygame import math import random import Particle import VesselRenderer9 class Ship begin set orbit_distance = 0 function __init__ self universe radius begin set name = none set mass = call Mass universe set universe_radius = radius comment Put this at the origin set universe_location = tuple 0 0 set permanent = ...
import pygame import math import random import Particle import VesselRenderer9 class Ship: orbit_distance = 0 def __init__(self, universe, radius): self.name = None self.mass = Particle.Mass(universe) self.mass.universe_radius = radius self.mass.universe_location...
Python
zaydzuhri_stack_edu_python
comment Question: https://www.hackerrank.com/challenges/queens-attack-2/problem set tuple n k = map int split call raw_input set tuple rq cq = map int split call raw_input set obs = list for i in range k begin append obs map int split call raw_input end set cells = list n - rq rq - 1 n - cq cq - 1 min n - rq n - cq mi...
# Question: https://www.hackerrank.com/challenges/queens-attack-2/problem n,k = map(int, raw_input().split()) rq,cq = map(int, raw_input().split()) obs=[] for i in range(k): obs.append((map(int, raw_input().split()))) cells = [n-rq,rq-1,n-cq,cq-1,min(n-rq,n-cq),min(n-cq,rq-1),min(rq-1,cq-1),min(n-rq,cq-1)] for...
Python
zaydzuhri_stack_edu_python
function __init__ self sublattices mcushers mcusher_weights=none rng=none begin call __init__ sublattices rng=rng set _mcushers = list set _weights = list set _p = list set steps = list if mcusher_weights is none begin set mcusher_weights = length mcushers * list 1 end for tuple weight usher in zip mcusher_weights ...
def __init__( self, sublattices, mcushers, mcusher_weights=None, rng=None, ): super().__init__(sublattices, rng=rng) self._mcushers = [] self._weights = [] self._p = [] self.spec.steps = [] if mcusher_weights is None: ...
Python
nomic_cornstack_python_v1
function compute_utility board color begin set tuple dark_color light_color = call get_score board if color == 1 begin return dark_color - light_color end else begin return light_color - dark_color end end function
def compute_utility(board, color): dark_color, light_color = get_score(board) if color == 1: return dark_color - light_color else: return light_color - dark_color
Python
nomic_cornstack_python_v1
function _expand_all_categories self begin set depth = 0 set df = call DataFrame columns=list string url string depth set duplicated = 0 set url_list = list set depth_list = list set html = page_source set soup = call bs html string html.parser set atag = find all soup string a class_=string CategoryTreeLabel for a i...
def _expand_all_categories(self): self.depth = 0 self.df = pd.DataFrame(columns=['url', 'depth']) self.duplicated = 0 url_list = [] depth_list = [] html = self.browser.page_source soup = bs(html, 'html.parser') atag = soup.find_all('a', class_='CategoryTre...
Python
nomic_cornstack_python_v1
function gen_llvm_c_export output underscore libs nm begin with call removing call touch_tempfile prefix=string dumpout suffix=string .txt as dumpout begin comment Get the right regex. set p = _UNDERSCORE_REGEX at underscore with open output string w+t as output_f begin comment For each lib get the LLVM* functions it e...
def gen_llvm_c_export(output, underscore, libs, nm): with removing(touch_tempfile(prefix='dumpout', suffix='.txt')) as dumpout: # Get the right regex. p = _UNDERSCORE_REGEX[underscore] with open(output, 'w+t') as output_f: # For each lib get the LLVM* functions it exports. ...
Python
nomic_cornstack_python_v1
from PIL import Image import numpy as np set a = array open string pangdi.jpg print shape dtype set b = list 255 255 255 - a set im = call fromarray as type b string uint8 save string pangdi2.jpg
from PIL import Image import numpy as np a = np.array(Image.open('pangdi.jpg')) print(a.shape, a.dtype) b = [255, 255, 255] - a im = Image.fromarray(b.astype('uint8')) im.save('pangdi2.jpg')
Python
zaydzuhri_stack_edu_python
import sys function all state begin set states = dict string Oregon string OR ; string Alabama string AL ; string New Jersey string NJ ; string Colorado string CO set capital_cities = dict string OR string Salem ; string AL string Montgomery ; string NJ string Trenton ; string CO string Denver set name = string if sta...
import sys def all(state): states = { "Oregon" : "OR", "Alabama" : "AL", "New Jersey": "NJ", "Colorado" : "CO" } capital_cities = { "OR": "Salem", "AL": "Montgomery", "NJ": "Trenton", "CO": "Denver" } name = '' if state in capital_cities.values(): for x in capital_cities: if state == capital_cities[...
Python
zaydzuhri_stack_edu_python