code
stringlengths
10
2.58M
original_code
stringlengths
3
3.18M
original_language
stringclasses
1 value
source
stringclasses
7 values
comment 4.7 Build Order class Project extends object begin string A project has a name and a list of prerequisite projects. Attributes: name: The name prereqs: Projects this one depends on. successors: Projects depending on this one. function __init__ self n begin set name = n set prereqs = list set successors = list ...
# 4.7 Build Order class Project(object): """A project has a name and a list of prerequisite projects. Attributes: name: The name prereqs: Projects this one depends on. successors: Projects depending on this one. """ def __init__(self, n): self.name = n self.pr...
Python
zaydzuhri_stack_edu_python
function from_mins_maxs_angles cls mins maxs angles precision=none begin set tuple x_min y_min z_min = mins set tuple x_max y_max z_max = maxs set lengths = tuple x_max - x_min y_max - y_min z_max - z_min return call cls lengths=lengths angles=angles precision=precision end function
def from_mins_maxs_angles(cls, mins, maxs, angles, precision=None): (x_min, y_min, z_min) = mins (x_max, y_max, z_max) = maxs lengths = (x_max - x_min, y_max - y_min, z_max - z_min) return cls(lengths=lengths, angles=angles, precision=precision)
Python
nomic_cornstack_python_v1
string day: 2020-09-14 url: https://leetcode-cn.com/problems/maximum-length-of-a-concatenated-string-with-unique-characters/ 题目名: 串联字符串的最大长度 给定一个字符串数组 arr,字符串 s 是将 arr 某一子序列字符串连接所得的字符串 如果 s 中的每一个字符都只出现过一次,那么它就是一个可行解。 请返回所有可行解 s 中最长长度 示例: 输入:arr = ["un","iq","ue"] 输出:4 思路: 深度遍历,判断每一种可能性. from typing import List class So...
""" day: 2020-09-14 url: https://leetcode-cn.com/problems/maximum-length-of-a-concatenated-string-with-unique-characters/ 题目名: 串联字符串的最大长度 给定一个字符串数组 arr,字符串 s 是将 arr 某一子序列字符串连接所得的字符串 如果 s 中的每一个字符都只出现过一次,那么它就是一个可行解。 请返回所有可行解 s 中最长长度 示例: 输入:arr = ["un","iq","ue"] 输出:4 思路: 深度遍历,判断每一种可能性. """ from typing import...
Python
zaydzuhri_stack_edu_python
from client import Client from company_name import Company from project import Project from headquarter import Headquarter from manager import Manager from PIL import Image , ImageDraw , ImageFont , ImageColor import random import math import os class TagCloud begin set FONTS = dict string aquawax string Aquawax Black ...
from client import Client from company_name import Company from project import Project from headquarter import Headquarter from manager import Manager from PIL import Image, ImageDraw, ImageFont, ImageColor import random import math import os class TagCloud(): FONTS = {'aquawax': 'Aquawax Black Trial.ttf', 'aria...
Python
zaydzuhri_stack_edu_python
function getStationFromConnection db labName domhub dorCard wirePair wirePosition begin set cursor = call cursor comment select the latest station to connection relation for the specified connection set sql = string SELECT fs.fat_station_id FROM FAT_Station fs INNER JOIN FAT_StationConnection fsc ON fsc.fat_station_id=...
def getStationFromConnection(db, labName, domhub, dorCard, wirePair, wirePosition): cursor = db.cursor() # select the latest station to connection relation for the specified connection sql = """ SELECT fs.fat_station_id FROM FAT_Station fs INNER JOIN FAT_StationConnection fsc ON fsc.fat...
Python
nomic_cornstack_python_v1
function mape_calc Y Yhat begin set n_sequences = shape at 1 set mape = list for i in range n_sequences begin comment Compute numerator and denominator set numerator = Y at tuple slice : : i - Yhat at tuple slice : : i set denominator = Y at tuple slice : : i comment Remove any elements with zeros in the deno...
def mape_calc(Y, Yhat): n_sequences = Y.shape[1] mape = [] for i in range(n_sequences): # Compute numerator and denominator numerator = Y[:, i] - Yhat[:, i] denominator = Y[:, i] # Remove any elements with zeros in the denominator non_zeros = denominator != 0 ...
Python
nomic_cornstack_python_v1
function test_ok_account_id self begin call tm string ../data/input.csv string ../output.csv with open string ../data/input.csv string r as rd ; open string ../output.csv string r as wr begin set csv_rdr = dict reader rd delimiter=string , set csv_wr = dict reader wr delimiter=string , assert equal 0 call cmp list comp...
def test_ok_account_id(self): tm("../data/input.csv","../output.csv"); with open("../data/input.csv","r") as rd,open("../output.csv","r") as wr: csv_rdr = csv.DictReader(rd, delimiter=','); csv_wr = csv.DictReader(wr, delimiter=','); self.assertEqual(0,c...
Python
nomic_cornstack_python_v1
from sys import exit from random import randint class Game extends object begin function __init__ self start begin set deck = list string Introduction string Problem string Closing string Flow Chart string Buzzwords set awake = 10 set pee = 0 set cash = 200 set start = start end function function play self begin set ne...
from sys import exit from random import randint class Game(object): def __init__(self, start): self.deck = [ "Introduction", "Problem", "Closing", "Flow Chart", "Buzzwords" ] self.awake = 10 self.pee =...
Python
zaydzuhri_stack_edu_python
function remove_overrides self begin raise call NotImplementedError format string {} Method `remove_overrides` not implemented! call repr self end function
def remove_overrides(self): raise NotImplementedError( "{} Method `remove_overrides` not implemented!".format( repr(self) ) )
Python
nomic_cornstack_python_v1
async function set_sticker_set_thumb self name user_id thumb=none read_timeout=DEFAULT_NONE write_timeout=DEFAULT_NONE connect_timeout=DEFAULT_NONE pool_timeout=DEFAULT_NONE api_kwargs=none begin call _warn message=string Bot API 6.6 renamed the method 'setStickerSetThumb' to 'setStickerSetThumbnail', hence method 'set...
async def set_sticker_set_thumb( self, name: str, user_id: Union[str, int], thumb: Optional[FileInput] = None, *, read_timeout: ODVInput[float] = DEFAULT_NONE, write_timeout: ODVInput[float] = DEFAULT_NONE, connect_timeout: ODVInput[float] = DEFAULT_NONE, ...
Python
nomic_cornstack_python_v1
function multiply a b begin print a string * b string = a * b end function for var in range 1 11 begin call multiply first var end
def multiply(a, b): print(a, "*", b, "=", a*b) for var in range(1, 11): multiply(first, var)
Python
zaydzuhri_stack_edu_python
function fibonacci n begin if n < 0 begin print string Incorrect input end else comment First Fibonacci number is 0 if n == 1 begin return 0 end else comment Second Fibonacci number is 1 if n == 2 begin return 1 end else begin return call fibonacci n - 1 + call fibonacci n - 2 end end function comment Driver Program se...
def fibonacci(n): if n<0: print("Incorrect input") # First Fibonacci number is 0 elif n==1: return 0 # Second Fibonacci number is 1 elif n==2: return 1 else: return fibonacci(n-1)+fibonacci(n-2) # Driver Program nterms = 4 for i in range(nterms): print(fibon...
Python
jtatman_500k
string Created on Jun 25, 2009 @author: bernie import serial class RW extends object begin function __init__ self port=string COM5 to=0.1 begin set port = port set bathPort = call Serial port timeout=to end function comment write to bath function write self str begin write bathPort str end function comment Read from ba...
''' Created on Jun 25, 2009 @author: bernie ''' import serial class RW(object): def __init__(self, port='COM5', to=0.1): self.port = port self.bathPort = serial.Serial(port, timeout=to) #write to bath def write(self, str): self.bathPort.write(str) ...
Python
zaydzuhri_stack_edu_python
while t begin set t = t - 1 set s = 0 set r = 0 set c = 0 set l1 = list set n = integer input for i in range n begin set l = list map int split input set s = s + l at i if length set l != n begin set r = r + 1 end append l1 l end set l3 = list for i in range n begin set l3 = list for j in range n begin append l3 l1 ...
while t: t -= 1 s = 0 r = 0 c = 0 l1 = [] n = int(input()) for i in range(n): l = list(map(int, input().split())) s += l[i] if len(set(l))!=n: r+=1 l1.append(l) l3=[] for i in range(n): l3=[] for j in range(n): l...
Python
zaydzuhri_stack_edu_python
from otherfunctions import * function get_features row_data begin string 输入:(list) : 一行数据 输入: (list):由特征组成的list function str_ row_data begin set str = 0 set num = 0 for i in row_data begin if i != string begin try begin set aa = decimal i set num = num + 1 end except any begin set str = str + 1 end end end if str >= n...
from otherfunctions import * def get_features(row_data): ''' 输入:(list) : 一行数据 输入: (list):由特征组成的list ''' def str_ (row_data): str = 0 num = 0 for i in row_data: if i != '': try: aa = float(i) ...
Python
zaydzuhri_stack_edu_python
import pickle import streamlit as st import pandas as pd set df = read csv string netflix_titles.csv set df_movies = reset index df at df at string type == string Movie set movies = call Series index index=df_movies at string title print string loading pickle file comment loading the trained model set pickle_in = open ...
import pickle import streamlit as st import pandas as pd df = pd.read_csv('netflix_titles.csv') df_movies = (df[df['type'] == 'Movie']).reset_index() movies = pd.Series(df_movies.index,index=df_movies['title']) print("loading pickle file") # loading the trained model pickle_in = open('classifier.pkl', 'rb') classif...
Python
zaydzuhri_stack_edu_python
function get_field_groupings_for_facility self facility_id page_options=none begin return call PagedRecords api=self url=string facilities/ { facility_id } /groupings options=page_options record_parser=from_api end function
def get_field_groupings_for_facility( self, facility_id: int, page_options: Optional[PageOptions] = None ) -> Iterable[FieldGrouping]: return PagedRecords( api=self, url=f"facilities/{facility_id}/groupings", options=page_options, record_parser=FieldGr...
Python
nomic_cornstack_python_v1
function omega self mass begin return square root spring_constant / mass end function
def omega(self, mass: float) -> float: return np.sqrt(self.spring_constant / mass)
Python
nomic_cornstack_python_v1
function get_all_function_definitions base_most_function begin comment We assume the provided function is the base-most function, so we check all derived contracts comment for a redefinition return list base_most_function + list comprehension function for derived_contract in derived_contracts for function in functions ...
def get_all_function_definitions(base_most_function): # We assume the provided function is the base-most function, so we check all derived contracts # for a redefinition return [base_most_function] + [ function for derived_contract in base_most_function.contract.derived_c...
Python
nomic_cornstack_python_v1
import numpy as np from matplotlib import pyplot as plt set x = array range 1 100 set y = call normal size=shape comment Average a rectangular window of up to 21 samples set yavg = zeros shape=shape for i in range size begin set imin = max i - 10 0 set imax = min i + 10 size set yavg at i = mean np y at slice imin : im...
import numpy as np from matplotlib import pyplot as plt x = np.arange(1, 100) y = np.random.normal(size=x.shape) # Average a rectangular window of up to 21 samples yavg = np.zeros(shape=x.shape) for i in range(yavg.size): imin = max(i - 10, 0) imax = min(i + 10, yavg.size) yavg[i] = np.mean(y[imin:imax]) ...
Python
zaydzuhri_stack_edu_python
comment !/usr/bin/python3 set update_dictionary = update_dictionary set print_sorted_dictionary = print_sorted_dictionary set a_dictionary = dict string language string C ; string number 89 ; string track string Low level set new_dict = call update_dictionary a_dictionary string language string Python call print_sorted...
#!/usr/bin/python3 update_dictionary = __import__('7-update_dictionary').update_dictionary print_sorted_dictionary = __import__('6-print_sorted_dictionary').print_sorted_dictionary a_dictionary = { 'language': "C", 'number': 89, 'track': "Low level" } new_dict = update_dictionary(a_dictionary, 'language', "Python...
Python
zaydzuhri_stack_edu_python
comment # codewars.com/kata/55c6126177c9441a570000cc comment My friend John and I are members of the "Fat to Fit Club (FFC)". John is worried because each month a list with the weights of members is published and each month he is the last on the list which means he is the heaviest. comment I am the one who establishes ...
# # codewars.com/kata/55c6126177c9441a570000cc # My friend John and I are members of the "Fat to Fit Club (FFC)". John is worried because each month a list with the weights of members is published and each month he is the last on the list which means he is the heaviest. # I am the one who establishes the list so I to...
Python
zaydzuhri_stack_edu_python
function how_many_seconds hours begin return hours * 3600 end function print how_many_seconds function find_perimeter length width begin return 2 * length + width end function print find_perimeter
def how_many_seconds(hours): return hours * 3600 print(how_many_seconds) def find_perimeter(length, width): return 2 * (length + width) print(find_perimeter)
Python
zaydzuhri_stack_edu_python
from operator import mul function slices series length begin if length > length series or length < 0 begin raise call ValueError string %s is shorter than %d characters series length end return list comprehension map int series at slice i : i + length : for i in range 0 length series - length + 1 end function function ...
from operator import mul def slices(series, length): if length > len(series) or length < 0: raise ValueError("%s is shorter than %d characters",series, length) return [map(int,series[i:i+length]) for i in range(0,len(series)-length+1)] def largest_product(digits, size): if size > len(digits) or size...
Python
zaydzuhri_stack_edu_python
import sys from os.path import exists from os import makedirs comment command args are in file, and out folder function parseIntoTables tablefile out_folder begin set fin = open tablefile set version_line = read line fin for status in list string pass string warn string fail begin set status_folder = string %s/%s % tup...
import sys from os.path import exists from os import makedirs #command args are in file, and out folder def parseIntoTables( tablefile, out_folder ) : fin = open( tablefile ) version_line = fin.readline() for status in ["pass","warn","fail"] : status_folder = "%s/%s" % (out_folder,status) ...
Python
zaydzuhri_stack_edu_python
class Descriptor begin function __get__ self instance_obj objtype begin raise exception string avoid this end function function decorate self f begin print string decorate f return f end function end class class A begin set my_attr = call Descriptor end class class B begin set _A_my_attr = variables A at string my_attr...
class Descriptor(): def __get__(self, instance_obj, objtype): raise Exception('avoid this') def decorate(self, f): print('decorate', f) return f class A(): my_attr = Descriptor() class B(): _A_my_attr = vars(A)['my_attr'] @_A_my_attr.decorate def foo(self): pri...
Python
zaydzuhri_stack_edu_python
comment !/usr/bin/env python comment coding: utf-8 comment In[ ]: set f = 80 set c = 75.5 set g = 90 set i = 44 print string ------Your Score------ print string Foundation English : + string f print string General Business : + string g print string Introduction to Computer: + string i print string Computer Programming:...
#!/usr/bin/env python # coding: utf-8 # In[ ]: f = 80 c = 75.5 g = 90 i = 44 print("------Your Score------") print("Foundation English :" + str(f)) print("General Business :" + str(g)) print("Introduction to Computer:" + str(i)) print("Computer Programming:" + str(c))
Python
zaydzuhri_stack_edu_python
function load_from_fasta_title self title begin set chromosome = split title string [positions: at 0 set strand = split split title string [strand: at 1 string ] at 0 call add_exons_from_positions_summary split split title string [positions: at 1 string ] at 0 end function
def load_from_fasta_title(self, title): self.chromosome = title.split('[positions:')[0] self.strand = title.split('[strand:')[1].split(']')[0] self.add_exons_from_positions_summary(title.split('[positions:')[1].split(']')[0])
Python
nomic_cornstack_python_v1
function close self begin set _handle_cache = none call llb_buildengine_destroy _engine set _engine = none end function
def close(self): self._handle_cache = None libllbuild.llb_buildengine_destroy(self._engine) self._engine = None
Python
nomic_cornstack_python_v1
comment !usr/bin/env python comment -*- coding:utf-8 -*- import sys import time import requests from lxml import etree from xpinyin import Pinyin call reload sys call setdefaultencoding string utf-8 class Spider begin function __init__ self begin set province = string set province_code = string set city = string set...
#!usr/bin/env python # -*- coding:utf-8 -*- import sys import time import requests from lxml import etree from xpinyin import Pinyin reload(sys) sys.setdefaultencoding('utf-8') class Spider(): def __init__(self): self.province = '' self.province_code = '' self.city = '' self.c...
Python
zaydzuhri_stack_edu_python
from random import randint set tuple m n = tuple 5 5 set Matrix = list comprehension list comprehension random integer - 10 10 for j in range n for i in range m for i in range length Matrix begin for j in range length Matrix at i begin print Matrix at i at j end=string end print end set Matrix = list comprehension list...
from random import randint m, n = 5, 5 Matrix = [[randint(-10, 10) for j in range(n)] for i in range(m)] for i in range(len(Matrix)): for j in range(len(Matrix[i])): print(Matrix[i][j], end=' ') print() Matrix = [[0 if i<j else Matrix[i][j] for j in range(n)] for i in range(m)] for i in range(...
Python
zaydzuhri_stack_edu_python
from itertools import * from functools import * from math import * import re from typing import * set input_file = string inputs/day5 function get_seat_rc b_pass begin set vals = list 64 32 16 8 4 2 1 set row = sum generator expression r for tuple r v in zip vals generator expression b == string B for b in b_pass at sl...
from itertools import * from functools import * from math import * import re from typing import * input_file = "inputs/day5" def get_seat_rc(b_pass): vals = [64, 32, 16, 8, 4, 2, 1] row = sum(r for r, v in zip(vals, (b == "B" for b in b_pass[:7])) if v) col = sum(c for c, v in zip(vals[-3:], (b == "R" ...
Python
zaydzuhri_stack_edu_python
comment !/usr/bin/env python comment coding: utf-8 import pandas as pd import numpy as np import datetime import os import matplotlib.pyplot as plt set dir = string ./../data/mock study/ set files = list directory dir set files_needed = list for file in files begin if string sensor in file begin append files_needed fi...
#!/usr/bin/env python # coding: utf-8 import pandas as pd import numpy as np import datetime import os import matplotlib.pyplot as plt dir = "./../data/mock study/" files = os.listdir(dir) files_needed = [] for file in files: if 'sensor' in file: files_needed.append(file) files_needed = sorted(files_nee...
Python
zaydzuhri_stack_edu_python
comment -*- coding:utf-8 -*- string Created on 2017��7��2�� @author: lijj set member = list string 小甲鱼 string 小布丁 string 米兔 3.1415 list 1 3 4 comment member.append() 加一个元素 append member string 福禄娃娃 print member string ['小甲鱼', '小布丁', '米兔', 3.1415, [1, 3, 4], '福禄娃娃'] comment member.extend() 加多个元素,列表形式 extend member list ...
# -*- coding:utf-8 -*- ''' Created on 2017��7��2�� @author: lijj ''' member =['小甲鱼','小布丁','米兔',3.1415,[1,3,4]] #member.append() 加一个元素 member.append('福禄娃娃') print(member) '''['小甲鱼', '小布丁', '米兔', 3.1415, [1, 3, 4], '福禄娃娃']''' #member.extend() 加多个元素,列表形式 member.extend(['意境',3.124]) print(member) '''['小甲...
Python
zaydzuhri_stack_edu_python
string Part 4: BeautifulSoup fetching of course information All results are printed to the output. import requests from bs4 import BeautifulSoup print string Fetching this course's information from the UMKC catalog using BeautifulSoup... set html = get requests string https://catalog.umkc.edu/course-offerings/graduate/...
""" Part 4: BeautifulSoup fetching of course information All results are printed to the output. """ import requests from bs4 import BeautifulSoup print("Fetching this course's information from the UMKC catalog using BeautifulSoup...") html = requests.get("https://catalog.umkc.edu/course-offerings/gradua...
Python
zaydzuhri_stack_edu_python
comment !/anaconda3/envs/tensorflow/bin/python comment -*- coding: utf-8 -*- string Created by Jingu Kang on 09/11/2018. Copyright © 2018 Jingu Kang. All rights reserved. DESCRIPTION: __getitem__, __len__ 추가. import reprlib import numbers comment 당번 class Duty begin set members = list string 진구 string 대하 string 근회 stri...
#!/anaconda3/envs/tensorflow/bin/python #-*- coding: utf-8 -*- """ Created by Jingu Kang on 09/11/2018. Copyright © 2018 Jingu Kang. All rights reserved. DESCRIPTION: __getitem__, __len__ 추가. """ import reprlib import numbers class Duty: # 당번 members = ['진구', '대하','근회','승현','성빈','지윤','상홍']...
Python
zaydzuhri_stack_edu_python
comment A function to find FXRTs given obsID import requests from io import BytesIO from astropy.io import votable from astropy.coordinates import SkyCoord from astropy.table import Table import math as math import pandas as pd from astropy import wcs from astropy.io import fits import numpy as np function get_wcs_evt ...
# A function to find FXRTs given obsID import requests from io import BytesIO from astropy.io import votable from astropy.coordinates import SkyCoord from astropy.table import Table import math as math import pandas as pd from astropy import wcs from astropy.io import fits import numpy as np def get_wcs_evt(fname): ...
Python
zaydzuhri_stack_edu_python
function init_servo self port begin set servo = call Motor brick port return servo end function
def init_servo(self, port): self.servo = Motor(self.brick, port) return self.servo
Python
nomic_cornstack_python_v1
function compare_versions from_version_id to_version_id begin set from_version = call find_snippet_version from_version_id set to_version = call find_snippet_version to_version_id set snippet = snippet set scope = scope if snippet_id != snippet_id begin call abort 400 string The versions do not belong to the same snipp...
def compare_versions(from_version_id, to_version_id): from_version = find_snippet_version(from_version_id) to_version = find_snippet_version(to_version_id) snippet = from_version.snippet scope = snippet.scope if from_version.snippet_id != to_version.snippet_id: abort(400, 'The versions do ...
Python
nomic_cornstack_python_v1
import unittest from trivia import Game class GameAddTest extends TestCase begin function setUp self begin set game = call Game end function function test_6_players_can_play self begin add game string 1 add game string 2 add game string 3 add game string 4 add game string 5 add game string 6 end function function test_...
import unittest from trivia import Game class GameAddTest(unittest.TestCase): def setUp(self): self.game = Game() def test_6_players_can_play(self): self.game.add('1') self.game.add('2') self.game.add('3') self.game.add('4') self.game.add('5') self.game...
Python
zaydzuhri_stack_edu_python
function calculate_opt_priority opts opt_dicts begin set opt_priority = dictionary generator expression tuple opt - 1 for opt in opts for tuple priority opt_dict in enumerate opt_dicts begin if opt_dict begin for tuple opt value in call iteritems begin if value is not none begin set opt_priority at opt = priority end e...
def calculate_opt_priority(opts, opt_dicts): opt_priority = dict((opt, -1) for opt in opts) for priority, opt_dict in enumerate(opt_dicts): if opt_dict: for opt, value in opt_dict.iteritems(): if value is not None: opt_priority[opt] = priority r...
Python
nomic_cornstack_python_v1
import webbrowser class Movie extends object begin string This class models movies for fan websites that display information about different films set VALID_RATINGS = list string G string PG string PG-13 string R function __init__ self movie_title movie_story_line movie_poster_image movie_youtube_trailer begin set titl...
import webbrowser class Movie(object): """This class models movies for fan websites that display information about different films """ VALID_RATINGS = ['G','PG','PG-13','R'] def __init__(self, movie_title, movie_story_line, movie_poster_image, movie_youtube_trailer): self.title = movie_title ...
Python
zaydzuhri_stack_edu_python
string You have to climb up a ladder. The ladder has exactly N rungs, numbered from 1 to N. With each step, you can ascend by one or two rungs. More precisely: with your first step you can stand on rung 1 or 2, if you are on rung K, you can move to rungs K + 1 or K + 2, finally you have to stand on rung N. Your task is...
""" You have to climb up a ladder. The ladder has exactly N rungs, numbered from 1 to N. With each step, you can ascend by one or two rungs. More precisely: with your first step you can stand on rung 1 or 2, if you are on rung K, you can move to rungs K + 1 or K + 2, finally you have to stand on rung N. Your task is t...
Python
zaydzuhri_stack_edu_python
function decision_vectors self val begin set __decision_vectors = val end function
def decision_vectors(self, val: np.ndarray): self.__decision_vectors = val
Python
nomic_cornstack_python_v1
function scrapeForBacon url crawler begin comment Confirm link is to a Wikipedia page - exit if not if search string wikipedia lower url is none begin print string That doesn't look like a Wikipedia link... print string Try again with a Wikipedia link! exit 1 end comment request html from user url set html = get reques...
def scrapeForBacon(url, crawler): # Confirm link is to a Wikipedia page - exit if not if re.search(r'wikipedia', url.lower()) is None: print("\nThat doesn't look like a Wikipedia link...") print("Try again with a Wikipedia link!") sys.exit(1) # request html from user url html ...
Python
nomic_cornstack_python_v1
function _start_mlflow_run self run_params pipeline begin set node_tags = reduce union list comprehension tags for n in nodes if not call is_nni_gen_search_space_mode and string train in run_params at string tags or string train in node_tags begin if call active_run is none begin comment Create MLFlow run in an experim...
def _start_mlflow_run(self, run_params: Dict[str, Any], pipeline: Pipeline): node_tags = functools.reduce(set.union, [n.tags for n in pipeline.nodes]) if not deepcv.meta.nni_tools.is_nni_gen_search_space_mode() and ('train' in run_params['tags'] or 'train' in node_tags): if mlflow.active_run...
Python
nomic_cornstack_python_v1
function _depth g begin function _explore v begin if depth < 0 begin set depth = if expression parents then 1 + max list - 1 + list comprehension call _explore annotated_graph at u for u in parents else 0 end return depth end function set annotated_graph = dictionary comprehension k : call _Node k v for tuple k v in it...
def _depth(g): def _explore(v): if v.depth < 0: v.depth = ((1 + max([-1] + [_explore(annotated_graph[u]) for u in v.parents])) if v.parents else 0) return v.depth annotated_graph = {k: _Node(k, v) for k, v in g.items()} for v in annotated_graph.valu...
Python
nomic_cornstack_python_v1
comment Author : Junho LEE comment input/output txt format :: Nth_bin Start_of_bin End_of_bin Entry comment filename :: D1H_rootHist_TXT_conversion.py function D1H_roothist_to_txt filename outputpath=string begin from ROOT import TFile , TCanvas , TPad import os if filename at 0 == string / begin set filename = filenam...
#Author : Junho LEE #input/output txt format :: Nth_bin Start_of_bin End_of_bin Entry #filename :: D1H_rootHist_TXT_conversion.py def D1H_roothist_to_txt(filename, outputpath = ''): from ROOT import TFile, TCanvas, TPad import os if(filename[0]=="/"): filename = filename elif(filename[0] == ...
Python
zaydzuhri_stack_edu_python
function taketurn self begin comment get my options from the game set opts = options set choice = random integer 0 length opts - 1 comment print("Choosing " + opts[choice]) comment figure out which color if opts at choice at 0 == string 0 and opts at choice at 2 == string 1 begin set startidx = 3 end else begin set sta...
def taketurn(self): # get my options from the game opts = self.game.options() choice = random.randint(0, len(opts)-1) # print("Choosing " + opts[choice]) # figure out which color if opts[choice][0] == '0' and opts[choice][2] == '1': startidx = 3 else: ...
Python
nomic_cornstack_python_v1
function non_repeating_char s begin set char_freq = dict for c in s begin if c in char_freq begin set char_freq at c = char_freq at c + 1 end else begin set char_freq at c = 1 end end for c in s begin if char_freq at c == 1 begin return c end end end function if __name__ == string __main__ begin print call non_repeati...
def non_repeating_char(s): char_freq = {} for c in s: if c in char_freq: char_freq[c] += 1 else: char_freq[c] = 1 for c in s: if char_freq[c] == 1: return c if __name__ == '__main__': print(non_repeating_char("the quick brown fox jumps ov...
Python
jtatman_500k
function _check_transactional_ddl self begin set table_name = format string yoyo_tmp_{} call get_random_string 10 set table_name_quoted = call quote_identifier table_name set sql = format create_test_table_sql table_name_quoted=table_name_quoted with call transaction as t begin execute self sql rollback t end try begin...
def _check_transactional_ddl(self): table_name = "yoyo_tmp_{}".format(utils.get_random_string(10)) table_name_quoted = self.quote_identifier(table_name) sql = self.create_test_table_sql.format(table_name_quoted=table_name_quoted) with self.transaction() as t: self.execute(sql...
Python
nomic_cornstack_python_v1
function gradient_accumulation_step self begin return get pulumi self string gradient_accumulation_step end function
def gradient_accumulation_step(self) -> Optional[str]: return pulumi.get(self, "gradient_accumulation_step")
Python
nomic_cornstack_python_v1
import time from selenium import webdriver set driver = call Chrome set xml_files = string view-source:http://acl-arc.comp.nus.edu.sg/archives/acl-arc-160301-parscit/ comment Retrieves the html source gode and captures all links. comment list_links is a list of chrome driver elements. get driver xml_files set list_link...
import time from selenium import webdriver driver = webdriver.Chrome() xml_files = 'view-source:http://acl-arc.comp.nus.edu.sg/archives/acl-arc-160301-parscit/' # Retrieves the html source gode and captures all links. # list_links is a list of chrome driver elements. driver.get(xml_files); list_links = driver.find_el...
Python
zaydzuhri_stack_edu_python
comment This implements the neighbor distance method for picking high scoring SNPs in a comment privacy preserving manner. Unlike previous approaches this takes constant time per SNP. comment Note this is still a fairly early version. comment Notation: comment R number of cases comment S number of controls comment N=R+...
############################################## ##This implements the neighbor distance method for picking high scoring SNPs in a ##privacy preserving manner. Unlike previous approaches this takes constant time per SNP. ##Note this is still a fairly early version. ################################################ ##Notat...
Python
zaydzuhri_stack_edu_python
while pin_finder != secret_pin begin set pin_finder = list num1 num2 num3 num4 print pin_finder if num4 == 9 begin if num3 == 9 begin if num2 == 9 begin set num1 = num1 + 1 set num2 = 0 set num3 = 0 set num4 = 0 end else begin set num2 = num2 + 1 set num3 = 0 set num4 = 0 end end else begin set num3 = num3 + 1 set num4...
while pin_finder != secret_pin: pin_finder = [num1, num2, num3, num4] print(pin_finder) if num4 == 9: if num3 == 9: if num2 == 9: num1 += 1 num2 = 0 num3 = 0 num4 = 0 else: num2 += 1 ...
Python
zaydzuhri_stack_edu_python
import numpy as np import cv2 import math import scipy.misc import PIL.Image import statistics import timeit import glob from sklearn import linear_model , datasets from collections import deque comment get a line from a point and unit vectors function lineCalc vx vy x0 y0 begin set scale = 10 set x1 = x0 + scale * vx ...
import numpy as np import cv2 import math import scipy.misc import PIL.Image import statistics import timeit import glob from sklearn import linear_model, datasets from collections import deque # get a line from a point and unit vectors def lineCalc(vx, vy, x0, y0): scale = 10 x1 = x0 + scale * vx y1 = y0...
Python
zaydzuhri_stack_edu_python
comment same method name same no of arguments class A begin function printv self name begin set name = name print string inside A name end function end class class B extends A begin function printv self class1 begin set class1 = class1 print string inside B class1 end function end class set b = call B call printv strin...
# same method name same no of arguments class A: def printv(self,name): self.name=name print("inside A",self.name) class B(A): def printv(self,class1): self.class1=class1 print("inside B",self.class1) b=B() b.printv("aaa") # child class method overrides parent class method
Python
zaydzuhri_stack_edu_python
function update_pit self value pit_index index begin if index == 1 begin set state at pit_index = value end else begin set state at pit_index + M + 1 = value end end function
def update_pit(self, value, pit_index, index): if index == 1: self.state[pit_index] = value else: self.state[pit_index + self.M + 1] = value
Python
nomic_cornstack_python_v1
comment ! usr/bin/env python3 from collections import Counter import sys set filename = argv at 1 comment start base counting at 0 set count = 0 set bases = counter comment parse and define each line type in the fastq file and count up the number comment of bases in each seq line for line in open filename begin set lin...
#! usr/bin/env python3 from collections import Counter import sys filename = sys.argv[1] #start base counting at 0 count = 0 bases = Counter() #parse and define each line type in the fastq file and count up the number # of bases in each seq line for line in open(filename): line = line.rstrip() if count...
Python
zaydzuhri_stack_edu_python
comment !/usr/bin/python from __future__ import print_function import sys import socket import json import time comment GLOBALS comment The amount of money we have set money = 0 set bond_fair = 1000 comment The current state of the market set book = dict comment The buy/sell requests that are sent to the exchange set ...
#!/usr/bin/python from __future__ import print_function import sys import socket import json import time #GLOBALS # The amount of money we have money = 0 bond_fair = 1000 # The current state of the market book = {} # The buy/sell requests that are sent to the exchange orders = [] # buy original prices original_pric...
Python
zaydzuhri_stack_edu_python
function apply fn module mutable=false capture_intermediates=false begin decorator wraps fn function scope_fn scope *args **kwargs begin append capture_stack capture_intermediates try begin return call fn clone module parent=scope *args keyword kwargs end finally begin pop capture_stack end end function if capture_inte...
def apply(fn: Callable[..., Any], module: Module, mutable: CollectionFilter = False, capture_intermediates: Union[bool, Callable[[Module, str], bool]] = False) -> Callable[..., Any]: @functools.wraps(fn) def scope_fn(scope, *args, **kwargs): _context.capture_stack.append(capture_intermediate...
Python
nomic_cornstack_python_v1
function make_anonymous_factorial begin return string YOUR_EXPRESSION_HERE end function
def make_anonymous_factorial(): return 'YOUR_EXPRESSION_HERE'
Python
nomic_cornstack_python_v1
function untrack_click_position self begin call remove_observer _click_observer set _click_observer = none end function
def untrack_click_position(self): self.remove_observer(self._click_observer) self._click_observer = None
Python
nomic_cornstack_python_v1
comment stop --> start = 0 , step = 1 comment star, stop --> step = 1 comment star, stop, step set rng = range 90 100 2 set lst = list rng print lst print rng
# stop --> start = 0 , step = 1 # star, stop --> step = 1 # star, stop, step rng = range(90, 100, 2) lst = list(rng) print(lst) print(rng)
Python
zaydzuhri_stack_edu_python
function _fire_event self event_name *fmtargs **kwargs begin set event = call create_event event_name *fmtargs debug string firing event: %s event call emit event keyword kwargs end function
def _fire_event(self, event_name, *fmtargs, **kwargs): event = self._session.create_event(event_name, *fmtargs) LOG.debug('firing event: %s', event) self._session.emit(event, **kwargs)
Python
nomic_cornstack_python_v1
function set_sweep_spacing self spacing=SWEEP_SPACING_LINEAR begin return string SWE:SPAC + spacing end function
def set_sweep_spacing(self, spacing=SWEEP_SPACING_LINEAR): return 'SWE:SPAC ' + spacing
Python
nomic_cornstack_python_v1
function _build_gradient_table self begin set random_generator = random for i in range 0 h begin for j in range 0 w begin set x = decimal random integer 1 2 * w - w / h set y = decimal random integer 1 2 * h - h / w set s = square root x * x + y * y if s != 0 begin set x = x / s set y = y / s end else begin set x = 0 s...
def _build_gradient_table(self): random_generator = random.Random() for i in range(0, self.h): for j in range(0, self.w): x = float((random_generator.randint(1, 2*self.w)) - self.w) / self.h y = float((random_generator.randint(1, 2*self.h)) - self.h) / self.w ...
Python
nomic_cornstack_python_v1
function __init__ self doi=string reference=string begin set doi = doi set reference = reference end function
def __init__(self, doi='', reference=''): self.doi = doi self.reference = reference
Python
nomic_cornstack_python_v1
import ee comment =========================================== comment MODIS comment =========================================== function get_modis_collection variable logger=none begin string Return the 8 or 16 day composite image collection for MODIS Args: variable: string indicating the variable/band to return (LST_D...
import ee #=========================================== # MODIS #=========================================== def get_modis_collection(variable, logger=None): """Return the 8 or 16 day composite image collection for MODIS Args: variable: string indicating the variable/band to return (LST_...
Python
zaydzuhri_stack_edu_python
import sys import matplotlib.pyplot as plt import csv function graph_file arg begin set y = list set x = list set file = open string ../graphs/ + arg string r with file as csvfile begin set plots = reader csvfile delimiter=string , set gens = 0 for row in plots begin append y decimal row at 0 append m decimal row at ...
import sys import matplotlib.pyplot as plt import csv def graph_file(arg): y = [] x = [] file = open('../graphs/'+arg, 'r') with file as csvfile: plots = csv.reader(csvfile, delimiter=',') gens = 0 for row in plots: y.append(float(row[0])) m.append(float(...
Python
zaydzuhri_stack_edu_python
import sys , os import curses from website import Website from monitor import Monitor from database import create_tables import time import threading import re from test import test_alert_logic function displayConsole displayTime hourlyCheck monitor begin string Displays in two columns : 'Statistiques ' and 'Alerts' th...
import sys, os import curses from website import Website from monitor import Monitor from database import create_tables import time import threading import re from test import test_alert_logic def displayConsole(displayTime,hourlyCheck, monitor): ''' Displays in two columns : 'Statistiques ' and 'Alerts' the up...
Python
zaydzuhri_stack_edu_python
function WritePolyData surface filename begin if not exists path filename begin set writer = call vtkXMLPolyDataWriter call SetInput surface call SetFileName filename write writer return filename end else begin return filename end end function
def WritePolyData(surface, filename): if not os.path.exists(filename): writer = vtk.vtkXMLPolyDataWriter() writer.SetInput(surface) writer.SetFileName(filename) writer.Write() return filename else: return filename
Python
nomic_cornstack_python_v1
import configparser set config = config parser read config string first.ini print sections config print config at string database at string User print config at string database at string Compression
import configparser config = configparser.ConfigParser() config.read('first.ini') print(config.sections()) print(config["database"]["User"]) print(config["database"]["Compression"])
Python
zaydzuhri_stack_edu_python
function construct_insert_file_query virtualFile physicalFile begin set queryTemplate = call Template string PREFIX mu: <http://mu.semte.ch/vocabularies/core/> PREFIX nfo: <http://www.semanticdesktop.org/ontologies/2007/03/22/nfo#> PREFIX nie: <http://www.semanticdesktop.org/ontologies/2007/01/19/nie#> PREFIX dct: <htt...
def construct_insert_file_query(virtualFile, physicalFile): queryTemplate = Template(""" PREFIX mu: <http://mu.semte.ch/vocabularies/core/> PREFIX nfo: <http://www.semanticdesktop.org/ontologies/2007/03/22/nfo#> PREFIX nie: <http://www.semanticdesktop.org/ontologies/2007/01/19/nie#> PREFIX dct: <htt...
Python
nomic_cornstack_python_v1
function __init__ self gateway=none ip_cidr=none ips=none netmask_bits=none netmask_ip_4=none begin comment Initialize members of the class set gateway = gateway set ip_cidr = ip_cidr set ips = ips set netmask_bits = netmask_bits set netmask_ip_4 = netmask_ip_4 end function
def __init__(self, gateway=None, ip_cidr=None, ips=None, netmask_bits=None, netmask_ip_4=None, ): # Initialize members of the class self.gateway = gateway self.ip_cidr = ip_cidr self.ips = i...
Python
nomic_cornstack_python_v1
for i in range length A begin set min_index = i for j in range i + 1 length A begin if A at min_index > A at j begin set min_index = j end end set tuple A at i A at min_index = tuple A at min_index A at i end print string Sorted array print A
for i in range(len(A)): min_index = i for j in range(i + 1, len(A)): if A[min_index] > A[j]: min_index = j A[i], A[min_index] = A[min_index], A[i] print("Sorted array") print(A)
Python
zaydzuhri_stack_edu_python
import redis set redis = call Redis call flushall set FEM = string female_names_set with open string female-names.txt string r as f begin for line in f begin call zadd FEM dict right strip line 0 end end print string Finished loading the names print call zrange FEM 4500 4510 print string Searching that start with susan...
import redis redis = redis.Redis() redis.flushall() FEM = "female_names_set" with open("female-names.txt", "r") as f: for line in f: redis.zadd(FEM, {line.rstrip(): 0}) print("Finished loading the names") print(redis.zrange(FEM, 4500, 4510)) print("Searching that start with susann") for tup in redis.zs...
Python
zaydzuhri_stack_edu_python
function get_voronoi_polygons per_location_data begin set points = geometry comment voronoi_regions_from_coords() returns only 2 values in our case. comment pylint: disable=unbalanced-tuple-unpacking set tuple region_polys _ = call voronoi_regions_from_coords points call load_israel_polygon set region_polys = call GeoS...
def get_voronoi_polygons(per_location_data): points = per_location_data.geometry # voronoi_regions_from_coords() returns only 2 values in our case. region_polys, _ = geovoronoi.voronoi_regions_from_coords( # pylint: disable=unbalanced-tuple-unpacking points, load_israel_polygon()) region_polys ...
Python
nomic_cornstack_python_v1
function _forward self *args calc_score=false begin with call using_config string train false ; call no_backprop_mode begin if calc_score begin call self *args return y end else begin if predictor is none begin print string [ERROR] predictor is not set or not build yet. return end comment TODO: it passes all the args, ...
def _forward(self, *args, calc_score=False): with chainer.using_config('train', False), chainer.no_backprop_mode(): if calc_score: self(*args) return self.y else: if self.predictor is None: print("[ERROR] predictor is no...
Python
nomic_cornstack_python_v1
async function create_and_store_credential_definition self origin_did schema signature_type=none tag=none support_revocation=false begin try begin set tuple cred_def cred_def_private key_proof = await call run_in_executor none lambda -> call create origin_did schema signature_type or DEFAULT_SIGNATURE_TYPE tag or DEFA...
async def create_and_store_credential_definition( self, origin_did: str, schema: dict, signature_type: str = None, tag: str = None, support_revocation: bool = False, ) -> Tuple[str, str]: try: ( cred_def, cred_def_pr...
Python
nomic_cornstack_python_v1
comment !/usr/bin/python comment -*- coding: utf-8 -*- import pygame import math from random import random , randint , uniform from os import getcwd , system from sys import exit comment color de fondo set background_colour = tuple 2 0 0 comment ruta de la carpeta actual set path = get current directory + string / comm...
#!/usr/bin/python # -*- coding: utf-8 -*- import pygame import math from random import random, randint, uniform from os import getcwd, system from sys import exit # color de fondo background_colour = (2,0,0) # ruta de la carpeta actual path = getcwd() +'/' # colores predeterminados blue = (0, 0, 255) red = (255, 0, ...
Python
zaydzuhri_stack_edu_python
import bisect import math import random class Leaf begin function __init__ self previous_leaf next_leaf parent branching_factor=16 begin comment 前驱叶子 set previous = previous_leaf comment 后驱叶子 set next = next_leaf comment 父亲结点 set parent = parent comment 分子因子 set branching_factor = branching_factor comment 用于存储key的结点 se...
import bisect import math import random class Leaf: def __init__(self, previous_leaf, next_leaf, parent, branching_factor=16): #前驱叶子 self.previous = previous_leaf #后驱叶子 self.next = next_leaf #父亲结点 self.parent = parent #分子因子 self.branching_factor = br...
Python
zaydzuhri_stack_edu_python
comment Basic password generator, no prompt import random set pool = string ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz1234567890!@#$%&? set passlen = 9 set gen_pw = string Your password is { join string random sample pool passlen } print gen_pw
# Basic password generator, no prompt import random pool = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz1234567890!@#$%&?" passlen = 9 gen_pw = F"Your password is {''.join(random.sample(pool,passlen))}" print(gen_pw)
Python
zaydzuhri_stack_edu_python
function update self dependency svc svc_ref old_properties new_value=false begin comment type: (Any, Any, ServiceReference, dict, bool) -> None string Called by a dependency manager when the properties of an injected dependency have been updated. :param dependency: The dependency handler :param svc: The injected servic...
def update(self, dependency, svc, svc_ref, old_properties, new_value=False): # type: (Any, Any, ServiceReference, dict, bool) -> None """ Called by a dependency manager when the properties of an injected dependency have been updated. :param dependency: The dependency handler ...
Python
jtatman_500k
comment ----------------------------------------------------------------------------- comment Name: Exercise 5 (Exercise5.py) comment Purpose: Understading statement coding in Python comment Author: Owen Wong comment Created: 10/12/2018 comment Updated: 10/15/2018 comment -----------------------------------------------...
#----------------------------------------------------------------------------- # Name: Exercise 5 (Exercise5.py) # Purpose: Understading statement coding in Python # # Author: Owen Wong # Created: 10/12/2018 # Updated: 10/15/2018 #----------------------------------------------------------------...
Python
zaydzuhri_stack_edu_python
import pandas from pandas.plotting import scatter_matrix import matplotlib.pyplot as plt from sklearn import model_selection from sklearn.metrics import classification_report from sklearn.metrics import confusion_matrix from sklearn.metrics import accuracy_score from sklearn.linear_model import LogisticRegression from ...
import pandas from pandas.plotting import scatter_matrix import matplotlib.pyplot as plt from sklearn import model_selection from sklearn.metrics import classification_report from sklearn.metrics import confusion_matrix from sklearn.metrics import accuracy_score from sklearn.linear_model import LogisticRegression from ...
Python
zaydzuhri_stack_edu_python
function predict_all self split=string valid mode=string tail_batch begin eval with no grad begin set results = dict set train_iter = iterate data_iter at format string {}_{} split split mode string _ at 0 set tuple total_sub total_rel total_obj total_ranks = tuple list list list list for tuple step batch in enume...
def predict_all(self, split='valid', mode='tail_batch'): self.model.eval() with torch.no_grad(): results = {} train_iter = iter(self.data_iter['{}_{}'.format(split, mode.split('_')[0])]) total_sub, total_rel, total_obj, total_ranks = [], [], [], [] for step, batch in enumerate(train_iter): sub, r...
Python
nomic_cornstack_python_v1
from toys import Toys class Workshop extends Toys begin string Workshop toy that extends toys function __init__ self battery min_age name description p_id width height rooms begin string Workshop initializer set _is_battery_operated = battery set _min_rec_age = min_age set _name = name set _description = description se...
from toys import Toys class Workshop(Toys): """Workshop toy that extends toys""" def __init__(self, battery, min_age, name, description, p_id, width, height, rooms): """Workshop initializer""" self._is_battery_operated = battery self._min_rec_age = min_age self._name = name ...
Python
zaydzuhri_stack_edu_python
comment Useful Metric class implementations for PyTorch mimicking tf.keras.metric API import numpy as np import torch from collections import defaultdict from sklearn.metrics import roc_auc_score , precision_recall_curve , auc class Accuracy begin string Update Accuracy in online function __init__ self begin set _num_s...
# Useful Metric class implementations for PyTorch mimicking tf.keras.metric API import numpy as np import torch from collections import defaultdict from sklearn.metrics import roc_auc_score, \ precision_recall_curve, auc class Accuracy: """ Update Accuracy in online """ def __init__(self): self...
Python
zaydzuhri_stack_edu_python
function test_convertable self begin for tuple graph labeled_edges in list tuple verma_1 set literal tuple string V1 string V2 tuple string V2 string V3 tuple string V3 string V4 tuple string { DEFULT_PREFIX } 0 string V2 tuple string { DEFULT_PREFIX } 0 string V4 begin with call subTest begin call assert_labeled_conve...
def test_convertable(self): for graph, labeled_edges in [ ( verma_1, { ("V1", "V2"), ("V2", "V3"), ("V3", "V4"), (f"{DEFULT_PREFIX}0", "V2"), (f"{DEFULT_PREFIX}0", "V4"...
Python
nomic_cornstack_python_v1
import ast import os class Values extends object begin function __init__ self begin if exists path string __atcp_configurations__/configuration.py begin from __atcp_configurations__ import configuration set __values = configuration end else begin set __values = dict end end function function __str__ self begin return ...
import ast import os class Values(object): def __init__(self): if os.path.exists('__atcp_configurations__/configuration.py'): from __atcp_configurations__ import configuration self.__values = configuration.configuration else: self.__values = {} def __str__(...
Python
zaydzuhri_stack_edu_python
from db import get_db class Rating begin function __init__ self user_id product_id rating begin set user_id = user_id set product_id = product_id set rating = rating end function decorator staticmethod function get user_id product_id begin set db = call get_db set rating = call fetchone if not rating begin return none ...
from db import get_db class Rating: def __init__(self, user_id, product_id, rating): self.user_id = user_id self.product_id = product_id self.rating = rating @staticmethod def get(user_id, product_id): db = get_db() rating = db.execute( "SELECT * FROM ra...
Python
zaydzuhri_stack_edu_python
function iqn self begin return get pulumi self string iqn end function
def iqn(self) -> str: return pulumi.get(self, "iqn")
Python
nomic_cornstack_python_v1
comment !/usr/bin/env python import helpers from imutils import paths import numpy as np import imutils import cv2 import pickle import os.path import argparse set parser = call ArgumentParser description=string Randomly solve captcha image. call add_argument string project nargs=string ? default=string default help=st...
#!/usr/bin/env python import helpers from imutils import paths import numpy as np import imutils import cv2 import pickle import os.path import argparse parser = argparse.ArgumentParser(description='Randomly solve captcha image.') parser.add_argument('project', nargs='?', default="default", help='n...
Python
zaydzuhri_stack_edu_python
function gc dna begin function isGC n begin if n == string C or n == string G begin return 1.0 end else begin return 0.0 end end function return sum map isGC dna / length dna * 100.0 end function comment dna = "CCACCCTCGTGGTATGGCTAGGCATTCAGGAACCGGAGAACGCTTCAGACCAGCCCGGACTGGGAACCTGCGGGCAGTAGGTGGAAT" comment print gc(dna...
def gc(dna): def isGC(n): if n == 'C' or n == 'G': return 1.0; else: return 0.0; return (sum(map(isGC,dna)) / len(dna)) * 100.0 #dna = "CCACCCTCGTGGTATGGCTAGGCATTCAGGAACCGGAGAACGCTTCAGACCAGCCCGGACTGGGAACCTGCGGGCAGTAGGTGGAAT" #print gc(dna) id = "" p = 0.0 with open("5_C...
Python
zaydzuhri_stack_edu_python
comment coding:utf-8 import sys set my_file = open argv at 1 string r set save_1 = open string col1.txt string w set save_2 = open string col2.txt string w for line in my_file begin set tuple item1 item2 item3 item4 = split strip line string write save_1 item1 + string write save_2 item2 + string end comment item = lin...
#coding:utf-8 import sys my_file = open(sys.argv[1], "r") save_1 = open("col1.txt", "w") save_2 = open("col2.txt", "w") for line in my_file: item1, item2, item3, item4 = line.strip().split("\t") save_1.write(item1+"\n") save_2.write(item2+"\n") #item = line.strip().split("\t") #print item[0] ...
Python
zaydzuhri_stack_edu_python
comment coding: utf8 from __future__ import unicode_literals from django.core.validators import RegexValidator from django.utils import timezone from django.db import models from geoposition.fields import GeopositionField from tagging.fields import TagField from tagging.models import Tag comment Create your models here...
# coding: utf8 from __future__ import unicode_literals from django.core.validators import RegexValidator from django.utils import timezone from django.db import models from geoposition.fields import GeopositionField from tagging.fields import TagField from tagging.models import Tag # Create your models here. class User...
Python
zaydzuhri_stack_edu_python
for i in range N begin append A integer input end set B = sorted A set C = list set D = list for i in range N begin if i % 2 == 0 begin append C A at i append D B at i end end print N + 1 // 2 - length set C ? set D
for i in range(N): A.append(int(input())) B=sorted(A) C=[] D=[] for i in range(N): if i%2==0: C.append(A[i]) D.append(B[i]) print((N+1)//2-len(set(C) & set(D)))
Python
zaydzuhri_stack_edu_python
comment -*- coding: utf-8 -*- comment @Time : 2020/3/17 22:27 comment @Author : guoyunfei.0603 comment @File : home_work.py string 一个足球队再寻找10-12岁的小女孩,编写一个程序,询问用户的性别(m男,f女) 然后显示一条消息这个人能否加入球队,询问10次后,输出满足条件的人数 comment def football(x,y): comment count = 0 comment for item in range(x,y): comment sex = input("请问你的性别是:") comm...
# -*- coding: utf-8 -*- # @Time : 2020/3/17 22:27 # @Author : guoyunfei.0603 # @File : home_work.py """ 一个足球队再寻找10-12岁的小女孩,编写一个程序,询问用户的性别(m男,f女) 然后显示一条消息这个人能否加入球队,询问10次后,输出满足条件的人数 """ # def football(x,y): # count = 0 # for item in range(x,y): # sex = input("请问你的性别是:") # # if sex == 'f': ...
Python
zaydzuhri_stack_edu_python
function exception_retry_middleware make_request web3 errors retries=5 begin function middleware method params begin if call check_if_retry_on_failure method begin for i in range retries begin try begin return call make_request method params end comment https://github.com/python/mypy/issues/5349 comment type: ignore ex...
def exception_retry_middleware( make_request: Callable[[RPCEndpoint, Any], RPCResponse], web3: "Web3", errors: Collection[Type[BaseException]], retries: int = 5, ) -> Callable[[RPCEndpoint, Any], RPCResponse]: def middleware(method: RPCEndpoint, params: Any) -> RPCResponse: if check_if_retry...
Python
nomic_cornstack_python_v1