code
stringlengths
10
2.58M
original_code
stringlengths
3
3.18M
original_language
stringclasses
1 value
source
stringclasses
7 values
function pichenyfcn x begin set n = shape at 1 assert n == 2 msg string The Picheny function is only defined on a 2D space. set X = 4 * x at tuple slice : : 0 - 2 set Y = 4 * x at tuple slice : : 1 - 2 set term = 1 + X + Y + 1 ^ 2 * 19 - 14 * X + 3 * X ^ 2 - 14 * Y + 6 * X * Y + 3 * Y ^ 2 * 30 + 2 * X - 3 * Y ^ 2...
def pichenyfcn(x: np.ndarray) -> np.ndarray: n = x.shape[1] assert n == 2, "The Picheny function is only defined on a 2D space." X = 4 * x[:, 0] - 2 Y = 4 * x[:, 1] - 2 term = ( 1 + ((X + Y + 1) ** 2) * ( 19 - (14 * X) + (3 * (X**2)) ...
Python
nomic_cornstack_python_v1
comment !/usr/bin/env python3 comment -*- coding: utf-8 -*- string @author: 闲欢 import json import pandas as pd from pyecharts.charts import Bar , Pie from pyecharts import options as opts import jieba from PIL import Image from wordcloud import WordCloud from matplotlib import pyplot as plt import numpy as np from os i...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ @author: 闲欢 """ import json import pandas as pd from pyecharts.charts import Bar, Pie from pyecharts import options as opts import jieba from PIL import Image from wordcloud import WordCloud from matplotlib import pyplot as plt import numpy as np from os import path c...
Python
zaydzuhri_stack_edu_python
function move_average source target tau=0.005 begin for tuple target_param param in zip parameters target parameters source begin call copy_ data * 1.0 - tau + data * tau end end function
def move_average(source, target, tau=0.005): for target_param, param in zip(target.parameters(), source.parameters()): target_param.data.copy_( target_param.data * (1.0 - tau) + param.data * tau )
Python
nomic_cornstack_python_v1
function isLoaded self begin update self if call isLoaded begin set ctrl = ref at string Static if call Texts at 0 == string Test Virtual Machine Call Home begin return true end else begin return false end end else begin return false end end function
def isLoaded(self): self.update() if super(VMCallHome, self).isLoaded(): ctrl = self.ref['Static'] if (ctrl.Texts())[0] == 'Test Virtual Machine Call Home': return True else: return False else: return False
Python
nomic_cornstack_python_v1
function go_left self begin if countrepeatleft <= 1 begin set change_x = - 6 set direction = string L end if is instance level Level_02 or is instance level Level_03 or is instance level Level_04 or is instance level Level_05 or is instance level Level_06 or is instance level Level_07 or is instance level Level_08 or i...
def go_left(self): if self.countrepeatleft <= 1: self.change_x = -6 self.direction = "L" if (isinstance(self.level, Level_02) or isinstance(self.level, Level_03) or isinstance(self.level, Level_04) or isinstance(self.level, Level_05) ...
Python
nomic_cornstack_python_v1
import pandas as pd import numpy as np comment df_indicator = pd.read_csv('/home/wasi/ML_FOLDER/DSND_Term2-master/lessons/ETLPipelines/data/population_data.csv', comment skiprows=4) comment df_indicator.drop(["Unnamed: 62"], axis=1, inplace=True) comment df_projects = pd.read_csv('/home/wasi/ML_FOLDER/DSND_Term2-master...
import pandas as pd import numpy as np # # df_indicator = pd.read_csv('/home/wasi/ML_FOLDER/DSND_Term2-master/lessons/ETLPipelines/data/population_data.csv', # skiprows=4) # df_indicator.drop(["Unnamed: 62"], axis=1, inplace=True) # # df_projects = pd.read_csv('/home/wasi/ML_FOLDER/DSND_Term...
Python
zaydzuhri_stack_edu_python
comment ! /usr/bin/env python3 import os import requests set feedbackPath = string /data/feedback/ for file in list directory feedbackPath begin set data = dict with open feedbackPath + file string r as f begin set lines = read lines f set data at string title = strip lines at 0 set data at string name = strip lines a...
#! /usr/bin/env python3 import os import requests feedbackPath = "/data/feedback/" for file in os.listdir(feedbackPath): data = {} with open(feedbackPath+file,'r') as f: lines = f.readlines() data["title"] = lines[0].strip() data["name"] = lines[1].strip() data["date"] = lines[...
Python
zaydzuhri_stack_edu_python
import sys import PlayerLib import enemyLib function create begin set list_ammo = list return list_ammo end function function clear list_ammo begin print list_ammo clear list_ammo end function function appendAmmo list_ammo type pos_x pos_y side color carac1=none carac2=none begin set ammo = dictionary set ammo at strin...
import sys import PlayerLib import enemyLib def create(): list_ammo = list() return list_ammo def clear(list_ammo): print(list_ammo) list_ammo.clear() def appendAmmo(list_ammo,type,pos_x,pos_y,side,color,carac1=None,carac2=None): ammo = dict() ammo["type"]=type ammo["pos_x"] = pos_x ...
Python
zaydzuhri_stack_edu_python
from tkinter import * from tkinter.font import Font import pickle from tkinter import filedialog set window = call Tk title window string To-Do list comment Methods function delete_task begin delete ANCHOR end function function add_task begin insert todoList END get task_name delete 0 END end function function done_tas...
from tkinter import * from tkinter.font import Font import pickle from tkinter import filedialog window = Tk() window.title("To-Do list") # Methods def delete_task(): todoList.delete((ANCHOR)) def add_task(): todoList.insert(END,task_name.get()) task_name.delete(0,END) def done_task(...
Python
zaydzuhri_stack_edu_python
function readFile self name begin return call PowhegProcs_readFile self name end function
def readFile(self, name): return _pythia8.PowhegProcs_readFile(self, name)
Python
nomic_cornstack_python_v1
string Create function create with one string argument. This function should return anonymous function that checks if the argument of function is equals to the argument of outer function. comment var1 anonymous function create password begin set x = lambda x -> password == x return x end function set tom = call create ...
''' Create function create with one string argument. This function should return anonymous function that checks if the argument of function is equals to the argument of outer function. ''' # var1 anonymous def create(password): x = lambda x: password == x return x tom = create("pass_...
Python
zaydzuhri_stack_edu_python
function returnOnlyCaps x begin set result = string for c in x begin if is upper c begin set result = result + c end end return result end function
def returnOnlyCaps(x): result = "" for c in x: if c.isupper(): result += c return result
Python
nomic_cornstack_python_v1
import os set PLOT_ARGUMENTS = dict set PLOT_ARGUMENTS at 0 = dict set PLOT_ARGUMENTS at 1 = dict set PLOT_ARGUMENTS at 2 = dict set PLOT_ARGUMENTS at 3 = dict set PLOT_ARGUMENTS at 4 = dict set PLOT_ARGUMENTS at 5 = dict set PLOT_ARGUMENTS at 0 at string title = string Angle Plot set PLOT_ARGUMENTS at 0 at stri...
import os PLOT_ARGUMENTS = {} PLOT_ARGUMENTS[0] = {} PLOT_ARGUMENTS[1] = {} PLOT_ARGUMENTS[2] = {} PLOT_ARGUMENTS[3] = {} PLOT_ARGUMENTS[4] = {} PLOT_ARGUMENTS[5] = {} PLOT_ARGUMENTS[0]['title'] = 'Angle Plot' PLOT_ARGUMENTS[0]['legend'] = 'Angle Legend' PLOT_ARGUMENTS[0]['xlabel'] = 'Angle' P...
Python
zaydzuhri_stack_edu_python
function calculate_extremes function begin function inner *args **kwargs begin print string Signal generated with function: { __name__ } print string Function decorated with function: { __name__ } set signal = call function *args set extremes = tuple call amin signal call amax signal print string Min and max values: { ...
def calculate_extremes(function): def inner(*args,**kwargs): print ( f'Signal generated with function: {function.__name__} ' ) print ( f'Function decorated with function: {calculate_extremes.__name__} ' ) signal = function(*args) extremes = np.amin(signal), np.amax(signal...
Python
nomic_cornstack_python_v1
from os.path import join class FunctionalScreen extends object begin string Base class for title/end screen. function __init__ self window type rectx=integer recty=integer string=string begin set background = grid set logoname = type + string logo.bmp set logo = load image join string data\screens type + string logo.bm...
from os.path import join class FunctionalScreen(object): """Base class for title/end screen. """ def __init__(self, window, type, rectx=int(), recty=int(), string=str()): self.background = window.grid self.logoname = type+"logo.bmp" self.logo = pygame.image.load(join("data\\screens",t...
Python
zaydzuhri_stack_edu_python
from PIL import Image import numpy as np from matplotlib import pyplot as plt import time class im_obj begin function __init__ self file begin set Name = file set im_obj = open file set tuple length width = size end function function details self begin string 传入图片名,显示基础参数 print Name print string 图片类型为 %s % format print...
from PIL import Image import numpy as np from matplotlib import pyplot as plt import time class im_obj: def __init__(self, file): self.Name = file self.im_obj = Image.open(file) self.length, self.width = self.im_obj.size def details(self): ''' 传入图片名...
Python
zaydzuhri_stack_edu_python
comment coding=utf-8 import sympy as sp import numpy as np from fractions import gcd import bitwise_operators_strings as bw function shift_register iniCond poly begin string Generates a maximum length sequence in a shift register from the next arguments: - iniCond: the initial condition of the shift register - poly: pr...
# coding=utf-8 import sympy as sp import numpy as np from fractions import gcd import bitwise_operators_strings as bw def shift_register(iniCond,poly): """Generates a maximum length sequence in a shift register from the next arguments: - iniCond: the initial condition of the shift register - poly: primiti...
Python
zaydzuhri_stack_edu_python
comment ---------Import---------- import SPRMethods import SPRRFID from tkinter import font comment For root import tkinter as tk comment More modern library import tkinter.ttk as ttk from PIL import ImageTk , Image comment ----------Constants----------- comment ukuran logo set logo_size = 350 comment ukuran lcd set lc...
# ---------Import---------- import SPRMethods import SPRRFID from tkinter import font import tkinter as tk # For root import tkinter.ttk as ttk # More modern library from PIL import ImageTk, Image #----------Constants----------- logo_size=350 #ukuran logo lcd_width=1280 #ukuran lcd lcd_height=800 tebal_garis_pembatas=...
Python
zaydzuhri_stack_edu_python
comment Write a Python program to get the largest number from a list. comment max_num_in_list([1, 2, -8, 0]) comment return 2 function max_num_in_list list begin set max = list at 0 for a in list begin if a > max begin set max = a end end return max end function print call max_num_in_list list 1 2 - 8 0
# Write a Python program to get the largest number from a list. # max_num_in_list([1, 2, -8, 0]) # return 2 def max_num_in_list(list): max = list[0] for a in list: if a > max: max = a return max print(max_num_in_list([1, 2, -8, 0]))
Python
zaydzuhri_stack_edu_python
from transformers import AutoTokenizer , AutoModelForQuestionAnswering import torch set tokenizer = call from_pretrained string bert-large-uncased-whole-word-masking-finetuned-squad set model = call from_pretrained string bert-large-uncased-whole-word-masking-finetuned-squad function generate_answers context questions ...
from transformers import AutoTokenizer, AutoModelForQuestionAnswering import torch tokenizer = AutoTokenizer.from_pretrained( "bert-large-uncased-whole-word-masking-finetuned-squad" ) model = AutoModelForQuestionAnswering.from_pretrained( "bert-large-uncased-whole-word-masking-finetuned-squad" ) def generate...
Python
zaydzuhri_stack_edu_python
function show_all_users self account_name=none account_id=none path=none user_name=none user_id=none search=false begin set list = call get_all_users account_name=account_name account_id=account_id path=path user_name=user_name user_id=user_id search=search debug string -------------------------------------------------...
def show_all_users(self, account_name=None, account_id=None, path=None, user_name=None, user_id=None, search=False ): list = self.get_all_users(account_name=account_name, account_id=account_id, path=path, user_name=user_name, user_id=user_id, search=search) self.debug('--------------------------------...
Python
nomic_cornstack_python_v1
comment !/usr/bin/env python comment -*- coding=utf-8 -*- import codecs from sre_compile import isstring class KeywordFilter extends object begin function __init__ self begin set __d = dictionary set __keywords = set end function function getKeywords self begin return __keywords end function function addKeywords self k...
#!/usr/bin/env python # -*- coding=utf-8 -*- import codecs from sre_compile import isstring class KeywordFilter(object): def __init__(self): self.__d = dict() self.__keywords = set() def getKeywords(self): return self.__keywords def addKeywords(self, keywords): for keywo...
Python
zaydzuhri_stack_edu_python
function product begin set a = 20 set b = 30 set c = a * b return c end function set d = product print d
def product(): a=20 b=30 c=a*b return c d=product() print(d)
Python
zaydzuhri_stack_edu_python
function subscribe_to_list self list option begin if is instance list str begin set backing at string lists = get backing string lists list for item in backing at string lists begin if string item at string list_id == list begin set item at string option = option set item at string unsubscribed = none return end end co...
def subscribe_to_list(self, list, option): if isinstance(list, str): self.backing["lists"] = self.backing.get("lists", []) for item in self.backing["lists"]: if str(item["list_id"]) == list: item["option"] = option item["unsubscribe...
Python
nomic_cornstack_python_v1
function station_stats df begin print string Calculating The Most Popular Stations and Trip... set start_time = time while true begin set answer = lower input string Would you like to show station stats? [y/n] if answer == string y begin set popular_start_st = mode at 0 print format string The most popular start statio...
def station_stats(df): print('\nCalculating The Most Popular Stations and Trip...\n') start_time = time.time() while True: answer = input("Would you like to show station stats? [y/n] \n").lower() if answer == "y": popular_start_st = df['Start Station'].mode()[0] ...
Python
nomic_cornstack_python_v1
if a // 4 != 0 and a // 400 != 0 begin print string високосный end else begin print string не високосный end
if a//4!=0 and a//400!=0: print('високосный') else: print('не високосный')
Python
zaydzuhri_stack_edu_python
if n == string Bob begin print string I don't recognize that name. end else if n == string Alice begin print string I don't recognize that name. end else begin print string Hello + n end
if n == "Bob": print("I don't recognize that name.") elif n == "Alice": print("I don't recognize that name.") else: print("Hello " + n)
Python
zaydzuhri_stack_edu_python
comment -*- coding: utf-8 -*- string Created on Thu Nov 19 16:21:06 2020 @author: bdaet from selenium import webdriver from selenium.common.exceptions import NoSuchElementException from selenium.common.exceptions import ElementNotInteractableException from selenium.webdriver.support.ui import WebDriverWait from seleniu...
# -*- coding: utf-8 -*- """ Created on Thu Nov 19 16:21:06 2020 @author: bdaet """ from selenium import webdriver from selenium.common.exceptions import NoSuchElementException from selenium.common.exceptions import ElementNotInteractableException from selenium.webdriver.support.ui import WebDriverWait from...
Python
zaydzuhri_stack_edu_python
string UCSB Rocket Propulsion Laboratory Propulsion Team Rocket Engine Simulation This file is converted from MATLAB to python function calculate_engine_thrust m_dot burn_time begin comment Assume pe=1 (accurate if burn is short and majority of combustion occurs at sea level comment Using this data: http://www.braeunig...
""" UCSB Rocket Propulsion Laboratory Propulsion Team Rocket Engine Simulation This file is converted from MATLAB to python """ def calculate_engine_thrust(m_dot, burn_time): ######################## ### Assume pe=1 (accurate if burn is short and majority of combustion occurs at sea level ### Using thi...
Python
zaydzuhri_stack_edu_python
function sec self s begin string Parse a public pair as a text SEC. Return a :class:`Key <pycoin.key.Key>` or None. set pair = call parse_colon_prefix s if pair is not none and pair at 0 == _wif_prefix begin set s = pair at 1 end try begin set sec = call h2b s return call public sec end except Exception begin pass end ...
def sec(self, s): """ Parse a public pair as a text SEC. Return a :class:`Key <pycoin.key.Key>` or None. """ pair = parse_colon_prefix(s) if pair is not None and pair[0] == self._wif_prefix: s = pair[1] try: sec = h2b(s) return ...
Python
jtatman_500k
import util import numpy as np function build_classifier_get_result input_data c builder begin shuffle random input_data set split_index = integer length input_data * 0.2 set learn_data = input_data at slice : split_index : set check_data = input_data at slice split_index : : set tuple vectors classes = zip *learn_...
import util import numpy as np def build_classifier_get_result(input_data, c, builder): np.random.shuffle(input_data) split_index = int(len(input_data) * 0.2) learn_data = input_data[:split_index] check_data = input_data[split_index:] vectors, classes = zip(*learn_data) smo = builder(c, vector...
Python
zaydzuhri_stack_edu_python
function lane self begin if is instance location Lane begin return location end return none end function
def lane(self): if isinstance(self.location, __road__.Lane): return self.location return None
Python
nomic_cornstack_python_v1
function __init__ self root size grids begin comment Patch for invalid size and grids set _root = root set tuple _grids _size = tuple grids size if _size % grids != 0 begin set _size = _size // grids * grids end comment Draw canvas set _root = root set _board = call Canvas root width=_size + PADDING * 2 height=_size + ...
def __init__(self, root: tkinter.Tk, size: int, grids: int) -> NoReturn: # Patch for invalid size and grids self._root = root self._grids, self._size = grids, size if self._size % grids != 0: self._size = (self._size // grids) * grids # Draw canvas self._root...
Python
nomic_cornstack_python_v1
function edit_tags request backend project repository=none template=string front/repository_main.html begin set context = dictionary obj=repository if not call is_ajax begin set context at string edit_tags = true end return call render request template context end function
def edit_tags(request, backend, project, repository=None, template='front/repository_main.html'): context = dict(obj = repository) if not request.is_ajax(): context['edit_tags'] = True return render(request, template, context)
Python
nomic_cornstack_python_v1
function test_capture_tee_output self begin set tuple returncode out = tee string echo "." call assertEquals out list string . call assertEquals returncode 0 end function
def test_capture_tee_output(self): returncode, out = self.shell.tee('echo "."') self.assertEquals(out, ['.']) self.assertEquals(returncode, 0)
Python
nomic_cornstack_python_v1
function _round_filters self filters begin set filters = filters * width_coefficient set new_filters = max depth_divisor integer filters + depth_divisor / 2 // depth_divisor * depth_divisor comment Make sure that round down does not go down by more than 10%. if new_filters < 0.9 * filters begin set new_filters = new_fi...
def _round_filters(self, filters): filters *= self.width_coefficient new_filters = max( self.depth_divisor, int(filters + self.depth_divisor / 2) // self.depth_divisor * self.depth_divisor, ) # Make sure that round down does not go down by ...
Python
nomic_cornstack_python_v1
comment !/usr/bin/python comment -*- coding: utf-8 -*- string Created on Sun Oct 08 10:14:39 2017 @author: PulkitMaloo import sys class Board extends object begin function __init__ self board begin set board = board end function function __str__ self begin return join string list comprehension join string board at sl...
#!/usr/bin/python # -*- coding: utf-8 -*- """ Created on Sun Oct 08 10:14:39 2017 @author: PulkitMaloo """ import sys class Board(object): def __init__(self, board): self.board = board def __str__(self): return "\n".join([" ".join(self.board[i:i+8]) for i in range(0,64,8)]) def succ(self, player="...
Python
zaydzuhri_stack_edu_python
import sys import bs4 from bs4 import BeautifulSoup import requests import re import os import csv comment Yield successive n-sized comment chunks from l. function divide_chunks l n begin comment looping till length l for i in range 0 length l n begin yield l at slice i : i + n : end end function set year = argv at 1 ...
import sys import bs4 from bs4 import BeautifulSoup import requests import re import os import csv # Yield successive n-sized # chunks from l. def divide_chunks(l, n): # looping till length l for i in range(0, len(l), n): yield l[i:i + n] year = sys.argv[1] team = sys.argv[2] url = f'https://ww...
Python
zaydzuhri_stack_edu_python
function expireat key timestamp host=none port=none db=none password=none begin string Set a keys expire at given UNIX time CLI Example: .. code-block:: bash salt '*' redis.expireat foo 1400000000 set server = call _connect host port db password return call expireat key timestamp end function
def expireat(key, timestamp, host=None, port=None, db=None, password=None): ''' Set a keys expire at given UNIX time CLI Example: .. code-block:: bash salt '*' redis.expireat foo 1400000000 ''' server = _connect(host, port, db, password) return server.expireat(key, timestamp)
Python
jtatman_500k
from pyspark.sql import SparkSession from pyspark.sql import Row import collections comment gives us spark context and sql context set spark = call getOrCreate function parse_lines line begin string create row objects set fields = split line string , comment ID, name, age, and numFriends columns that are typed -> great...
from pyspark.sql import SparkSession from pyspark.sql import Row import collections # gives us spark context and sql context spark = SparkSession.builder.appName('SparkSQL').getOrCreate() def parse_lines(line): ''' create row objects ''' fields = line.split(',') # ID, name, age, and numFriends columns that are t...
Python
zaydzuhri_stack_edu_python
async function _get_timestamp self channel msg_id begin try begin set msg = await call fetch_message msg_id end except tuple NotFound Forbidden HTTPException as err begin error string Error fetching message: %s err set msg = none end return if expression msg is none then msg else created_at end function
async def _get_timestamp( self, channel: TextChannel, msg_id: int, ) -> Optional[datetime]: try: msg = await channel.fetch_message(msg_id) except (NotFound, Forbidden, HTTPException) as err: self.logger.error("Error fetching message: %s", err) ...
Python
nomic_cornstack_python_v1
comment Author: William Hanau comment Date: 12-3-16 comment Updated Version(v2.0) of my MasterMind python game from graphics import * import random set G_WINDOW_WIDTH = 360 set G_WINDOW_HEIGHT = 700 set LEFTMOST_X = 50 set CIRCLE_RADIUS = 20 set CIRCLE_DIAMETER = CIRCLE_RADIUS * 2 set H_CIRCLE_SPACING = 5 set V_CIRCLE_...
#Author: William Hanau #Date: 12-3-16 #Updated Version(v2.0) of my MasterMind python game from graphics import * import random G_WINDOW_WIDTH = 360 G_WINDOW_HEIGHT = 700 LEFTMOST_X = 50 CIRCLE_RADIUS = 20 CIRCLE_DIAMETER = CIRCLE_RADIUS * 2 H_CIRCLE_SPACING = 5 V_CIRCLE_SPACING = 10 PALETTE_X = LEFTMOST...
Python
zaydzuhri_stack_edu_python
function domains_to_samples domains sample_column=string contig_id target_column=none begin set samples = group by domains sample_column set sample_ids = list keys groups set samples = list comprehension call get_group i for i in sample_ids if target_column begin set targets = list comprehension sample at target_column...
def domains_to_samples(domains, sample_column='contig_id', target_column=None): samples = domains.groupby(sample_column) sample_ids = list(samples.groups.keys()) samples = [samples.get_group(i) for i in sample_ids] if target_column: targets = [sample[target_column] for sample in samples] ...
Python
nomic_cornstack_python_v1
comment splitting words into things that make sense function build_bigram_source source_text=none filter=50 begin string Builds bigrams out of a source text. Usually news source_text is a string, or is blank. If a string, will be tokenized, etc filter is an integer that lets you filter out import nltk from nltk.colloca...
# splitting words into things that make sense def build_bigram_source(source_text=None, filter=50): """ Builds bigrams out of a source text. Usually news source_text is a string, or is blank. If a string, will be tokenized, etc filter is an integer that lets you filter out """ import nltk from nltk.colloc...
Python
zaydzuhri_stack_edu_python
function __str__ self begin return string { user_id } , { account } end function
def __str__(self): return f'{self.user_id}, {self.account}'
Python
nomic_cornstack_python_v1
comment encode:utf-8 from GridMap import GridMap from Agent import Agent from State import State class Controller begin function chaseTarget self chaser target grid state begin set dire = call nextDirection chaser target grid walk dire end function function gameSet self chaser target grid state begin call Spawn grid ca...
#encode:utf-8 from GridMap import GridMap from Agent import Agent from State import State class Controller(): def chaseTarget(self, chaser:Agent, target:Agent, grid:GridMap, state:State): dire = state.nextDirection(chaser, target, grid) chaser.Walk(dire) def gameSet(self, chaser:Agent,...
Python
zaydzuhri_stack_edu_python
comment Andrew manages a pipe warehouse. He wishes to aotumate the process of transferring the pipes comment from the warehouse to the carrier truck. There are N pipes in the warehouse placed vertically comment along a wall. In the automated system, a drone picks the pipes by length and carries them to comment the carr...
# Andrew manages a pipe warehouse. He wishes to aotumate the process of transferring the pipes # from the warehouse to the carrier truck. There are N pipes in the warehouse placed vertically # along a wall. In the automated system, a drone picks the pipes by length and carries them to # the carrier truck. In each turn,...
Python
zaydzuhri_stack_edu_python
import json import pickle set file = open string names.txt string w encoding=string utf-8 set names = list string zhangsan string lisi string jack string tony comment 序列化方法 dumps dump comment x = json.dumps(names) comment print(x) comment file.write(x) comment file.write(str(names)) dump names file close file comment 反...
import json import pickle file = open('names.txt', 'w', encoding='utf-8') names = ['zhangsan', 'lisi', 'jack', 'tony'] # 序列化方法 dumps dump # x = json.dumps(names) # print(x) # file.write(x) # file.write(str(names)) json.dump(names, file) file.close() # 反序列化 loads load x = '["zhangsan", "lisi", "jack", "tony"]' p =...
Python
zaydzuhri_stack_edu_python
comment coding=utf-8 comment 用图片做词云模板定制特定的词云 from PIL import Image import numpy as np import matplotlib.pyplot as plt import jieba from wordcloud import WordCloud , STOPWORDS set text = read open string ./txt/coder.txt set zh_text = join string call cut text set alice_mask = array open string ./img/alice_mask.png set ...
#coding=utf-8 #用图片做词云模板定制特定的词云 from PIL import Image import numpy as np import matplotlib.pyplot as plt import jieba from wordcloud import WordCloud,STOPWORDS text = open('./txt/coder.txt').read() zh_text = ' '.join(jieba.cut(text)) alice_mask = np.array(Image.open('./img/alice_mask.png')) stopwords = set(STOPWORDS...
Python
zaydzuhri_stack_edu_python
if appeal in dictionary begin set f = open extract string w write f input string Enter text close f end
if appeal in dictionary: f = open(extract, 'w') f.write(input('Enter text ')) f.close()
Python
zaydzuhri_stack_edu_python
function yvec self begin return _yvec end function
def yvec(self): return self._yvec
Python
nomic_cornstack_python_v1
function __init__ __self__ group_id=none resource_type=none begin if group_id is not none begin set __self__ string group_id group_id end if resource_type is not none begin set __self__ string resource_type resource_type end end function
def __init__(__self__, *, group_id: Optional[pulumi.Input[str]] = None, resource_type: Optional[pulumi.Input['ResourceGroupResourceType']] = None): if group_id is not None: pulumi.set(__self__, "group_id", group_id) if resource_type is not None: ...
Python
nomic_cornstack_python_v1
import frequencies as fqs import numpy as np import simpleaudio as sa set sample_rate = 44100 comment keep amplitude always "one" comment it's okay if when superposing amplitude gets more than one comment finally normalize evrything by dividing by max amplitude comment createNote will always return with amplitude one c...
import frequencies as fqs import numpy as np import simpleaudio as sa sample_rate = 44100 # keep amplitude always "one" # it's okay if when superposing amplitude gets more than one # finally normalize evrything by dividing by max amplitude # createNote will always return with amplitude one # phi : initial ...
Python
zaydzuhri_stack_edu_python
string O princípio de funcionamento deste algoritmo é transferir o menor valor do vetor para a primeira posição e, em seguida, o segundo menor valor para a segunda posição, e assim sucessivamente, para os n-1 elementos até os últimos dois elementos function executar_selection_sort lista begin set n = length lista for i...
""" O princípio de funcionamento deste algoritmo é transferir o menor valor do vetor para a primeira posição e, em seguida, o segundo menor valor para a segunda posição, e assim sucessivamente, para os n-1 elementos até os últimos dois elementos """ def executar_selection_sort(lista): n = len(lista) for i in r...
Python
zaydzuhri_stack_edu_python
function test_video_detail_no_permission mock_user_moira_lists logged_in_apiclient user_admin_list_data begin set tuple client _ = logged_in_apiclient set return_value = set literal string some_other_list set url = reverse string video-detail kwargs=dict string video_key hexkey set result = get client url assert status...
def test_video_detail_no_permission( mock_user_moira_lists, logged_in_apiclient, user_admin_list_data ): client, _ = logged_in_apiclient mock_user_moira_lists.return_value = {"some_other_list"} url = reverse( "video-detail", kwargs={"video_key": user_admin_list_data.video.hexkey} ) resul...
Python
nomic_cornstack_python_v1
function save_key_bio self bio *args **kw begin return call save_pub_key_bio bio end function
def save_key_bio(self, bio, *args, **kw): return self.save_pub_key_bio(bio)
Python
nomic_cornstack_python_v1
function say_goodbye begin call print_goodbye end function
def say_goodbye(): view.print_goodbye()
Python
nomic_cornstack_python_v1
import core as ft from pandas.plotting import scatter_matrix import matplotlib.pyplot as plt import seaborn as sns import pandas as pd function clean_data data begin set df = drop missing call DataFrame data set feat = df at string Hogwarts House set df = df at columns at slice 6 : : return tuple df feat end function...
import core as ft from pandas.plotting import scatter_matrix import matplotlib.pyplot as plt import seaborn as sns import pandas as pd def clean_data(data): df = pd.DataFrame(data).dropna() feat = df['Hogwarts House'] df = df[data.columns[6:]] return df, feat def main(): data = ft.get_csv() tr...
Python
zaydzuhri_stack_edu_python
from collections import Counter class QGrams extends Counter begin set term = string set term_ss = string set ordered_list = list function __init__ self term qval=2 start_stop=string $# begin set term = term if length term < qval or qval < 1 begin return end if start_stop and qval > 1 begin set term = start_stop at ...
from collections import Counter class QGrams(Counter): term = '' term_ss = '' ordered_list = [] def __init__(self, term, qval=2, start_stop='$#'): self.term = term if len(term) < qval or qval < 1: return if start_stop and qval > 1: term = start_...
Python
zaydzuhri_stack_edu_python
comment 词云展示 from nltk.tokenize import word_tokenize from wordcloud import WordCloud import matplotlib.pyplot as plt import pandas as pd comment 去掉停用词 function remove_stop_words f begin set stop_words = list string Movie string aaa for stop_word in stop_words begin set f = replace f stop_word string end return f end fu...
#词云展示 from nltk.tokenize import word_tokenize from wordcloud import WordCloud import matplotlib.pyplot as plt import pandas as pd #去掉停用词 def remove_stop_words(f): stop_words=['Movie','aaa'] for stop_word in stop_words: f=f.replace(stop_word,'') return f #生成词云 def create_word_cloud(f): print('根...
Python
zaydzuhri_stack_edu_python
function increment self address fn=none user_agent=none begin try begin set cur = call cursor execute cur string INSERT INTO clients (addr, filename, user_agent) VALUES (%s, %s, %s); tuple call _addr_hash address fn user_agent end except Error as e begin raise call CursorError cur e end end function
def increment(self, address, fn=None, user_agent=None): try: cur = self._db.cursor() cur.execute("INSERT INTO clients (addr, filename, user_agent) " "VALUES (%s, %s, %s);", (_addr_hash(address), fn, user_agent,)) except mdb.Error as...
Python
nomic_cornstack_python_v1
function get_recipe_hits elastic_hits begin set elements = list for tuple i hit in enumerate elastic_hits begin set btn1 = call get_ingredient_button i set btn2 = call get_nutrient_button i set btn3 = call get_recipe_button string full hit at string url append elements call Element title=hit at string title item_url=h...
def get_recipe_hits(elastic_hits): elements = [] for i,hit in enumerate(elastic_hits): btn1 = get_ingredient_button(i) btn2 = get_nutrient_button(i) btn3 = get_recipe_button('full', hit['url']) elements.append(Element( title=hit['title'], item_url=hit...
Python
nomic_cornstack_python_v1
import argparse function get_args begin set parser = call ArgumentParser description=string Bottles of beer song formatter_class=ArgumentDefaultsHelpFormatter call add_argument string -n string --num metavar=string number type=int default=10 help=string How many bottles set args = call parse_args if num < 1 begin error...
import argparse def get_args(): parser = argparse.ArgumentParser(description='Bottles of beer song',formatter_class=argparse.ArgumentDefaultsHelpFormatter) parser.add_argument('-n','--num',metavar='number',type=int,default=10,help='How many bottles') args = parser.parse_args() if args.num < 1: ...
Python
zaydzuhri_stack_edu_python
function get_tag self key begin return call get_tag name key end function
def get_tag(self, key: str) -> str: return self.workspace.get_tag(self.name, key)
Python
nomic_cornstack_python_v1
comment киноман-2 comment Демонстрирует переключатель from tkinter import * class Application extends Frame begin string GUI-приложение, позволяющее выбрать один любимый жанр кино function __init__ self master begin call __init__ master grid call create_widgets end function function create_widgets self begin string Соз...
# киноман-2 # Демонстрирует переключатель from tkinter import * class Application(Frame): """ GUI-приложение, позволяющее выбрать один любимый жанр кино """ def __init__(self, master): super(Application, self).__init__(master) self.grid() self.create_widgets() def create_widgets(se...
Python
zaydzuhri_stack_edu_python
function apply self image begin comment initialize pixel model if it hasn't yet if samples is none begin call initialize image end comment predict foreground mask set repeated_image = repeat image at tuple newaxis slice : : slice : : slice : : sample_amount axis=0 set distances = square root sum call square ca...
def apply(self, image): # initialize pixel model if it hasn't yet if self.samples is None: self.initialize(image) # predict foreground mask repeated_image = np.repeat(image[np.newaxis, :, : , :], self.sample_amount, axis=0) distances = np.sqrt(np.sum(np.square(np.sub...
Python
nomic_cornstack_python_v1
function save self *args **kwargs begin comment this is a totally new instance, create uuid value if not id begin set url_uuid = replace string uuid 4 string - string end save *args keyword kwargs end function
def save(self, *args, **kwargs): if not self.id: # this is a totally new instance, create uuid value self.url_uuid = str(uuid.uuid4()).replace("-", "") super(ObfuscatedUrlInfo, self).save(*args, **kwargs)
Python
nomic_cornstack_python_v1
function test_fibonacci self begin set fibonacci = list comprehension x for x in call fibonacci 10 assert equal fibonacci at 7 21 end function
def test_fibonacci(self): fibonacci = [x for x in generators.fibonacci(10)] self.assertEqual(fibonacci[7], 21)
Python
nomic_cornstack_python_v1
comment ! usr/bin/env python comment -*- coding: utf-8 -*- from datetime import date , timedelta , datetime from decimal import Decimal from scrapy.http.request import Request from scrapy.selector import Selector from scrapy.spiders import Spider from starform.items import resultsItem import os import re import unicode...
#! usr/bin/env python # -*- coding: utf-8 -*- from datetime import date, timedelta, datetime from decimal import Decimal from scrapy.http.request import Request from scrapy.selector import Selector from scrapy.spiders import Spider from starform.items import resultsItem import os import re import unicodecsv def amend...
Python
zaydzuhri_stack_edu_python
function get_gender begin set gender = input string Which kind of name would you like? Enter m for male or f for female while true begin try begin return dict string m string male ; string f string female at gender end except KeyError begin print string Please enter 1 for male or 2 for female end end end function
def get_gender(): gender = input('Which kind of name would you like? Enter m for male or f for female ') while True: try: return {'m': 'male', 'f': 'female'}[gender] except KeyError: print("Please enter 1 for male or 2 for female")
Python
nomic_cornstack_python_v1
comment -*- coding: utf-8 -*- comment @Time : 2019/12/4 20:42 comment @Author : Li Sen string 输入一个矩阵,按照从外向里以顺时针的顺序依次打印出每一个数字, 例如,如果输入如下4 X 4矩阵: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 则依次打印出数字1,2,3,4,8,12,16,15,14,13,9,5,6,7,11,10. 可以模拟魔方逆时针旋转的方法,一直做取出第一行的操作 例如 1 2 3 4 5 6 7 8 9 输出并删除第一行后,再进行一次逆时针旋转,就变成: 6 9 5 8 4 7 继续重...
# -*- coding: utf-8 -*- # @Time : 2019/12/4 20:42 # @Author : Li Sen """ 输入一个矩阵,按照从外向里以顺时针的顺序依次打印出每一个数字, 例如,如果输入如下4 X 4矩阵: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 则依次打印出数字1,2,3,4,8,12,16,15,14,13,9,5,6,7,11,10. 可以模拟魔方逆时针旋转的方法,一直做取出第一行的操作 例如 1 2 3 4 5 6 7 8 9 输出并删除第一行后,再进行一次逆时针旋转,就变成: 6 9 5 8 4 7 继续重复上述操作即可。 Pytho...
Python
zaydzuhri_stack_edu_python
function send oobhandler session *args **kwargs begin set obj = call get_puppet_or_player set ret = dict end function
def send(oobhandler, session, *args, **kwargs): obj = session.get_puppet_or_player() ret = {}
Python
nomic_cornstack_python_v1
function load_index self dataset_name file begin append indices list dataset_name file end function
def load_index(self, dataset_name, file): self.indices.append([dataset_name, file])
Python
nomic_cornstack_python_v1
import requests , re set url = string http://www.gutenberg.org/cache/epub/16/pg16.txt comment si on passe par le proxy univ orleans : set proxy = dict string http string http://wwwcache.univ-orleans.fr:3128/ set r = get requests url proxies=proxy comment si pas de proxy : comment r=requests.get(url) set PeterPan = text...
import requests, re url='http://www.gutenberg.org/cache/epub/16/pg16.txt' # si on passe par le proxy univ orleans : proxy ={"http":"http://wwwcache.univ-orleans.fr:3128/"} r=requests.get(url ,proxies=proxy) # si pas de proxy : # r=requests.get(url) PeterPan = r.text print(len(r.text)) r.encoding it=re.finditer('(The [^...
Python
zaydzuhri_stack_edu_python
from flask import Flask , current_app set app = call Flask __name__ comment 应用上下文 对象 Flask comment 请求上下文 对象 Request comment Flask AppContext comment Request RequestContext comment 离线应用,单元测试 comment ctx = app.app_context() comment ctx.push() comment a = current_app comment d = current_app.config['DEBUG'] comment ctx.pop...
from flask import Flask,current_app app = Flask(__name__) # 应用上下文 对象 Flask # 请求上下文 对象 Request # Flask AppContext # Request RequestContext # 离线应用,单元测试 # ctx = app.app_context() # ctx.push() # a = current_app # d = current_app.config['DEBUG'] # ctx.pop() # with改写 with app.app_context(): #上下文表达式 a = current_app d = c...
Python
zaydzuhri_stack_edu_python
for i in range 0 l / 2 begin for j in range 0 l / 2 begin set a = s at slice i : l - j : set num = l - j - i for k in range 0 num begin set b = a at slice 0 : k + 1 : set c = a at slice k + 1 : : set d = replace b string 1 string set e = length d if e > k / 2 begin set f = replace c string 1 string set g = length f...
for i in range(0,l/2): for j in range(0,l/2): a = s[i:l-j] num = l-j-i for k in range(0,num): b = a[0:k + 1] c = a[k + 1:] d = b.replace('1','') e = len(d) if(e > (k)/2): f = c.replace('1','') g = len(f) if(e < (l - j - k)/2): jj...
Python
zaydzuhri_stack_edu_python
comment !/usr/bin/env python comment -*- coding: utf-8 -*- comment @Date : 2017-11-20 17:23:30 comment @Author : TaoYuan (1876665310@qq.com) comment @Link : http://blog.csdn.net/lftaoyuan Python互助学习qq群:315857408 comment @Version : $Id$ function test_d d begin for tuple k v in items d begin return tuple k string = v end...
#!/usr/bin/env python # -*- coding: utf-8 -*- # @Date : 2017-11-20 17:23:30 # @Author : TaoYuan (1876665310@qq.com) # @Link : http://blog.csdn.net/lftaoyuan Python互助学习qq群:315857408 # @Version : $Id$ def test_d(d): for k, v in d.items(): return k, '=', v def test_s(L): L2 = [] for s in L:...
Python
zaydzuhri_stack_edu_python
function get_max_atoms_per_core self begin set current_found_max_atoms_per_core = _n_atoms for constraint in constraints begin if is instance constraint PartitionerMaximumSizeConstraint and size <= current_found_max_atoms_per_core begin set current_found_max_atoms_per_core = size end end return current_found_max_atoms_...
def get_max_atoms_per_core(self): current_found_max_atoms_per_core = self._n_atoms for constraint in self.constraints: if (isinstance(constraint, PartitionerMaximumSizeConstraint) and constraint.size <= current_found_max_atoms_per_core): current_found_max_...
Python
nomic_cornstack_python_v1
import requests import json import os import asyncio from PIL import Image , ImageFont , ImageDraw , ImageFilter import discord from discord.ext import commands class GatoText extends Cog begin function __init__ self client begin set client = client end function decorator call command async function gatotext self ctx t...
import requests import json import os import asyncio from PIL import Image,ImageFont,ImageDraw, ImageFilter import discord from discord.ext import commands class GatoText(commands.Cog): def __init__(self, client): self.client = client @commands.command() async def gatotext(self, ctx, *, text=""):...
Python
zaydzuhri_stack_edu_python
for i in range 0 5 begin print i end for i in range 4 - 1 - 1 begin print numbers at i end for i in range 0 5 begin print numbers at i print numbers at slice 1 : 5 : end
for i in range(0, 5): print(i) for i in range(4, -1, -1): print(numbers[i]) for i in range(0, 5): print(numbers[i]) print(numbers[1:5])
Python
zaydzuhri_stack_edu_python
from collections import deque class Stack begin function __init__ self begin set q1 = deque set q2 = deque set head = none end function string @param: x: An integer @return: nothing function push self x begin append q1 x set head = x end function string @return: nothing function pop self begin while length q1 > 1 begin...
from collections import deque class Stack: def __init__(self): self.q1 = deque() self.q2 = deque() self.head = None """ @param: x: An integer @return: nothing """ def push(self, x): self.q1.append(x) self.head = x """ @return: nothing """ ...
Python
zaydzuhri_stack_edu_python
from src.dominio import Usuario , Leilao from src.excecoes import LanceInvalido import pytest decorator fixture function arthur begin return call Usuario string arthur 100.0 end function decorator fixture function leilao begin return call Leilao string celular end function function test_deve_subtrair_valor_da_carteira_...
from src.dominio import Usuario, Leilao from src.excecoes import LanceInvalido import pytest @pytest.fixture def arthur(): return Usuario('arthur', 100.0) @pytest.fixture def leilao(): return Leilao('celular') def test_deve_subtrair_valor_da_carteira_do_usuario_quando_este_propor_um_lance(arthur,leilao): ...
Python
zaydzuhri_stack_edu_python
function compare_strings string1 string2 begin comment Count the number of characters in each string set len1 = length string1 set len2 = length string2 comment Check if the number of characters is equal if len1 != len2 begin return false end comment Count the number of vowels and consonants in each string set vowels1 ...
def compare_strings(string1, string2): # Count the number of characters in each string len1 = len(string1) len2 = len(string2) # Check if the number of characters is equal if len1 != len2: return False # Count the number of vowels and consonants in each string vowels1 = sum...
Python
greatdarklord_python_dataset
function remove self address begin with lock begin for connection in pop connections address tuple begin try begin close connection end except IOError begin pass end end end end function
def remove(self, address): with self.lock: for connection in self.connections.pop(address, ()): try: connection.close() except IOError: pass
Python
nomic_cornstack_python_v1
function search txt pat begin set m = length txt set n = length pat for i in range m - n + 1 begin for j in range n begin if txt at i + j != pat at j begin break end end if j == n - 1 begin print string Pattern pat string found at index i end end end function search string THIS IS A TEST TEXT TEST string TEST
def search(txt, pat): m = len(txt) n = len(pat) for i in range(m - n + 1): for j in range(n): if txt[i+j] != pat[j]: break if j == n -1: print('Pattern', pat, 'found at index', i) search('THIS IS A TEST TEXT TEST', 'TEST')
Python
zaydzuhri_stack_edu_python
function pixel_to_grid self pixel_pos begin if pixel_pos >= GameB_Size begin set pixel_pos = GameB_Size - 1 end set grid_pos = integer pixel_pos / Tile_size return grid_pos end function
def pixel_to_grid(self, pixel_pos): if pixel_pos >= GameB_Size: pixel_pos = GameB_Size - 1 grid_pos = int(pixel_pos / Tile_size) return grid_pos
Python
nomic_cornstack_python_v1
while password != PASSWORD begin if tries > 0 begin set tries = tries - 1 set password = input string Incorrect pin re Enter! end else begin print string Account blocked.Wrong password! ): exit end end print string Welcome (: set user_choice = integer input string Select Option 1. Withdraw 2. Deposit 3. View Balance if...
while password != PASSWORD: if tries > 0: tries -=1 password = input("Incorrect pin re Enter! ") else: print ("Account blocked.Wrong password! ):") exit() print ("Welcome (:") user_choice = int(input(''' Select Option 1. Withdraw 2. Deposit 3. View Balance''')) if user_choice == 1: amount = ...
Python
zaydzuhri_stack_edu_python
string Given a binary tree, find its minimum depth. The minimum depth is the number of nodes along the shortest path from the root node down to the nearest leaf node. NOTE : The path has to end on a leaf node. Example : 1 / 2 min depth = 2. comment Definition for a binary tree node. comment class TreeNode: comment def ...
''' Given a binary tree, find its minimum depth. The minimum depth is the number of nodes along the shortest path from the root node down to the nearest leaf node. NOTE : The path has to end on a leaf node. Example : 1 / 2 min depth = 2. ''' # Definition for a binary tree node....
Python
zaydzuhri_stack_edu_python
comment -*- coding: utf-8 -*- string Created on Wed Feb 3 21:04:52 2021 @author: Divya import numpy as np set A = array list list 11 12 13 list 21 22 23 list 31 32 3 set B = array list list 11 102 13 list 201 22 203 list 31 32 303 print dot A B print A + B print A == B print call array_equal A B print call array_equal ...
# -*- coding: utf-8 -*- """ Created on Wed Feb 3 21:04:52 2021 @author: Divya """ import numpy as np A = np.array([ [11, 12, 13], [21, 22, 23], [31, 32, 3] ]) B = np.array([ [11, 102, 13], [201, 22, 203], [31, 32, 303] ]) print(np.dot(A,B)) print(A+B) print(A==B) print(np.array_equal(A,B)) prin...
Python
zaydzuhri_stack_edu_python
class people begin comment 姓名 set __name = string comment 性别 set __sex = string comment 年龄 set __age = 0 comment 剩余话费 set __sy = 0 comment 品牌 set __pp = string comment 手机电池容积 set __rl = 0 comment 屏幕尺寸 set __size = 0 comment 待机时长 set __time = 0 comment 拥有积分 set __jifen = 0 function setName self name begin set __name ...
class people: __name=''#姓名 __sex=''#性别 __age=0#年龄 __sy=0#剩余话费 __pp=''#品牌 __rl=0#手机电池容积 __size=0#屏幕尺寸 __time=0#待机时长 __jifen=0#拥有积分 def setName(self,name): self.__name=name def getName(self): return self.__name def setsex(self,sex): se...
Python
zaydzuhri_stack_edu_python
function generate_test_map_coords begin set zcoord = 0 set tile = call query_tiles name yield call MapCoord xcoord=- 1 ycoord=1 zcoord=zcoord tile_id=id set tile = call query_tiles name yield call MapCoord xcoord=0 ycoord=1 zcoord=zcoord tile_id=id set tile = call query_tiles name yield call MapCoord xcoord=1 ycoord=1 ...
def generate_test_map_coords(): zcoord = 0 tile = query_tiles(Tile.wall_narrow_corner_nw.name) yield db.MapCoord(xcoord=-1, ycoord=1, zcoord=zcoord, tile_id=tile.id) tile = query_tiles(Tile.wall_narrow_n.name) yield db.MapCoord(xcoord=0, ycoord=1, zcoord=zcoord, tile_id=tile.id) tile = query_til...
Python
nomic_cornstack_python_v1
import sympy set a = call Symbol string a set b = call Symbol string b set c = call Symbol string c set d = call Symbol string d set e = call Symbol string e set f = call Symbol string f set g = call Symbol string g function cos m begin set res = cos m return res end function function sin n begin set res = sin n return...
import sympy a = sympy.Symbol('a') b = sympy.Symbol('b') c = sympy.Symbol('c') d = sympy.Symbol('d') e = sympy.Symbol('e') f = sympy.Symbol('f') g = sympy.Symbol('g') def cos(m): res = sympy.cos(m) return res def sin(n): res = sympy.sin(n) return res x = -65*(((-sin(a)*sin(c) + cos(a)*cos(b)*cos(c))...
Python
zaydzuhri_stack_edu_python
function len_argsort seq begin return sorted range length seq key=lambda x -> length seq at x end function
def len_argsort(seq): return sorted(range(len(seq)), key=lambda x: len(seq[x]))
Python
nomic_cornstack_python_v1
function logout self begin try begin call quit end except any begin comment Catch error if no FTP connection to close (already timed out) pass end end function
def logout(self): try: self.ftp.quit() except: pass # Catch error if no FTP connection to close (already timed out)
Python
nomic_cornstack_python_v1
function run self begin debug format string Fetcher ({}) ready & waiting for responses... _id while not halt begin set info = get response if info is not none begin notify self keyword info end end debug format string Fetcher ({}) exiting... _id end function
def run(self): log.debug("Fetcher ({}) ready & waiting for responses...".format(self._id)) while not self.halt: info = self.response.get() if info is not None: self.notify(**info) log.debug("Fetcher ({}) exiting...".format(self._id))
Python
nomic_cornstack_python_v1
function test_retrival_of_tag self begin set reverse_ip_tag = call ReverseIPTag string 0 1 0 0 1 assert is not none reverse_ip_tag set tag = tag assert equal 0 tag end function
def test_retrival_of_tag(self): reverse_ip_tag = ReverseIPTag("", 0, 1, 0, 0, 1) self.assertIsNotNone(reverse_ip_tag) tag = reverse_ip_tag.tag self.assertEqual(0, tag)
Python
nomic_cornstack_python_v1
class Cell extends object begin set row = 0 set col = 0 set value = none function __init__ self row col value=none begin set row = row set col = col set value = value end function function get_coords self begin return tuple row col end function end class class Completed extends object begin function __init__ self resul...
class Cell(object): row = 0 col = 0 value = None def __init__(self, row, col, value=None): self.row = row self.col = col self.value = value def get_coords(self): return self.row, self.col class Completed(object): def __init__(self, result): self.result...
Python
zaydzuhri_stack_edu_python
function add_repo project_name begin call cprint string Creating repositories.. comment create em repositories set repositories_to_create = list string %s-ios % project_name string %s-android % project_name string %s-plop % project_name string %s-cfg % project_name set bb = call Bitbucket BITBUCKET_USERNAME BITBUCKET_P...
def add_repo(project_name): cprint("Creating repositories..") #create em repositories repositories_to_create = [ "%s-ios" % (project_name), "%s-android" % (project_name), "%s-plop" % (project_name), "%s-cfg" % (project_name), ] bb = Bitbucket(BITBUCKET_USERNAME, BITBU...
Python
nomic_cornstack_python_v1
function notify_once begin call _sd_notify true string READY=1 end function
def notify_once(): _sd_notify(True, 'READY=1')
Python
nomic_cornstack_python_v1
function __init__ self policy_cfg mcts_cfg loss_cfg optimizer_cfg final_selection train_epochs grad_clip temperature device begin call __init__ policy_cfg=policy_cfg loss_cfg=loss_cfg mcts_cfg=mcts_cfg optimizer_cfg=optimizer_cfg final_selection=final_selection train_epochs=train_epochs grad_clip=grad_clip device=devic...
def __init__( self, policy_cfg: DictConfig, mcts_cfg: DictConfig, loss_cfg: DictConfig, optimizer_cfg: DictConfig, final_selection: str, train_epochs: int, grad_clip: float, temperature: float, device: str, ) -> None: super()._...
Python
nomic_cornstack_python_v1