code
stringlengths
10
2.58M
original_code
stringlengths
3
3.18M
original_language
stringclasses
1 value
source
stringclasses
7 values
function add cls name code begin set attribute cls name code end function
def add(cls, name: str, code: int) -> None: setattr(cls, name, code)
Python
nomic_cornstack_python_v1
import json from pyvis.network import Network import os class show_path begin function __init__ self begin set graph = call Network height=string 750px width=string 100% directed=true with open string layouts\path_layout.json as f begin set composite_options = load json f end end function function show_graph self begin...
import json from pyvis.network import Network import os class show_path: def __init__(self): self.graph = Network(height="750px", width="100%", directed=True) with open('layouts\path_layout.json') as f: self.composite_options = json.load(f) def show_graph(self): dirOutpu...
Python
zaydzuhri_stack_edu_python
comment !/usr/bin/env python comment -*- coding: utf-8 -*- import json import gzip function extract user begin string Returns the id, name from the json data set j_form = loads user set tuple twitter_id screen_name = tuple j_form at string id j_form at string screen_name return tuple twitter_id screen_name end function...
#!/usr/bin/env python # -*- coding: utf-8 -*- import json import gzip def extract(user): """Returns the id, name from the json data""" j_form = json.loads(user) twitter_id, screen_name = j_form['id'], j_form['screen_name'] return twitter_id, screen_name def extract_users_from_files(data_filename, sa...
Python
zaydzuhri_stack_edu_python
set name = list string andela set another_name = name set name at 1 = string a set another_name = join string another_name print another_name
name = list("andela") another_name = name name[1] = "a" another_name = "".join(another_name) print(another_name)
Python
zaydzuhri_stack_edu_python
class LinkedList begin function __init__ self head=none begin set head = head end function function __iter__ self begin set current = head return self end function function __next__ self begin if not current begin raise StopIteration end set node = current set current = next_node return node end function function add s...
class LinkedList(): def __init__(self, head=None): self.head = head def __iter__(self): self.current = self.head return self def __next__(self): if not self.current: raise StopIteration node = self.current self.current = self.current.next_node return node def add(self, data...
Python
zaydzuhri_stack_edu_python
import csv import Image import numpy as np import matplotlib.pyplot as plt function get_data begin with open string letter.data string r as f begin set images = reader f delimiter=string set X = list set Y = list for row in images begin set inp = list set out = row at 1 comment out = getCharIndexArray(char) set p = ...
import csv import Image import numpy as np import matplotlib.pyplot as plt def get_data(): with open("letter.data",'r') as f: images = csv.reader(f, delimiter='\t') X=[] Y=[] for row in images: inp=[] out = row[1] #out = getCharIndexArray(char) p = row[6:] for j in p: if j=='': continu...
Python
zaydzuhri_stack_edu_python
function rename_pulsar oldname newname existdb=none begin set db = existdb or call Database call connect comment Get the pulsar_id of the entry to rename set pulsar_id = call get_pulsarid oldname set trans = call begin try begin comment Check if the new name is valid call check_new_name pulsar_id newname comment Rename...
def rename_pulsar(oldname, newname, existdb=None): db = existdb or database.Database() db.connect() # Get the pulsar_id of the entry to rename pulsar_id = utils.get_pulsarid(oldname) trans = db.begin() try: # Check if the new name is valid check_new_name(pulsar_id, newname) ...
Python
nomic_cornstack_python_v1
comment -*- coding: utf-8 -*- import scrapy from bs4 import BeautifulSoup from beikeSpider.items import IpItem class XiciSpider extends Spider begin set cur_page = 1 set max_page = 3869 set base_url = string http://www.xicidaili.com/nn/%s set name = string xici set allowed_domains = list string www.xicidaili.com set st...
# -*- coding: utf-8 -*- import scrapy from bs4 import BeautifulSoup from beikeSpider.items import IpItem class XiciSpider(scrapy.Spider): cur_page = 1 max_page = 3869 base_url = "http://www.xicidaili.com/nn/%s" name = 'xici' allowed_domains = ['www.xicidaili.com'] start_urls = [base_url % cur_...
Python
zaydzuhri_stack_edu_python
comment Python program for implementation of MergeSort function mergesort list begin if length list > 1 begin set mid = length list // 2 set left_list = list at slice : mid : set right_list = list at slice mid : : call mergesort left_list call mergesort right_list set tuple i j k = tuple 0 0 0 while i < length left...
# Python program for implementation of MergeSort def mergesort(list): if len(list)>1: mid = len(list)//2 left_list = list[:mid] right_list = list[mid:] mergesort(left_list) mergesort(right_list) i, j, k = 0, 0, 0 while i < len(left_list) and j < len(right_list...
Python
zaydzuhri_stack_edu_python
function run self begin set parser = call ArgumentParser description=string CLI for process json comment parse CLI arg : keys levels for final output json call add_argument string output_dict_keys type=str nargs=string + help=string run the script via : cat Python/data/input.json | python Python/src/nest_dev.py <key1> ...
def run(self): parser = argparse.ArgumentParser(description='CLI for process json') # parse CLI arg : keys levels for final output json parser.add_argument('output_dict_keys', type=str, nargs='+', help="""run the script via : \n cat Python...
Python
nomic_cornstack_python_v1
set message = string This is a message. print message set message = string This replaces the first message. print message
message = "This is a message." print(message) message = "This replaces the first message." print(message)
Python
zaydzuhri_stack_edu_python
function __onbt__ self begin pass end function
def __onbt__(self): pass
Python
nomic_cornstack_python_v1
function test_parameters_missing begin with raises ValueError begin call Cosmology Omega_c=0.25 end comment Check that a single missing compulsory parameter is noticed with raises ValueError begin call Cosmology Omega_c=0.25 Omega_b=0.05 h=0.7 A_s=2.1e-09 end with raises ValueError begin call Cosmology Omega_c=0.25 Ome...
def test_parameters_missing(): with pytest.raises(ValueError): ccl.Cosmology(Omega_c=0.25) # Check that a single missing compulsory parameter is noticed with pytest.raises(ValueError): ccl.Cosmology(Omega_c=0.25, Omega_b=0.05, h=0.7, A_s=2.1e-9) with pytest.raises(ValueError): ...
Python
nomic_cornstack_python_v1
function test_evidencevariable_2 base_settings begin set filename = base_settings at string unittest_data_dir / string evidencevariable-example-mRS0-2-at-90days.json set inst = call parse_file filename content_type=string application/json encoding=string utf-8 assert string EvidenceVariable == resource_type call impl_e...
def test_evidencevariable_2(base_settings): filename = ( base_settings["unittest_data_dir"] / "evidencevariable-example-mRS0-2-at-90days.json" ) inst = evidencevariable.EvidenceVariable.parse_file( filename, content_type="application/json", encoding="utf-8" ) assert "Evidence...
Python
nomic_cornstack_python_v1
class Solution extends object begin function kClosest self points K begin comment points.sort(key= lambda x: x[0]**2 + x[1]**2) set res = sorted points key=lambda x -> x at 0 ^ 2 + x at 1 ^ 2 return res at slice : K : end function end class
class Solution(object): def kClosest(self, points, K): # points.sort(key= lambda x: x[0]**2 + x[1]**2) res = sorted(points, key= lambda x: x[0]**2 + x[1]**2) return res[:K]
Python
zaydzuhri_stack_edu_python
function get cls name begin call initialize if is instance name cls begin return name end else begin return mapping at name end end function
def get(cls, name): cls.initialize() if isinstance(name, cls): return name else: return cls.mapping[name]
Python
nomic_cornstack_python_v1
function __init__ __self__ application tenant endpoint_ltm_policies=none existing_monitor=none existing_pool=none existing_snat_pool=none existing_tls_client_profile=none existing_tls_server_profile=none existing_waf_security_policy=none load_balancing_mode=none monitor=none pool_members=none security_log_profiles=none...
def __init__(__self__, *, application: pulumi.Input[str], tenant: pulumi.Input[str], endpoint_ltm_policies: Optional[pulumi.Input[Sequence[pulumi.Input[str]]]] = None, existing_monitor: Optional[pulumi.Input[str]] = None, existing_pool...
Python
nomic_cornstack_python_v1
function menuItemJson restaurant_id menuitem_id begin set items = call one return call jsonify MenuItem=serialize end function
def menuItemJson(restaurant_id, menuitem_id): items = session.query(MenuItem).filter_by(id=menuitem_id).one() return jsonify(MenuItem=items.serialize)
Python
nomic_cornstack_python_v1
function _generate_pdf self req_id begin set pdf = none for tuple page_num image_path in enumerate call _save_pages req_id 1 begin call page_update req_id page_num if pdf is none begin set im = open image_path set wheight = size at 0 set wwidth = size at 1 close im set pdf = call FPDF string L string pt list wwidth whe...
def _generate_pdf(self, req_id): pdf = None for page_num, image_path in enumerate(self._save_pages(req_id), 1): page_update(req_id, page_num) if pdf is None: im = Image.open(image_path) wheight = im.size[0] wwidth = im.size[1] ...
Python
nomic_cornstack_python_v1
comment !/usr/bin/python3 from lxml import html import requests from time import sleep import json import argparse from random import randint import urllib3 import sys from pprint import pprint call disable_warnings InsecureRequestWarning function parse_finance_page symbol begin set headers = dict string Accept string ...
#!/usr/bin/python3 from lxml import html import requests from time import sleep import json import argparse from random import randint import urllib3 import sys from pprint import pprint urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning) def parse_finance_page(symbol): headers = { "A...
Python
zaydzuhri_stack_edu_python
function __eq__ self other begin return __dict__ == __dict__ end function
def __eq__(self, other): return self.__dict__ == other.__dict__
Python
nomic_cornstack_python_v1
set a = 1 set b = 3 set c = a + b print c
a=1 b=3 c=a+b print(c)
Python
zaydzuhri_stack_edu_python
import json import datetime as dt import os import csv import emoji set fieldnames = list string date string username string text with open string scanteaksg.csv mode=string w encoding=string utf-8 as csv_file begin set writer = dict writer csv_file fieldnames=fieldnames call writeheader for filename in list directory ...
import json import datetime as dt import os import csv import emoji fieldnames = ['date', 'username', 'text'] with open('scanteaksg.csv', mode='w', encoding="utf-8") as csv_file: writer = csv.DictWriter(csv_file, fieldnames=fieldnames) writer.writeheader() for filename in os.listdir(os.getcwd()): with o...
Python
zaydzuhri_stack_edu_python
comment -*- coding: utf-8 -*- string This module creates a spectrum of the data given using the A matrix. It uses a Data file which gathers all the paths toward the needed data. Those are : - the A matrix of the lane - the fts file of which we want the spectrum - the envelope and the thickness of the lanes - the number...
# -*- coding: utf-8 -*- """ This module creates a spectrum of the data given using the A matrix. It uses a Data file which gathers all the paths toward the needed data. Those are : - the A matrix of the lane - the fts file of which we want the spectrum - the envelope ...
Python
zaydzuhri_stack_edu_python
function is_confirmed self begin return button_pressed == BUTTON_YES end function
def is_confirmed(self): return self.button_pressed == self.BUTTON_YES
Python
nomic_cornstack_python_v1
import heapq from collections import Counter , namedtuple class Node extends named tuple string Node list string left string right begin function walk self code acc begin walk code acc + string 0 walk code acc + string 1 end function end class class Leaf extends named tuple string Leaf list string char begin function w...
import heapq from collections import Counter,namedtuple class Node(namedtuple("Node",["left","right"])): def walk(self,code,acc): self.left.walk(code,acc+"0") self.right.walk(code, acc+"1") class Leaf(namedtuple("Leaf",["char"])): def walk(self,code,acc): code[self.char]=acc or "0" # ...
Python
zaydzuhri_stack_edu_python
function tunnel1_phase1_dh_group_numbers self begin return get pulumi self string tunnel1_phase1_dh_group_numbers end function
def tunnel1_phase1_dh_group_numbers(self) -> Optional[pulumi.Input[Sequence[pulumi.Input[int]]]]: return pulumi.get(self, "tunnel1_phase1_dh_group_numbers")
Python
nomic_cornstack_python_v1
function print_metadata self camera pixel_size file=stdout begin print self end=string file=file print call cam_to_string camera end=string file=file print format string pixels;{} pixel_size file=file end function
def print_metadata(self, camera, pixel_size, file = sys.stdout): print(self, end = '\n', file = file) print(cam_to_string(camera), end = '\n', file = file) print("pixels;{}".format(pixel_size), file = file)
Python
nomic_cornstack_python_v1
import sys import math import numpy as np import scipy.io import matplotlib.pyplot as plt from svm import SVM , plot_data , plot_linear_separator function svmLinearToyExample begin string - Load linear separable toy dataset - Train a linear SVM - Print training and test error - Plot data and separator set C = 10 string...
import sys import math import numpy as np import scipy.io import matplotlib.pyplot as plt from svm import SVM, plot_data, plot_linear_separator def svmLinearToyExample(): ''' - Load linear separable toy dataset - Train a linear SVM - Print training and test error - Plot data and separator ...
Python
zaydzuhri_stack_edu_python
function get_phi_chi_omega self angles begin set tuple phi chi omega = angles at slice 0 : 3 : return tuple phi chi omega end function
def get_phi_chi_omega(self, angles): (phi, chi, omega) = angles[0:3] return (phi, chi, omega)
Python
nomic_cornstack_python_v1
string The Celery framework works with the concept of distribution of work units (tasks) by exchanging messages among the machines that are interconnected as a network, or local workers. A task is the key concept in Celery; any sort of job we must distribute has to be encapsulated in a task beforehand. why use celery W...
""" The Celery framework works with the concept of distribution of work units (tasks) by exchanging messages among the machines that are interconnected as a network, or local workers. A task is the key concept in Celery; any sort of job we must distribute has to be encapsulated in a task beforehand. why use celery We...
Python
zaydzuhri_stack_edu_python
comment !/usr/bin/env python import sys import re comment YOUR CODE GOES HERE class ParseException extends Exception begin function __init__ self value begin set _value = value end function function __str__ self begin return string _value end function end class function parse_line line begin if not starts with line str...
#!/usr/bin/env python import sys import re # YOUR CODE GOES HERE class ParseException(Exception): def __init__(self, value): self._value = value def __str__(self): return str(self._value) def parse_line(line): if not line.startswith('a'): if not line.startswith('c'): if...
Python
zaydzuhri_stack_edu_python
comment !/usr/bin/env python2 comment Copyright (c) 2015-2016 The Bitcoin Core developers comment Distributed under the MIT software license, see the accompanying comment file COPYING or http://www.opensource.org/licenses/mit-license.php. import hashlib import sys import os from random import SystemRandom import base64...
#!/usr/bin/env python2 # Copyright (c) 2015-2016 The Bitcoin Core developers # Distributed under the MIT software license, see the accompanying # file COPYING or http://www.opensource.org/licenses/mit-license.php. import hashlib import sys import os from random import SystemRandom import base64 import hmac if len(s...
Python
jtatman_500k
function unbind self begin if _program_id is none begin raise call RuntimeError string Error while trying unbind a non-compiled shader program. end call glUseProgram 0 end function
def unbind(self): if self._program_id is None: raise RuntimeError("Error while trying unbind a non-compiled shader program.") GL.glUseProgram(0)
Python
nomic_cornstack_python_v1
function has_common_target self drug_a drug_b begin set set_a = target_data at drug_a set set_b = target_data at drug_b set num_common_targets = length intersection set_a set_b if num_common_targets == 0 begin return 0 end else begin return 1 end end function
def has_common_target(self, drug_a, drug_b): set_a = self.target_data[drug_a] set_b = self.target_data[drug_b] num_common_targets = len(set_a.intersection(set_b)) if num_common_targets == 0: return 0 else: return 1
Python
nomic_cornstack_python_v1
comment !/usr/bin/env python3 comment -*- coding: utf-8 -*- import base64 from pprint import PrettyPrinter set pp = call PrettyPrinter indent=4 class User extends object begin function __init__ self username password name email begin set username = username set password = password set name = name set email = email end ...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- import base64 from pprint import PrettyPrinter pp = PrettyPrinter(indent=4) class User(object): def __init__(self, username, password, name, email): self.username = username self.password = password self.name = name self.email = email...
Python
zaydzuhri_stack_edu_python
function make_album artist title tracks=0 begin if tracks != 0 begin return dict string artist artist ; string title title ; string tracks tracks end return dict string artist artist ; string title title end function print call make_album string Weezer string The Green Album print call make_album string Avicii string T...
def make_album(artist, title, tracks=0): if tracks != 0: return {'artist': artist, 'title': title, 'tracks': tracks} return {'artist': artist, 'title': title} print(make_album('Weezer', 'The Green Album')) print(make_album('Avicii', 'The Nights')) print(make_album('Weird Al', 'Running with Scissors')) ...
Python
zaydzuhri_stack_edu_python
comment calculate correlation import numpy as np import json import math from CausalCalculator import CausalCalculator function calcCausalFlow granger_list begin set flow_x = 0 set flow_y = 0 set intensity = 0 for i in list - 1 0 1 begin set flow_x = flow_x + - 1 * granger_list at - 1 + 1 at i + 1 + granger_list at 1 +...
# calculate correlation import numpy as np import json import math from CausalCalculator import CausalCalculator def calcCausalFlow(granger_list): flow_x = 0 flow_y = 0 intensity = 0 for i in [-1, 0, 1]: flow_x += -1 * granger_list[-1 + 1][i + 1] + granger_list[1 + 1][i + 1] flow_y += ...
Python
zaydzuhri_stack_edu_python
comment !/usr/bin/env python3 import sys , os , pdb import glob , re import pickle , copy , shutil import numpy as np import matplotlib.pyplot as plt import seaborn as sns from unit_dict import UnitDict from AMSOSseed import Seed import Plots set ud = call UnitDict class Sim extends object begin function __init__ self ...
#!/usr/bin/env python3 import sys, os, pdb import glob, re import pickle, copy, shutil import numpy as np import matplotlib.pyplot as plt import seaborn as sns from unit_dict import UnitDict from AMSOSseed import Seed import Plots ud = UnitDict() class Sim(object): def __init__(self, cwd=None, label='default...
Python
zaydzuhri_stack_edu_python
comment Program written by: Utkarsh Ranjan (200050147) comment Program part of: CS 152/CS154 Laboratory, 2021 batch comment Program for: problem 11.2.2 (lab11, problem 2, program 2) = reverse.py function reverse l begin if length l != 1 begin set x = l at 0 pop l 0 reverse l append l x end return l end function print r...
# Program written by: Utkarsh Ranjan (200050147) # Program part of: CS 152/CS154 Laboratory, 2021 batch # Program for: problem 11.2.2 (lab11, problem 2, program 2) = reverse.py def reverse(l): if len(l) != 1: x = l[0] l.pop(0) reverse(l) l.append(x) return l print(rever...
Python
zaydzuhri_stack_edu_python
string tests.complex ================= Purpose ------- Offers support for testing complex structures. Meta ---- :Authors: Neil Tallim <flan@uguu.ca> :Version: 1.0.0 : Feb. 18, 2011 Legal ----- This work is licensed under the Creative Commons Attribution-ShareAlike 3.0 Unported License. To view a copy of this license, v...
""" tests.complex ================= Purpose ------- Offers support for testing complex structures. Meta ---- :Authors: Neil Tallim <flan@uguu.ca> :Version: 1.0.0 : Feb. 18, 2011 Legal ----- This work is licensed under the Creative Commons Attribution-ShareAlike 3.0 Unported License. To view a copy of this licens...
Python
zaydzuhri_stack_edu_python
from gevent import monkey call patch_all import gevent , requests , bs4 , openpyxl from gevent.queue import Queue set work = queue set url_1 = string http://www.boohee.com/food/group/{type}?page={page} for i in range 1 4 begin for j in range 1 4 begin set real_url = format url_1 type=i page=j call put_nowait real_url e...
from gevent import monkey monkey.patch_all() import gevent, requests, bs4, openpyxl from gevent.queue import Queue work = Queue() url_1 = "http://www.boohee.com/food/group/{type}?page={page}" for i in range(1, 4): for j in range(1, 4): real_url = url_1.format(type=i, page=j) work.put_nowait(real...
Python
zaydzuhri_stack_edu_python
function get_metadata html url begin set metadata = extract extruct html base_url=call get_base_url html url syntaxes=list string json-ld at string json-ld at 0 return metadata end function
def get_metadata(html, url): metadata = extruct.extract( html, base_url=get_base_url(html, url), syntaxes=['json-ld'], )['json-l...
Python
nomic_cornstack_python_v1
string Definition of SegmentTreeNode: class SegmentTreeNode: def __init__(self, start, end, max): self.start, self.end, self.max = start, end, max self.left, self.right = None, None class Solution begin comment @param root, start, end: The root of segment tree and comment an segment / interval comment @return: The coun...
""" Definition of SegmentTreeNode: class SegmentTreeNode: def __init__(self, start, end, max): self.start, self.end, self.max = start, end, max self.left, self.right = None, None """ class Solution: # @param root, start, end: The root of segment tree and # an segme...
Python
zaydzuhri_stack_edu_python
import numpy as np from matplotlib import pyplot as plt from sklearn import linear_model from sklearn.linear_model import LogisticRegression comment Generate a toy dataset set toy_samples = 50 set X_toy = linear space - 5 5 toy_samples set Xtoy_test = linear space - 5 5 200 comment gaussian noise added set X_toy = X_to...
import numpy as np from matplotlib import pyplot as plt from sklearn import linear_model from sklearn.linear_model import LogisticRegression # Generate a toy dataset toy_samples = 50 X_toy = np.linspace(-5, 5, toy_samples) Xtoy_test = np.linspace(-5, 5, 200) # gaussian noise added X_toy = X_toy + 2 * np.random.normal(...
Python
zaydzuhri_stack_edu_python
function complies_to_password_rule range char pwd begin set char_count = count pwd char return char_count >= integer range at 0 and char_count <= integer range at 1 end function function complies_to_new_rule position char pwd begin set correct_count = 0 for pos in position begin if pwd at integer pos - 1 == char begin ...
def complies_to_password_rule(range,char, pwd): char_count = pwd.count(char) return char_count >= int(range[0]) and char_count <= int(range[1]) def complies_to_new_rule(position, char, pwd): correct_count = 0 for pos in position: if pwd[int(pos)-1] == char: correct_count += 1 return correct_count =...
Python
zaydzuhri_stack_edu_python
string TITLE: Ex-6-4 AUTHOR: Alex Pizzuto DATE: 3/05/17 DESCRIPTION: numberListToString and rangeString defined and tested MODIFICATION HISTORY AND OUTSIDE RESOURCES: Creation date: 3/05/17 function numberListToString numList begin set myString = string for num in numList begin set myString = myString + string num + s...
''' TITLE: Ex-6-4 AUTHOR: Alex Pizzuto DATE: 3/05/17 DESCRIPTION: numberListToString and rangeString defined and tested MODIFICATION HISTORY AND OUTSIDE RESOURCES: Creation date: 3/05/17 ''' def numberListToString(numList): myString = '' for num in numList: myString = myString + str(num) + ' ' ...
Python
zaydzuhri_stack_edu_python
function page self priority=unset assignment_status=unset workflow_sid=unset workflow_name=unset task_queue_sid=unset task_queue_name=unset evaluate_task_attributes=unset ordering=unset has_addons=unset page_token=unset page_number=unset page_size=unset begin string Retrieve a single page of TaskInstance records from t...
def page(self, priority=values.unset, assignment_status=values.unset, workflow_sid=values.unset, workflow_name=values.unset, task_queue_sid=values.unset, task_queue_name=values.unset, evaluate_task_attributes=values.unset, ordering=values.unset, has_addons=values.unse...
Python
jtatman_500k
comment Write a program to sort a list of numbers provided on standard input comment (for instance, the numbers you generated above). You are NOT allowed comment to call external routines to do the sorting for you. After sorting comment the numbers, print them out. Focus on a simple method (not an comment efficient met...
## Write a program to sort a list of numbers provided on standard input # (for instance, the numbers you generated above). You are NOT allowed # to call external routines to do the sorting for you. After sorting # the numbers, print them out. Focus on a simple method (not an # efficient method). def mergeSort(list_of_...
Python
zaydzuhri_stack_edu_python
import os import re set rootdir = string ./documentation/ set dirs_dict = dictionary function same_name file root begin set filename = sub string ^[0-9]+_ string replace file string .md string set rootname = sub string ^[0-9]+_ string base name path root print filename rootname return filename == rootname end functio...
import os import re rootdir = './documentation/' dirs_dict = dict() def same_name(file, root): filename = re.sub("^[0-9]+_", "", file.replace(".md", "")) rootname = re.sub("^[0-9]+_", "", os.path.basename(root)) print(filename, rootname) return filename == rootname def do_display(files, root): ...
Python
zaydzuhri_stack_edu_python
from tkinter import * import tkinter as tk import tkinter.ttk as ttk import csv from tkinter import messagebox import sys append path string ../ from Scripts.main import * from Scripts.config import * from Library.lib import * function main_window begin string Функция создает главное окно приложения и описывает функции...
from tkinter import * import tkinter as tk import tkinter.ttk as ttk import csv from tkinter import messagebox import sys sys.path.append('../') from Scripts.main import * from Scripts.config import * from Library.lib import * def main_window(): """ Функция создает главное окно приложения и описывает функци...
Python
zaydzuhri_stack_edu_python
function location_to_coord self location begin return string { get get location string location string lat } | { get get location string location string lng } end function
def location_to_coord(self, location): return f"{location.get('location').get('lat')}|{location.get('location').get('lng')}"
Python
nomic_cornstack_python_v1
comment 변수는 저장 공간 comment num = 10 comment 리스트는 여러개의 변수를 저장하는 공간 comment list = [변수1 , 변수2 , 변수3 -- ] comment 문제51 : 여러개 변수를 저장하는 공간 [ ] 안에 변수 넣기 set movie_rank = list string 닥터 스트레인지 string 스플릿 string 럭키 print movie_rank comment 문제52 : 리스트명.append( 추가할변수 ) : 리스트에 변수 추가 set movie_rank = list string 닥터 스트레인지 string 스플릿 ...
# 변수는 저장 공간 # num = 10 #리스트는 여러개의 변수를 저장하는 공간 # list = [변수1 , 변수2 , 변수3 -- ] #문제51 : 여러개 변수를 저장하는 공간 [ ] 안에 변수 넣기 movie_rank = ["닥터 스트레인지" , "스플릿" , "럭키" ] print(movie_rank) #문제52 : 리스트명.append( 추가할변수 ) : 리스트에 변수 추가 movie_rank = ["닥터 스트레인지" , "스플릿" , "럭키" ] movie_rank.append("베트맨") print(movie_rank) #문제53 : ...
Python
zaydzuhri_stack_edu_python
import sys import math import math import threading import time class Square begin function __init__ self height=string 0 width=string 0 begin set height = height set width = width end function decorator property function height self begin return __height end function decorator setter function height self value begin i...
import sys import math import math import threading import time class Square: def __init__(self, height="0", width="0"): self.height = height self.width = width @property def height(self): return self.__height @height.setter def height(self, value): if value.isdigit(): self.__height = v...
Python
zaydzuhri_stack_edu_python
function ndcg_at_k rec_items holdout_items begin assert length rec_items == length holdout_items set idcg = call dcg_at_k sorted holdout_items reverse=true set ndcg = if expression idcg > 0.0 then call dcg_at_k rec_items / idcg else 0.0 return ndcg end function
def ndcg_at_k(rec_items, holdout_items): assert len(rec_items) == len(holdout_items) idcg = dcg_at_k(sorted(holdout_items, reverse=True)) ndcg = (dcg_at_k(rec_items) / idcg) if idcg > 0.0 else 0.0 return ndcg
Python
nomic_cornstack_python_v1
function new self password key=none uuid=none path=none begin if key is none begin set key = call mk_random_privkey end set keystore = call make_keystore_json key password set keystore at string id = uuid return call Keystore keystore password path end function
def new(self, password, key=None, uuid=None, path=None): if key is None: key = mk_random_privkey() keystore = keys.make_keystore_json(key, password) keystore['id'] = uuid return Keystore(keystore, password, path)
Python
nomic_cornstack_python_v1
function testEventFromString self begin debug string testEventFromString set evtStr = string 2008-10-26 18:18:24,184 http://id.webbrick.co.uk/events/webbrick/CT,webbrick/9/CT/3,{'srcChannel': 3, 'curhi': 100.0, 'val': 19.600000000000001, 'fromNode': 9, 'curlo': -50.0, 'defhi': 100.0, 'deflo': -50.0} set evt = call Even...
def testEventFromString(self): self._log.debug( "\ntestEventFromString" ) evtStr = "2008-10-26 18:18:24,184 http://id.webbrick.co.uk/events/webbrick/CT,webbrick/9/CT/3,{'srcChannel': 3, 'curhi': 100.0, 'val': 19.600000000000001, 'fromNode': 9, 'curlo': -50.0, 'defhi': 100.0, 'deflo': -50.0...
Python
nomic_cornstack_python_v1
comment -*- coding: utf-8 -*- string Created on Mon May 04 12:56:39 2015 @author: Gonçalo import cv2 import numpy as np class RoiSet begin function __init__ self rois offset=tuple 0 0 scale=tuple 1 1 dtype=float64 flipxy=false begin set rois = list comprehension list comprehension tuple x * scale at 0 + offset at 0 y *...
# -*- coding: utf-8 -*- """ Created on Mon May 04 12:56:39 2015 @author: Gonçalo """ import cv2 import numpy as np class RoiSet: def __init__(self, rois, offset=(0,0), scale=(1,1), dtype=np.float64, flipxy=False): self.rois = [[(x*scale[0]+offset[0], ...
Python
zaydzuhri_stack_edu_python
comment !/usr/bin/env python comment import sys for handling command line argument comment import socket for network communications import sys , socket function simulateClient num begin comment hard-wire the port number for safety's sake comment then take the names of the host and file from the command line set port = ...
#!/usr/bin/env python # import sys for handling command line argument # import socket for network communications import sys, socket def simulateClient(num): # hard-wire the port number for safety's sake # then take the names of the host and file from the command line port = 8080 #host = sys.argv[1] ...
Python
zaydzuhri_stack_edu_python
from Node import Node set head = call Node 5 set left = call Node 3 set right = call Node 8 set left = call Node 2 set right = call Node 4 set left = call Node 1 set left = call Node 7 set right = call Node 10 function LCA root p q begin if not root or root == p or root == q begin return root end set left = call LCA le...
from Node import Node head = Node(5) head.left = Node(3) head.right = Node(8) head.left.left = Node(2) head.left.right = Node(4) head.left.left.left = Node(1) head.right.left = Node(7) head.right.right = Node(10) def LCA(root, p, q): if not root or root == p or root == q: return root left = LCA(root.l...
Python
zaydzuhri_stack_edu_python
function _generate_file_label begin return join string _ list string stack at 1 at 3 string format time now string %Y%m%d_%H%M%S end function
def _generate_file_label(): return "_".join([str(inspect.stack()[1][3]),datetime.datetime.now().strftime("%Y%m%d_%H%M%S")])
Python
nomic_cornstack_python_v1
comment %% import re import os import logging import json from ECommHandler import ECommHandler comment %% set logger = call getLogger __name__ comment %% class CmdHandler begin function __init__ self chat_id keyword=none url=none begin set chat_id = chat_id set keyword = keyword set url = url set prods = list comment ...
#%% import re import os import logging import json from ECommHandler import ECommHandler #%% logger = logging.getLogger(__name__) #%% class CmdHandler: def __init__(self, chat_id, keyword=None, url=None): self.chat_id = chat_id self.keyword = keyword self.url = url self.p...
Python
zaydzuhri_stack_edu_python
function yum_updates _broker begin if not get _broker IsRhel7 begin raise call SkipComponent string Yum updates currently only works on RHEL 7 end with call UpdatesManager as umgr begin load umgr set response = dict string releasever releasever ; string basearch basearch ; string update_list dict set data = dict strin...
def yum_updates(_broker): if not _broker.get(IsRhel7): raise SkipComponent("Yum updates currently only works on RHEL 7") with UpdatesManager() as umgr: umgr.load() response = { "releasever": umgr.releasever, "basearch": umgr.basearch, "update_list":...
Python
nomic_cornstack_python_v1
from json_value_history.controller import SaveController from json_value_history.models import DiffTypeEnum from json_value_history.util import pprint function run begin set saver = call SaveController call init dict string name string 양지훈 ; string mail string zhuny936772@gmail.com ; string github string https://github...
from json_value_history.controller import SaveController from json_value_history.models import DiffTypeEnum from json_value_history.util import pprint def run(): saver = SaveController() saver.init({ "name": "양지훈", "mail": "zhuny936772@gmail.com", "github": "https://github.com/zhuny", ...
Python
zaydzuhri_stack_edu_python
function run_evaluation categories groundtruth detections excluded_keys verbose=true begin set pascal_evaluator = call PascalDetectionEvaluator categories set tuple boxes labels _ = groundtruth set gt_keys = list set pred_keys = list for image_key in boxes begin if image_key in excluded_keys begin info string Found e...
def run_evaluation( categories, groundtruth, detections, excluded_keys, verbose=True ): pascal_evaluator = object_detection_evaluation.PascalDetectionEvaluator( categories ) boxes, labels, _ = groundtruth gt_keys = [] pred_keys = [] for image_key in boxes: if image_key in...
Python
nomic_cornstack_python_v1
comment coding: utf-8 from gphoto import GPhoto from gphoto import ImageAnalyzer import RPi.GPIO as GPIO from gpio import * import subprocess import math import os import time from subprocess import call set camera = call GPhoto subprocess comment connects to ground set BUTTON = 3 function init begin call setmode BCM s...
# coding: utf-8 from gphoto import GPhoto from gphoto import ImageAnalyzer import RPi.GPIO as GPIO from gpio import * import subprocess import math import os import time from subprocess import call camera = GPhoto(subprocess) BUTTON = 3 # connects to ground def init(): GPIO.setmode(GPIO.BCM) GPIO.setup(B...
Python
zaydzuhri_stack_edu_python
function upload_protocol sheet_no data_struct begin global num_uploads set client = call authorize creds set sheet = call get_worksheet sheet_no print string uploading... for tuple key val in items data_struct begin sleep 7 set d = string format time key string %m/%d/%Y set t = string format time key string %H:%M:%S se...
def upload_protocol(sheet_no, data_struct): global num_uploads client = gspread.authorize(creds) sheet = client.open('Fridge Data Testing').get_worksheet(sheet_no) print('uploading...') for key, val in data_struct.items(): time.sleep(7) d = key.strftime('%m/%d/%Y ') t = ...
Python
nomic_cornstack_python_v1
function parse_first_page self response begin set meta = meta set total_page = extract call xpath string //*[@id="content"]//div[@class="paginator"]/a[last()]/text() set total_page = if expression total_page then integer total_page at 0 else 1 for page in range total_page begin set request_url = format meta at string u...
def parse_first_page(self, response): meta = response.meta total_page = response.xpath('//*[@id="content"]//div[@class="paginator"]/a[last()]/text()').extract() total_page = int(total_page[0]) if total_page else 1 for page in range(total_page): request_url = meta['url_templat...
Python
nomic_cornstack_python_v1
function settings_outside_clinical_bounds cir isf sbr begin return decimal isf < 10 ? decimal isf > 500 ? decimal cir < 2 ? decimal cir > 150 ? decimal sbr < 0.05 ? decimal sbr > 30 end function
def settings_outside_clinical_bounds(cir, isf, sbr): return ( (float(isf) < 10) | (float(isf) > 500) | (float(cir) < 2) | (float(cir) > 150) | (float(sbr) < 0.05) | (float(sbr) > 30) )
Python
nomic_cornstack_python_v1
function problem_4 begin set largest_palindrome = 1 for i in range 999 99 - 1 begin for j in range 999 99 - 1 begin set prod = i * j comment is prod a palindrome? set num_digits = 0 while 10 ^ num_digits <= prod begin set num_digits = num_digits + 1 end comment Ok, we know the number of digits; let's compare each digit...
def problem_4(): largest_palindrome = 1 for i in range(999, 99, -1): for j in range(999, 99, -1): prod = i * j # is prod a palindrome? num_digits = 0 while 10 ** num_digits <= prod: num_digits += 1 # Ok, we know the number of ...
Python
nomic_cornstack_python_v1
function Create *args **kwargs begin return call PGArrayEditorDialog_Create *args keyword kwargs end function
def Create(*args, **kwargs): return _propgrid.PGArrayEditorDialog_Create(*args, **kwargs)
Python
nomic_cornstack_python_v1
comment coding: utf-8 comment In[ ]: comment coding: utf-8 comment In[ ]: function backend list2 begin import json with open list2 as datafile begin set data = load json datafile end import numpy as np set year = list for index in range 0 52 begin append year data at index at string YEAR end set years = array year set...
# coding: utf-8 # In[ ]: # coding: utf-8 # In[ ]: def backend(list2): import json with open(list2) as datafile: data =json.load(datafile) import numpy as np year = [] for index in range(0,52): year.append(data[index]["YEAR"]) years =np.array(year) x = [] for index in ...
Python
zaydzuhri_stack_edu_python
function test_b_traversal_from_deep_node_gets_full_node_list full_weight_graph_tree begin assert call breadth_first_traversal 1 == list 1 2 3 4 5 6 7 end function
def test_b_traversal_from_deep_node_gets_full_node_list(full_weight_graph_tree): assert full_weight_graph_tree.breadth_first_traversal(1) == [1, 2, 3, 4, 5, 6, 7]
Python
nomic_cornstack_python_v1
function new self obj begin set key = format string {}.{} __name__ id set __objects at key = obj end function
def new(self, obj): key = '{}.{}'.format(obj.__class__.__name__, obj.id) self.__objects[key] = obj
Python
nomic_cornstack_python_v1
function merge begin set a = list set b = list set c = list set d = list end function
def merge(): a = [] b = [] c = [] d = []
Python
nomic_cornstack_python_v1
function set_logger log_path begin set logger = call getLogger call setLevel INFO if not handlers begin comment Logging to a file set file_handler = call FileHandler log_path call setFormatter call Formatter string %(asctime)s:%(levelname)s: %(message)s call addHandler file_handler comment Logging to console set stream...
def set_logger(log_path): logger = logging.getLogger() logger.setLevel(logging.INFO) if not logger.handlers: # Logging to a file file_handler = logging.FileHandler(log_path) file_handler.setFormatter(logging.Formatter('%(asctime)s:%(levelname)s: %(message)s')) logger.addHand...
Python
nomic_cornstack_python_v1
comment extracting the plain text in conllu format comment - again simply from stdin to stdout comment use "pip install opencc-python-reimplemented" to install opencc import sys import re comment from opencc import OpenCC from argparse import ArgumentParser set HEADLINE_PATTERN = compile string ^# ([a-zA-Z_]*) = (.*)$ ...
# # extracting the plain text in conllu format # - again simply from stdin to stdout # use "pip install opencc-python-reimplemented" to install opencc import sys import re # from opencc import OpenCC from argparse import ArgumentParser HEADLINE_PATTERN = re.compile(r"^# ([a-zA-Z_]*) = (.*)$") def iter_file(fin): ...
Python
zaydzuhri_stack_edu_python
function fetch_contents self source begin set slides = list if type source is list begin for entry in source begin extend slides call fetch_contents entry end end else if is directory path source begin log string Entering %s % source set entries = list directory source sort entries for entry in entries begin extend sl...
def fetch_contents(self, source): slides = [] if type(source) is list: for entry in source: slides.extend(self.fetch_contents(entry)) elif os.path.isdir(source): self.log(u"Entering %s" % source) entries = os.listdir(source) entrie...
Python
nomic_cornstack_python_v1
comment Matplotlib Plotting Tutorials comment Polar bar plot import numpy as np import matplotlib.pyplot as plt set n = 21 comment Data set theta = linear space 0 2.0 * pi n set heights = call rand n comment Get an axes handle/object set ax1 = subplot 111 polar=true comment Plot set bars = bar theta heights color=call ...
# Matplotlib Plotting Tutorials # Polar bar plot import numpy as np import matplotlib.pyplot as plt n = 21 # Data theta = np.linspace(0, 2.0*np.pi, n) heights = np.random.rand(n) # Get an axes handle/object ax1 = plt.subplot(111, polar=True) # Plot bars = ax1.bar(theta, heights, # color='xkcd:salmon', ...
Python
zaydzuhri_stack_edu_python
function BLOCK value affectClass source target *extra begin set available_block = Block set blocked_damage = min value available_block set value = value - blocked_damage set Block = available_block - blocked_damage return value end function
def BLOCK(value, affectClass, source, target, *extra): available_block = target.Block blocked_damage = min(value, available_block) value -= blocked_damage target.Block = available_block - blocked_damage return value
Python
nomic_cornstack_python_v1
function test_response_no_content_type self begin comment probably only an issue in testing, but still... set data = dict string status string ok ; string foo string bar set content = dumps data set res = call Mock status_code=200 content=content set result = call parse_response res assert equal data result end functio...
def test_response_no_content_type(self): # probably only an issue in testing, but still... data = {"status": "ok", "foo": "bar"} content = json.dumps(data) res = Mock(status_code=200, content=content) result = parse_response(res) self.assertEqual(data, result)
Python
nomic_cornstack_python_v1
function next_step self begin if time_point + 1 >= length data begin print string Error: at last time point end else begin set time_point = time_point + 1 call load_frame end end function
def next_step(self): if self.time_point + 1 >= len(self.data): print("Error: at last time point") else: self.time_point = self.time_point + 1 self.load_frame()
Python
nomic_cornstack_python_v1
function test_sys_favourites_and_dates self begin with call SetupDbAndCredentials as s begin set args = list string --favourites-only string --max-retries string 6 string --max-threads string 2 call test_setup string test_sys_favourites args=args trash_files=true trash_db=true start gp parsed_args set db = call LocalDa...
def test_sys_favourites_and_dates(self): with ts.SetupDbAndCredentials() as s: args = ["--favourites-only", "--max-retries", "6", "--max-threads", "2"] s.test_setup( "test_sys_favourites", args=args, trash_files=True, trash_db=True ) s.gp.start(s....
Python
nomic_cornstack_python_v1
import numpy as np set pred = array list list 2 0.3 list 72 - 2 set pred at 0 at pred at 0 >= 0.5 = 1 print pred
import numpy as np pred=np.array([[2,0.3],[72,-2]]) pred[0][pred[0]>=0.5]=1 print(pred)
Python
zaydzuhri_stack_edu_python
from more_itertools import sliced function compute_day08 input m n begin set layers = list call sliced strip input m * n set min_layer = min layers key=lambda l -> count l string 0 set part1 = count min_layer string 1 * count min_layer string 2 set image = list comprehension next generator expression x for x in p if x ...
from more_itertools import sliced def compute_day08(input, m, n): layers = list(sliced(input.strip(), m*n)) min_layer = min(layers, key=lambda l: l.count('0')) part1 = min_layer.count('1') * min_layer.count('2') image = [next(x for x in p if x != '2') for p in zip(*layers)] disp_image = ''.join(im...
Python
zaydzuhri_stack_edu_python
function removeAttribute self attribute begin pass end function
def removeAttribute(self, attribute): pass
Python
nomic_cornstack_python_v1
import numpy as np from scipy.special import expit as sigmoidal from Clasificador import Clasificador class ClasificadorRegresionLogistica extends Clasificador begin function __init__ self begin call __init__ set w = list end function function entrenamiento self datosTrain atributosDiscretos diccionario nepocas=10 con...
import numpy as np from scipy.special import expit as sigmoidal from Clasificador import Clasificador class ClasificadorRegresionLogistica(Clasificador): def __init__(self): super().__init__() self.w = [] def entrenamiento(self, datosTrain, atributosDiscretos, diccionario, nepocas=10, co...
Python
zaydzuhri_stack_edu_python
function put_bomb self begin set s = self if bombs == 0 begin return end set block = blocks at stype at 0 set xinf = x - x % len_blocks set yinf = y - y % len_blocks set length = len_blocks set new_bomb = call Rectangle call Vector xinf yinf call Vector xinf + length yinf + length set bombs = list if string bomb in blo...
def put_bomb(self): s = self if s.bombs == 0: return block = s.physics.blocks[s.stype][0] xinf = block.inf.x - block.inf.x % s.physics.len_blocks yinf = block.inf.y - block.inf.y % s.physics.len_blocks length = s.physics.len_blocks new_bomb = Rectang...
Python
nomic_cornstack_python_v1
function map self func module=none in_place=false group_by=none level_method=CLIP *args **kwargs begin from starfish.core.image import Filter set mapper = map func *args module=module in_place=in_place group_by=group_by level_method=level_method keyword kwargs return run self *args end function
def map( self, func: Union[str, FunctionSourceBundle], module: Optional[FunctionSource] = None, in_place: bool = False, group_by: Optional[Set[Union[Axes, str]]] = None, level_method: Levels = Levels.CLIP, *args, **kwargs) -...
Python
nomic_cornstack_python_v1
function findNumTwoSum dic begin comment the number of target values that passed the requirement set numSatisfied = 0 comment [2500, 4000] for target in range 2500 4001 begin for x in dic begin set y = target - x comment ensure dictinctness if y in dic and y != x begin set numSatisfied = numSatisfied + 1 break end end ...
def findNumTwoSum(dic): numSatisfied = 0 # the number of target values that passed the requirement for target in range(2500, 4001): # [2500, 4000] for x in dic: y = target - x if y in dic and y != x: # ensure dictinctness numSatisfied += 1 break ...
Python
nomic_cornstack_python_v1
from flask import Flask , request , redirect , render_template from flask_sqlalchemy import SQLAlchemy set app = call Flask __name__ set config at string DEBUG = true set config at string SQLALCHEMY_DATABASE_URI = string mysql+pymysql://build-a-blog:build-a-blog@localhost:8889/build-a-blog set config at string SQLALCHE...
from flask import Flask, request, redirect, render_template from flask_sqlalchemy import SQLAlchemy app = Flask(__name__) app.config['DEBUG'] = True app.config['SQLALCHEMY_DATABASE_URI'] = 'mysql+pymysql://build-a-blog:build-a-blog@localhost:8889/build-a-blog' app.config['SQLALCHEMY_ECHO'] = True db = SQLAlchemy(app) ...
Python
zaydzuhri_stack_edu_python
function label_list_to_label_matrix labels distinct=true begin set w = integer ceil square root length labels set h = w set labelMatrix = zeros list w h set idx = 0 for i in range 0 h begin for j in range 0 w begin if distinct begin if labels at idx > 0.5 begin set l = 1 end else begin set l = 0 end end else begin set ...
def label_list_to_label_matrix(labels, distinct=True): w = int(numpy.ceil(math.sqrt(len(labels)))) h = w labelMatrix = numpy.zeros([w, h]) idx = 0 for i in range(0,h): for j in range(0,w): if distinct: if labels[idx] > 0.5: l = 1 ...
Python
nomic_cornstack_python_v1
function ask_custom_command self begin set shell = string Bash if platform == string win32 begin set shell = string Batch end call show_text_box_popup format string Please Enter A {} Command: shell handle_user_command end function
def ask_custom_command(self): shell='Bash' if platform == 'win32': shell='Batch' self.manager.root.show_text_box_popup('Please Enter A {} Command:'.format(shell), self.handle_user_command)
Python
nomic_cornstack_python_v1
function user_stats df begin print string Calculating User Stats... set start_time = time comment TO DO: Display counts of user types set user_types = value counts df at string User Type print string Total types of users shown below; user_types comment TO DO: Display counts of gender if string Gender in columns begin s...
def user_stats(df): print('\nCalculating User Stats...\n') start_time = time.time() # TO DO: Display counts of user types user_types=df['User Type'].value_counts() print('Total types of users shown below;\n', user_types) # TO DO: Display counts of gender if 'Gender' in df.columns: ...
Python
nomic_cornstack_python_v1
function _is_megacounty fips begin return ends with fips string 000 and length fips == 5 end function
def _is_megacounty(fips: str) -> bool: return fips.endswith("000") and len(fips) == 5
Python
nomic_cornstack_python_v1
function dist p1 p2 begin set dx = p1 at 0 at 0 - p2 at 0 at 0 set dy = p1 at 0 at 1 - p2 at 0 at 1 return square root dx ^ 2 + dy ^ 2 end function
def dist(p1, p2): dx = p1[0][0] - p2[0][0] dy = p1[0][1] - p2[0][1] return np.sqrt(dx ** 2 + dy ** 2)
Python
nomic_cornstack_python_v1
comment Course: Python Data Structures: Stacks, Queues, and Deques #### class Queue begin string FIFO We are using a List as the base of our Queue. The left Side of the List is the end (back) of our Queue and the right side is the beginning (front) of the Queue. function __init__ self begin string Constructor for Queue...
######################################################################## #### Course: Python Data Structures: Stacks, Queues, and Deques #### ######################################################################### class Queue(): """ FIFO We are using a List as the base of our Queue. The left Side of ...
Python
zaydzuhri_stack_edu_python
function reverse_string string begin set vowels = list string a string e string i string o string u string A string E string I string O string U set special_chars = list string ! string @ string # string $ string % string ^ string & string * string ( string ) string - string _ string + string = string [ string ] string...
def reverse_string(string): vowels = ['a', 'e', 'i', 'o', 'u', 'A', 'E', 'I', 'O', 'U'] special_chars = ['!', '@', '#', '$', '%', '^', '&', '*', '(', ')', '-', '_', '+', '=', '[', ']', '{', '}', '|', '\\', ':', ';', '<', '>', ',', '.', '?', '/', '`', '~'] reversed_string = string[::-1] # Reverse the s...
Python
jtatman_500k
function makeInverseIndex strlist begin set d = dict for tuple i document in enumerate strlist begin for word in split document begin if word and word in d begin add d at word i end else if word begin set d at word = set literal i end end end return d end function
def makeInverseIndex(strlist): d = {} for i, document in enumerate(strlist): for word in document.split(): if word and word in d: d[word].add(i) elif word: d[word] = {i} return d
Python
nomic_cornstack_python_v1
function aln_from_fasta_codons seqs array_type=none Alphabet=none begin if is instance seqs str begin set seqs = split seqs string end return call aln_from_model_seqs list comprehension call CodonSequenceGap s Label=l for tuple l s in call MinimalFastaParser seqs function xsample self n=none with_replacement=false moti...
def aln_from_fasta_codons(seqs, array_type=None, Alphabet=None): if isinstance(seqs, str): seqs = seqs.split('\n') return aln_from_model_seqs([CodonSequenceGap(s, Label=l) for l, s \ in cogent.parse.fasta.MinimalFastaParser(seqs)]) def xsample(self, n=None, with_replacement=False, motif_len...
Python
nomic_cornstack_python_v1