code
stringlengths
10
2.58M
original_code
stringlengths
3
3.18M
original_language
stringclasses
1 value
source
stringclasses
7 values
function set_calib_offsets self acc_offset mag_offset gyr_offset mag_radius acc_radius begin comment Must switch to config mode to write out if not call transmit BNO055_OPR_MODE_ADDR 1 bytes list OPERATION_MODE_CONFIG begin error string Unable to set IMU into config mode end sleep 0.025 comment Seems to only work when ...
def set_calib_offsets(self, acc_offset, mag_offset, gyr_offset, mag_radius, acc_radius): # Must switch to config mode to write out if not (self.con.transmit(registers.BNO055_OPR_MODE_ADDR, 1, bytes([registers.OPERATION_MODE_CONFIG]))): self.node.get_logger().error('Unable to set IMU into con...
Python
nomic_cornstack_python_v1
comment !/usr/bin/python import argparse import requests from requests.auth import HTTPBasicAuth from bs4 import BeautifulSoup set parser = call ArgumentParser description=string Script om reistijden van NS te matchen met actuele vertrektijden call add_argument string --fromStation type=str help=string De code (afkorti...
#!/usr/bin/python import argparse import requests from requests.auth import HTTPBasicAuth from bs4 import BeautifulSoup parser = argparse.ArgumentParser(description='Script om reistijden van NS te matchen met actuele vertrektijden') parser.add_argument('--fromStation', type=str, help='De code (afkorting) of korte naam...
Python
zaydzuhri_stack_edu_python
function test_uw_login_required rf begin decorator uw_login_required function fake_view request begin return string is_auth end function set req = get rf string / set session = dict set uwnetid = none set response = call fake_view req assert status_code == 302 set uwnetid = string joe assert call fake_view req == stri...
def test_uw_login_required(rf): @uw_login_required def fake_view(request): return 'is_auth' req = rf.get('/') req.session = {} req.uwnetid = None response = fake_view(req) assert response.status_code == 302 req.uwnetid = 'joe' assert fake_view(req) == 'is_auth'
Python
nomic_cornstack_python_v1
comment !/usr/bin/env python import get_array
#!/usr/bin/env python import get_array
Python
zaydzuhri_stack_edu_python
function _move self row column begin set piece = call get_piece row column if selected and piece == 0 and tuple row column in valid_moves begin move selected row column set skipped = valid_moves at tuple row column if skipped begin remove board skipped end call next_turn end else begin return false end return true end ...
def _move(self, row, column): piece = self.board.get_piece(row, column) if self.selected and piece == 0 and (row, column) in self.valid_moves: self.board.move(self.selected, row, column) skipped = self.valid_moves[(row, column)] if skipped: self.board....
Python
nomic_cornstack_python_v1
function __init__ __self__ start_time=none begin if start_time is not none begin set __self__ string start_time start_time end end function
def __init__(__self__, *, start_time: Optional[pulumi.Input[str]] = None): if start_time is not None: pulumi.set(__self__, "start_time", start_time)
Python
nomic_cornstack_python_v1
import random from datetime import datetime comment Selection Sorting function selectionsort list begin print string The original list is { list } set b = length list set list2 = list at slice : : for j in range b begin set a = list at 0 for i in range b - j begin if list at i < a begin set a = list at i end end set...
import random from datetime import datetime #Selection Sorting def selectionsort(list): print(f'The original list is {list}') b=len(list) list2=list[:] for j in range(b): a=list[0] for i in range(b-j): if list[i]<a: a=list[i] list2[j]=a list.pop(list.index(a)) return f'The ordered li...
Python
zaydzuhri_stack_edu_python
function _create_add_queue_message self mbox profile_name message begin set thread_id = message at string X-oc-thread-id for q_no in mbox begin set q = get mbox q_no if id == thread_id begin comment Found the queue. add q message break end end for else begin comment Need a new queue. set new_q_id = call _new_id mbox se...
def _create_add_queue_message(self, mbox, profile_name, message): thread_id = message['X-oc-thread-id'] for q_no in mbox: q = mbox.get(q_no) if q.id == thread_id: # Found the queue. q.add(message) break else: ...
Python
nomic_cornstack_python_v1
function deal_with_letter self the_entire_flat_range the_flat_range flat_address list_address begin comment check if it is a character if is instance the_flat_range at 0 str begin for k in range index ascii_lowercase lower the_flat_range at 0 index ascii_lowercase lower the_flat_range at 1 + 1 begin append the_entire_f...
def deal_with_letter(self, the_entire_flat_range, the_flat_range, flat_address, list_address): if isinstance(the_flat_range[0], str): # check if it is a character for k in range(string.ascii_lowercase.index(the_flat_range[0].lower()), string.ascii_lowercase.index(the_flat...
Python
nomic_cornstack_python_v1
function ecran_vide self begin call fill ARRIEREPLAN_Couleur end function
def ecran_vide(self): self.screen.fill(ARRIEREPLAN_Couleur)
Python
nomic_cornstack_python_v1
function query self query time_precision=string s chunked=false begin string Query data into DataFrames. Returns a DataFrame for a single time series and a map for multiple time series with the time series as value and its name as key. :param time_precision: [Optional, default 's'] Either 's', 'm', 'ms' or 'u'. :param ...
def query(self, query, time_precision='s', chunked=False): """Query data into DataFrames. Returns a DataFrame for a single time series and a map for multiple time series with the time series as value and its name as key. :param time_precision: [Optional, default 's'] Either 's', 'm', '...
Python
jtatman_500k
async function start host=call SettingsOption PREFECT_SERVER_API_HOST port=call SettingsOption PREFECT_SERVER_API_PORT keep_alive_timeout=call SettingsOption PREFECT_SERVER_API_KEEPALIVE_TIMEOUT log_level=call SettingsOption PREFECT_LOGGING_SERVER_LEVEL scheduler=call SettingsOption PREFECT_API_SERVICES_SCHEDULER_ENABL...
async def start( host: str = SettingsOption(PREFECT_SERVER_API_HOST), port: int = SettingsOption(PREFECT_SERVER_API_PORT), keep_alive_timeout: int = SettingsOption(PREFECT_SERVER_API_KEEPALIVE_TIMEOUT), log_level: str = SettingsOption(PREFECT_LOGGING_SERVER_LEVEL), scheduler: bool = SettingsOption(P...
Python
nomic_cornstack_python_v1
function loss_function mapping12 begin global dm1 dm2 set loss = norm dm1 at call triu_indices size1 - dm2 at tuple mapping12 at tuple slice : : none mapping12 at call triu_indices size1 return loss end function
def loss_function(mapping12): global dm1, dm2 loss = np.linalg.norm(dm1[np.triu_indices(size1)] - dm2[mapping12[:,None], mapping12][np.triu_indices(size1)]) return loss
Python
nomic_cornstack_python_v1
function deregister_status_field self field begin debug string Deregistering status field %s with PluginManager field try begin del status_fields at field end except any begin warning string Unable to deregister status field %s field end end function
def deregister_status_field(self, field): log.debug("Deregistering status field %s with PluginManager", field) try: del self.status_fields[field] except: log.warning("Unable to deregister status field %s", field)
Python
nomic_cornstack_python_v1
function list_of_numbers lst1 begin set n = 0 for i in lst1 begin if i > 0 begin set n = n + 1 end end return format string Count of positive numbers = {} n end function set lst2 = list 10 - 4 2 - 2 - 4 4 print call list_of_numbers lst2
def list_of_numbers(lst1): n =0 for i in lst1 : if i > 0: n += 1 return "Count of positive numbers = {}".format(n) lst2 = [10, -4, 2, -2, -4, 4] print(list_of_numbers(lst2))
Python
zaydzuhri_stack_edu_python
function main begin string This is the solution for the problem 31 https://projecteuler.net/problem=31 set ma = list 1 2 4 10 20 40 100 200 set count = 0 for a in range ma at 0 begin for b in range ma at 1 begin for c in range ma at 2 begin for d in range ma at 3 begin for e in range ma at 4 begin for f in range ma at ...
def main(): """ This is the solution for the problem 31 https://projecteuler.net/problem=31 """ ma=[1,2,4,10,20,40,100,200] count = 0 for a in range(ma[0]): for b in range(ma[1]): for c in range(ma[2]): for d in range(ma[3]): for e...
Python
zaydzuhri_stack_edu_python
function evaluate self **kwargs begin if string values in keys kwargs begin try begin return list value * length kwargs at string values at 1 end except KeyError begin set length = 1 if length values kwargs at string values == 0 begin set length = length * 0 end for a_list in values kwargs at string values begin set le...
def evaluate(self, **kwargs) -> object or [object]: if "values" in kwargs.keys(): try: return [self.value] * len(kwargs["values"][1]) except KeyError: length = 1 if len(kwargs["values"].values()) == 0: length = length * ...
Python
nomic_cornstack_python_v1
string Given an integer array nums sorted in non-decreasing order, remove the duplicates in-place such that each unique element appears only once. The relative order of the elements should be kept the same. Since it is impossible to change the length of the array in some languages, you must instead have the result be p...
""" Given an integer array nums sorted in non-decreasing order, remove the duplicates in-place such that each unique element appears only once. The relative order of the elements should be kept the same. Since it is impossible to change the length of the array in some languages, you must instead have the result be ...
Python
zaydzuhri_stack_edu_python
function eckhardt q alpha beta init_value=none window=7 begin if alpha <= 0 or alpha >= 1.0 begin raise call ValueError string Parameter alpha should be between range 0 < alpha < 1. end if beta <= 0 or beta >= 1.0 begin raise call ValueError string Parameter beta should be between range 0 < beta < 1. end comment Filter...
def eckhardt(q, alpha, beta, init_value=None, window=7): if (alpha <= 0) or (alpha >= 1.): raise ValueError( 'Parameter alpha should be between range 0 < alpha < 1.') if (beta <= 0) or (beta >= 1.): raise ValueError( 'Parameter beta should be between range 0 < beta < 1....
Python
nomic_cornstack_python_v1
function getmet era var=string useT1=false verb=0 begin set branch = if expression string 2017 in era and string UL not in era then string METFixEE2017 else string MET if useT1 and string unclustEn not in var begin set branch = branch + string _T1 if var == string nom begin set var = string end end set pt = string %s...
def getmet(era,var="",useT1=False,verb=0): branch = 'METFixEE2017' if ('2017' in era and 'UL' not in era) else 'MET' if useT1 and 'unclustEn' not in var: branch += "_T1" if var=='nom': var = "" pt = '%s_pt'%(branch) phi = '%s_phi'%(branch) if var: pt += '_'+var phi += '_'+va...
Python
nomic_cornstack_python_v1
import pandas as pd comment Removeing starting spaces in notepad++ comment Find : ^\s+ comment Search mode -- tick regular expression comment Enter csv file name set csv_file_name = string DT_MDL4.csv comment Verilog File name set verilog_file_name = string dummy_test.v set df = read csv csv_file_name index_col=false n...
import pandas as pd # Removeing starting spaces in notepad++ # Find : ^\s+ # Search mode -- tick regular expression # Enter csv file name csv_file_name = 'DT_MDL4.csv' # Verilog File name verilog_file_name = 'dummy_test.v' df = pd.read_csv(csv_file_name, index_col=False, names=["ID", "p_if/cla...
Python
zaydzuhri_stack_edu_python
function _add_test_tags self values description=none mutable=none type_=none plugin=none concept=none begin set tags = list shuffle values for value in values begin set tag = call _create_test_tag value=string Tag_ + call unicode value description=description type_=type_ mutable=mutable plugin=plugin concept=concept a...
def _add_test_tags(self, values, description=None, mutable=None, type_=None, plugin=None, concept=None): tags = [] shuffle(values) for value in values: tag = self._create_test_tag(value=u'Tag_'+unicode(value), ...
Python
nomic_cornstack_python_v1
comment !/usr/bin/python3 function uppercase str begin set strUPPER = string for lowToUpp in str begin if ordinal lowToUpp < 97 or ordinal lowToUpp > 122 begin set strUPPER = strUPPER + lowToUpp end else if ordinal lowToUpp > 97 or ordinal lowToUpp < 122 begin set uP = ordinal lowToUpp - 32 set strUPPER = strUPPER + c...
#!/usr/bin/python3 def uppercase(str): strUPPER = "" for lowToUpp in str: if ((ord(lowToUpp) < 97 or ord(lowToUpp) > 122)): strUPPER = strUPPER + lowToUpp elif (ord(lowToUpp) > 97 or ord(lowToUpp) < 122): uP = (ord(lowToUpp) - 32) strUPPER = strUPPER + (chr(u...
Python
zaydzuhri_stack_edu_python
comment -*- coding: utf-8 -*- string Created on Wed Dec 18 12:09:25 2019 @author: Novin from newsapi.newsapi_client import NewsApiClient import pymongo import pandas as pd from datetime import datetime , timedelta function getCryptoNews startDate endDate begin try begin set newsapi = call NewsApiClient api_key=string e...
# -*- coding: utf-8 -*- """ Created on Wed Dec 18 12:09:25 2019 @author: Novin """ from newsapi.newsapi_client import NewsApiClient import pymongo import pandas as pd from datetime import datetime,timedelta def getCryptoNews(startDate,endDate): try: newsapi = NewsApiClient(api_key='ef9f89...
Python
zaydzuhri_stack_edu_python
function proof_of_work self block begin set nonce = 0 set computed_hash = call compute_hash while not starts with computed_hash string 0 * 5 begin set nonce = nonce + 1 set computed_hash = call compute_hash print computed_hash end print format string 最终结果是:{}, 随机数:{} computed_hash nonce return computed_hash end functio...
def proof_of_work(self, block): block.nonce = 0 computed_hash = block.compute_hash() while not computed_hash.startswith('0' * 5): block.nonce += 1 computed_hash = block.compute_hash() print(computed_hash) print('最终结果是:{}, 随机数:{}'.format(computed_hash,b...
Python
nomic_cornstack_python_v1
import JS comment Reading the input file D1 with open string D1.txt string r as inputFile begin set data1 = read lines inputFile end comment Reading the input file D2 with open string D2.txt string r as inputFile begin set data2 = read lines inputFile end comment Reading the input file D3 with open string D3.txt string...
import JS #Reading the input file D1 with open('D1.txt', 'r') as inputFile: data1 = inputFile.readlines() #Reading the input file D2 with open('D2.txt', 'r') as inputFile: data2 = inputFile.readlines() #Reading the input file D3 with open('D3.txt', 'r') as inputFile: data3 = inputFile.readlines() #Reading the ...
Python
zaydzuhri_stack_edu_python
function allow_create function begin decorator wraps function function _wrapped_func *args **kwargs begin set form = args at 0 comment If this argument is not a form, there are a lot of chances that comment you didn't decorate the right method. comment This decorator is only to be used decorating "form_valid()" if is i...
def allow_create(function): @wraps(function) def _wrapped_func(*args, **kwargs): form = args[0] # If this argument is not a form, there are a lot of chances that # you didn't decorate the right method. # This decorator is only to be used decorating "form_valid()" if isins...
Python
nomic_cornstack_python_v1
function test_read_face_node_connectivity begin set ug = call from_ncfile string files/ElevenPoints_UGRIDv0.9.nc assert shape == tuple 13 3 comment # not ideal to pull specific values out, but how else to test? comment note: file is 1-indexed, so these values are adjusted assert call array_equal faces at tuple 0 slice ...
def test_read_face_node_connectivity(): ug = UGrid.from_ncfile('files/ElevenPoints_UGRIDv0.9.nc') assert ug.faces.shape == (13, 3) # # not ideal to pull specific values out, but how else to test? ## note: file is 1-indexed, so these values are adjusted assert np.array_equal( ug.faces[0,:], (2, 3, 10) ) assert ...
Python
nomic_cornstack_python_v1
function get_floating_ip cls cloudname floating_ip_or_id output=string table begin try begin set cloud_provider = provider set result = none comment check if argument is ip or uuid if call isIPAddr ip_or_id=floating_ip_or_id begin comment get floating ip list set floating_ips = call get_floating_ip_list cloudname for f...
def get_floating_ip(cls, cloudname, floating_ip_or_id, output='table'): try: cloud_provider = CloudProvider(cloudname).provider result = None # check if argument is ip or uuid if cls.isIPAddr(ip_or_id=floating_ip_or_id): # get floating ip list ...
Python
nomic_cornstack_python_v1
function add_basic_gate self gate circuit *args **kwargs begin set op = op_lookup at name try begin set g = op at length control if call is_controlled begin set pyquil_gate = call g *[self.qubit(q) for q in gate.control + gate.target] end else begin set pyquil_gate = call g *[self.qubit(t) for t in gate.target] end end...
def add_basic_gate(self, gate, circuit, *args, **kwargs): op = self.op_lookup[gate.name] try: g = op[len(gate.control)] if gate.is_controlled(): pyquil_gate = g(*[self.qubit(q) for q in gate.control + gate.target]) else: pyquil_gate = g...
Python
nomic_cornstack_python_v1
import json set dog_breeds = dict string Labrador Retriever dict string Origin string United Kingdom ; string Temperament string Friendly ; string Life Expectancy string 12-13 years ; string French Bulldog dict string Origin string France ; string Temperament string Adaptable ; string Life Expectancy string 10-12 years...
import json dog_breeds = { "Labrador Retriever": { "Origin": "United Kingdom", "Temperament": "Friendly", "Life Expectancy": "12-13 years" }, "French Bulldog": { "Origin": "France", "Temperament": "Adaptable", "Life Expectancy": "10-12 years" }, "Siberian Husky": { "Origin": "Russ...
Python
flytech_python_25k
function check_forbidden_words song result begin set song_name = replace call slugify name string - string set to_check = replace call slugify name string - string set words = list for word in FORBIDDEN_WORDS begin if word in to_check and word not in song_name begin append words word end end return tuple length words ...
def check_forbidden_words(song: Song, result: Result) -> Tuple[bool, List[str]]: song_name = slugify(song.name).replace("-", "") to_check = slugify(result.name).replace("-", "") words = [] for word in FORBIDDEN_WORDS: if word in to_check and word not in song_name: words.append(word...
Python
nomic_cornstack_python_v1
function get_default_config self begin string Returns default settings for collector. set config = call get_default_config update config dict string path string lxc ; string sys_path string /sys/fs/cgroup/lxc return config end function
def get_default_config(self): """ Returns default settings for collector. """ config = super(MemoryLxcCollector, self).get_default_config() config.update({ "path": "lxc", "sys_path": "/sys/fs/cgroup/lxc", }) return config
Python
jtatman_500k
function lineIntersectOnce a1 a2 b1 b2 begin if not type a1 == ndarray begin set a1 = array a1 set a2 = array a2 set b1 = array b1 set b2 = array b2 end set v1 = a2 - a1 set v2 = b2 - b1 set c = b1 - a1 if norm call cross v1 v2 == 0 begin return 0 end comment not in the same plane if dot c call cross v1 v2 != 0 begin r...
def lineIntersectOnce(a1,a2,b1,b2): if not type(a1) == np.ndarray: a1 = np.array(a1) a2 = np.array(a2) b1 = np.array(b1) b2 = np.array(b2) v1 = a2- a1 v2 = b2 -b1 c = b1-a1 if np.linalg.norm(np.cross(v1, v2)) == 0: return 0 if np.dot(c, np.cr...
Python
nomic_cornstack_python_v1
from tkinter import * from tkinter import filedialog as fdialog from datetime import * import csv set win = call Tk title win string Tournament Scheduler call geometry string 800x600 function get_time_inputs begin global numberOfGames global gamesPerDay global start_h global start_m global gmWidth set numberOfGames = i...
from tkinter import * from tkinter import filedialog as fdialog from datetime import * import csv win = Tk() win.title('Tournament Scheduler') win.geometry('800x600') def get_time_inputs(): global numberOfGames global gamesPerDay global start_h global start_m global gmWidth numberOfGames ...
Python
zaydzuhri_stack_edu_python
import caffe import numpy as np import sys , os import cv2 import random import re import logging class FileIter begin function __init__ self traindata_dir bgr_mean=tuple 117 117 117 data_name=string data label_name=string l2_label begin set traindata_dir = traindata_dir comment (B, G, R) set mean = array bgr_mean set ...
import caffe import numpy as np import sys, os import cv2 import random import re import logging class FileIter(): def __init__(self, traindata_dir, bgr_mean = (117, 117, 117), data_name = "data", label_name = "l2_label"): self.traindata_dir = traindata_d...
Python
zaydzuhri_stack_edu_python
import random import sys class Dealer begin string A computer dealer for blackjack function __init__ self game begin string Constructs a dealer with the necessary features comment self.hand = hand() # For when we treat cards as objects comment ST: Back references like this let us talk back to other components of the "g...
import random import sys class Dealer : """ A computer dealer for blackjack """ def __init__(self, game): """ Constructs a dealer with the necessary features """ # self.hand = hand() # For when we treat cards as objects self.game = game #ST: Back references like ...
Python
zaydzuhri_stack_edu_python
comment !/usr/bin/env python import sys function readline begin return right strip read line stdin string end function function testcase begin set case_desc = iterate split read line set C = integer next set combinations = dict for i in call xrange C begin set tuple a b c = next set combinations at a + b = c set combi...
#!/usr/bin/env python import sys def readline(): return sys.stdin.readline().rstrip("\r\n") def testcase(): case_desc = iter(readline().split()) C = int(case_desc.next()) combinations = {} for i in xrange(C): a, b, c = case_desc.next() combinations[a+b] = c combinations[b...
Python
zaydzuhri_stack_edu_python
string Написать функцию num_translate(), переводящую числительные от 0 до 10 c английского на русский язык. function num_translate alert begin for tuple rus eng in items dict_of_numbers begin if alert == rus begin return eng end end end function set dict_of_numbers = dict string один string one ; string два string two ...
""" Написать функцию num_translate(), переводящую числительные от 0 до 10 c английского на русский язык. """ def num_translate(alert): for rus, eng in dict_of_numbers.items(): if alert == rus: return eng dict_of_numbers = { 'один': 'one', 'два': 'two', 'три': 'three',...
Python
zaydzuhri_stack_edu_python
from nodes import TLT , Statement , Program , Action , Function , Conditional , Dialogue , CompilationException import sys class Dummy begin pass end class
from nodes import TLT, Statement, Program, Action, Function, Conditional, Dialogue, CompilationException import sys class Dummy: pass
Python
zaydzuhri_stack_edu_python
function longitude self begin if not _data begin return none end return longitude end function
def longitude(self) -> float | None: if not self._data: return None return self._data.longitude
Python
nomic_cornstack_python_v1
function get_volume_in_range self lower_price_bound upper_price_bound begin set volume_sum = 0 if call __valid_price lower_price_bound and call __valid_price upper_price_bound begin comment Generate indices from input prices set left_index = integer decimal lower_price_bound * 100 - 1 + __price_points set right_index =...
def get_volume_in_range(self, lower_price_bound: float, upper_price_bound: float) -> float: volume_sum = 0 if(self.__valid_price(lower_price_bound) and self.__valid_price(upper_price_bound)): # Generate indices from input pr...
Python
nomic_cornstack_python_v1
function sum_pair array target_sum begin set res_pair = list comment Sort the array sort array comment Set the left and right pointers set tuple l r = tuple 0 length array - 1 while l != r begin if array at l + array at r == target_sum begin append res_pair tuple array at l array at r set l = l + 1 set r = r - 1 end e...
def sum_pair(array, target_sum): res_pair = [] # Sort the array array.sort() # Set the left and right pointers l, r = 0, len(array) - 1 while l != r: if array[l] + array[r] == target_sum: res_pair.append((array[l], array[r])) l += 1 r -= 1 ...
Python
iamtarun_python_18k_alpaca
comment -*- coding: utf-8 -*- string Created on Sat Feb 1 16:59:43 2020 https://qiita.com/phyblas/items/a801b0f319742245ad2e @author: PC from astropy.coordinates import SkyCoord , PrecessedGeocentric set b1875 = call PrecessedGeocentric equinox=string B1875 set b1875_hokkyoku = call SkyCoord ra=0 dec=90 unit=string deg...
# -*- coding: utf-8 -*- """ Created on Sat Feb 1 16:59:43 2020 https://qiita.com/phyblas/items/a801b0f319742245ad2e @author: PC """ from astropy.coordinates import SkyCoord,PrecessedGeocentric b1875 = PrecessedGeocentric(equinox='B1875') b1875_hokkyoku = SkyCoord(ra=0,dec=90,unit='deg',frame=b1875) print(b1875_hokk...
Python
zaydzuhri_stack_edu_python
comment !/usr/bin/env python3 import svgwrite import random import svgwrite set rows = 20 set cols = 20 function squares_touching_wall w begin set s1 = w at slice 0 : 2 : if w at 2 == string N and w at 0 != 0 begin return list s1 tuple w at 0 - 1 w at 1 end else if w at 2 == string W and w at 1 != 0 begin return list ...
#!/usr/bin/env python3 import svgwrite import random import svgwrite rows = 20 cols = 20 def squares_touching_wall(w): s1 = w[0:2] if w[2] == 'N' and w[0] != 0: return [s1, (w[0] - 1, w[1])] elif w[2] == 'W' and w[1] != 0: return [s1, (w[0], w[1] - 1)] else: raise RuntimeErro...
Python
zaydzuhri_stack_edu_python
function dag qobj begin return call dag end function
def dag(qobj): return qobj.dag()
Python
nomic_cornstack_python_v1
from django.shortcuts import render from django.http import JsonResponse import json import random from django.views.decorators.csrf import csrf_exempt comment All win positions set win_positions = list list 0 1 2 list 3 4 5 list 6 7 8 list 0 3 6 list 1 4 7 list 2 5 8 list 0 4 8 list 2 4 6 function index request begin ...
from django.shortcuts import render from django.http import JsonResponse import json import random from django.views.decorators.csrf import csrf_exempt #All win positions win_positions = [[0, 1, 2], [3, 4, 5], [6, 7, 8], [0, 3, 6], [1, 4, 7], [2, 5, 8], [0, 4, 8], [2, 4, 6]] def index(request): ...
Python
zaydzuhri_stack_edu_python
comment ! -*- coding:utf-8 -*- comment 2019.1.23 模型重新梳理,一次PL汇率换算,加上了手数的因素 import time import re import pymysql import requests from lxml import etree from selenium import webdriver comment 还是要用PhantomJS import datetime import string from math import floor comment 暂时没有找到洲际交易所的FTFE100好的数据源,官网行不通.所以这里直接用lse的官网的 comment 的股...
# ! -*- coding:utf-8 -*- # 2019.1.23 模型重新梳理,一次PL汇率换算,加上了手数的因素 import time import re import pymysql import requests from lxml import etree from selenium import webdriver # 还是要用PhantomJS import datetime import string from math import floor # 暂时没有找到洲际交易所的FTFE100好的数据源,官网行不通.所以这里直接用lse的官网的 # 的股票指数代替,这样在windows下也可以去跑脚本...
Python
zaydzuhri_stack_edu_python
from toboggan_trajectory import multiply_all , is_tree , count_trees , count_right3_down1_trees import pytest decorator fixture function basic_data begin return list string ..##....... string #...#...#.. string .#....#..#. string ..#.#...#.# string .#...##..#. string ..#.##..... string .#.#.#....# string .#........# st...
from toboggan_trajectory import \ multiply_all, \ is_tree, \ count_trees, \ count_right3_down1_trees import pytest @pytest.fixture def basic_data(): return [ "..##.......", "#...#...#..", ".#....#..#.", "..#.#...#.#", ".#....
Python
zaydzuhri_stack_edu_python
import constants import torch import torch.nn as nn import matplotlib.pyplot as plt import os from datetime import datetime from utils.CompositeAverageMeter import CompositeAverageMeter from utils.Metrics import Metrics class Trainer begin string Wraps PyTorch model training. function __init__ self logger load_provider...
import constants import torch import torch.nn as nn import matplotlib.pyplot as plt import os from datetime import datetime from utils.CompositeAverageMeter import CompositeAverageMeter from utils.Metrics import Metrics class Trainer: '''Wraps PyTorch model training.''' def __init__(self, logger, load_provide...
Python
zaydzuhri_stack_edu_python
from __future__ import division import numpy as np import networkx as nx import matplotlib as mpl import matplotlib.pyplot as plt import itertools from random import choices import json from collections import defaultdict comment mpl.rcParams['savefig.dpi'] = 120 comment mpl.rcParams['figure.dpi'] = 120 comment import ...
from __future__ import division import numpy as np import networkx as nx import matplotlib as mpl import matplotlib.pyplot as plt import itertools from random import choices import json from collections import defaultdict # mpl.rcParams['savefig.dpi'] = 120 # mpl.rcParams['figure.dpi'] = 120 # import matplotlib as mp...
Python
zaydzuhri_stack_edu_python
function generate_parameters self cluster_center std_dev num_tasks begin return call normal cluster_center std_dev num_tasks end function
def generate_parameters(self, cluster_center, std_dev, num_tasks): return np.random.normal(cluster_center, std_dev, num_tasks)
Python
nomic_cornstack_python_v1
import numpy as np from scipy.io import loadmat from sklearn.utils import shuffle import matplotlib.pyplot as plt class MNISTData extends object begin function __init__ self begin pass end function function loadFlatData self begin set train = call loadmat string Data/HouseNumbers/train_32x32.mat set test = call loadmat...
import numpy as np from scipy.io import loadmat from sklearn.utils import shuffle import matplotlib.pyplot as plt class MNISTData(object): def __init__(self): pass def loadFlatData(self): train = loadmat('Data/HouseNumbers/train_32x32.mat') test = loadmat('Data/HouseNumbers/test_32x32.mat') Xtrain = self...
Python
zaydzuhri_stack_edu_python
comment -*- coding: utf-8 -*- from max.exceptions import DuplicatedItemError from max.exceptions import MissingField from max.exceptions import ObjectNotSupported from max.exceptions import ValidationError from max.utils.dicts import RUDict from max.utils.dicts import flatten from pyramid.security import ACLAllowed fro...
# -*- coding: utf-8 -*- from max.exceptions import DuplicatedItemError from max.exceptions import MissingField from max.exceptions import ObjectNotSupported from max.exceptions import ValidationError from max.utils.dicts import RUDict from max.utils.dicts import flatten from pyramid.security import ACLAllowed from bso...
Python
zaydzuhri_stack_edu_python
function download_updated_data_to_csv self begin comment get tickers list. set ticker_list = call load_tickers_from_ini set data = call download tickers=ticker_list period=string 1y interval=string 1d group_by=string ticker auto_adjust=false prepost=false threads=true proxy=none comment switch columns and rows for df s...
def download_updated_data_to_csv(self): ticker_list = yf_func.load_tickers_from_ini() # get tickers list. data = yf.download( tickers=ticker_list, period='1y', interval='1d', group_by='ticker', auto_adjust=False, prepost=False, ...
Python
nomic_cornstack_python_v1
function get_actions self request begin set actions = call get_actions request del actions at string delete_selected return actions end function
def get_actions(self, request): actions = super(NagiosContactGroupAdmin, self).get_actions(request) del actions['delete_selected'] return actions
Python
nomic_cornstack_python_v1
function predict self X_test begin set pred = list for test in X_test begin set predicted = integer argument maximum dot w T append pred predicted end return pred end function
def predict(self, X_test: np.ndarray) -> np.ndarray: pred = [] for test in X_test: predicted = int(np.argmax(np.dot(self.w, test.T))) pred.append(predicted) return pred
Python
nomic_cornstack_python_v1
function from_value_rowids_bridge values value_rowids=none nrows=none validate=true begin return call from_value_rowids values value_rowids=value_rowids nrows=nrows validate=validate end function
def from_value_rowids_bridge(values, value_rowids=None, nrows=None, validate=True): return tf.RaggedTensor.from_value_rowids( values, value_rowids=value_rowids, nrows=nrows , validate=validate )
Python
nomic_cornstack_python_v1
from os import getcwd from sys import path set cwd = get current directory append path cwd from Task_2.Class.controller import cls_Controller import pytest class Test_mtd_Pascoa begin function test_pascoa_1 self begin set obj = call cls_Controller assert call mtd_Pascoa 2021 == string 2021-04-04 end function function t...
from os import getcwd from sys import path cwd = getcwd() path.append(cwd) from Task_2.Class.controller import cls_Controller import pytest class Test_mtd_Pascoa: def test_pascoa_1(self): obj = cls_Controller() assert obj.mtd_Pascoa(2021) == '2021-04-04' def test_pascoa_2(self): obj = cls_Controller() asse...
Python
zaydzuhri_stack_edu_python
function generate basic n N result begin if n == 0 begin if eval result <= N begin return 1 end else begin return 0 end end else begin set n = n - 1 set res = 0 for x in basic begin set temp = result + x set res = res + call generate basic n N temp end return res end end function set D = split input string , set N = in...
def generate(basic,n,N,result): if(n == 0): if(eval(result) <= N): return 1 else: return 0 else: n = n - 1 res = 0 for x in basic: temp = result + x res += generate(basic,n,N,temp) return res D = input().split(",") ...
Python
zaydzuhri_stack_edu_python
function get_queryset self begin if upper method in list string GET string OPTIONS begin set queryset = filter deleted_at__isnull=true organization__is_active=true end return call get_queryset end function
def get_queryset(self): if self.request.method.upper() in ["GET", "OPTIONS"]: self.queryset = Project.prefetched.filter( deleted_at__isnull=True, organization__is_active=True ) return super().get_queryset()
Python
nomic_cornstack_python_v1
function get_client opts custom_headers=none **kwargs begin if is instance opts Namespace begin set opts = variables opts end comment Allow explicit setting "do not verify certificates" set verify = get opts string cafile if lower string verify == string false begin warning string Unverified HTTPS requests (cafile=fals...
def get_client(opts, custom_headers=None, **kwargs): if isinstance(opts, Namespace): opts = vars(opts) # Allow explicit setting "do not verify certificates" verify = opts.get("cafile") if str(verify).lower() == "false": LOG.warning("Unverified HTTPS requests (cafile=false).") re...
Python
nomic_cornstack_python_v1
function flatten obj_list all_objs=none feat_list=none begin if all_objs is none begin set all_objs = dict end for obj in obj_list begin try begin update all_objs flatten children all_objs feat_list comment oooh recursion if feat_list begin if feat_type not in feat_list begin continue end end set all_objs at name = ob...
def flatten(obj_list, all_objs=None, feat_list=None): if all_objs is None: all_objs = {} for obj in obj_list: try: all_objs.update( flatten(obj.children, all_objs, feat_list)) # oooh recursion if feat_list: if obj.feat_type not in feat_list...
Python
nomic_cornstack_python_v1
comment !/bin/python3 import math import os import random import re import sys comment Complete the twoStrings function below. function twoStrings s1 s2 begin if set s1 ? set s2 begin return string YES end return string NO end function if __name__ == string __main__ begin set s1 = string hello set s2 = string world pri...
#!/bin/python3 import math import os import random import re import sys # Complete the twoStrings function below. def twoStrings(s1, s2): if set(s1) & set(s2): return "YES" return "NO" if __name__ == '__main__': s1 = "hello" s2 = "world" print(twoStrings(s1, s2)) s1 = "hi" s2 ...
Python
zaydzuhri_stack_edu_python
function _apply_scores self scores value scores_mask=none training=none begin if scores_mask is not none begin set padding_mask = call logical_not scores_mask comment Bias so padding positions do not contribute to attention distribution. comment Note 65504. is the max float16 value. if dtype is float16 begin set scores...
def _apply_scores(self, scores, value, scores_mask=None, training=None): if scores_mask is not None: padding_mask = math_ops.logical_not(scores_mask) # Bias so padding positions do not contribute to attention distribution. # Note 65504. is the max float16 value. if scores.dtype is dtypes.flo...
Python
nomic_cornstack_python_v1
function possible_sums the_list begin set sums = list for i in range 0 length the_list begin for j in range 0 length the_list begin if i == j begin pass end else begin set sums = sums + list the_list at i + the_list at j end end end return sums end function
def possible_sums(the_list): sums = [] for i in range(0, len(the_list)): for j in range(0, len(the_list)): if i == j: pass else: sums += [the_list[i] + the_list[j]] return sums
Python
nomic_cornstack_python_v1
import cv2 import time import numpy as ny set fourcc = call VideoWriter_fourcc *'XVID' set output_file = call VideoWriter string output.avi fourcc 20.0 tuple 640 480 set cap = call VideoCapture 0 sleep 2 set bg = 0
import cv2 import time import numpy as ny fourcc = cv2.VideoWriter_fourcc(*'XVID') output_file = cv2.VideoWriter('output.avi',fourcc,20.0,(640,480)) cap = cv2.VideoCapture(0) time.sleep(2) bg = 0
Python
zaydzuhri_stack_edu_python
comment A simple image processing client. comment Receives frame of bouncing ball, calculates comment it's position and returns the coordinates. comment Author: Dhruv Sirohi from aiortc import RTCPeerConnection , MediaStreamTrack , RTCSessionDescription , RTCIceCandidate from aiortc.contrib.media import MediaRelay from...
# A simple image processing client. # Receives frame of bouncing ball, calculates # it's position and returns the coordinates. # Author: Dhruv Sirohi from aiortc import RTCPeerConnection, MediaStreamTrack, RTCSessionDescription, RTCIceCandidate from aiortc.contrib.media import MediaRelay from aiortc.contrib.signaling ...
Python
zaydzuhri_stack_edu_python
function read_csv_header csv_path begin with open csv_path string r as csv_file begin set first_line = read line csv_file seek csv_file 0 if string , not in first_line begin comment csv.Sniffer doesn't work if there's only one column in the file try begin integer first_line set has_header = false end except any begin s...
def read_csv_header(csv_path): with open(csv_path, 'r') as csv_file: first_line = csv_file.readline() csv_file.seek(0) if ',' not in first_line: # csv.Sniffer doesn't work if there's only one column in the file try: int(first_line) has_...
Python
nomic_cornstack_python_v1
function get_paginator request products num_x_pag begin try begin set page = integer get GET string page 1 end except ValueError begin set page = 1 end set paginator = call Paginator products num_x_pag try begin set products_per_pag = object_list end except tuple InvalidPage EmptyPage begin set products_per_pag = objec...
def get_paginator(request, products, num_x_pag): try: page = int(request.GET.get('page', 1)) except ValueError: page = 1 paginator = Paginator(products, num_x_pag) try: products_per_pag = paginator.page(page).object_list except (InvalidPage, EmptyPage): products_per...
Python
nomic_cornstack_python_v1
comment Craps Roller import random set first_die = random integer 1 6 set second_die = random integer 1 6 print string You rolled first_die string and second_die while first_die == 6 and second_die == 6 begin print string Welldone, you have earned an extra roll! input string \Press Enter to roll again... set first_die ...
#Craps Roller import random first_die = random.randint(1, 6) second_die = random.randint(1, 6) print ("\nYou rolled", first_die, "and", second_die) while first_die == 6 and second_die == 6: print ("\nWelldone, you have earned an extra roll!") input ("\n\n\Press Enter to roll again...") first_die = rando...
Python
zaydzuhri_stack_edu_python
comment -*- coding: utf-8 -*- string andy@datassis.com comment --------------维护词典:衰退淘汰机制---------------################ import json import time import collections function store data fdir begin with open fdir string w encoding=string utf8 as json_file begin write json_file dumps data ensure_ascii=false end end function...
# -*- coding: utf-8 -*- """ andy@datassis.com """ #############--------------维护词典:衰退淘汰机制---------------################ import json import time import collections def store(data,fdir): with open(fdir, 'w',encoding='utf8') as json_file: json_file.write(json.dumps(data,ensure_ascii=False)) def load(fdir): ...
Python
zaydzuhri_stack_edu_python
function get_property_value dictionary property_name default_value=none trim_string=false empty_value=string begin comment If property_name is not in the dictionary, set value to null_value if property_name in dictionary begin set value = dictionary at property_name if value is none begin set value = default_value end ...
def get_property_value(dictionary, property_name, default_value=None, trim_string=False, empty_value=""): # If property_name is not in the dictionary, set value to null_value if property_name in dictionary: value = dictionary[property_name] if value is None: value = default_valu...
Python
nomic_cornstack_python_v1
function train_supervised self labelled_sequences estimator=none begin comment default to the MLE estimate if estimator is none begin set estimator = lambda fdist bins -> call MLEProbDist fdist end comment count occurrences of starting states, transitions out of each state comment and output symbols observed in each st...
def train_supervised(self, labelled_sequences, estimator=None): # default to the MLE estimate if estimator is None: estimator = lambda fdist, bins: MLEProbDist(fdist) # count occurrences of starting states, transitions out of each state # and output symbols observed in each...
Python
nomic_cornstack_python_v1
function simplify_points points value=100 begin from shapely.geometry import Polygon as ShapelyPolygon if length points > 199 begin set factor = length points * value * GRID set sp = call simplify factor set points = list comprehension list p at 0 p at 1 for p in coords end return points end function
def simplify_points(points, value=100): from shapely.geometry import Polygon as ShapelyPolygon if len(points) > 199: factor = len(points) * value * RDD.GDSII.GRID sp = ShapelyPolygon(points).simplify(factor) points = [[p[0], p[1]] for p in sp.exterior.coords] return points
Python
nomic_cornstack_python_v1
import torch from torch.autograd import Variable from torch.optim import Adam , LBFGS from torch.utils.data import Dataset , DataLoader set temp = list 1 2 3 4 5 print list zip temp temp at slice : - 1 : class Nnet extends Module begin function __init__ self input_dim hidden_layer_sizes loss sigmoid=false begin call _...
import torch from torch.autograd import Variable from torch.optim import Adam, LBFGS from torch.utils.data import Dataset, DataLoader temp = [1, 2, 3, 4, 5] print(list(zip(temp, temp[:-1]))) class Nnet(torch.nn.Module): def __init__(self, input_dim, hidden_layer_sizes, loss, sigmoid = False): super().__i...
Python
zaydzuhri_stack_edu_python
function __init__ self ignored_attributes=list na_values=list target_index=- 1 *args **kwargs begin set ignored_attributes = ignored_attributes set na_values = list string ? string na extend na_values na_values set params = kwargs comment Parameters are ignored when data.csv and meta_data.json exist comment Same for ...
def __init__(self, ignored_attributes=[], na_values=[], target_index=-1, *args, **kwargs): self.ignored_attributes = ignored_attributes self.na_values = ["?", "na"] self.na_values.extend(na_values) self....
Python
nomic_cornstack_python_v1
function transform self X begin set X = call function X return X end function
def transform(self, X): X = self.function(X) return X
Python
nomic_cornstack_python_v1
function test_deploy_with_remote_host self begin set remote_host = remote_host set transportfile = call _make_transport_file call guest_create userid 1 1024 disk_list=disks call guest_deploy userid image_name transportfiles=transportfile remotehost=remote_host call guest_start userid set powered_on = call wait_until_gu...
def test_deploy_with_remote_host(self): remote_host = CONF.tests.remote_host transportfile = self._make_transport_file() self.sdkapi.guest_create(self.userid, 1, 1024, disk_list=self.disks) self.sdkapi.guest_deploy(self.userid, self.image_name, ...
Python
nomic_cornstack_python_v1
function populate self myEmpireDict mySystemDict begin set myEmpireDict = myEmpireDict set mySystemDict = mySystemDict comment disable buttons call disable call disable call disable call disable comment load resources try begin set myEmpirePict = string %s%s.png % tuple simImagePath myEmpireDict at string imageFile set...
def populate(self, myEmpireDict, mySystemDict): self.myEmpireDict = myEmpireDict self.mySystemDict = mySystemDict # disable buttons self.btnChangeCity.disable() self.btnRemoveIndustry.disable() self.btnUpgradeIndustry.disable() self.btnCancelOrder.disable() ...
Python
nomic_cornstack_python_v1
function platform_inactive_state self begin set kwargs = dictionary recursion=true set cmd = call AgentCommand command=INITIALIZE kwargs=kwargs call execute_agent cmd timeout=receive_timeout end function
def platform_inactive_state(self): kwargs = dict(recursion=True) cmd = AgentCommand(command=PlatformAgentEvent.INITIALIZE, kwargs=kwargs) self.platform_agent.execute_agent(cmd, timeout=self.receive_timeout)
Python
nomic_cornstack_python_v1
function _xys date begin string Get The X, Y and s coordinates Args: date (Date): Return: 3-tuple of float: Values of X, Y and s, in radians set tuple X Y s_xy2 = call _xysxy2 date comment convert milli-arcsecond to arcsecond set tuple dX dY = tuple dx / 1000.0 dy / 1000.0 comment Convert arcsecond to degrees then to r...
def _xys(date): """Get The X, Y and s coordinates Args: date (Date): Return: 3-tuple of float: Values of X, Y and s, in radians """ X, Y, s_xy2 = _xysxy2(date) # convert milli-arcsecond to arcsecond dX, dY = date.eop.dx / 1000., date.eop.dy / 1000. # Convert arcsecond...
Python
jtatman_500k
function create_socket begin set host = string 192.168.101.72 set port = 5000 set sock = call socket AF_INET SOCK_STREAM call bind tuple host port call listen SOCK_LISTEN_SIZE print string Server setup while true begin set tuple conn address = call accept print address string has connected to the server start thread ta...
def create_socket(): host = '192.168.101.72' port = 5000 sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sock.bind((host, port)) sock.listen(SOCK_LISTEN_SIZE) print("Server setup") while True: conn, address = sock.accept() print(address, "has connected t...
Python
nomic_cornstack_python_v1
function __init__ self opdef result_dir filter_fused=true rename_aib=true begin set name = name if type == string tc begin set data = call load_tc join path result_dir string { bm } -result.csv if filter_fused and string fused in name begin call _filter_fused_configs end end else if type == string kernel begin set data...
def __init__(self, opdef, result_dir, filter_fused=True, rename_aib=True): self.name = opdef.name if opdef.type == 'tc': self.data = load_tc(os.path.join( result_dir, f'{opdef.bm}-result.csv')) if filter_fused and 'fused' in self.name: self._filter...
Python
nomic_cornstack_python_v1
function negations propSentence begin if is instance propSentence str begin set prop = propSentence end else begin set listElement = propSentence at 0 if listElement == string not begin set others = propSentence at 1 if is instance others str begin set prop = list append prop string not append prop others end else beg...
def negations(propSentence) : if isinstance(propSentence, str) : prop = propSentence else : listElement = propSentence[0] if listElement == "not" : others = propSentence[1] if isinstance(others, str) : prop = [] prop.appen...
Python
nomic_cornstack_python_v1
function get_available_testcases self begin set list_tc = call get_available_tc for key in keys list_tc begin set list_tc_init at key = call end end function
def get_available_testcases(self): self.list_tc = testcases.get_available_tc() for key in self.list_tc.keys(): self.list_tc_init[key] = self.list_tc[key]()
Python
nomic_cornstack_python_v1
function get_multiparm_template_name parm begin comment Return None if the parameter isn't a multiparm instance. if not call isMultiParmInstance begin return none end if is instance parm Parm begin set parm = tuple end return call string_decode call get_multiparm_template_name parm end function
def get_multiparm_template_name(parm: Union[hou.Parm, hou.ParmTuple]) -> Optional[str]: # Return None if the parameter isn't a multiparm instance. if not parm.isMultiParmInstance(): return None if isinstance(parm, hou.Parm): parm = parm.tuple() return utils.string_decode(_cpp_methods.g...
Python
nomic_cornstack_python_v1
function get_jinja_filename_environment templates begin set loader = call DictLoader dictionary comprehension name : name for template in templates return call Environment loader=loader trim_blocks=true lstrip_blocks=true end function
def get_jinja_filename_environment(templates) -> jinja2.Environment: loader = jinja2.DictLoader( {template.name: template.name for template in templates} ) return jinja2.Environment( loader=loader, trim_blocks=True, lstrip_blocks=True )
Python
nomic_cornstack_python_v1
function value_range self rng begin set tuple start end = split rng string : set tuple row_offset column_offset = call a1_to_rowcol start set tuple last_row last_column = call a1_to_rowcol end set out = list for col in values at slice row_offset - 1 : last_row : begin extend out col at slice column_offset - 1 : last_...
def value_range(self, rng): start, end = rng.split(':') (row_offset, column_offset) = a1_to_rowcol(start) (last_row, last_column) = a1_to_rowcol(end) out = [] for col in self.values[row_offset - 1:last_row]: out.extend(col[column_offset - 1:last_column]) retu...
Python
nomic_cornstack_python_v1
while asd != c - 1 begin comment [Event "Rated Classical game"] if contents at asd == string begin set n = n + 1 if n == 3 begin set lcvtitle = lcvtitle + 1 close set temp = string chess + string lcvtitle + string .txt set x = open temp string a set n = 1 end end write x contents at asd set lcv3 = lcv3 + 1 set asd = a...
while asd != (c-1): ## [Event "Rated Classical game"] if (contents[asd]) == '\n': n= n + 1 if n == 3: lcvtitle = lcvtitle + 1 x.close temp = "chess" + str(lcvtitle) + ".txt" x = open(temp , "a") n = 1 x.write(content...
Python
zaydzuhri_stack_edu_python
function series_3_start begin set fruit_list = list string Apples string Pears string Oranges string Peaches print string Starting series 3..... print fruit_list set items_to_delete = list for item in fruit_list begin set ask = input format string Do you like {}? lower item while ask not in set literal string yes stri...
def series_3_start(): fruit_list = ["Apples", "Pears", "Oranges", "Peaches"] print("Starting series 3.....") print(fruit_list) items_to_delete = [] for item in fruit_list: ask = input("Do you like {}? ".format(item.lower())) while ask not in {'yes', 'no'}: print("Pleas...
Python
nomic_cornstack_python_v1
import json import socket function readParameters begin with open string parameter.json as file begin set k = load json file end return k string for elemento in k: if elemento['sistema']['computador'] == socket.gethostname(): caminhoDataset = elemento['sistema']['datasetPath'] trackerPath = elemento['tracker']['tracker...
import json import socket def readParameters(): with open('parameter.json') as file: k = json.load(file) return k ''' for elemento in k: if elemento['sistema']['computador'] == socket.gethostname(): caminhoDataset = elemento['sistema']['datasetPath'] trackerPath = elemento['tracker']['trackerPath']...
Python
zaydzuhri_stack_edu_python
comment -*- coding: utf-8 -*- string Created on Thu Sep 2 19:38:10 2021 @author: admin comment https://edabit.com/challenge/2C3gtb4treAFyWJMg from string import ascii_uppercase set ls = list ascii_uppercase remove ls string J set ls at index ls string I = string I/J set letter_dic = dict for i in range 1 6 begin for j...
# -*- coding: utf-8 -*- """ Created on Thu Sep 2 19:38:10 2021 @author: admin """ #https://edabit.com/challenge/2C3gtb4treAFyWJMg from string import ascii_uppercase ls= list(ascii_uppercase) ls.remove("J") ls[ls.index("I")] = "I/J" letter_dic = {} for i in range(1,6): for j in range(1,6): letter_dic[i...
Python
zaydzuhri_stack_edu_python
comment coding:utf-8 string a company model set __author__ = string David West : admin@dxscx.com import position_model class Company_Model begin function __init__ self begin comment 公司uuid set uuid = string comment 公司信息来源url set url = string comment 公司名 set name = string comment 公司简称 set short_name = string comment...
# coding:utf-8 ' a company model ' __author__ = 'David West : admin@dxscx.com' import position_model class Company_Model: def __init__(self): #公司uuid self.uuid="" # 公司信息来源url self.url = "" # 公司名 self.name = "" # 公司简称 self.short_name = "" # 公司...
Python
zaydzuhri_stack_edu_python
comment !/usr/bin/env python comment coding: utf-8 comment input 1 line from stdin comment remove newline character set str = call raw_input
#!/usr/bin/env python # coding: utf-8 # input 1 line from stdin # remove newline character str = raw_input()
Python
zaydzuhri_stack_edu_python
function finals self short=false **kwargs begin comment get courses that have finals records in them set finals_courses = list comprehension c for c in call get_sorted_courses include_unscheduled=true if finals is not none if length finals_courses == 0 begin print string No finals added yet! exit 0 end comment build a ...
def finals(self, short=False, **kwargs): # get courses that have finals records in them finals_courses = [c for c in self.get_sorted_courses(include_unscheduled=True) if c.finals is not None] if len(finals_courses) == 0: print("No finals added yet!") sys.exit(0) ...
Python
nomic_cornstack_python_v1
import bradata.utils import bradata.connection import os import io from zipfile import ZipFile import pandas as pd import glob import yaml import shutil import luigi import luigi.contrib.postgres function _find_header data_type year path begin with open path string r as f begin set data = load yaml f end set a = data a...
import bradata.utils import bradata.connection import os import io from zipfile import ZipFile import pandas as pd import glob import yaml import shutil import luigi import luigi.contrib.postgres def _find_header(data_type, year, path): with open(path, 'r') as f: data = yaml.load(f) a = data[data_ty...
Python
iamtarun_python_18k_alpaca
function start self begin set color = GREEN call on end function comment self.run()
def start(self): self.led.left.color = LED.COLOR.GREEN self.led.left.on() # self.run()
Python
nomic_cornstack_python_v1
function test_conflict self begin set tuple code _ err = call run_vhdeps string dump string -i DIR + string /simple/all-good string -i DIR + string /simple/timeout assert equal code 1 assert true string ResolutionError: entity work.test_tc is defined in multiple, ambiguous files: in err end function
def test_conflict(self): code, _, err = run_vhdeps( 'dump', '-i', DIR + '/simple/all-good', '-i', DIR + '/simple/timeout') self.assertEqual(code, 1) self.assertTrue('ResolutionError: entity work.test_tc is defined in ' 'multiple, ambigu...
Python
nomic_cornstack_python_v1
function __init__ self features token=none features_list=none begin set token = token set features = features set features_list = features_list or list string acousticness string analysis_url string danceability string duration_ms string energy string id string instrumentalness string key string liveness string loudnes...
def __init__(self, features, token=None, features_list=None): self.token = token self.features = features self.features_list = (features_list or ['acousticness', 'analysis_url', 'danceability', \ 'duration_ms', 'energy', 'id', 'instrumentalness', \ 'key', 'l...
Python
nomic_cornstack_python_v1