code
stringlengths
10
2.58M
original_code
stringlengths
3
3.18M
original_language
stringclasses
1 value
source
stringclasses
7 values
comment 따라하며 배우는 파이썬과 데이터과학(생능출판사 2020) comment 8.2 딕셔너리의 기능을 알아보자, 201쪽 set person_dic = dict string Name string 홍길동 ; string Age 27 ; string Class string 초급 comment 딕셔너리의 'Name'이라는 키로 값을 조회함 print person_dic at string Name comment 딕셔너리의 'Age'이라는 키로 값을 조회함 print person_dic at string Age
# # 따라하며 배우는 파이썬과 데이터과학(생능출판사 2020) # 8.2 딕셔너리의 기능을 알아보자, 201쪽 # person_dic = {'Name': '홍길동', 'Age': 27, 'Class': '초급'} print(person_dic['Name']) # 딕셔너리의 'Name'이라는 키로 값을 조회함 print(person_dic['Age']) # 딕셔너리의 'Age'이라는 키로 값을 조회함
Python
zaydzuhri_stack_edu_python
from lib.equation import Equation try begin set equation = parse Equation input string Enter a chemical equation to balance: end except Exception as error begin print string ERROR: { msg } call quit end call balance assert call is_balanced msg string Could not balance: { equation } print equation
from lib.equation import Equation try: equation = Equation.parse(input("Enter a chemical equation to balance: ")) except Exception as error: print(f"ERROR: {error.msg}") quit() equation.balance() assert equation.is_balanced(), f"Could not balance: {equation}" print(equation)
Python
zaydzuhri_stack_edu_python
function three_layer_convnet x params begin set tuple conv_w1 conv_b1 conv_w2 conv_b2 fc_w fc_b = params set scores = none comment Implement the forward pass for the three-layer ConvNet. # set conv1 = conv 2d x conv_w1 conv_b1 stride=1 padding=2 set relu1 = relu conv1 set conv2 = conv 2d relu1 conv_w2 conv_b2 stride=1 ...
def three_layer_convnet(x, params): conv_w1, conv_b1, conv_w2, conv_b2, fc_w, fc_b = params scores = None ################################################################################ # Implement the forward pass for the three-layer ConvNet. # ######################################...
Python
nomic_cornstack_python_v1
comment -*- coding: utf-8 -*- import dbwrite from kivy.app import App from kivy.uix.screenmanager import ScreenManager , Screen from kivy.lang import Builder from kivy.uix.image import Image from kivy.uix.behaviors import ButtonBehavior from kivy.uix.screenmanager import NoTransition from kivy.config import Config set ...
# -*- coding: utf-8 -*- import dbwrite from kivy.app import App from kivy.uix.screenmanager import ScreenManager, Screen from kivy.lang import Builder from kivy.uix.image import Image from kivy.uix.behaviors import ButtonBehavior from kivy.uix.screenmanager import NoTransition from kivy.config import Config Config.set...
Python
zaydzuhri_stack_edu_python
function to_str self begin return call pformat call to_dict end function
def to_str(self): return pprint.pformat(self.to_dict())
Python
nomic_cornstack_python_v1
function write_settings settings_path begin set priority = list set host = if expression xnat_host then string %s % xnat_host else string if p_order begin set priority = split p_order string , set p_mod = string { set p_proc = string { for tuple ind project in enumerate priority begin if ind == 0 begin set p_mod = p_...
def write_settings(settings_path): priority = [] host = '%s' % args.xnat_host if args.xnat_host else '' if args.p_order: priority = args.p_order.split(",") p_mod = '{' p_proc = '{' for ind, project in enumerate(priority): if ind == 0: p_mod += '"%s...
Python
nomic_cornstack_python_v1
function convert_to_csv path begin set directory = directory name path path set file_name_w_ext = base name path path set file_name = call splitext file_name_w_ext at 0 set csv_file_path = join path directory file_name + string .csv set data_xls = call read_excel path string Data-Residential Composition to csv data_xls...
def convert_to_csv(path): directory = os.path.dirname(path) file_name_w_ext = os.path.basename(path) file_name = os.path.splitext(file_name_w_ext)[0] csv_file_path = os.path.join(directory, file_name + ".csv") data_xls = pd.read_excel(path, 'Data-Residential Composition') data_xls.to_csv(cs...
Python
nomic_cornstack_python_v1
comment course_master.csvからコース番号を入力することでコースの情報を取り込んで辞書に入れる import csv set file_path = string course_master.csv comment csvを辞書に変換して計算をするクラスを作成 class course_info begin function __init__ self name begin set name = name end function function course_name self begin with open file_path newline=string encoding=string utf-8 a...
# course_master.csvからコース番号を入力することでコースの情報を取り込んで辞書に入れる import csv file_path = "course_master.csv" # csvを辞書に変換して計算をするクラスを作成 class course_info: def __init__(self,name): self.name = name def course_name(self): with open(file_path, newline='', encoding='utf-8') as csvfile: reader = csv...
Python
zaydzuhri_stack_edu_python
function set self key value begin set k = call hash_function key set item = item key value comment Check for hash presence if table at k begin comment Check for specific presence if key == key begin set value = value end else begin comment Handle collision call double_hash set k = call hash_function key append table at...
def set(self, key, value): k = self.hash_function(key) self.item = Item(key, value) if self.table[k]: # Check for hash presence if self.table[k][0].key == key: # Check for specific presence self.table[k][0].value = value else: ...
Python
nomic_cornstack_python_v1
function is_leap_year year begin if year % 4 == 0 and year % 100 != 0 or year % 400 == 0 begin return true end return false end function
def is_leap_year(year): if year%4==0 and (year%100!=0 or year%400==0): return True return False
Python
zaydzuhri_stack_edu_python
function append self item begin set validated_value = call get_validated_object item if validated_value is not none begin append __modified_data__ validated_value end end function
def append(self, item): validated_value = self.get_validated_object(item) if validated_value is not None: self.__modified_data__.append(validated_value)
Python
nomic_cornstack_python_v1
function _parse_subroutine_type self die begin set prototyped_attribute = get attributes string DW_AT_prototyped set prototyped = if expression prototyped_attribute is none then string else call _get_value_by_attribute die prototyped_attribute set subroutine_type = call Subroutine prototyped set attribute subroutine_t...
def _parse_subroutine_type(self, die): prototyped_attribute = die.attributes.get("DW_AT_prototyped") prototyped = "" if prototyped_attribute is None else \ self._get_value_by_attribute(die, prototyped_attribute) subroutine_type = Subroutine(prototyped) setattr(subroutine_type...
Python
nomic_cornstack_python_v1
function getSuccessor self state action begin set successor = call generateSuccessor index action set pos = call getPosition if pos != call nearestPoint pos begin comment Only half a grid position was covered set successor = call generateSuccessor index action end return successor end function
def getSuccessor(self, state, action): successor = state.generateSuccessor(self.index, action) pos = successor.getAgentState(self.index).getPosition() if pos != nearestPoint(pos): # Only half a grid position was covered successor = successor.generateSuccessor(self.index, ...
Python
nomic_cornstack_python_v1
function updateInfo self info begin if not is directory path loc and subs == list begin call addFileToInfos tuple info end else begin for sub in subs begin call updateInfo info end end end function
def updateInfo(self, info): if not os.path.isdir(self.loc) and self.subs == []: self.addFileToInfos((info,)) else: for sub in self.subs: sub.updateInfo(info)
Python
nomic_cornstack_python_v1
function name self begin return get pulumi self string name end function
def name(self) -> pulumi.Input[str]: return pulumi.get(self, "name")
Python
nomic_cornstack_python_v1
from __future__ import print_function , division from keras.models import load_model import numpy as np from GAN import fid class CGAN begin function __init__ self load_path num_classes=10 latent_dim=100 gen_save_step=1000 begin comment Input shape set img_rows = 32 set img_cols = 32 set channels = 1 set img_shape = tu...
from __future__ import print_function, division from keras.models import load_model import numpy as np from GAN import fid class CGAN(): def __init__(self, load_path, num_classes=10, latent_dim=100, gen_save_step=1000): # Input shape self.img_rows = 32 self.img_cols = 32 self.chann...
Python
zaydzuhri_stack_edu_python
function call self vm begin for opcode in global_code begin execute opcode vm self end end function
def call(self, vm): for opcode in self.global_code: opcode.execute(vm, self)
Python
nomic_cornstack_python_v1
comment ! /usr/bin/env python comment -*- coding: utf-8 -*- comment __author__ = "Bonnie Li" comment Email: bonnie922713@126.com comment Date: 6/14/18 function print_log msg log_type=string info begin string 写个通用的打印log 的程序 if log_type == string info begin print string %s % msg end else if log_type == string ...
#! /usr/bin/env python # -*- coding: utf-8 -*- # __author__ = "Bonnie Li" # Email: bonnie922713@126.com # Date: 6/14/18 def print_log(msg, log_type='info'): """写个通用的打印log 的程序""" if log_type == 'info': print('\033[32;1m%s\033[0m' % msg) elif log_type == 'error': print('\033[31;1m%s\033[0m' ...
Python
zaydzuhri_stack_edu_python
import click import itertools decorator call command decorator call option string --f type=call File default=string day1.txt function cli f begin set all_nums_str = read f set all_nums = list comprehension integer i for i in split all_nums_str string set all_combos = product all_nums all_nums with call progressbar all_...
import click import itertools @click.command() @click.option('--f', type=click.File(), default='day1.txt') def cli(f): all_nums_str = f.read() all_nums = [int(i) for i in all_nums_str.split('\n')] all_combos = itertools.product(all_nums, all_nums) with click.progressbar(all_combos, label='part1') as pb...
Python
zaydzuhri_stack_edu_python
function kruskal Grafo diferencia begin set edges = list comment print(diferencia,"la diferencia" ) comment collect the edges in G for i in range length Grafo begin for tuple v w in Grafo at i begin if w != - 1 begin append edges tuple i v w end end end comment sort the edges in ascending order w.r.t weights in the edg...
def kruskal(Grafo,diferencia): edges = list() #print(diferencia,"la diferencia" ) for i in range(len(Grafo)): # collect the edges in G for v,w in Grafo[i]: if (w!=-1): edges.append((i,v,w)) # sort the edges in ascending order w.r.t weights in the edges edges.sort(key=lambda x: ...
Python
nomic_cornstack_python_v1
function test_create_source tmpdir begin set one = make directory tmpdir string one set two = make directory tmpdir string two set three = make directory tmpdir string three set four = make directory two string four set one_ap = format string {} {} strpath string ../three write join one string settings.ini format PATHS...
def test_create_source(tmpdir): one = tmpdir.mkdir('one') two = tmpdir.mkdir('two') three = tmpdir.mkdir('three') four = two.mkdir('four') one_ap = '\n {}\n {}'.format(two.strpath, '../three') one.join('settings.ini').write(PATHS_FRAGMENT_TEMPLATE.format(one_ap)) one.join('one').write...
Python
nomic_cornstack_python_v1
function create_dense_model only_digits=false hidden_units=200 begin set num_classes = if expression only_digits then 10 else 62 function forward_pass batch begin set network = sequential list flatten hk linear hidden_units relu linear hidden_units relu linear num_classes return call network batch at string x end funct...
def create_dense_model(only_digits: bool = False, hidden_units: int = 200) -> models.Model: num_classes = 10 if only_digits else 62 def forward_pass(batch): network = hk.Sequential([ hk.Flatten(), hk.Linear(hidden_units), jax.nn.relu, hk.Linear(hidden_unit...
Python
nomic_cornstack_python_v1
function remove_vowels string begin comment List of vowels set vowels = string aeiouAEIOU comment Loop through each character in the string for char in string begin comment Check if the character is a vowel if char in vowels begin comment Remove the vowel from the string set string = replace string char string end end ...
def remove_vowels(string): vowels = 'aeiouAEIOU' # List of vowels # Loop through each character in the string for char in string: # Check if the character is a vowel if char in vowels: # Remove the vowel from the string string = string.replace(char, '') ...
Python
jtatman_500k
function loadSavedModel folder spark_session begin from sparknlp.internal import _T5Loader set jModel = _java_obj return call T5Transformer java_model=jModel end function
def loadSavedModel(folder, spark_session): from sparknlp.internal import _T5Loader jModel = _T5Loader(folder, spark_session._jsparkSession)._java_obj return T5Transformer(java_model=jModel)
Python
nomic_cornstack_python_v1
comment Practica1 Ordenacion topologica de un grafo G. comment Cristhian Carmona Torres comment README! Ingresar fichero con extension. Ex: nombreFichero.txt import networkx as nx function llegir_graf begin string lee el grafo de un fichero de texto global Grafo set Grafo = call Graph set nom = call raw_input string Do...
# Practica1 Ordenacion topologica de un grafo G. # Cristhian Carmona Torres # README! Ingresar fichero con extension. Ex: nombreFichero.txt import networkx as nx def llegir_graf(): '''lee el grafo de un fichero de texto''' global Grafo Grafo = nx.Graph() nom = raw_input("Doneu el nom del graf: ") ...
Python
zaydzuhri_stack_edu_python
class Solution begin string @param S: a string @return: a list of integers representing the size of these parts function partitionLabels self S begin comment first get the counter of chars in S comment loop over S, char_set.add(first char) comment substract count of char and add char to set until the set is null commen...
class Solution: """ @param S: a string @return: a list of integers representing the size of these parts """ def partitionLabels(self, S): # first get the counter of chars in S # loop over S, char_set.add(first char) # substract count of char and add char to set until the set ...
Python
zaydzuhri_stack_edu_python
comment -*- coding: utf-8 -*- import math set a = integer input string Digite o número 1: set b = integer input string Digite o número 2: set c = integer input string Digite o número 3: set d = integer input string Digite o número 4: set e = integer input string Digite o número 5: comment CONTINUE... if a < b and c and...
# -*- coding: utf-8 -*- import math a = int(input('Digite o número 1: ')) b = int(input('Digite o número 2: ')) c = int(input('Digite o número 3: ')) d = int(input('Digite o número 4: ')) e = int(input('Digite o número 5: ')) #CONTINUE... if a<b and c and d and e: print(a) elif b<a and c and d and e: print(b...
Python
zaydzuhri_stack_edu_python
comment use deque as stack from collections import deque set q = deque append q string first append q string second append q string third print q print pop q print pop q print pop q print q
# use deque as stack from collections import deque q = deque() q.append('first') q.append('second') q.append('third') print(q) print(q.pop()) print(q.pop()) print(q.pop()) print(q)
Python
zaydzuhri_stack_edu_python
function flag_video self video_id flag_reason=string begin print string flag_video needs implementation end function
def flag_video(self, video_id, flag_reason=""): print("flag_video needs implementation")
Python
nomic_cornstack_python_v1
comment Enter your code here from functools import reduce function collapse L begin set reducer = lambda x -> if expression is instance x list then call collapse x else x return reduce lambda x y -> call reducer x + string + call reducer y L end function
# Enter your code here from functools import reduce def collapse(L): reducer = lambda x: collapse(x) if isinstance(x, list) else x return reduce(lambda x,y: reducer(x) + " " + reducer(y), L)
Python
zaydzuhri_stack_edu_python
function serialize_numpy self buff numpy begin try begin set _x = self write buff call pack seq secs nsecs set _x = frame_id set length = length _x if python3 or type _x == unicode begin set _x = encode _x string utf-8 set length = length _x end if python3 begin write buff call pack string <I%sB % length length *_x end...
def serialize_numpy(self, buff, numpy): try: _x = self buff.write(_struct_3I.pack(_x.pose.header.seq, _x.pose.header.stamp.secs, _x.pose.header.stamp.nsecs)) _x = self.pose.header.frame_id length = len(_x) if python3 or type(_x) == unicode: _x = _x.encode('utf-8') lengt...
Python
nomic_cornstack_python_v1
import pandas as pd import os import ast set negative_examples_dir = string /path/to/9_FINAL/data/negative_examples/ set negative_examples_files = list directory negative_examples_dir function extractPIDs x begin comment get the pids in the array of dictionaries and append if not already existing set pids = list for a...
import pandas as pd import os import ast negative_examples_dir = '/path/to/9_FINAL/data/negative_examples/' negative_examples_files = os.listdir(negative_examples_dir) def extractPIDs(x): # get the pids in the array of dictionaries and append if not already existing pids = [] for array in x: elem...
Python
zaydzuhri_stack_edu_python
function type self begin return container at string type end function
def type(self): return self.container['type']
Python
nomic_cornstack_python_v1
string View classes to transform reports/tables into readable form. import sys from bnk.tables import Table class NativeView extends object begin string A simple view of a table, mainly useful for debugging and diffing. The table is transformed into strings, one cell per line with the cell location displayed along with...
"""View classes to transform reports/tables into readable form.""" import sys from bnk.tables import Table class NativeView(object): """A simple view of a table, mainly useful for debugging and diffing. The table is transformed into strings, one cell per line with the cell location displayed along with ...
Python
zaydzuhri_stack_edu_python
function pogo_path x y begin set path = string if x > 0 begin set path = path + string WE * x end else if x < 0 begin set path = path + string EW * - x end if y > 0 begin set path = path + string SN * y end else if y < 0 begin set path = path + string NS * - y end return path end function set cases = integer call raw_...
def pogo_path(x, y): path = '' if x > 0: path += 'WE' * x elif x < 0: path += 'EW' * -x if y > 0: path += 'SN' * y elif y < 0: path += 'NS' * -y return path cases = int(raw_input()) for case in range(cases): x, y = map(int, raw_input().split()) path = pogo_path(x, y)
Python
zaydzuhri_stack_edu_python
comment !/usr/bin/python comment -*- coding: utf-8 -*- comment Start Gateway: start gw comment Restart Gateway: restart gw comment Stop Gateway: stop gw import os import json if __name__ == string __main__ begin set ruleslist = dict string nodes list set abspath = get current directory set file = open abspath + string...
#!/usr/bin/python # -*- coding: utf-8 -*- # Start Gateway: start gw # Restart Gateway: restart gw # Stop Gateway: stop gw import os import json if __name__ == '__main__': ruleslist = {"nodes":[]} abspath = os.getcwd() file = open(abspath + "/firewall_conf.json", "a+") sizefile = os.path.getsize(abspa...
Python
zaydzuhri_stack_edu_python
function solution n begin set count = 1 set nature_list = list range n // 2 + 2 set _sum = 0 set start = 0 for tuple i num in enumerate nature_list begin set _sum = _sum + i if _sum == n begin set count = count + 1 end else begin while _sum > n begin set _sum = _sum - nature_list at start set start = start + 1 end if _...
def solution(n): count = 1 nature_list = list(range(n // 2 + 2)) _sum = 0 start = 0 for i, num in enumerate(nature_list): _sum += i if _sum == n: count += 1 else: while _sum > n: _sum -= nature_list[start] start += 1 ...
Python
zaydzuhri_stack_edu_python
if 0 < integer s at slice : 2 : <= 12 and 0 < integer s at slice 2 : : <= 12 begin print string AMBIGUOUS end else if 0 < integer s at slice : 2 : <= 12 and integer s at slice 2 : : >= 12 begin print string MMYY end else if 0 < integer s at slice : 2 : < 12 and integer s at slice 2 : : == 0 begin print string MMY...
if 0 < int(s[:2]) <= 12 and 0 < int(s[2:]) <= 12: print('AMBIGUOUS') elif 0 < int(s[:2]) <= 12 and int(s[2:]) >= 12: print('MMYY') elif 0 < int(s[:2]) < 12 and int(s[2:]) == 0: print('MMYY') elif int(s[:2]) >= 12 > 0 and 0 < int(s[2:]) <= 12: print('YYMM') elif int(s[:2]) == 0 and 0 < int(s[2:]) <= 12: ...
Python
zaydzuhri_stack_edu_python
function setSortingOrder self text begin call setSort call fieldIndex title_to_field at text AscendingOrder select model end function
def setSortingOrder(self, text): self.model.setSort(self.model.fieldIndex(self.title_to_field[text]), Qt.AscendingOrder) self.model.select()
Python
nomic_cornstack_python_v1
function __init__ self finger_urdf_path tip_link_names begin set urdf_path = string /opt/blmc_ei/src/robot_properties_fingers/urdf/pro/trifingerpro.urdf set tip_link_names = list string finger_tip_link_0 string finger_tip_link_120 string finger_tip_link_240 set robot_model = call buildModelFromUrdf finger_urdf_path set...
def __init__( self, finger_urdf_path: str, tip_link_names: typing.Iterable[str] ): self.urdf_path = '/opt/blmc_ei/src/robot_properties_fingers/urdf/pro/trifingerpro.urdf' self.tip_link_names = [ "finger_tip_link_0", "finger_tip_link_120", "finger_tip_link_...
Python
nomic_cornstack_python_v1
async function spaced self ctx text begin await call send strip replace text string string end function
async def spaced(self, ctx: DogbotContext, *, text: clean_content): await ctx.send(text.replace('', ' ').strip())
Python
nomic_cornstack_python_v1
import random set n = 10 set my_array = list function generate_an_array n begin for i in range n begin set s = random integer 0 100 append my_array s end return my_array end function print my_array for i in range length my_array - 1 0 - 1 begin for j in range i begin if my_array at j > my_array at j + 1 begin set t = ...
import random n=10 my_array=[] def generate_an_array(n): for i in range(n): s=random.randint(0,100) my_array.append(s) return my_array print(my_array) for i in range(len(my_array)-1,0,-1): for j in range(i): if(my_array[j]>my_array[j+1]): t=my_array[j] my_array[j]=my_array...
Python
zaydzuhri_stack_edu_python
function set_ssl_addr self addr begin set t_ssl_addresses at call get_ident = addr end function
def set_ssl_addr(self, addr): Server.t_ssl_addresses[threading.get_ident()] = addr
Python
nomic_cornstack_python_v1
function add_random_objects scene_struct num_objects args camera begin comment Load the property file with open properties_json string r as f begin set properties = load json f set color_name_to_rgba = dict for tuple name rgb in items properties at string colors begin set rgba = list comprehension decimal c / 255.0 fo...
def add_random_objects(scene_struct, num_objects, args, camera): # Load the property file with open(args.properties_json, 'r') as f: properties = json.load(f) color_name_to_rgba = {} for name, rgb in properties['colors'].items(): rgba = [float(c) / 255.0 for c in rgb] + [1.0...
Python
nomic_cornstack_python_v1
function ingress_class_name self value begin set _properties at string ingressClassName = value end function
def ingress_class_name(self, value: str): self._properties["ingressClassName"] = value
Python
nomic_cornstack_python_v1
import torch import torch.nn as nn import torchvision.models as models class EncoderCNN extends Module begin function __init__ self embed_size begin call __init__ set resnet = call resnet50 pretrained=true for param in parameters resnet begin call requires_grad_ false end set modules = list call children at slice : - ...
import torch import torch.nn as nn import torchvision.models as models class EncoderCNN(nn.Module): def __init__(self, embed_size): super(EncoderCNN, self).__init__() resnet = models.resnet50(pretrained=True) for param in resnet.parameters(): param.requires_grad_(False) ...
Python
zaydzuhri_stack_edu_python
function lsncuricmpsessions self begin try begin return _lsncuricmpsessions end except Exception as e begin raise e end end function
def lsncuricmpsessions(self) : try : return self._lsncuricmpsessions except Exception as e: raise e
Python
nomic_cornstack_python_v1
string 3 layer neural network (can be used to compute XOR ) *input layer has 2 input neurons (plus one for bias) *hidden layer has 2 neurons (plus one for bias) *output layer has one neuron note: number of layers can be changed depending on the inputs. import numpy as np function sigmoid x begin return 1 / 1 + exp - x ...
''' 3 layer neural network (can be used to compute XOR ) *input layer has 2 input neurons (plus one for bias) *hidden layer has 2 neurons (plus one for bias) *output layer has one neuron note: number of layers can be changed depending on the inputs. ''' import numpy as np def sigmoid(x): return (1/(1 + n...
Python
zaydzuhri_stack_edu_python
function add_metadata_for_subject rdf_graph subject_uri namespaces nidm_obj begin comment Cycle through remaining metadata and add attributes for tuple predicate objects in call predicate_objects subject=subject_uri begin comment if find qualified association if predicate == call URIRef PROV at string qualifiedAssociat...
def add_metadata_for_subject (rdf_graph,subject_uri,namespaces,nidm_obj): #Cycle through remaining metadata and add attributes for predicate, objects in rdf_graph.predicate_objects(subject=subject_uri): #if find qualified association if predicate == URIRef(Constants.PROV['qualifiedAssociation'])...
Python
nomic_cornstack_python_v1
function solve self env begin raise call SkipTest string This is an abstract test case end function
def solve(self, env) -> Callable[[MapfEnv, Dict], ValueFunctionPolicy]: raise unittest.SkipTest("This is an abstract test case")
Python
nomic_cornstack_python_v1
comment py:UR.is_facing_north function is_facing_north self begin return call is_facing_north_ body end function
def is_facing_north(self): #py:UR.is_facing_north return RUR._UR.is_facing_north_(self.body)
Python
nomic_cornstack_python_v1
function test_title_with_latex_backslash begin comment note the raw string set latex_text = string $\lim_t v^{A}$ with figure string test_plot file_identifier=string figtest as fig begin plot XX_test_linspace label=latex_text end set fcontent = call get_gnuplot_file_content assert string title "%s" % replace latex_text...
def test_title_with_latex_backslash(): # note the raw string latex_text = r"$\lim_t v^{A}$" with autogpy.Figure("test_plot", file_identifier="figtest") as fig: fig.plot(XX_test_linspace, label=latex_text) fcontent = fig.get_gnuplot_file_content() assert 'title "%s"' % latex_text.replace("...
Python
nomic_cornstack_python_v1
import requests from pprint import pprint set API_KEY = string 595695c3 set URL = string http://www.omdbapi.com/?apikey= set titulo = string The Matrix set busqueda = URL + API_KEY + string &t= + titulo set respuesta = get requests busqueda set dic_peli = json respuesta comment pprint(dic_peli) print dic_peli at string...
import requests from pprint import pprint API_KEY ="595695c3" URL= "http://www.omdbapi.com/?apikey=" titulo="The Matrix" busqueda = URL + API_KEY+ "&t=" + titulo respuesta = requests.get(busqueda) dic_peli = respuesta.json() #pprint(dic_peli) print(dic_peli["Year"]) #ej1. consultar el api de OMDB e pri,ir el nombre ...
Python
zaydzuhri_stack_edu_python
class Animal begin function __init__ self name age type begin set name = name set age = age set type = type end function function validate_age self begin if not is instance age int or age < 1 or age > 20 begin return false end return true end function function validate_name self begin if not is instance name str or not...
class Animal: def __init__(self, name, age, type): self.name = name self.age = age self.type = type def validate_age(self): if not isinstance(self.age, int) or self.age < 1 or self.age > 20: return False return True def validate_name(self): if no...
Python
greatdarklord_python_dataset
string Módulo collection = Named Tuple Collections = High-perfomance Container Datetypes from collections import namedtuple set cachorro = named tuple string cachorro list string idade string raça string nome comment cachorro = namedtuple('cachorro', 'idade raça nome') comment ou cachorro = namedtuple('cachorro', 'idad...
""" Módulo collection = Named Tuple Collections = High-perfomance Container Datetypes """ from collections import namedtuple cachorro = namedtuple('cachorro', ['idade', 'raça', 'nome']) #cachorro = namedtuple('cachorro', 'idade raça nome') #ou cachorro = namedtuple('cachorro', 'idade, raça, nome') ray = cac...
Python
zaydzuhri_stack_edu_python
import tkinter import re set box = call Tk title box string 计算器 call geometry string 300x300+400+100 call resizable false false function button btn begin comment 获取文本框中的内容 set content = get contentVar comment 如果已有内容是以小数点开头的,在前面加0 if starts with content string . begin comment 字符串可以直接用+来增加字符 set content = string 0 + cont...
import tkinter import re box = tkinter.Tk() box.title('计算器') box.geometry('300x300+400+100') box.resizable(False, False) def button(btn): content = contentVar.get() # 获取文本框中的内容 # 如果已有内容是以小数点开头的,在前面加0 if content.startswith('.'): content = '0' + content # 字符串可以直接用+来增加字符 # 根据不同的按钮作出不同的反应 if...
Python
zaydzuhri_stack_edu_python
comment Nick Abbott comment 10/2/19 import os import sys import json import spotipy import webbrowser import spotipy.util as util from json.decoder import JSONDecodeError comment print(json.dumps(VARIABLE, sort_keys = True, indent = 4)) set userID = string nabbott335 set id = true set secret = true set url = string htt...
#Nick Abbott #10/2/19 import os import sys import json import spotipy import webbrowser import spotipy.util as util from json.decoder import JSONDecodeError #print(json.dumps(VARIABLE, sort_keys = True, indent = 4)) userID = 'nabbott335' id = True secret = True url = 'http://google.com/' #Read access to user's priv...
Python
zaydzuhri_stack_edu_python
function group_population self population begin return population end function
def group_population(self, population): return population
Python
nomic_cornstack_python_v1
comment ! /usr/bin/env python comment -*- coding:utf-8 -*- class Solution extends object begin function fractionToDecimal self numerator denominator begin string :type numerator: int :type denominator: int :rtype: str set is_fu = false if numerator < 0 and denominator > 0 or numerator > 0 and denominator < 0 begin set ...
#! /usr/bin/env python # -*- coding:utf-8 -*- class Solution(object): def fractionToDecimal(self,numerator,denominator): """ :type numerator: int :type denominator: int :rtype: str """ is_fu=False if (numerator<0 and denominator>0) or (numerator>0 and denominator<0): is_fu=True if numerator<0: ...
Python
zaydzuhri_stack_edu_python
function movefiles files destdir confirm=true verbose=true copy=true begin if not is directory path destdir begin make directory os destdir end for file in files begin set perform_action = string y end end function
def movefiles(files, destdir, confirm=True, verbose=True, copy=True): if not os.path.isdir(destdir): os.mkdir(destdir) for file in files: perform_action = 'y'
Python
nomic_cornstack_python_v1
comment !/usr/bin/env python comment -*- coding:utf-8 -*- comment Licensed under the Open Software License ("OSL") v. 3.0 (the "License"); comment you may not use this file except in compliance with the License. comment You may obtain a copy of the License at comment http://www.opensource.org/licenses/osl-3.0.php comme...
#!/usr/bin/env python #-*- coding:utf-8 -*- # Licensed under the Open Software License ("OSL") v. 3.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # http://www.opensource.org/licenses/osl-3.0.php # Unless required by applicable law ...
Python
zaydzuhri_stack_edu_python
from flask import jsonify from flask_restful import Resource class HelloWorld extends Resource begin function get self name age begin return call jsonify data=string Hello World { name } , your age is { age } end function function user_details self name age begin return call jsonify data=string Hello World { name } , y...
from flask import jsonify from flask_restful import Resource class HelloWorld(Resource): def get(self, name, age): return jsonify(data=f"Hello World {name}, your age is {age}") def user_details(self, name, age): return jsonify(data=f"Hello World {name}, your age is {age}") def post(self)...
Python
zaydzuhri_stack_edu_python
string This file tests the TC100 error: >> Missing 'from __future__ import annotations' import The idea is that we should raise one of these errors if a file contains any type-checking imports and one is missing. One thing to note: futures imports should always be at the top of a file, so we only need to check one line...
""" This file tests the TC100 error: >> Missing 'from __future__ import annotations' import The idea is that we should raise one of these errors if a file contains any type-checking imports and one is missing. One thing to note: futures imports should always be at the top of a file, so we only need to check one ...
Python
zaydzuhri_stack_edu_python
function remove_handler self callback=none begin comment remove all if not callback begin set registered_handlers = list return end if callback in registered_handlers begin remove registered_handlers callback end end function
def remove_handler(self, callback=None): if not callback: # remove all self.registered_handlers = [] return if callback in self.registered_handlers: self.registered_handlers.remove(callback)
Python
nomic_cornstack_python_v1
function sqrDistForCoords x1 x2 y1 y2 begin return square root power x1 - x2 2 + power y1 - y2 2 end function
def sqrDistForCoords(x1, x2, y1, y2): return sqrt(pow(x1 - x2, 2) + pow(y1 - y2, 2))
Python
nomic_cornstack_python_v1
function nominify_css_from_files request filenames begin return call nominify_from_files request filenames end function
def nominify_css_from_files(request, filenames): return nominify_from_files(request, filenames)
Python
nomic_cornstack_python_v1
import numpy as np from skopt import gp_minimize function f x begin set y = x at 0 - 1 ^ 2 + x at 1 ^ 2 print x y return y end function comment return (np.sin(5 * x[0]) * (1 - np.tanh(x[0] ** 2)) * comment np.random.randn() * 0.1) set res = call gp_minimize func=f dimensions=list tuple - 2.0 2.0 tuple - 2.0 2.0 n_calls...
import numpy as np from skopt import gp_minimize def f(x): y = ((x[0]-1)**2 + x[1]**2) print(x, y) return y # return (np.sin(5 * x[0]) * (1 - np.tanh(x[0] ** 2)) * # np.random.randn() * 0.1) res = gp_minimize(func=f, dimensions=[(-2.0, 2.0), (-2.0, 2.0)], n_calls=40) print(res)
Python
zaydzuhri_stack_edu_python
function get_action self q_values iteration training valid_idxs begin set epsilon = call get_epsilon iteration=iteration training=training try begin set epsilon = call read_value end except AttributeError begin pass end comment Probability of choosing random action if random < epsilon begin set action = random choice v...
def get_action(self, q_values, iteration, training, valid_idxs): epsilon = self.get_epsilon(iteration=iteration, training=training) try: epsilon = epsilon.read_value() except AttributeError: pass # Probability of choosing random action if np.ra...
Python
nomic_cornstack_python_v1
function get_series_by_name self series_name begin try begin return tuple call search_series name=series_name none end except TVDBRequestException as err begin exception string search for series %s failed series_name return tuple none call _as_str err end end function
def get_series_by_name(self, series_name): try: return self.api.search_series(name=series_name), None except exceptions.TVDBRequestException as err: LOG.exception('search for series %s failed', series_name) return None, _as_str(err)
Python
nomic_cornstack_python_v1
function mask_test_mixin__simple_test_mask ctx self x img_metas det_bboxes det_labels **kwargs begin set batch_size = size det_bboxes 0 set det_bboxes = det_bboxes at tuple Ellipsis slice : 4 : set batch_index = call expand size det_bboxes 0 size det_bboxes 1 1 set mask_rois = call cat list batch_index det_bboxes dim...
def mask_test_mixin__simple_test_mask(ctx, self, x, img_metas, det_bboxes, det_labels, **kwargs): batch_size = det_bboxes.size(0) det_bboxes = det_bboxes[..., :4] batch_index = torch.arange( det_bboxes.size(0), device=det_bboxes.device).float().view(-1, ...
Python
nomic_cornstack_python_v1
function make_move self column begin comment transpose the set trans_board = transpose numpy __board at slice : : 1 comment board so that columns are now arrays if 0 not in trans_board at column or call get_winner or column >= BOARD_COLUMNS or column < 0 begin comment column is full, illegal or the game is already fi...
def make_move(self, column): trans_board = numpy.transpose(self.__board[::1]) # transpose the # board so that columns are now arrays if 0 not in trans_board[column] or self.get_winner() or column >= \ self.BOARD_COLUMNS or column < 0: # column is full, illegal or...
Python
nomic_cornstack_python_v1
function isValidMove self environment currentCell x2 y2 checkVisited=true begin set tuple x1 y1 = tuple x y comment Check if within bounds if x2 < 0 or x2 >= length or y2 < 0 or y2 >= breadth begin return false end comment Check if cell is a wall set nextCell = grid at x2 at y2 if type == string wall begin return false...
def isValidMove(self, environment, currentCell, x2, y2, checkVisited = True): x1, y1 = currentCell.location.x, currentCell.location.y # Check if within bounds if x2 < 0 or x2 >= environment.length or y2 < 0 or y2 >= environment.breadth: return False # Check if cell is a wa...
Python
nomic_cornstack_python_v1
import csv import sys import os import matplotlib.pyplot as plt function import_log file_name begin print format string Opening {} file_name set data_dict = dict with open file_name as csv_file begin set csv_reader = reader csv_file delimiter=string , set line_count = 0 for row in csv_reader begin set line_count = lin...
import csv import sys import os import matplotlib.pyplot as plt def import_log(file_name): print('Opening {}'.format(file_name)) data_dict = {} with open(file_name) as csv_file: csv_reader = csv.reader(csv_file, delimiter=',') line_count = 0 for row in csv_reader: line...
Python
zaydzuhri_stack_edu_python
comment sql_database_app.py import sqlite3 import csv function csv_to_sqldb_migration p_csv_path p_connection p_table_name begin with open p_csv_path string r as file begin set no_records = 0 print file for row in file begin if split row string , at 0 == string begin pass end else begin print split row string , execut...
# sql_database_app.py import sqlite3 import csv def csv_to_sqldb_migration(p_csv_path, p_connection, p_table_name): with open(p_csv_path, "r") as file: no_records = 0 print(file) for row in file: if row.split(",")[0] == "": pass else: ...
Python
zaydzuhri_stack_edu_python
function tokenize_and_append_eos dataset output_features copy_pretokenized=true begin return call tokenize dataset output_features copy_pretokenized with_eos=true end function
def tokenize_and_append_eos( dataset: tf.data.Dataset, output_features: OutputFeaturesType, copy_pretokenized: bool = True, ) -> tf.data.Dataset: return tokenize(dataset, output_features, copy_pretokenized, with_eos=True)
Python
nomic_cornstack_python_v1
set input_date = string 12/31/20 set splitted_date = split input_date string / set day = splitted_date at 1 set month = splitted_date at 0 set year = string 20 + splitted_date at 2 set output_date = join string - list day month year print output_date
input_date = '12/31/20' splitted_date = input_date.split('/') day = splitted_date[1] month = splitted_date[0] year = '20' + splitted_date[2] output_date = '-'.join([day, month, year]) print(output_date)
Python
zaydzuhri_stack_edu_python
function attach_filter node begin set ifname = name + string -eth2 info string attaching filter to node %r % node call cmd string tc qdisc del dev %s clsact % ifname call cmd string tc qdisc add dev %s clsact % ifname call cmd string rm bpf_fifo; mkfifo bpf_fifo comment this is when call cmd string rm /tmp/bpf call cmd...
def attach_filter(node): ifname = node.name + "-eth2" logging.info("attaching filter to node %r" % node) node.cmd("tc qdisc del dev %s clsact" % ifname) node.cmd("tc qdisc add dev %s clsact" % ifname ) node.cmd("rm bpf_fifo; mkfifo bpf_fifo") # this is when node.cmd("rm /tmp/bpf") nod...
Python
nomic_cornstack_python_v1
function test_counts self test_case_count test_method_count begin execute conn update SA Builds whereclause=id == build_id values=dict string method_count test_method_count end function
def test_counts(self, test_case_count, test_method_count): self.conn.execute(SA.update(self.Builds, whereclause=(self.Builds.c.id == self.build_id), values={ 'method_count' : test_method_count, } ))
Python
nomic_cornstack_python_v1
function strContains s w begin return string + w + string in string + s + string end function
def strContains(s, w): return (' ' + w + ' ') in (' ' + s + ' ')
Python
nomic_cornstack_python_v1
function get_redirect_url self *args route **kwargs begin set permanent = permanent return target end function
def get_redirect_url(self, *args, route, **kwargs): self.permanent = route.permanent return route.target
Python
nomic_cornstack_python_v1
string =========================== UKWAC documents are separated by the URLs from which they were retrieved. We don't want these, so remove them here. =========================== Dr. Cai Wingfield --------------------------- Embodied Cognition Lab Department of Psychology University of Lancaster c.wingfield@lancaster.a...
""" =========================== UKWAC documents are separated by the URLs from which they were retrieved. We don't want these, so remove them here. =========================== Dr. Cai Wingfield --------------------------- Embodied Cognition Lab Department of Psychology University of Lancaster c.wingfield@lancaster.ac....
Python
zaydzuhri_stack_edu_python
function test_002 self begin set page = call Page string files/test.txt assert equal path string files/test.txt assert equal text none assert equal words none end function
def test_002(self): page = Page("files/test.txt") self.assertEqual(page.path, "files/test.txt") self.assertEqual(page.text, None) self.assertEqual(page.words, None)
Python
nomic_cornstack_python_v1
import re set s = input set a = search string ([0-9]{4})/([0-9]{2})/([0-9]{2}) s if integer call group 2 > 4 begin print string TBD end else begin print string Heisei end
import re s=input() a=re.search('([0-9]{4})/([0-9]{2})/([0-9]{2})',s) if int(a.group(2))>4: print('TBD') else: print('Heisei')
Python
zaydzuhri_stack_edu_python
function get_tiles tiles_file=none use_cache=true write_cache=true bgs_footprint=none begin global _cached_tiles set log = call get_logger set config = call Configuration set tiles_file = tiles_file or call tiles_file if use_cache and tiles_file in _cached_tiles begin set tiles = _cached_tiles at tiles_file debug forma...
def get_tiles(tiles_file=None, use_cache=True, write_cache=True, bgs_footprint=None): global _cached_tiles log = desiutil.log.get_logger() config = desisurvey.config.Configuration() tiles_file = tiles_file or config.tiles_file() if use_cache and tiles_file in _cached_tiles: tiles = _cached...
Python
nomic_cornstack_python_v1
import gensim.models as g import gensim.utils import json import numpy as np import pickle class doc_to_vector begin function __init__ self reviewfile model begin set f = open reviewfile string r set raw_reviews = load json f set model = load Doc2Vec model set labels = list set reviews = list set out_vectors = list ...
import gensim.models as g import gensim.utils import json import numpy as np import pickle class doc_to_vector: def __init__(self, reviewfile, model): f = open(reviewfile, 'r') self.raw_reviews = json.load(f) self.model = g.Doc2Vec.load(model) self.labels = [] self.reviews...
Python
zaydzuhri_stack_edu_python
function get_conn args begin if args == string localhost begin set conn = call connect string localhost string root string string song_identifier end else if args == string remote begin set conn = call connect host=MYSQL_HOST port=MYSQL_PORT user=MYSQL_USER password=MYSQL_PASSWORD db=MYSQL_DB end return list conn call...
def get_conn(args): if args == 'localhost': conn = pymysql.connect("localhost", "root", "", "song_identifier") elif args == 'remote': conn = pymysql.connect( host=MYSQL_HOST, port=MYSQL_PORT, user=MYSQL_USER, password=MYSQL_PASSWORD, d...
Python
nomic_cornstack_python_v1
function populate self machobj attributes=none begin set items = tuple string module_system string environment_variables string resource_limits string mpirun set default_run_suffix = call get_child string default_run_suffix root=root set group_node = call make_child string group dict string id string compliant_values s...
def populate(self, machobj, attributes=None): items = ("module_system", "environment_variables", "resource_limits", "mpirun") default_run_suffix = machobj.get_child("default_run_suffix", root=machobj.root) group_node = self.make_child("group", {"id": "compliant_values"}) settings = {"ru...
Python
nomic_cornstack_python_v1
function change_order nums fun begin if length nums == 0 begin return end set p1 = 0 set p2 = length nums - 1 while p1 < p2 begin if call fun nums at p1 begin set p1 = p1 + 1 end else if call fun nums at p2 begin set tuple nums at p1 nums at p2 = tuple nums at p2 nums at p1 end else begin set p2 = p2 - 1 end end end fu...
def change_order(nums, fun): if len(nums) == 0: return p1 = 0 p2 = len(nums) - 1 while p1 < p2: if fun(nums[p1]): p1 += 1 elif fun(nums[p2]): nums[p1], nums[p2] = nums[p2], nums[p1] else: p2 -= 1 def odd_first(num1): if num1 & 1 =...
Python
zaydzuhri_stack_edu_python
function tearDown self begin comment Flushing leftover SQL to the database at the end of every test catches bugs that manifest themselves only comment at the database level, such as constraint violations or model attributes with values that cannot be comment represented in SQL but are perfectly fine in Python. SQLAlche...
def tearDown(self): # Flushing leftover SQL to the database at the end of every test catches bugs that manifest themselves only # at the database level, such as constraint violations or model attributes with values that cannot be # represented in SQL but are perfectly fine in Python. SQLAlchemy...
Python
nomic_cornstack_python_v1
function numel self begin return numel mask end function
def numel(self) -> int: return self.mask.numel()
Python
nomic_cornstack_python_v1
function less x y begin return x < y end function
def less(x, y): return x < y
Python
nomic_cornstack_python_v1
function m_time self begin return call getmtime self end function
def m_time(self): return os.path.getmtime(self)
Python
nomic_cornstack_python_v1
function raw_to_relative positions cell_transpose cell_dot_inverse begin set relative_positions = matrix multiply matrix multiply positions cell_transpose cell_dot_inverse return relative_positions end function
def raw_to_relative(positions: 'ndarray', cell_transpose: 'ndarray', cell_dot_inverse: 'ndarray')-> 'ndarray': relative_positions = \ np.matmul(np.matmul(positions, cell_transpose), cell_dot_inverse) return relative_positions
Python
nomic_cornstack_python_v1
import os import requests from os.path import join , isfile from nerblackbox.modules.datasets.formatter.base_formatter import BaseFormatter class CoNLL2003Formatter extends BaseFormatter begin function __init__ self begin set ner_dataset = string conll2003 set ner_tag_list = list string PER string ORG string LOC string...
import os import requests from os.path import join, isfile from nerblackbox.modules.datasets.formatter.base_formatter import BaseFormatter class CoNLL2003Formatter(BaseFormatter): def __init__(self): ner_dataset = "conll2003" ner_tag_list = ["PER", "ORG", "LOC", "MISC"] super().__init__(n...
Python
jtatman_500k
import tornado function test begin set a = list 1 2 3 4 5 6 7 1 2 3 for i in a begin if i == 1 begin yield i end if i == 5 begin yield i end end end function set m = call test print type m for i in m begin print i end
import tornado def test(): a=[1,2,3,4,5,6,7,1,2,3] for i in a: if i ==1: yield i if i==5: yield i m=test() print (type(m)) for i in m: print (i)
Python
zaydzuhri_stack_edu_python
function get_user_permissions uid **kwargs begin string Get the roles for a user. @param user_id try begin call _get_user uid set user_perms = all return user_perms end except any begin raise call HydraError format string Permissions not found for user (user_id={}) uid end end function
def get_user_permissions(uid, **kwargs): """ Get the roles for a user. @param user_id """ try: _get_user(uid) user_perms = db.DBSession.query(Perm).filter(Perm.id==RolePerm.perm_id, RolePerm.role_id==Role.id, ...
Python
jtatman_500k
function _ensure_object_absent self endpoint_name name begin if nb_object begin set diff = call _delete_netbox_object set result at string msg = string %s %s deleted % tuple endpoint_name name set result at string changed = true set result at string diff = diff end else begin set result at string msg = string %s %s alr...
def _ensure_object_absent(self, endpoint_name, name): if self.nb_object: diff = self._delete_netbox_object() self.result["msg"] = "%s %s deleted" % (endpoint_name, name) self.result["changed"] = True self.result["diff"] = diff else: self.result...
Python
nomic_cornstack_python_v1
function load_annotations_from_file_in_kittimot_format filepath frame_id begin with open filepath string r as f begin set json_obj = load json f comment print(json_obj) set bounding_boxes = json_obj at string bounding_boxes comment filter out noisy annotations comment and convert the data to kitti MOTS data format comm...
def load_annotations_from_file_in_kittimot_format(filepath: str, frame_id: int) -> List[Union[str, int, float]]: with open(filepath, 'r') as f: json_obj = json.load(f) # print(json_obj) bounding_boxes = json_obj['bounding_boxes'] # filter out noisy annotations # and ...
Python
nomic_cornstack_python_v1
comment !/usr/bin/python comment -*- coding: utf-8 -*- comment Thư viện Toán trong Python import math function chuvi rad begin string Tính chu vi đường tròn set CV = 2 * pi * rad return CV end function comment Bán kính của đường tròn set R = list 2 3 4 5
#!/usr/bin/python # -*- coding: utf-8 -*- import math # Thư viện Toán trong Python def chuvi(rad): """ Tính chu vi đường tròn """ CV = 2*math.pi*rad return CV R = [2, 3, 4, 5] # Bán kính của đường tròn
Python
zaydzuhri_stack_edu_python
function func s begin set s = split s set rev = list for idx in range length s - 1 - 1 - 1 begin append rev s at idx end return join string rev end function print call func string Hello Miki, Me Mini print call func string hello world!
def func(s): s = s.split() rev = [] for idx in range(len(s)-1, -1, -1): rev.append(s[idx]) return ' '.join(rev) print(func('Hello Miki, Me Mini')) print(func(" hello world! "))
Python
zaydzuhri_stack_edu_python