code
stringlengths
10
2.58M
original_code
stringlengths
3
3.18M
original_language
stringclasses
1 value
source
stringclasses
7 values
function decode_eth header begin if length header < h_len begin raise call DecodeException string Ethernet header lenth error: (%d) % length header end set eth_header = call unpack string !6s6sH header at slice : h_len : set next_proto = call ntohs eth_header at 2 set mac_addr = lambda x -> string %.2x % x set src_mac...
def decode_eth(header): if len(header) < Ethernet.h_len: raise DecodeException('Ethernet header lenth error: (%d)' % len(header)) eth_header = unpack('!6s6sH', header[:Ethernet.h_len]) next_proto = socket.ntohs(eth_header[2]) mac_addr = lambda x: "%.2x" % x src_mac = ':'.join(map(mac_addr,et...
Python
nomic_cornstack_python_v1
import random import time comment the start varable is used to ask if the person wants to roll. set start = string comment the games varable is used to have a list of my games. set games = split string StarWarsEmpireAtWar StarWarsEmpireAtWarForcesOfCorruption Shogun2 AgeOfMythology Skyrim Fallout3 FarmingSimulator17 A...
import random import time ## the start varable is used to ask if the person wants to roll. start = '' ## the games varable is used to have a list of my games. games = 'StarWarsEmpireAtWar StarWarsEmpireAtWarForcesOfCorruption Shogun2 AgeOfMythology Skyrim Fallout3 FarmingSimulator17 AgeOfEmpires3 AgeOfEmpires2 D...
Python
zaydzuhri_stack_edu_python
function __init__ self *args **kwargs begin set name = string samtools set version = string 1.2 set env_var = string SAM set url = string https://github.com/samtools/samtools/releases/download/1.2/samtools-1.2.tar.bz2 call __init__ *args keyword kwargs end function
def __init__(self, *args, **kwargs): self.name = 'samtools' self.version = '1.2' self.env_var = "SAM" self.url = 'https://github.com/samtools/samtools/releases/download/1.2/samtools-1.2.tar.bz2' super(Samtools, self).__init__(*args, **kwargs)
Python
nomic_cornstack_python_v1
comment -*- coding: utf-8 -*- import rospy from silbot3_msgs.srv import TTSMake from silbot3_msgs.srv import TTSMakeRequest from silbot3_msgs.srv import SoundPlay from silbot3_msgs.srv import SoundPlayRequest from std_msgs.msg import String from std_msgs.msg import Empty class TTS begin function __init__ self begin set...
#-*- coding: utf-8 -*- import rospy from silbot3_msgs.srv import TTSMake from silbot3_msgs.srv import TTSMakeRequest from silbot3_msgs.srv import SoundPlay from silbot3_msgs.srv import SoundPlayRequest from std_msgs.msg import String from std_msgs.msg import Empty class TTS : def __init__(self): TTS_SRV...
Python
zaydzuhri_stack_edu_python
function init_locally_processed_dataset directory source_datasets uuid_=none begin set md = call DatasetMetadata id_=uuid_ creation_dt=call utcfromtimestamp st_ctime lineage=call LineageMetadata machine=call MachineMetadata hostname=call getfqdn runtime_id=_RUNTIME_ID uname=join string call uname source_datasets=sourc...
def init_locally_processed_dataset(directory, source_datasets, uuid_=None): md = ptype.DatasetMetadata( id_=uuid_, # Default creation time is creation of an image. creation_dt=datetime.datetime.utcfromtimestamp(directory.stat().st_ctime), lineage=ptype.LineageMetadata( ma...
Python
nomic_cornstack_python_v1
from datetime import datetime from sklearn import model_selection , svm from sklearn.neighbors import KNeighborsClassifier from sklearn.ensemble import RandomForestClassifier from sklearn.linear_model import LogisticRegression from sklearn.tree import DecisionTreeClassifier function find_the_best_classifier train targe...
from datetime import datetime from sklearn import model_selection, svm from sklearn.neighbors import KNeighborsClassifier from sklearn.ensemble import RandomForestClassifier from sklearn.linear_model import LogisticRegression from sklearn.tree import DecisionTreeClassifier def find_the_best_classifier(train...
Python
zaydzuhri_stack_edu_python
function get_site_node self site_name begin set site = call get_site site_name if site begin set physical_path = default_app at string physicalPath set zoo_config_path = join path physical_path string .zoo set node = dict string name site_name ; string path call combine_virtual_path site_name string / ; string physical...
def get_site_node(self, site_name): site = self.get_site(site_name) if site: physical_path = site.default_app["physicalPath"] zoo_config_path = os.path.join(physical_path, ".zoo") node = { "name": site_name, "path": combine_virtual_path...
Python
nomic_cornstack_python_v1
comment !/usr/bin/env python function buildsparse connectivity begin string Build a sparse matrix as a dictionary: smat[(i,j)] holds matrix with row-column pair (i,j). smat is returned. Input is the connectivity array associated with finite element grids. connectivity(e,r) gives the global matrix degree of freedom (i o...
#!/usr/bin/env python def buildsparse(connectivity): """ Build a sparse matrix as a dictionary: smat[(i,j)] holds matrix with row-column pair (i,j). smat is returned. Input is the connectivity array associated with finite element grids. connectivity(e,r) gives the global matrix degree of f...
Python
zaydzuhri_stack_edu_python
import asyncio import components.snips.commandWraps as wraps from components.snips.discordModule import DiscordModule from components.snips.discordModule import CommandError from pubsub import pub import random import discord import dataset import sqlalchemy from stuf import stuf import re import datetime import random...
import asyncio import components.snips.commandWraps as wraps from components.snips.discordModule import DiscordModule from components.snips.discordModule import CommandError from pubsub import pub import random import discord import dataset import sqlalchemy from stuf import stuf import re import datetime import random...
Python
zaydzuhri_stack_edu_python
comment p = input("What is the perimeter length?") set p = 60000 set p = integer p set e = integer p / 2 comment create a blank dictionary set a = dict for x in range 0 e begin set y = e - x set area = x * y set tooMuch = x + y if tooMuch > e begin print string Done break end else begin comment print ( x, '*', y, '=',...
#p = input("What is the perimeter length?") p = 60000 p = int(p) e = int(p/2) #create a blank dictionary a = {} for x in range(0,e): y = e - x area = x * y tooMuch = x + y if tooMuch > e: print ("Done") break else: #print ( x, '*', y, '=', area) a[area] = x, y #print (a) maxiumum = max(a.keys(), key=i...
Python
zaydzuhri_stack_edu_python
string http://apps.topcoder.com/wiki/display/tc/SRM+655 function AbleToDraw board begin for k in range 2 begin set bad = false for i in range length board begin for j in range length board at 0 begin if board at i at j != string ? begin if board at i at j != if expression k + i + j % 2 != 0 then string W else string B ...
''' http://apps.topcoder.com/wiki/display/tc/SRM+655 ''' def AbleToDraw(board): for k in range(2): bad = False for i in range(len(board)): for j in range(len(board[0])): if board[i][j] != '?': if board[i][j] != ('W' if (k + i + j) % 2 != 0 e...
Python
zaydzuhri_stack_edu_python
from py2neo import Graph , Path , Node , Relationship set graph = call Graph string bolt://localhost:7687 auth=tuple string neo4j string bram123 set tx = call begin set nodes = list for name in list string Alice string Bob string Carol begin set a = call Node string Person name=name append nodes a call create a end se...
from py2neo import Graph, Path, Node, Relationship graph = Graph("bolt://localhost:7687", auth=("neo4j", "bram123")) tx = graph.begin() nodes = [] for name in ["Alice", "Bob", "Carol"]: a = Node("Person", name=name) nodes.append(a) tx.create(a) friends = Relationship(nodes[0], "KNOWS", nodes[1]) friend...
Python
zaydzuhri_stack_edu_python
function isVowel char begin return char in string aeiouAEIOU end function function remove_vowels s begin set index = 0 set vowel_str = string while index < length s begin if call isVowel s at index begin set vowel_str = vowel_str + s at index end set index = index + 1 end return vowel_str end function function count_v...
def isVowel(char): return char in 'aeiouAEIOU' def remove_vowels(s): index = 0 vowel_str = "" while index < len(s): if isVowel(s[index]): vowel_str += s[index] index += 1 return vowel_str def count_vowels(s): x = remove_vowels(s) y = len(x) return y print(i...
Python
zaydzuhri_stack_edu_python
comment !/usr/bin/env python3 comment The main YouDown program comment TODO : add DASH streams support, and stitching with ffmpeg comment Importing from other files in the repository. from LinkGen import URLList from DownloadScript import Download from PlayVid import PLAY comment Main UI print string Welcome to YouDown...
#!/usr/bin/env python3 # The main YouDown program # TODO : add DASH streams support, and stitching with ffmpeg # Importing from other files in the repository. from LinkGen import URLList from DownloadScript import Download from PlayVid import PLAY # Main UI print("Welcome to YouDown!") print("What would you like to ...
Python
zaydzuhri_stack_edu_python
from sympy import symbols , hessian , latex , pretty from Assignment2.A2_Utilities import solve_single_eq_constraint set tuple x1 x2 = call symbols string x1 x2 set J = x1 + x2 set g = x1 ^ 2 + x1 * x2 + x2 ^ 2 - 1 set soln = call solve_single_eq_constraint cost_function=J constraint=g set hess = call hessian J list x1...
from sympy import symbols, hessian, latex, pretty from Assignment2.A2_Utilities import solve_single_eq_constraint x1, x2 = symbols("x1 x2") J = x1 + x2 g = x1 ** 2 + x1 * x2 + x2 ** 2 - 1 soln = solve_single_eq_constraint(cost_function=J, constraint=g) hess = hessian(J, [x1, x2]) print("\nHessian:") pri...
Python
zaydzuhri_stack_edu_python
function base_urls self begin return list call url string ^(?P<resource_name>%s)(?:/(?P<id>.*))?$ % tuple resource_name call wrap_view string dispatch_detail name=call url_name end function
def base_urls(self): return [ url( r"^(?P<resource_name>%s)(?:/(?P<id>.*))?$" % (self._meta.resource_name, ), self.wrap_view('dispatch_detail'), name=self.url_name()) ]
Python
nomic_cornstack_python_v1
function one_away s t begin set ln_s = length s set ln_t = length t if absolute ln_s - ln_t > 1 begin return false end if max ln_t ln_s == 1 and ln_t != ln_s begin return true end set i = 0 set j = 0 set error = 0 while i < ln_s and j < ln_t begin if s at i != t at j begin set error = error + 1 if ln_s > ln_t begin set...
def one_away(s, t): ln_s = len(s) ln_t = len(t) if abs(ln_s - ln_t) > 1: return False if max(ln_t, ln_s) == 1 and ln_t != ln_s: return True i = j = error = 0 while i < ln_s and j < ln_t: if s[i] != t[j]: error += 1 if ln_s > ln_t: ...
Python
nomic_cornstack_python_v1
comment So for this one, I take N slopes, take the result, and multiple them comment So I took my code from part1 and turned it into a function set file = open string input.txt string r set input = list for line in file begin append input line end close file function numTrees right down begin comment my position top l...
# So for this one, I take N slopes, take the result, and multiple them # So I took my code from part1 and turned it into a function file = open(r"input.txt","r") input = [] for line in file: input.append(line) file.close() def numTrees(right,down): # my position top left posX = 0 posY = 0 # my slope is right...
Python
zaydzuhri_stack_edu_python
function draw_keypoints img kp begin for p in kp begin set p = as type p int call rectangle img tuple p at 0 p at 1 tuple p at 0 p at 1 tuple 0 255 0 5 end image show call cvtColor img COLOR_BGR2RGB show end function
def draw_keypoints(img, kp): for p in kp: p = p.astype(int) cv2.rectangle(img, (p[0], p[1]), (p[0], p[1]), (0, 255, 0), 5) plt.imshow(cv2.cvtColor(img, cv2.COLOR_BGR2RGB)) plt.show()
Python
nomic_cornstack_python_v1
function add_remotes items config begin if get config KEY begin set config = config at KEY end else if get config CONFIG_KEY begin set config = config at CONFIG_KEY end set find_fn = call _find_file config return call fill_remote items find_fn _is_remote end function
def add_remotes(items, config): if config.get(KEY): config = config[KEY] elif config.get(CONFIG_KEY): config = config[CONFIG_KEY] find_fn = _find_file(config) return sret.fill_remote(items, find_fn, _is_remote)
Python
nomic_cornstack_python_v1
function read_image_data path begin return as type flatten call get_data float64 end function
def read_image_data(path): return nib.load(path).get_data().flatten().astype(np.float64)
Python
nomic_cornstack_python_v1
function add_xlsx self file_name action_type begin set table_columns = list set table_rows = list set wb = call open_workbook string ./input/ { file_name } set sheet = call sheet_by_index 0 for i in range ncols begin append table_columns call cell_value 0 i end info string Table columns - { table_columns } for i in r...
def add_xlsx(self, file_name, action_type): table_columns = [] table_rows = [] wb = xlrd.open_workbook(f"./input/{file_name}") sheet = wb.sheet_by_index(0) for i in range(sheet.ncols): table_columns.append(sheet.cell_value(0, i)) logging.info(f"Table column...
Python
nomic_cornstack_python_v1
function use_vqsr algs begin for alg in algs begin set callers = get alg string variantcaller string gatk if is instance callers basestring begin set callers = list callers end else comment no variant calling, no VQSR if not callers begin continue end set vqsr_supported_caller = false for c in callers begin if c in lis...
def use_vqsr(algs): for alg in algs: callers = alg.get("variantcaller", "gatk") if isinstance(callers, basestring): callers = [callers] elif not callers: # no variant calling, no VQSR continue vqsr_supported_caller = False for c in callers: ...
Python
nomic_cornstack_python_v1
function is_prime n begin if n < 2 begin return false end for i in range 2 integer n ^ 0.5 + 1 begin if n % i == 0 begin return false end end return true end function function contains_digit_three n begin while n > 0 begin if n % 10 == 3 begin return true end set n = n // 10 end return false end function function print...
def is_prime(n): if n < 2: return False for i in range(2, int(n**0.5) + 1): if n % i == 0: return False return True def contains_digit_three(n): while n > 0: if n % 10 == 3: return True n = n // 10 return False def print_prime_numbers(): ...
Python
jtatman_500k
function is_set self begin pass end function
def is_set(self, ): pass
Python
nomic_cornstack_python_v1
function select_recs self **kwargs begin if sql begin comment self.sql is assumed to be a fully formed sql statement set recs = query table sql end else begin set filters = call get_list_filters set recs = select table where=where order_by=order_by keyword kwargs end end function
def select_recs(self,**kwargs): if self.sql: # self.sql is assumed to be a fully formed sql statement self.recs = self.table.query(self.sql) else: filters = self.get_list_filters() self.recs = self.table.select(where=filters.where,order_by=filters.order_by...
Python
nomic_cornstack_python_v1
if a < 0 begin print string - end=string set b = list string a pop b 0 reverse b while b at 0 == string 0 begin pop b 0 end print join string b end else begin set b = list string a reverse b while b at 0 == string 0 begin pop b 0 end print join string b end
if a<0: print('-',end='') b=list(str(a)) b.pop(0) b.reverse() while b[0]=='0': b.pop(0) print(''.join(b)) else: b=list(str(a)) b.reverse() while b[0]=='0': b.pop(0) print(''.join(b))
Python
zaydzuhri_stack_edu_python
comment ------------------- comment | decryption module | comment ------------------- comment Input: an encrypted message and the private key comment Output: the encrypted message (ciphtertext.txt) function decrypt begin comment open ciphertext.txt and get the encrypted message with open string ciphertext.txt string r ...
# ------------------- # | decryption module | # ------------------- # Input: an encrypted message and the private key # Output: the encrypted message (ciphtertext.txt) def decrypt(): # open ciphertext.txt and get the encrypted message with open('ciphertext.txt', 'r') as g: message = long(g...
Python
zaydzuhri_stack_edu_python
function _build_preconditions_table self begin string Builds the local action precondition expressions. set local_action_preconditions = dictionary set global_action_preconditions = list set action_fluents = action_fluents for precond in preconds begin set scope = scope set action_scope = list comprehension action for...
def _build_preconditions_table(self): '''Builds the local action precondition expressions.''' self.local_action_preconditions = dict() self.global_action_preconditions = [] action_fluents = self.action_fluents for precond in self.preconds: scope = precond.scope ...
Python
jtatman_500k
function test_fma_invalid_param_floatarray_intarray_intarray_bytes_94 self begin comment This version is expected to pass. call fma floatarrayx floatarrayy floatarrayz floatarrayout comment This is the actual test. with assert raises TypeError begin call fma floatarrayx intarrayy intarrayz bytesout end end function
def test_fma_invalid_param_floatarray_intarray_intarray_bytes_94(self): # This version is expected to pass. arrayfunc.fma(self.floatarrayx, self.floatarrayy, self.floatarrayz, self.floatarrayout) # This is the actual test. with self.assertRaises(TypeError): arrayfunc.fma(self.floatarrayx, self.intarrayy, se...
Python
nomic_cornstack_python_v1
string Given a positive integer, check whether it has alternating bits: namely, if two adjacent bits will always have different values. For example: Input: 5 Output: True because the binary representation of 5 is: 101. Input: 7 Output: False because the binary representation of 7 is: 111. Input: 11 Output: False becaus...
""" Given a positive integer, check whether it has alternating bits: namely, if two adjacent bits will always have different values. For example: Input: 5 Output: True because the binary representation of 5 is: 101. Input: 7 Output: False because the binary representation of 7 is: 111. Input: 11 Output: False because t...
Python
zaydzuhri_stack_edu_python
comment Author: Donovan Guelde comment CSCI-3104 Fall 2015 comment Assignment 6 comment cloth cutting comment "On my honor, as a University of Colorado at Boulder student, I have neither given nor received unauthorized assistance." import sys class Graph extends object begin function __init__ self productArray profitMa...
# Author: Donovan Guelde # CSCI-3104 Fall 2015 # Assignment 6 # cloth cutting #"On my honor, as a University of Colorado at Boulder student, I have neither given nor received unauthorized assistance." import sys class Graph(object): def __init__(self,productArray,profitMap): self.productArray = productArray se...
Python
zaydzuhri_stack_edu_python
function test_raw_query self begin set id = call get_rand_string set prefix = call get_rand_string comment Same data and user_id set user_id = prefix + string - + call get_rand_string set data = prefix + string - + call get_rand_string add conn id=id user_id=user_id data=data commit conn comment Issue a prefix query, r...
def test_raw_query(self): id = get_rand_string() prefix = get_rand_string() # Same data and user_id user_id = data = prefix + "-" + get_rand_string() self.conn.add(id=id, user_id=user_id, data=data) self.conn.commit() # Issue a prefix query, return data only (w...
Python
nomic_cornstack_python_v1
function inflexion_points data ncast variable=string salinity lamb=500000 begin comment Imports import statsmodels.api as sm import pandas as pd import numpy as np comment Smooth the profile with its tendency set tuple var_cicle var_tend = call hpfilter data at ncast at variable lamb=lamb comment Calculate the 2nd deri...
def inflexion_points(data, ncast, variable='salinity', lamb=500000): #Imports import statsmodels.api as sm import pandas as pd import numpy as np #Smooth the profile with its tendency var_cicle, var_tend = sm.tsa.filters.hpfilter(data[ncast][variable],lamb=lamb) #Calculate the 2nd derivative...
Python
nomic_cornstack_python_v1
string Lecture 7 - Our first image manipulation example Prof. Stewart Demonstrates opening images, accessing their properties, converting them to gray scale, resizing them, displaying them and saving them to new files. from PIL import Image set filename = string chipmunk.jpg set im = open filename print string ********...
""" Lecture 7 - Our first image manipulation example Prof. Stewart Demonstrates opening images, accessing their properties, converting them to gray scale, resizing them, displaying them and saving them to new files. """ from PIL import Image filename = "chipmunk.jpg" im = Image.open(filename) print('\n*************...
Python
zaydzuhri_stack_edu_python
comment Definition for singly-linked list. comment class ListNode: comment def __init__(self, x): comment self.val = x comment self.next = None class Solution begin function hasCycle self head begin set fp = head set sp = head while sp is not none begin set fp = next set sp = next if sp is none begin return false end e...
# Definition for singly-linked list. # class ListNode: # def __init__(self, x): # self.val = x # self.next = None class Solution: def hasCycle(self, head: ListNode) -> bool: fp = head sp = head while sp is not None: fp = fp.next ...
Python
zaydzuhri_stack_edu_python
import datetime from kivy.uix.popup import Popup from kivy.uix.label import Label class DataBase begin function __init__ self filename begin set filename = filename set users = none set file = none load self end function function load self begin set file = open filename string r set users = dict for line in file begin...
import datetime from kivy.uix.popup import Popup from kivy.uix.label import Label class DataBase: def __init__(self, filename): self.filename = filename self.users = None self.file = None self.load() def load(self): self.file = open(self.filename, "r") self.users...
Python
zaydzuhri_stack_edu_python
comment pi.py comment 割圆术 import math set polygon = 6 set r = 10 set M = r while polygon < 6 * 2 ^ 24 begin set G = square root r ^ 2 - M ^ 2 / 4 set j = r - G comment SQRT((M/2)^2+j^2) set m = square root M / 2 ^ 2 + j ^ 2 set polygon = 2 * polygon set perimeter = m * polygon set pi = perimeter / 2 * r print string 圆周...
#pi.py #割圆术 import math polygon = 6 r = 10 M = r while polygon < 6*(2**24): G = math.sqrt(r**2-M**2/4) j = r - G m = math.sqrt((M/2)**2 + j**2) # SQRT((M/2)^2+j^2) polygon = 2*polygon perimeter = m*polygon pi = perimeter/(2*r) print(f'圆周率({polygon}边形):{pi}') print(f'圆周率:{math.pi}') ...
Python
zaydzuhri_stack_edu_python
comment write a method to sort an array of string so that all the anagrams are next to each other comment DS: dic <key, list of anagrams> function anagrams list1 hashmap begin for item in list1 begin set key = join string sorted item if key not in hashmap begin set hashmap at key = list item end else begin append hash...
#write a method to sort an array of string so that all the anagrams are next to each other #DS: dic <key, list of anagrams> def anagrams(list1, hashmap): for item in list1: key = ''.join(sorted(item)) if key not in hashmap: hashmap[key] = [item] else: hashmap[key].append(item) result = [] for key in...
Python
zaydzuhri_stack_edu_python
function solution str1 str2 begin set str1 = lower str1 set str2 = lower str2 set str1_ls = list set str2_ls = list for i in range length str1 - 1 begin if is alpha str1 at i and is alpha str1 at i + 1 begin append str1_ls str1 at slice i : i + 2 : end end for i in range length str2 - 1 begin if is alpha str2 at i an...
def solution(str1, str2): str1 = str1.lower() str2 = str2.lower() str1_ls = [] str2_ls = [] for i in range(len(str1) - 1): if str1[i].isalpha() and str1[i + 1].isalpha(): str1_ls.append(str1[i:i + 2]) for i in range(len(str2) - 1): if str2[i].isalpha() and str2[i +...
Python
zaydzuhri_stack_edu_python
function test_replicate_pg_to_rs self begin call assert_run_tap_success string postgres_to_rs string redshift list string singer comment Add an object reference to avoid to use classmethod. TODO: Add more real tests assert e2e == e2e end function
def test_replicate_pg_to_rs(self): assertions.assert_run_tap_success('postgres_to_rs', 'redshift', ['singer']) # Add an object reference to avoid to use classmethod. TODO: Add more real tests assert self.e2e == self.e2e
Python
nomic_cornstack_python_v1
comment list comment it is a collection of elements.it is mutable in nature which means it can be comment changed or modified set list1 = list 1 2 3 string a string c 3.2 print list1 for i in range length list1 begin print list1 at i end=string end print for c in list1 begin print c end=string end comment -------------...
#list #it is a collection of elements.it is mutable in nature which means it can be # changed or modified list1=[1,2,3,'a','c',3.2] print(list1) for i in range(len(list1)): print(list1[i],end=' ') print() for c in list1: print(c,end=' ') #----------------modify a list list1[2]=99 print(list1) #-----------...
Python
zaydzuhri_stack_edu_python
import png import functools import operator function output_gen begin string 出力用のデータ列を作る関数 set result = list comment 高さ分の繰り返し for y in range 256 begin comment 一行分のデータの並び comment データは以下のように r, g, b, の並びで一ピクセルを表現する comment [r, g, b, r, g, b, ..., r, g, b] set row = list comment 幅の分の繰り返し for x in range 256 begin comment...
import png import functools import operator def output_gen(): ''' 出力用のデータ列を作る関数 ''' result = [] # 高さ分の繰り返し for y in range(256): # 一行分のデータの並び # データは以下のように r, g, b, の並びで一ピクセルを表現する # [r, g, b, r, g, b, ..., r, g, b] row = [] # 幅の分の繰り返し for x in range(2...
Python
zaydzuhri_stack_edu_python
function get_hosts self begin return sorted keys host_data end function
def get_hosts(self): return sorted(self.host_data.keys())
Python
nomic_cornstack_python_v1
import matplotlib.pyplot as plt import numpy as np set filename = call raw_input string File: set label = call raw_input string Label: set f = open filename set fwhm = list for line in f begin set t = split line string - if t at 0 != string nan begin append fwhm decimal t at 0 end end figure set bins = array range 0.5...
import matplotlib.pyplot as plt import numpy as np filename = raw_input("File: ") label = raw_input("Label: ") f = open(filename) fwhm = [] for line in f: t = line.split('-') if t[0]!="nan": fwhm.append(float(t[0])) plt.figure() bins = np.arange(0.5,3.0,0.1) plt.hist(fwhm,bins,label=label) plt.xlabel("FWHM (a...
Python
zaydzuhri_stack_edu_python
function year_fraction date begin set year = year set this_year_start = call datetime year=year month=1 day=1 set next_year_start = call datetime year=year + 1 month=1 day=1 set days_elapsed = tm_yday - 0.5 set days_total = days return days_elapsed / days_total end function
def year_fraction(date): year = date.year this_year_start = datetime(year=year, month=1, day=1) next_year_start = datetime(year=year+1, month=1, day=1) days_elapsed = date.timetuple().tm_yday - 0.5 days_total = (next_year_start - this_year_start).days return days_elapsed/days_total
Python
nomic_cornstack_python_v1
import sys set input = readline set moves = list tuple 1 - 2 tuple 2 - 1 tuple 2 1 tuple 1 2 tuple - 1 2 tuple - 2 1 tuple - 2 - 1 tuple - 1 - 2 function add_paths r c begin for move in moves begin set nr = r + move at 0 set nc = c + move at 1 if nr > 0 and nr < row + 1 and nc > 0 and nc < col + 1 and not visited at nr...
import sys input = sys.stdin.readline moves = [(1, -2), (2, -1), (2, 1), (1, 2), (-1, 2), (-2, 1), (-2, -1), (-1, -2)] def add_paths(r, c): for move in moves: nr = r + move[0] nc = c + move[1] if (nr > 0 and nr < row +1 and nc > 0 and nc < col + 1) and not visited[nr][nc...
Python
zaydzuhri_stack_edu_python
comment !/usr/bin/env python import numpy as np import cvxopt import matplotlib.pyplot as plt from matplotlib import animation comment import pdb comment animate globals set fig_animation = figure 4 set ax_animation = call axes xlim=tuple - 2 2 ylim=tuple - 0.5 2 call set_aspect string equal adjustable=string box grid ...
#!/usr/bin/env python import numpy as np import cvxopt import matplotlib.pyplot as plt from matplotlib import animation # import pdb # animate globals fig_animation = plt.figure(4) ax_animation = plt.axes(xlim=(-2, 2), ylim=(-0.5, 2)) ax_animation.set_aspect('equal', adjustable='box') ax_animation.grid() line, = ax_a...
Python
zaydzuhri_stack_edu_python
comment !/usr/bin/env python comment coding: utf-8 comment ## Brief description of the data set and a summary of its attributes comment In this project, I have performed exploratory data analysis over NESTLE INDIA stock dataset traded over NSE in last 11 years. comment link of stock - https://in.finance.yahoo.com/quote...
#!/usr/bin/env python # coding: utf-8 # ## Brief description of the data set and a summary of its attributes # # In this project, I have performed exploratory data analysis over NESTLE INDIA stock dataset traded over NSE in last 11 years. # # link of stock - https://in.finance.yahoo.com/quote/NESTLEIND.NS?p=NESTLEIN...
Python
zaydzuhri_stack_edu_python
comment !/usr/bin/env python3 comment -*- coding: utf-8 -*- string Created on Sat Mar 24 14:31:00 2018 @author: bijayamanandhar string 01/ reverse string function rev_string text begin set x = list set y = list text set z = length text while z > 0 begin set z = z - 1 append x y at z end return join string x end funct...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Sat Mar 24 14:31:00 2018 @author: bijayamanandhar """ """ 01/ reverse string """ def rev_string(text): x = [] y = list(text) z = len(text) while z > 0: z -= 1 x.append(y[z]) return "".join(x) ...
Python
zaydzuhri_stack_edu_python
import yaml import numbers from util import format_amount class RecipeBuilder extends object begin function __init__ self arg=none begin set name = none set tags = none set inputs = none set ticks = 0 set amount = 0 set buildings = 1 if is instance arg Recipe begin set recipe = arg set name = name set tags = tags set i...
import yaml import numbers from util import format_amount class RecipeBuilder(object): def __init__(self, arg=None): self.name = None self.tags = None self.inputs = None self.ticks = 0 self.amount = 0 self.buildings = 1 if isinstance(arg, Recipe): recipe = arg self.name = r...
Python
zaydzuhri_stack_edu_python
function make_curve self nu=150 phi=0 debug=debug begin set theta = linear space 0 2 * pi endpoint=true num=nu set r = 0 * theta set z = 0 * theta for n in range - nphi2 nphi2 + 1 begin for m in range 0 mpol begin comment be careful of the +/- sign set arg = m * theta - n * phi set cosarg = cos arg set sinarg = sin arg...
def make_curve(self, nu=150, phi=0,debug=debug): theta = linspace(0,2*pi,endpoint=True, num=nu) r = 0*theta z = 0*theta for n in range(-self.nphi2,self.nphi2+1): for m in range(0,self.mpol): arg = m*theta - n*phi # be careful of the +/- sign ...
Python
nomic_cornstack_python_v1
import sys call setrecursionlimit 10 ^ 7 set N = integer read line stdin comment stack set s = list set res = 0 for i in range N begin set v = integer read line stdin if not s begin append s tuple i v end else comment push case: top < current histogram height if s at - 1 at 1 < v begin append s tuple i v end else begi...
import sys sys.setrecursionlimit(10 ** 7) N = int(sys.stdin.readline()) s = [] # stack res = 0 for i in range(N): v = int(sys.stdin.readline()) if not s: s.append((i, v)) else: # push case: top < current histogram height if s[-1][1] < v: s.append((i, v)) else: # pop case: top >= curr...
Python
zaydzuhri_stack_edu_python
comment -*- coding: utf-8 -*- comment -*- version: Python 3.6.3 -*- string Created on Thu May 17 23:19:12 2018 @author: Maxim Bondarenko comment %% function calculate_dist data begin string This function replaces NaN values for median and scaling values to [0 1] it also calculates three vectors of Euclidean, Mahalanobi...
# -*- coding: utf-8 -*- # -*- version: Python 3.6.3 -*- """ Created on Thu May 17 23:19:12 2018 @author: Maxim Bondarenko """ #%% def calculate_dist(data): """ This function replaces NaN values for median and scaling values to [0 1] it also calculates three vectors of Euclidean, Mahalano...
Python
zaydzuhri_stack_edu_python
function map self internalize externalize begin string Transforms the Basis so that it applies to wrapped qubits. Args: externalize: Converts an internal qubit understood by the underlying basis into an external qubit understood by the caller. internalize: Converts an external qubit understood by the caller into an int...
def map(self, internalize: Callable[[TExternalQubit], TInternalQubit], externalize: Callable[[TInternalQubit], TExternalQubit] ) -> 'QubitOrder': """Transforms the Basis so that it applies to wrapped qubits. Args: externalize: Converts an internal qubit u...
Python
jtatman_500k
import random import datetime string for reading and writting in the excel file from openpyxl import load_workbook set wb = call load_workbook string COVID.xlsx set sheet = active string function to extract last character of word and add it as dictionary function extraction word begin return dict string lastchar word a...
import random import datetime '''for reading and writting in the excel file''' from openpyxl import load_workbook wb = load_workbook('COVID.xlsx') sheet = wb.active '''function to extract last character of word and add it as dictionary''' def extraction(word): return{'lastchar' : word[-1]} '''list of names extra...
Python
zaydzuhri_stack_edu_python
import pygame.surfarray import engine.entity as Entity import pygame.surface import pygame.math as math import pygame.transform as transform from engine.transform import Transform from engine.entity_manager import EntityManager from engine.terrain import Terrain import cv2 as cv import config class Camera extends Trans...
import pygame.surfarray import engine.entity as Entity import pygame.surface import pygame.math as math import pygame.transform as transform from engine.transform import Transform from engine.entity_manager import EntityManager from engine.terrain import Terrain import cv2 as cv import config class Camera(Transform):...
Python
zaydzuhri_stack_edu_python
comment https://www.lintcode.com/problem/3sum-smaller/description comment Solution 1: sort the array first; then use the two-pointer method class Solution begin string @param nums: an array of n integers @param target: a target @return: the number of index triplets satisfy the condition nums[i] + nums[j] + nums[k] < ta...
# https://www.lintcode.com/problem/3sum-smaller/description # Solution 1: sort the array first; then use the two-pointer method class Solution: """ @param nums: an array of n integers @param target: a target @return: the number of index triplets satisfy the condition nums[i] + nums[j] + nums[k]...
Python
zaydzuhri_stack_edu_python
class ParseData begin function __init__ self file_name begin set file_name = file_name end function function list_of_rows self begin with open file_name string r as file begin set array = list for rows in file begin append array rows end end return array end function end class function main begin set parsed_data = cal...
class ParseData(): def __init__(self, file_name): self.file_name = file_name def list_of_rows(self): with open(self.file_name, "r") as file: array = [] for rows in file: array.append(rows) return array def main(): parsed_data = ParseData('mo...
Python
zaydzuhri_stack_edu_python
import math set x = integer input set count = 0 for n in range 1 floor square root x - 1 begin if x % n == 0 begin set count = count + 1 print n end end set count = integer power count 2 if square root x % 2 == 0 begin set count = count + 1 end print count
import math x = int(input()) count = 0 for n in range(1, math.floor(math.sqrt(x))-1): if x % n == 0: count += 1 print(n) count = int(math.pow(count, 2)) if(math.sqrt(x) % 2 == 0): count += 1 print(count)
Python
zaydzuhri_stack_edu_python
function Pfail_lt fitRate hours n=1 begin set expected = decimal fitRate * hours / 1000000000 set tot = decimal 0 set i = n - 1 while i >= 0 begin set p = call Pn expected i set tot = tot + p set i = i - 1 end return tot end function
def Pfail_lt(fitRate, hours, n=1): expected = float(fitRate) * hours / 1000000000 tot = float(0) i = n - 1 while i >= 0: p = Pn(expected, i) tot += p i -= 1 return tot
Python
nomic_cornstack_python_v1
for i in range n begin append L integer input string Enter the value end for i in range length L begin if L at i > p begin append L1 L at i end else begin append L2 L at i end end print string values greater than median print L1 print string values less than median print L2
for i in range (n): L.append(int(input("Enter the value"))) for i in range(len(L)): if(L[i]>p): L1.append(L[i]) else: L2.append(L[i]) print("values greater than median ") print(L1) print("values less than median ") print(L2)
Python
zaydzuhri_stack_edu_python
function make_paragraph_dataset src_dir begin set listing = list directory src_dir set paragraph_struct = dictionary for subdir in listing begin if is directory path src_dir + string / + subdir begin set paragraph_struct at subdir = dictionary set files = list directory src_dir + string / + subdir for filename in files...
def make_paragraph_dataset(src_dir): listing = os.listdir(src_dir) paragraph_struct = dict() for subdir in listing: if os.path.isdir(src_dir + '/' + subdir): paragraph_struct[subdir] = dict() files = os.listdir(src_dir + '/' + subdir) for filename in files: ...
Python
nomic_cornstack_python_v1
function connect self begin call active true call config essid=ssid password=pwd channel=3 while not call active begin pass end call ifconfig tuple string 192.168.4.5 string 255.255.255.0 string 192.168.4.1 string 208.67.222.222 end function
def connect(self): self.net.active(True) self.net.config(essid=self.ssid, password=self.pwd, channel=3) while not self.net.active(): pass self.net.ifconfig(("192.168.4.5", "255.255.255.0", "192.168.4.1", "208.67.222.222"))
Python
nomic_cornstack_python_v1
from clicktripz.serialize.Serializable import Serializable from clicktripz.serialize.String import String from clicktripz.serialize.Field import Field from clicktripz.serialize.Array import Array from decimal import Decimal class Bid extends Serializable begin string At least one bid object is required in a bid set obj...
from clicktripz.serialize.Serializable import Serializable from clicktripz.serialize.String import String from clicktripz.serialize.Field import Field from clicktripz.serialize.Array import Array from decimal import Decimal class Bid(Serializable): """At least one bid object is required in a bid set object. F...
Python
zaydzuhri_stack_edu_python
function test_other_systems begin comment KIT set kit_dir = io_dir / string kit / string tests / string data set sqd_path = kit_dir / string test.sqd set mrk_path = kit_dir / string test_mrk.sqd set elp_path = kit_dir / string test_elp.txt set hsp_path = kit_dir / string test_hsp.txt set raw_kit = call read_raw_kit sqd...
def test_other_systems(): # KIT kit_dir = io_dir / "kit" / "tests" / "data" sqd_path = kit_dir / "test.sqd" mrk_path = kit_dir / "test_mrk.sqd" elp_path = kit_dir / "test_elp.txt" hsp_path = kit_dir / "test_hsp.txt" raw_kit = read_raw_kit(sqd_path, str(mrk_path), str(elp_path), str(hsp_path)...
Python
nomic_cornstack_python_v1
function list self request *args **kwargs begin set queryset = call filter_queryset call get_queryset set page = call paginate_queryset queryset if page is not none begin set serializer = call get_serializer page many=true return call get_paginated_response data end set serializer = call get_serializer queryset many=tr...
def list(self, request, *args, **kwargs): queryset = self.filter_queryset(self.get_queryset()) page = self.paginate_queryset(queryset) if page is not None: serializer = self.get_serializer(page, many=True) return self.get_paginated_response(serializer.data) seri...
Python
nomic_cornstack_python_v1
function combine_strings string1 string2 begin return string1 + string + string2 end function set string1 = string Hello set string2 = string World set result = call combine_strings string1 string2 print result
def combine_strings(string1, string2): return string1 + ' ' + string2 string1 = "Hello" string2 = "World" result = combine_strings(string1, string2) print(result)
Python
jtatman_500k
comment Atualizar o pip comment python -m pip install --upgrade pip comment Instalar o BeautifulSoup comment pip install beautifulsoup4 comment Instalar o requests comment pip install requests comment Página fonte comment http://loteriasbr.com/site/home/?search=2018-11-02 comment Danton Cavalcanti Franco Junior - falec...
# Atualizar o pip # python -m pip install --upgrade pip # # Instalar o BeautifulSoup # pip install beautifulsoup4 # # Instalar o requests # pip install requests # # Página fonte # http://loteriasbr.com/site/home/?search=2018-11-02 # # Danton Cavalcanti Franco Junior - falecom@dantonjr.com.br from bs4 imp...
Python
zaydzuhri_stack_edu_python
comment CMB_sampling.py comment Takes Planck CMB data fits file and converts into array in various ways: comment (1) galactic coord with max sample (get_galactic()) comment (2) ecliptic coord with max sample (get_ecliptic()) comment (3) at specified resolution (sampling()) comment (4) scatter test plot (plot_test()) co...
# CMB_sampling.py # # Takes Planck CMB data fits file and converts into array in various ways: # (1) galactic coord with max sample (get_galactic()) # (2) ecliptic coord with max sample (get_ecliptic()) # (3) at specified resolution (sampling()) # (4) scatter test plot (plot_test()) # (5) rectangular plot(plo...
Python
zaydzuhri_stack_edu_python
function initial_query session model year begin set budget_authority_line_max = if expression year <= 2020 then 1042 else 1067 return query session allocation_transfer_agency agency_identifier beginning_period_of_availa ending_period_of_availabil availability_type_code main_account_code sub_account_code call label stri...
def initial_query(session, model, year): budget_authority_line_max = 1042 if year <= 2020 else 1067 return session.query( model.allocation_transfer_agency, model.agency_identifier, model.beginning_period_of_availa, model.ending_period_of_availabil, model.availability_type...
Python
nomic_cornstack_python_v1
import sys from collections import deque set prev_line = deque list right strip read line stdin set next_line = deque set t = integer read line stdin print prev_line print next_line for i in range t begin set cmd = read line stdin if cmd at 0 == string L begin if prev_line begin call appendleft pop prev_line end end el...
import sys from collections import deque prev_line = deque(list(sys.stdin.readline().rstrip())) next_line = deque() t=int(sys.stdin.readline()) print(prev_line) print(next_line) for i in range(t): cmd =sys.stdin.readline() if cmd[0] == 'L': if prev_line: next_line.appendleft(prev_line.pop())...
Python
zaydzuhri_stack_edu_python
comment coding:utf-8 import sys import re import _collections import collections comment https://www.regextester.com/21 set tabela_simbolos = list append tabela_simbolos string Tabela de Símbolos set token_entrada = dict set tabela_erro = list append tabela_erro string Erros nas linhas: set linha = 0 set tabela_temp...
# coding:utf-8 import sys import re import _collections import collections #https://www.regextester.com/21 tabela_simbolos = [] tabela_simbolos.append("Tabela de Símbolos") token_entrada = {} tabela_erro = [] tabela_erro.append("Erros nas linhas:") linha = 0 tabela_temp = [] tabela_temp2 = [] def exibe_imprime(nome, li...
Python
zaydzuhri_stack_edu_python
comment -*- coding: utf-8 -*- string Created on Tue Jan 16 09:42:10 2018 @author: dell import os import sys import re string 扫描文件夹dir中所有文件,返回文件的相对路径列表 function GetFileList dir fileList begin set newDir = dir comment 如果是文件则添加进 fileList if is file path dir begin append fileList dir end else if is directory path dir begin...
# -*- coding: utf-8 -*- """ Created on Tue Jan 16 09:42:10 2018 @author: dell """ import os import sys import re ''' 扫描文件夹dir中所有文件,返回文件的相对路径列表 ''' def GetFileList(dir, fileList): newDir = dir if os.path.isfile(dir): # 如果是文件则添加进 fileList fileList.append(dir) elif os.path.isdir(dir): ...
Python
zaydzuhri_stack_edu_python
set grausFahrenheit = decimal input string Informe a temperatura em graus Fahrenheit: set conversaoCelsius = decimal grausFahrenheit - 32 * 5 / 9 print grausFahrenheit string graus Fahrenheit equivalem a round conversaoCelsius 2 string graus celsius
grausFahrenheit = float (input("Informe a temperatura em graus Fahrenheit: ")) conversaoCelsius = float ((grausFahrenheit)-32) * (5/9) print(grausFahrenheit,"graus Fahrenheit equivalem a",round(conversaoCelsius,2),"graus celsius")
Python
zaydzuhri_stack_edu_python
comment Definition for singly-linked list. class ListNode begin function __init__ self x next=none begin set val = x set next = next end function end class function overlapping_lists l1 l2 begin set tuple root1 root2 = tuple call detectCycle l1 call detectCycle l2 if not root1 and not root2 begin return call overlappin...
# Definition for singly-linked list. class ListNode: def __init__(self, x, next=None): self.val = x self.next = next def overlapping_lists(l1: ListNode, l2: ListNode) -> ListNode: root1, root2 = detectCycle(l1), detectCycle(l2) if not root1 and not root2: return overlapping_lists_w...
Python
zaydzuhri_stack_edu_python
comment !/usr/bin/env python comment coding:utf-8 import HTMLParser import urllib import sys comment urlString = 'http://www.python.org' function getImage addr begin string 将HTML解析成功的Images链接接收,并保存为图片 set u = url open addr set data = read u set splitPath = split addr string / set fName = splitPath at - 1 end function
#!/usr/bin/env python #coding:utf-8 import HTMLParser import urllib import sys #urlString = 'http://www.python.org' def getImage(addr): ''' 将HTML解析成功的Images链接接收,并保存为图片 ''' u = urllib.urlopen(addr) data = u.read() splitPath = addr.split("/") fName = splitPath[-1]
Python
zaydzuhri_stack_edu_python
comment print(tmp_a, tmp_b) for i in range min tmp_a tmp_b max tmp_a + 1 tmp_b + 1 + 1 begin if integer i * 0.08 // 1 == a and integer i * 0.1 // 1 == b begin print i set check = false break end end if check begin print - 1 end
# print(tmp_a, tmp_b) for i in range(min(tmp_a,tmp_b), max(tmp_a + 1, tmp_b + 1) + 1): if int((i * 0.08)//1) == a and int((i * 0.10)//1) == b: print(i) check = False break if check: print(-1)
Python
zaydzuhri_stack_edu_python
function load_adversarial architecture pretrained num_classes begin if architecture == string resnet18 begin set model = call resnet18 pretrained=pretrained set fc = linear 512 num_classes end else if architecture == string resnet101 begin set model = call resnet101 pretrained=pretrained set fc = linear 2048 num_classe...
def load_adversarial(architecture, pretrained, num_classes): if architecture == 'resnet18': model = torchvision_models.resnet18(pretrained=pretrained) model.fc = torch.nn.Linear(512, num_classes) elif architecture == 'resnet101': model = torchvision_models.resnet101(pretrained=pretrained...
Python
nomic_cornstack_python_v1
comment draft kings data import pandas as pd set roto = read csv string http://rotoguru1.com/cgi-bin/nba-dhd-2017.pl?&user=jasonjjchen&key=J8987209841 sep=string : set roto1 = iloc at tuple slice : - 1 : slice : : set loc at tuple slice : : string Date = call to_datetime as type Date int format=string %Y%m%d co...
#draft kings data import pandas as pd roto = pd.read_csv('http://rotoguru1.com/cgi-bin/nba-dhd-2017.pl?&user=jasonjjchen&key=J8987209841',sep = ':') roto1 = roto.iloc[:-1,:] roto1.loc[:,'Date'] = pd.to_datetime(roto1.Date.astype(int),format='%Y%m%d') # roto1 = roto1.iloc[2:,:] #remove na for unfinished games ro...
Python
zaydzuhri_stack_edu_python
function sfr_tab self begin if not has attribute self string _sfr_tab begin set _sfr_tab = zeros list Nz Nm for tuple i z in enumerate z begin if use_sfe begin set _sfr_tab at i = eta at i * call MAR z M * fbar_over_fcdm * call SFE z M end else begin pass end set mask = M >= Mmin at i set _sfr_tab at i = _sfr_tab at i ...
def sfr_tab(self): if not hasattr(self, '_sfr_tab'): self._sfr_tab = np.zeros([self.halos.Nz, self.halos.Nm]) for i, z in enumerate(self.halos.z): if self.use_sfe: self._sfr_tab[i] = self.eta[i] * self.MAR(z, self.halos.M) \ * ...
Python
nomic_cornstack_python_v1
comment Import the MCP4725 module. import Adafruit_MCP4725 comment Create a DAC instance. set dac = call MCP4725 address=96 comment Note you can change the I2C address from its default (0x62), and/or the I2C comment bus by passing in these optional parameters: comment dac = Adafruit_MCP4725.MCP4725(address=0x49, busnum...
# Import the MCP4725 module. import Adafruit_MCP4725 # Create a DAC instance. dac = Adafruit_MCP4725.MCP4725(address=0x60) # Note you can change the I2C address from its default (0x62), and/or the I2C # bus by passing in these optional parameters: #dac = Adafruit_MCP4725.MCP4725(address=0x49, busnum=1) #desired vol...
Python
zaydzuhri_stack_edu_python
from typing import Dict import requests import threading import os from tqdm import tqdm class ThreadedFileDownloader begin string Class to download multiple files from a page at a time given a list of URLs. Derived from Stefan Fortuin's code @ https://stefanfortuin.nl/article/making-a-multithreaded-file-downloader-in-...
from typing import Dict import requests import threading import os from tqdm import tqdm class ThreadedFileDownloader: """ Class to download multiple files from a page at a time given a list of URLs. Derived from Stefan Fortuin's code @ https://stefanfortuin.nl/article/making-a-multithreaded-file-downlo...
Python
zaydzuhri_stack_edu_python
import math comment There is a bunch of functions in math -- https://docs.python.org/3/library/math.html function createpoint pointnumber begin print string Processing point pointnumber set x = decimal input string Enter x: set y = decimal input string Enter y: set point = tuple x y return point end function function d...
import math # There is a bunch of functions in math -- https://docs.python.org/3/library/math.html def createpoint(pointnumber): print("Processing point", pointnumber) x = float ( input("Enter x:") ) y = float ( input("Enter y:") ) point = (x,y) return point def distance(point1, point2): # ass...
Python
zaydzuhri_stack_edu_python
function get_str_mapping joystick begin set map_str = none comment ===== FROM GameController ===== if map_str is none begin try begin set map_str = call SDL_GameControllerMapping gamecontroller end except any begin try begin set map_str = call SDL_GameControllerMapping joystick end except any begin pass end end end com...
def get_str_mapping(joystick): map_str = None # ===== FROM GameController ===== if map_str is None: try: map_str = sdl2.SDL_GameControllerMapping(joystick.gamecontroller) except: try: map_str = sdl2.SDL_GameControllerMapping(joystick) exce...
Python
nomic_cornstack_python_v1
function SetPixelValueMinMax self min max begin return call itkScalarImageToRunLengthFeaturesFilterIUC2_SetPixelValueMinMax self min max end function
def SetPixelValueMinMax(self, min: 'unsigned char', max: 'unsigned char') -> "void": return _itkScalarImageToRunLengthFeaturesFilterPython.itkScalarImageToRunLengthFeaturesFilterIUC2_SetPixelValueMinMax(self, min, max)
Python
nomic_cornstack_python_v1
function gcd a b begin while b begin set tuple a b = tuple b a % b end return a end function
def gcd(a, b): while b: a, b = b, a % b return a
Python
nomic_cornstack_python_v1
function factorial x begin string Factorial using a loop set prod = 1 for i in range 1 x + 1 begin set prod = prod * i end comment print (prod) return prod end function function recur_factorial x begin string Factorial with recursion if x == 1 begin return x end else begin return x * call factorial x - 1 end end functi...
def factorial(x): """ Factorial using a loop """ prod = 1 for i in range(1, x+1): prod *=i #print (prod) return prod def recur_factorial(x): """ Factorial with recursion """ if x==1: return x else: return x*factorial(x-1) def odd(x): """ Returns True if ...
Python
zaydzuhri_stack_edu_python
function create cls begin comment create layout widgets set obj = call cls set mainrow = call HBox set ticker1_box = call HBox width=500 set ticker2_box = call HBox width=500 set ticker3_box = call HBox width=467 set ticker4_box = call HBox width=500 set ticker5_box = call HBox width=500 set second_row = call HBox set ...
def create(cls): # create layout widgets obj = cls() obj.mainrow = HBox() obj.ticker1_box = HBox(width=500) obj.ticker2_box = HBox(width=500) obj.ticker3_box = HBox(width=467) obj.ticker4_box = HBox(width=500) obj.ticker5_box = HBox(width=500) obj....
Python
nomic_cornstack_python_v1
function name self begin return get pulumi self string name end function
def name(self) -> str: return pulumi.get(self, "name")
Python
nomic_cornstack_python_v1
comment coding=utf-8 comment !/usr/bin/env python import sys call reload sys call setdefaultencoding string utf-8 from collections import defaultdict import re
#coding=utf-8 #!/usr/bin/env python import sys reload(sys) sys.setdefaultencoding('utf-8') from collections import defaultdict import re
Python
zaydzuhri_stack_edu_python
comment Write a script called diff.py that take two file names as arguments and checks if the content of comment both the files is same and prints true or false. import filecmp function diff f1 f2 begin comment shallow comparison set result = call cmp f1 f2 print result comment deep comparison set result = call cmp f1 ...
# Write a script called diff.py that take two file names as arguments and checks if the content of # both the files is same and prints true or false. import filecmp def diff(f1, f2): # shallow comparison result = filecmp.cmp(f1, f2) print(result) # deep comparison result = filecmp.cmp(f1, f2, sha...
Python
zaydzuhri_stack_edu_python
function checkFeatureInSet self featureSet currFeature idxValue begin set found = false set currFeatureID = currFeature at idxValue for feature in sorted featureSet key=lambda f -> f at idxValue begin set attr = call attributes set currValue = attr at idxValue if currFeatureID == currValue begin set found = true return...
def checkFeatureInSet(self, featureSet, currFeature, idxValue): found = False currFeatureID = currFeature[idxValue] for feature in sorted(featureSet, key=lambda f: f[idxValue]): attr = feature.attributes() currValue = attr[idxValue] if currFeatureID == curr...
Python
nomic_cornstack_python_v1
function set_tag_estimated_pose self tag_ID x y z roll pitch yaw begin comment perform homogeneous transformation on data set position_data_frame = T set position_mpl_frame = call vector_hom_transformation position_data_frame comment extract coordinates set x = item position_mpl_frame 0 set y = item position_mpl_frame ...
def set_tag_estimated_pose(self, tag_ID, x, y, z, roll, pitch, yaw): # perform homogeneous transformation on data position_data_frame = np.array([[x,y,z]]).T position_mpl_frame = self.vector_hom_transformation(position_data_frame) # extract coordinates x = position_mpl_frame.it...
Python
nomic_cornstack_python_v1
comment -*- coding: utf-8 -*- string Created on Sat Jul 6 08:44:18 2019 @author: Flavio Fontanella import numpy as np import pandas as pd function rate_table entrada begin set ratings = list set i = 1 for line in entrada begin while i != line at 0 begin append ratings list i 0.0 set i = i + 1 end set rate = list 0 0.0...
# -*- coding: utf-8 -*- """ Created on Sat Jul 6 08:44:18 2019 @author: Flavio Fontanella """ import numpy as np import pandas as pd def rate_table(entrada): ratings = [] i=1 for line in entrada: while i!=line[0]: ratings.append([i,0.0]) i+=1 rate = [0, 0.0] ...
Python
zaydzuhri_stack_edu_python
string Name:Hrishikesh N Moholkar file:wordLength.py this file computes the distribution of word length and the five no.summary of those word length . from wordData import * from boxAndWhisker import * function summaryFromWords words year begin string this function computes the distribution of word length and the five ...
""" Name:Hrishikesh N Moholkar file:wordLength.py this file computes the distribution of word length and the five no.summary of those word length . """ from wordData import* from boxAndWhisker import* def summaryFromWords(words,year): """ this function computes the distribution of word length and the five...
Python
zaydzuhri_stack_edu_python
comment !/usr/bin/env python3 import re import os.path as osp import argparse as arp import numpy as np import pandas as pd import matplotlib.pyplot as plt from scipy.stats import ttest_1samp as ttest from scipy.stats import wilcoxon from scipy.stats import t as tdist from typing import Union , Tuple set rcParams at st...
#!/usr/bin/env python3 import re import os.path as osp import argparse as arp import numpy as np import pandas as pd import matplotlib.pyplot as plt from scipy.stats import ttest_1samp as ttest from scipy.stats import wilcoxon from scipy.stats import t as tdist from typing import Union,Tuple plt.rcParams['svg.font...
Python
zaydzuhri_stack_edu_python
function get_jit_network_access_policy asc_location=none jit_network_access_policy_name=none resource_group_name=none opts=none begin set __args__ = dictionary set __args__ at string ascLocation = asc_location set __args__ at string jitNetworkAccessPolicyName = jit_network_access_policy_name set __args__ at string reso...
def get_jit_network_access_policy(asc_location: Optional[str] = None, jit_network_access_policy_name: Optional[str] = None, resource_group_name: Optional[str] = None, opts: Optional[pulumi.InvokeOptions] = None) -> Awa...
Python
nomic_cornstack_python_v1
from collections import defaultdict , Counter class sudoku begin function __init__ self numbers size=3 begin function is_proper numbers begin if length numbers != size ^ 2 begin return false end for row in numbers begin if length row != size ^ 2 begin return false end end return true end function if call is_proper numb...
from collections import defaultdict, Counter class sudoku(): def __init__(self, numbers, size=3): def is_proper(numbers): if len(numbers) != size**2: return False for row in numbers: if len(row) != size**2: return False ...
Python
zaydzuhri_stack_edu_python
function team_members_id_team_product_pdf_color_profiles_fk_put self id fk **kwargs begin set kwargs at string _return_http_data_only = true if get kwargs string callback begin return call team_members_id_team_product_pdf_color_profiles_fk_put_with_http_info id fk keyword kwargs end else begin set data = call team_memb...
def team_members_id_team_product_pdf_color_profiles_fk_put(self, id, fk, **kwargs): kwargs['_return_http_data_only'] = True if kwargs.get('callback'): return self.team_members_id_team_product_pdf_color_profiles_fk_put_with_http_info(id, fk, **kwargs) else: (data) = self.t...
Python
nomic_cornstack_python_v1