code
stringlengths
10
2.58M
original_code
stringlengths
3
3.18M
original_language
stringclasses
1 value
source
stringclasses
7 values
function run self begin set last_update_time = time while not call is_dead begin update game_model update bullet_model call draw set last_update_time = time update display end end function
def run(self): last_update_time = time.time() while not(self.game_model.is_dead()): self.game_model.update() self.bullet_model.update() self.view.draw() last_update_time = time.time() pygame.display.update()
Python
nomic_cornstack_python_v1
function upgrade_python c begin set newc = c set newc = replace replace newc string Python string Anaconda string python string anaconda return newc end function
def upgrade_python(c): newc = c newc = newc.replace('Python', 'Anaconda').replace('python', 'anaconda') return newc
Python
nomic_cornstack_python_v1
function train begin comment DO NOT CHANGE SEEDS! comment Set the random seeds for reproducibility seed 42 set epoch_num = 3 comment PUT YOUR CODE HERE # set model = call ConvNet 3 10 comment Obtain Dataset set train_dataset = call get_cifar10 at string train set val_dataset = call get_cifar10 at string validation set ...
def train(): ### DO NOT CHANGE SEEDS! # Set the random seeds for reproducibility np.random.seed(42) epoch_num = 3 ######################## # PUT YOUR CODE HERE # ####################### model = ConvNet(3, 10) #Obtain Dataset train_dataset = cifar10_utils.get_cifar10()['train'] val_dataset = cif...
Python
nomic_cornstack_python_v1
function test_tail_after_append_in_list new_dll begin append new_dll 6 assert value == 6 end function
def test_tail_after_append_in_list(new_dll): new_dll.append(6) assert new_dll.tail.value == 6
Python
nomic_cornstack_python_v1
function on_session_started session_started_request session begin print string on_session_started requestId= + session_started_request at string requestId + string , sessionId= + session at string sessionId end function
def on_session_started(session_started_request, session): print("on_session_started requestId=" + session_started_request['requestId'] + ", sessionId=" + session['sessionId'])
Python
nomic_cornstack_python_v1
from typing import List class Solution begin function findMedianSortedArrays self nums1 nums2 begin set nums = nums1 + nums2 set nums = sorted nums set left = 0 set right = 0 if length nums % 2 == 0 begin set right = length nums / 2 set left = right - 1 end else begin set right = length nums // 2 set left = length nums...
from typing import List class Solution: def findMedianSortedArrays(self, nums1: List[int], nums2: List[int]) -> float: nums = nums1 + nums2 nums = sorted(nums) left = right = 0 if len(nums) % 2 == 0: right = len(nums) / 2 left = right - 1 else: ...
Python
zaydzuhri_stack_edu_python
function test_graph_system_group_traverse_user self begin pass end function
def test_graph_system_group_traverse_user(self): pass
Python
nomic_cornstack_python_v1
function pq_compute_multi_core matched_annotations_list gt_folder pred_folder categories file_client=none nproc=32 begin if PQStat is none begin raise call RuntimeError string panopticapi is not installed, please install it by: pip install git+https://github.com/cocodataset/panopticapi.git. end if file_client is none b...
def pq_compute_multi_core(matched_annotations_list, gt_folder, pred_folder, categories, file_client=None, nproc=32): if PQStat is None: raise RuntimeError( 'panoptica...
Python
nomic_cornstack_python_v1
async function test_dhcp_match_macaddress hass begin set integration_matchers = list dict string domain string mock-domain ; string macaddress string B8B7F1* set packet = call Ether RAW_DHCP_REQUEST set async_handle_dhcp_packet = await call _async_get_handle_dhcp_packet hass integration_matchers with call object flow s...
async def test_dhcp_match_macaddress(hass: HomeAssistant) -> None: integration_matchers = [{"domain": "mock-domain", "macaddress": "B8B7F1*"}] packet = Ether(RAW_DHCP_REQUEST) async_handle_dhcp_packet = await _async_get_handle_dhcp_packet( hass, integration_matchers ) with patch.object(has...
Python
nomic_cornstack_python_v1
import xlsxwriter string Helper function that writes a particular section of a worksheet, including the relevant information for all twenty teams as well as some basic formatting. @param worksheet The worksheet object (part of xlsxwriter) @param sheet_name The name of the worksheet (str) @param section_name The name of...
import xlsxwriter ''' Helper function that writes a particular section of a worksheet, including the relevant information for all twenty teams as well as some basic formatting. @param worksheet The worksheet object (part of xlsxwriter) @param sheet_name The name of the worksheet (str) @param...
Python
zaydzuhri_stack_edu_python
from Game import * from Player import * import pickle set NB_BATON = 15 set jeu = call Game NB_BATON comment Nom du joueur (l'humain) set playerName = input string Entrez votre nom : comment Mode de jeu (easy, medium, hard) set gameMode = string while gameMode != string easy and gameMode != string medium and gameMode ...
from Game import * from Player import * import pickle NB_BATON = 15 jeu = Game(NB_BATON) # Nom du joueur (l'humain) playerName = input('Entrez votre nom : \n') # Mode de jeu (easy, medium, hard) gameMode="" while (gameMode != "easy") and (gameMode != "medium") and (gameMode != "hard"): gameMode = input('Choisir...
Python
zaydzuhri_stack_edu_python
comment -*- coding: utf-8 -*- string Lab 2 - arrangenumbers_0_2.py Task: -Enter a List of Numbers - create a tuple containing values -rearrange the values in correct ascending order -Print the result Created on Sun Jan 17 08:10:31 2021 @author: Ayush print string 8 puzzle - arrange the numbers by swapping them with the...
# -*- coding: utf-8 -*- """ Lab 2 - arrangenumbers_0_2.py Task: -Enter a List of Numbers - create a tuple containing values -rearrange the values in correct ascending order -Print the result Created on Sun Jan 17 08:10:31 2021 @author: Ayush """ print ('8 puzzle - arrange the numbers by swapping them with the empty p...
Python
zaydzuhri_stack_edu_python
function get_future_expire days=3 begin set limit_date = now + time delta days=days set q = filter email != none comment Expire now < expiration < N days set q = filter paid_until > now set q = filter paid_until < limit_date comment Only send notice if the last one was before the first time we could have comment sent a...
def get_future_expire(days=3): limit_date = datetime.now() + timedelta(days=days) q = DBSession.query(User) \ .filter(User.email != '') \ .filter(User.email != None) # Expire now < expiration < N days q = q.filter(User.paid_until > datetime.now()) q = q.filter(Us...
Python
nomic_cornstack_python_v1
import numpy as np import seaborn as sns import matplotlib.pyplot as plt set dataset = call load_dataset string tips comment violin plots are same as box plot and there is one more argument split which sets to True for combining the comment hue else False, bydefault it sets to False comment palette used for coloring ca...
import numpy as np import seaborn as sns import matplotlib.pyplot as plt dataset = sns.load_dataset('tips') #violin plots are same as box plot and there is one more argument split which sets to True for combining the #hue else False, bydefault it sets to False #palette used for coloring sns.violinplot(x ='day', y = '...
Python
zaydzuhri_stack_edu_python
function best_first_graph_search problem f begin set f = call memoize f string f return call graph_search problem call PriorityQueue min f end function
def best_first_graph_search(problem, f): f = memoize(f, 'f') return graph_search(problem, PriorityQueue(min, f))
Python
nomic_cornstack_python_v1
function message self begin return _message end function
def message(self) -> str: return self._message
Python
nomic_cornstack_python_v1
function evaluate self truth_value=dict include_not=true begin set left = evaluate call get_left truth_value set right = evaluate call get_right truth_value if _operator == AND begin if call has_not begin return not left and right end return left and right end if _operator == OR begin if call has_not begin return not ...
def evaluate(self, truth_value = {}, include_not = True): left = self.get_left().evaluate(truth_value) right = self.get_right().evaluate(truth_value) if self._operator == LogicNode.AND: if self.has_not(): return not (left and right) return left and right...
Python
nomic_cornstack_python_v1
string 23. セクション構造 記事中に含まれるセクション名とそのレベル(例えば"== セクション名 =="なら1)を表示せよ. (root) kanekojunjunoMacBook-Pro:part3 kanekojunki$ python q23.py Section name: 国名 Section level 1 Section name: 歴史 Section level 1 Section name: 地理 Section level 1 Section name: 気候 Section level 2 Section name: 政治 Section level 1 ... 長いので省略 Section nam...
""" 23. セクション構造 記事中に含まれるセクション名とそのレベル(例えば"== セクション名 =="なら1)を表示せよ. (root) kanekojunjunoMacBook-Pro:part3 kanekojunki$ python q23.py Section name: 国名 Section level 1 Section name: 歴史 Section level 1 Section name: 地理 Section level 1 Section name: 気候 Section level 2 Section name: 政治 Section level 1 ... 長いので省略 Section...
Python
zaydzuhri_stack_edu_python
comment -*- coding: utf-8 -*- comment 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可 comment 返回能交换奖品的最大数量 comment @param a int整型 comment @param b int整型 comment @param c int整型 comment @return int整型 class Solution begin function numberofprize self a b c begin comment write code here set res = 0 set l = sorted list a b c while true...
# -*- coding: utf-8 -*- # # 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可 # 返回能交换奖品的最大数量 # @param a int整型 # @param b int整型 # @param c int整型 # @return int整型 # class Solution: def numberofprize(self, a, b, c): # write code here res = 0 l = sorted([a, b, c]) while True: d = min(l) ...
Python
zaydzuhri_stack_edu_python
function spherical_to_cartesian lons lats depths=none begin set phi = call radians lons set theta = call radians lats if depths is none begin set rr = EARTH_RADIUS end else begin set rr = EARTH_RADIUS - array depths end set cos_theta_r = rr * cos theta try begin set shape = shape end comment a list/tuple was passed exc...
def spherical_to_cartesian(lons, lats, depths=None): phi = numpy.radians(lons) theta = numpy.radians(lats) if depths is None: rr = EARTH_RADIUS else: rr = EARTH_RADIUS - numpy.array(depths) cos_theta_r = rr * numpy.cos(theta) try: shape = lons.shape except AttributeEr...
Python
nomic_cornstack_python_v1
import sys import pygame from ObjectsInSpace import * class Game begin function __init__ self screen begin comment screen size for convenience during initialization string at some point, the screen should be abstracted away from the Game class presently, we're doing the rendering and the handling of each "game" in the ...
import sys import pygame from ObjectsInSpace import * class Game: def __init__(self, screen: pygame.Surface): # screen size for convenience during initialization """at some point, the screen should be abstracted away from the Game class presently, we're doing the rendering and the handli...
Python
zaydzuhri_stack_edu_python
function _get_genes self genes begin if is instance genes str begin set up = call read_table genes header=none comment=string # dtype=str set ups = as type values str set ups = list squeeze np ups end else if is instance genes tuple list tuple begin set ups = genes end else begin raise exception string genes must be fi...
def _get_genes(self, genes: Union[str, List[str]]) -> List[str]: if isinstance(genes, str): up = pd.read_table(genes, header=None, comment="#", dtype=str) ups= up.values.astype(str) ups = list(np.squeeze(ups)) elif isinstance(genes, (list, tuple)): ups = g...
Python
nomic_cornstack_python_v1
function toJson self begin return dumps dict string type value ; string data dumps data end function
def toJson(self) -> str: return json.dumps({'type': self.type.value, 'data': json.dumps(self.data)})
Python
nomic_cornstack_python_v1
import MySQLdb import getExcelData function convert txt begin set txt = replace txt string ' string '' set txt = replace txt string \ string \\ return txt end function function csv_from_excel begin set fname = string ../External_Links_Report_Module_Breakdown_with_Summary_5_22_15.xlsx comment fname = '../test.xlsx' set ...
import MySQLdb import getExcelData def convert(txt): txt = txt.replace("'", "''") txt = txt.replace("\\", "\\\\") return txt def csv_from_excel(): fname = '../External_Links_Report_Module_Breakdown_with_Summary_5_22_15.xlsx' #fname = '../test.xlsx' rcDict = getExcelData.getFileData(fname) ...
Python
zaydzuhri_stack_edu_python
import pickle import os import matplotlib.pyplot as plt import numpy as np set avg_lowend_impr = dict 20 0.0 ; 40 0.0 ; 80 0.0 set avg_highend_impr = dict 20 0.0 ; 40 0.0 ; 80 0.0 set avg_online_impr = dict 20 0.0 ; 40 0.0 ; 80 0.0 set count = 0 for filename in list directory string results begin set count = count + 1 ...
import pickle import os import matplotlib.pyplot as plt import numpy as np avg_lowend_impr = {20 : 0.0, 40 : 0.0, 80 : 0.0} avg_highend_impr = {20 : 0.0, 40 : 0.0, 80 : 0.0} avg_online_impr = {20 : 0.0, 40 : 0.0, 80 : 0.0} count = 0 for filename in os.listdir('results'): count += 1 if count != 2: continue
Python
zaydzuhri_stack_edu_python
from __future__ import division , print_function import os , pickle import numpy as np import warnings from hmmlearn import hmm set BASE_PATH = directory name path directory name path absolute path path __file__ set MODEL_PATH = join path BASE_PATH string model/gmmhmm set WORD_DICT = list string 语音 string 余音 string 识别 ...
from __future__ import division,print_function import os,pickle import numpy as np import warnings from hmmlearn import hmm BASE_PATH = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) MODEL_PATH = os.path.join(BASE_PATH,'model/gmmhmm') WORD_DICT = [ '语音','余音','识别','失败','中国', '中国','忠告','北京','背景','商...
Python
zaydzuhri_stack_edu_python
function test_create_routing_slip session staff_user_mock begin set routing_slip_payload : Dict at tuple str any = dict string number string 206380834 ; string routingSlipDate string format time now DT_SHORT_FORMAT ; string paymentAccount dict string accountName string TEST ; string payments list dict string paymentMet...
def test_create_routing_slip(session, staff_user_mock): routing_slip_payload: Dict[str, any] = { 'number': '206380834', 'routingSlipDate': datetime.now().strftime(DT_SHORT_FORMAT), 'paymentAccount': { 'accountName': 'TEST' }, 'payments': [{ 'paymentMet...
Python
nomic_cornstack_python_v1
function dointerval self conf=0.683 begin set nd = norm call dopoint verbose=false set n = ymax / call pdf 0 / call pdf call interval conf at 0 / 2 set res = call fsolve func n args=conf xtol=xtol full_output=debug set interval = call minmax res at 0 comment print('interval:', interval[0], interval[1]) return tuple int...
def dointerval(self, conf=0.683): nd = norm() self.dopoint(verbose=False) n = self.ymax / (nd.pdf(0) / (nd.pdf(nd.interval(conf)[0]) / 2)) res = optimize.fsolve(self.func, n, args=(conf), xtol=self.xtol, full_output=self.debug) self.interval = self.minmax(res[0]) #print('...
Python
nomic_cornstack_python_v1
import sys set n = 10 set n = integer argv at 1 for i in range 1 n + 1 begin tuple print i end
import sys n = 10 n = int(sys.argv[1]) for i in range (1, n+1): print (i),
Python
zaydzuhri_stack_edu_python
function test_default_product_weight self begin set prod = product string Test Product assert equal weight 20 end function
def test_default_product_weight(self): prod = Product("Test Product") self.assertEqual(prod.weight, 20)
Python
nomic_cornstack_python_v1
comment Samantha Voigt comment Class that represents the different option frames available for the course browser app from Tkinter import * class ScrollableOptionFrame extends Frame begin function __init__ self master option allDistributions allSubjects allDepartments searchVars **options begin call __init__ self maste...
# Samantha Voigt # Class that represents the different option frames available for the course browser app from Tkinter import * class ScrollableOptionFrame(Frame): def __init__(self, master, option, allDistributions, allSubjects, allDepartments, searchVars, **options): Frame.__init__(self, master, **optio...
Python
zaydzuhri_stack_edu_python
function quantity self quantity begin set _quantity = quantity end function
def quantity(self, quantity): self._quantity = quantity
Python
nomic_cornstack_python_v1
comment !/usr/bin/env python comment Packages Used comment As taken from the [[https://github.com/miso-belica/sumy#python-api][Sumy api page.]] from __future__ import absolute_import from __future__ import division , print_function , unicode_literals from sumy.parsers.html import HtmlParser from sumy.parsers.plaintext ...
#!/usr/bin/env python # Packages Used # As taken from the [[https://github.com/miso-belica/sumy#python-api][Sumy api page.]] from __future__ import absolute_import from __future__ import division, print_function, unicode_literals from sumy.parsers.html import HtmlParser from sumy.parsers.plaintext import PlaintextP...
Python
zaydzuhri_stack_edu_python
function tags self begin return get pulumi self string tags end function
def tags(self) -> Optional[pulumi.Input[Mapping[str, Any]]]: return pulumi.get(self, "tags")
Python
nomic_cornstack_python_v1
function voc_eval self detpath annopath imagesetfile classname cachedir ovthresh=0.5 use_07_metric=false begin comment assumes detections are in detpath.format(classname) comment assumes annotations are in annopath.format(imagename) comment assumes imagesetfile is a text file with each line an image name comment cached...
def voc_eval(self, detpath, annopath, imagesetfile, classname, cachedir, ovthresh=0.5, use_07_metric=False): # assumes detections are in detpath.format(classname) # assumes annotations ...
Python
nomic_cornstack_python_v1
comment perform function on a value, regardless if its a variable or not. set my_variable = list 1 3 4 5 split my_variable string split string 2, 3 split string text count string text
# perform function on a value, regardless if its a variable or not. my_variable = [1, 3, 4, 5] my_variable.split("") "2, 3".split() "text".split() "text".count()
Python
zaydzuhri_stack_edu_python
function test_invalid_rule_not_stripped self begin set html = string <div class="pink">test</div> set css = string .pink { opacity: 0.8; } set expected = string <div class="pink" style="opacity: 0.8;">test</div> set result = call inline_css html css strip_unsupported_css=false pretty_print=false assert equal expected r...
def test_invalid_rule_not_stripped(self): html = '<div class="pink">test</div>' css = '.pink { opacity: 0.8; }' expected = '<div class="pink" style="opacity: 0.8;">test</div>' result = inline_css(html, css, strip_unsupported_css=False, pretty_print=False) self.assertEqual(expecte...
Python
nomic_cornstack_python_v1
from cybecube.database import engine from cybecube.database import Base from cybecube.database import session from sqlalchemy import Column , Integer , String class User extends Base begin set __tablename__ = string user set user_id = call Column Integer primary_key=true set name = call Column call String 250 nullable=...
from cybecube.database import engine from cybecube.database import Base from cybecube.database import session from sqlalchemy import Column, Integer, String class User(Base): __tablename__ = 'user' user_id = Column(Integer, primary_key=True) name = Column(String(250), nullable=False) def create_table_u...
Python
zaydzuhri_stack_edu_python
function create_dir directory begin if not exists path directory begin make directories directory end end function
def create_dir(directory): if not os.path.exists(directory): os.makedirs(directory)
Python
nomic_cornstack_python_v1
import csv import ntpath import random import numpy as np comment Utility Functions function shuffle_and_split_list_with_ratio input_list ratio begin string Shuffles and separates a list into two lists whose sizes are determined by the ratio input :param input_list: List that will be shuffled and split into two separat...
import csv import ntpath import random import numpy as np # Utility Functions def shuffle_and_split_list_with_ratio(input_list, ratio): """ Shuffles and separates a list into two lists whose sizes are determined by the ratio input :param input_list: List that will be shuffled and split into two separate l...
Python
zaydzuhri_stack_edu_python
function get_M F begin set M = dict for i in range length F begin if F at i not in keys M begin set M at F at i = i end end return M end function
def get_M(F): M = {} for i in range(len(F)): if F[i] not in M.keys(): M[F[i]] = i return M
Python
nomic_cornstack_python_v1
function test_reminder_time_not_required self begin set node = call create_xml_patient dict string Reminder_Time string set payload = call create_payload list node call parse_patient node payload assert equal count patients 1 set patient = all at 0 assert false reminder_time end function
def test_reminder_time_not_required(self): node = self.create_xml_patient({'Reminder_Time': ''}) payload = self.create_payload([node]) parse_patient(node, payload) self.assertEqual(payload.patients.count(), 1) patient = payload.patients.all()[0] self.assertFalse(patient.r...
Python
nomic_cornstack_python_v1
comment !/usr/bin/python2.7 set t = tuple 19 42 21 set msg = format string The 3 numbers are: {}, {}, {} 19 42 21 print msg
#!/usr/bin/python2.7 t = (19, 42, 21) msg = """ The 3 numbers are: {}, {}, {}""".format(19, 42, 21) print(msg)
Python
zaydzuhri_stack_edu_python
from functools import partial from operator import add set data = call textFile string /Project/web-Google.txt minPartitions=10 function parse_nodes line begin string Function to map over RDD lines. Finds the from and to ids. Parameters ---------- line: string CSV (space) delimited line from RDD. Returns ------- nodes:...
from functools import partial from operator import add data = sc.textFile("/Project/web-Google.txt", minPartitions=10) def parse_nodes(line): """Function to map over RDD lines. Finds the from and to ids. Parameters ---------- line: string CSV (space) delimited line from RDD....
Python
zaydzuhri_stack_edu_python
function __init__ self ch_in ch_out k pool_size norm_type freeze_norm=false name=string act=string leaky data_format=string NCHW begin call __init__ set pool = call ModuleList set data_format = data_format for tuple i size in enumerate pool_size begin call add_module format string {}_pool_{} name i call MaxPool2d kern...
def __init__(self, ch_in, ch_out, k, pool_size, norm_type, freeze_norm=False, name='', act='leaky', data_format='NCHW'): super(SPP, self).__init__() self.pool = nn.ModuleList() self.data_format = data_format for i, size in enumerate(pool_size): self.pool.add_module('{}_pool_{...
Python
nomic_cornstack_python_v1
function island_perimeter grid begin set land = 0 for c in range length grid begin for i in range length grid at c begin if grid at c at i == 1 begin if c - 1 < 0 begin set land = land + 1 end else if grid at c - 1 at i == 0 begin set land = land + 1 end if i - 1 < 0 begin set land = land + 1 end else if grid at c at i...
def island_perimeter(grid): land = 0 for c in range(len(grid)): for i in range(len(grid[c])): if grid[c][i] == 1: if c - 1 < 0: land += 1 elif grid[c - 1][i] == 0: land += 1 if i - 1 < 0: ...
Python
nomic_cornstack_python_v1
function get_iou bb1 bb2 begin assert bb1 at 0 < bb1 at 2 assert bb1 at 1 < bb1 at 3 assert bb2 at 0 < bb2 at 2 assert bb2 at 1 < bb2 at 3 comment Determine the coordinates of the intersection rectangle set x_left = max bb1 at 0 bb2 at 0 set y_top = max bb1 at 1 bb2 at 1 set x_right = min bb1 at 2 bb2 at 2 set y_bottom...
def get_iou(bb1, bb2): assert bb1[0] < bb1[2] assert bb1[1] < bb1[3] assert bb2[0] < bb2[2] assert bb2[1] < bb2[3] # Determine the coordinates of the intersection rectangle x_left = max(bb1[0], bb2[0]) y_top = max(bb1[1], bb2[1]) x_right = min(bb1[2], bb2[2]) y_bottom =...
Python
nomic_cornstack_python_v1
import cv2 import numpy as np import face_recognition import os from datetime import datetime set folder = string images set images = list set imagesNames = list set imgList = list directory folder print imgList for each in imgList begin set oneImg = call imread string { folder } / { each } append images oneImg appen...
import cv2 import numpy as np import face_recognition import os from datetime import datetime folder = "images" images = [] imagesNames = [] imgList = os.listdir(folder) print(imgList) for each in imgList: oneImg = cv2.imread(f'{folder}/{each}') images.append(oneImg) imagesNames.append(os.path.splitext(ea...
Python
zaydzuhri_stack_edu_python
import random comment DecisionFactory communicates with the framework class DecisionFactory begin function __init__ self name=string Davros begin set name = name set directions = list string wait string up string down string right string left set last_result = string success set last_direction = string wait set past_di...
import random #DecisionFactory communicates with the framework class DecisionFactory: def __init__(self , name='Davros' ): self.name = name self.directions = [ 'wait', 'up', 'down', 'right', 'left' ] self.last_result = 'success' self.last_direction = 'wait' self.past_directions = ['wait'] self.num_moves =...
Python
zaydzuhri_stack_edu_python
function isolate_titles targets predictions begin set all_target_titles = list set all_prediction_titles = list for tuple tar pred in zip targets predictions begin set target_titles = find all string \@([^@]*\([^@]*\)[^@]*)\@ tar set prediction_titles = find all string \@([^@]*\([^@]*\)[^@]*)\@ pred append all_target...
def isolate_titles(targets, predictions): all_target_titles = [] all_prediction_titles = [] for tar, pred in zip(targets, predictions): target_titles = re.findall(r"\@([^@]*\([^@]*\)[^@]*)\@", tar) prediction_titles = re.findall(r"\@([^@]*\([^@]*\)[^@]*)\@", pred) all_target_titles.append([x.strip() f...
Python
nomic_cornstack_python_v1
function make_response event_list begin set appointments = list for event in event_list begin set description = string if string description in event begin set description = event at string description end set appointment = dict string id event at string id ; string link event at string htmlLink ; string title event ...
def make_response(event_list): appointments = [] for event in event_list: description = '' if 'description' in event: description = event['description'] appointment = { 'id': event['id'], 'link': event['htmlLink'], 'title': event['summary']...
Python
zaydzuhri_stack_edu_python
function specific_place_comment begin set user_id = get session string user_id set user = get query user_id set comment = form at string comment set place_id = form at string place_id set created_date = now set rating = form at string rating set new_comment = call Place_comment user_id=user_id place_id=place_id comment...
def specific_place_comment(): user_id = session.get("user_id") user = User.query.get(user_id) comment = request.form["comment"] place_id = request.form["place_id"] created_date = datetime.now() rating = request.form["rating"] new_comment = Place_comment(user_id=user_id, place_id=place...
Python
nomic_cornstack_python_v1
comment -*- coding: utf-8 -*- for i in range 0 3 begin print i end
# -*- coding: utf-8 -*- for i in range(0, 3): print(i)
Python
zaydzuhri_stack_edu_python
function list begin string List blink(1) devices connected, by serial number :return: List of blink(1) device serial numbers try begin set devs = enumerate VENDOR_ID PRODUCT_ID set serials = list map lambda d -> get d string serial_number devs return serials end except IOError as e begin return list end end function
def list(): """ List blink(1) devices connected, by serial number :return: List of blink(1) device serial numbers """ try: devs = hid.enumerate(VENDOR_ID,PRODUCT_ID) serials = list(map(lambda d:d.get('serial_number'), devs)) return serials ...
Python
jtatman_500k
class Test begin set num = 0 function __init__ self begin set num = num + 1 end function end class set a = call Test set b = call Test set c = call Test print num
class Test: num = 0 def __init__(self): Test.num += 1 a = Test() b = Test() c = Test() print(Test.num)
Python
zaydzuhri_stack_edu_python
comment !/bin/env python3 function recursive arr begin set size = length arr if 0 == size begin return 0 end else if 1 == size begin return arr at 0 end else begin return arr at 0 + call recursive arr at slice 1 : size : end end function if __name__ == string __main__ begin set arrList = list 1 2 3 4 print string %s's ...
#!/bin/env python3 def recursive(arr): size = len(arr) if 0 == size: return 0 elif 1 == size: return arr[0] else: return arr[0]+recursive(arr[1:size]) if __name__ == "__main__": arrList = [1,2,3,4] print("%s's sum :%s" % (arrList, recursive(arrList)))
Python
zaydzuhri_stack_edu_python
comment -*- coding: utf-8 -*- string Created on Sun Jan 6 03:08:49 2019 @author: ratin import dash import dash_core_components as dcc import dash_html_components as html from dash.dependencies import Input , Output import plotly.graph_objs as go import pandas as pd from subprocess import check_output from sklearn.prepr...
# -*- coding: utf-8 -*- """ Created on Sun Jan 6 03:08:49 2019 @author: ratin """ import dash import dash_core_components as dcc import dash_html_components as html from dash.dependencies import Input, Output import plotly.graph_objs as go import pandas as pd from subprocess import check_output from sk...
Python
zaydzuhri_stack_edu_python
function factorielle n begin if n == 0 begin return 1 end else begin return n * call factorielle n - 1 end end function function puissance x n begin set S = 1 for i in range 0 n begin set S = S * x end return S end function function calculateSum x n begin set S = 0 for i in range 0 n begin set N = 2 * i + 1 set S = S +...
def factorielle(n): if (n == 0): return 1 else: return n * factorielle(n - 1) def puissance(x, n): S = 1 for i in range(0, n): S *= x return S def calculateSum(x, n): S = 0 for i in range(0, n): N = 2*i + 1 S += puissance(x, N) / factorielle(N) ...
Python
zaydzuhri_stack_edu_python
comment import calendar comment year = int(input("Type in the year number: ")) comment calendar.prcal(year) comment above can also be rewritten as: from calendar import prcal set year = integer input string Type in the year number: call prcal year
# import calendar # # year = int(input("Type in the year number: ")) # calendar.prcal(year) # above can also be rewritten as: from calendar import prcal year = int(input("Type in the year number: ")) prcal(year)
Python
zaydzuhri_stack_edu_python
function get_with_boundaries self name boundaries begin string Get a color table from the registry with a corresponding norm. Builds a `matplotlib.colors.BoundaryNorm` using `boundaries`. Parameters ---------- name : str The name under which the color table will be stored boundaries : array_like The list of boundaries ...
def get_with_boundaries(self, name, boundaries): r"""Get a color table from the registry with a corresponding norm. Builds a `matplotlib.colors.BoundaryNorm` using `boundaries`. Parameters ---------- name : str The name under which the color table will be stored ...
Python
jtatman_500k
comment ! /usr/bin/env python from datetime import datetime import re import sys set log_mask = compile string ^(\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}) \+\d{4}, (?:([^:]+):\d+), ([a-z]+) ([^ ]+) ([0-9]+)( .*)?$ function parse_file fname begin with open fname as infile begin for line in infile begin set match = match line...
#! /usr/bin/env python from datetime import datetime import re import sys log_mask = re.compile( r"^(\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}) \+\d{4}, (?:([^:]+):\d+), ([a-z]+) ([^ ]+) ([0-9]+)( .*)?$" ) def parse_file(fname): with open(fname) as infile: for line in infile: match = log_mask.ma...
Python
zaydzuhri_stack_edu_python
function adjust_ratio cat1 cat2 sm_sentlen pos_unigrs begin set cat1_count = get pos_unigrs cat1 0.0 set cat2_count = get pos_unigrs cat2 0.0 if cat1_count == 0.0 or cat2_count == 0.0 begin return 0.0 end else begin return call smooth cat1_count sm_sentlen / call smooth cat2_count sm_sentlen end end function
def adjust_ratio(cat1,cat2, sm_sentlen, pos_unigrs): cat1_count = pos_unigrs.get(cat1, 0.0) cat2_count = pos_unigrs.get(cat2, 0.0) if cat1_count == 0.0 or cat2_count == 0.0: return 0.0 else: return smooth(cat1_count, sm_sentlen) / smooth(cat2_count, sm_sentlen)
Python
nomic_cornstack_python_v1
comment !/usr/bin/env python comment coding: utf-8 comment # Data Preparation comment ## Why do this step? comment - The data we scraped from the UFC website is raw data. Every row contains information about a fight that took place i.e. details like how many strikes were thrown in that fight and who won the fight. comm...
#!/usr/bin/env python # coding: utf-8 # # Data Preparation # ## Why do this step? # # - The data we scraped from the UFC website is raw data. Every row contains information about a fight that took place i.e. details like how many strikes were thrown in that fight and who won the fight. # - To prepare the data for pr...
Python
zaydzuhri_stack_edu_python
function sensor_class self begin return _zone_type end function
def sensor_class(self): return self._zone_type
Python
nomic_cornstack_python_v1
import pandas as pd from pandas import concat import numpy as np import time import sys import os from datetime import date import calendar set t0 = time import psycopg2 import psycopg2.extras from dateutil import parser import csv from unidecode import unidecode import configparser set ini_file = string argv at 1 set ...
import pandas as pd from pandas import concat import numpy as np import time import sys import os from datetime import date import calendar t0 = time.time() import psycopg2 import psycopg2.extras from dateutil import parser import csv from unidecode import unidecode import configparser ini_file = str...
Python
zaydzuhri_stack_edu_python
comment tagging from lxml.html import parse import sys function traverse root begin if root is none begin return end else begin set attr_id = string attrib at string id end end function
#tagging from lxml.html import parse import sys def traverse(root): if root is None: return else: attr_id = str(root.attrib['id'])
Python
zaydzuhri_stack_edu_python
function choose multichoice question correct begin set counter = 1 set ncorrect = 0 set allowed = string 12345 print string choose a synonym for + question for option in values multichoice begin print string counter + string ) + option if option == correct begin set ncorrect = counter end set counter = counter + 1 end ...
def choose(multichoice, question, correct): counter = 1 ncorrect = 0 allowed = '12345' print("choose a synonym for "+question) for option in multichoice.values(): print(str(counter)+")"+option) if option == correct: ncorrect = counter counter = counter + 1 res...
Python
nomic_cornstack_python_v1
import logging from keyboard import main_keyboard comment Функция greet_user будет вызаваться, когда пользователь напишет /start или подключится к боту в первый раз comment Параметря принято называть bot & update (должно быть как минимум 2 параметра) function greet_user bot update begin comment text = '''Hello, you can...
import logging from keyboard import main_keyboard # Функция greet_user будет вызаваться, когда пользователь напишет /start или подключится к боту в первый раз #Параметря принято называть bot & update (должно быть как минимум 2 параметра) def greet_user(bot, update): #text = '''Hello, you can rule some command and ...
Python
zaydzuhri_stack_edu_python
function update_cid_groups self body begin comment [PATCH] https://assets.falcon.crowdstrike.com/support/api/swagger.html#/mssp/updateCIDGroups return call process_service_request calling_object=self endpoints=Endpoints operation_id=string updateCIDGroups body=body end function
def update_cid_groups(self: object, body: dict) -> dict: # [PATCH] https://assets.falcon.crowdstrike.com/support/api/swagger.html#/mssp/updateCIDGroups return process_service_request( calling_object=self, endpoints=Endpoints, operation_id="updateCIDGroups", ...
Python
nomic_cornstack_python_v1
function relabel_based_on_majority_labels predicted_labels ground_truth transform=true begin set unique_predicted_labels = unique predicted_labels set bool_array_list = list set most_frequent_label_list = list for cluster_id in unique_predicted_labels begin append bool_array_list predicted_labels == cluster_id end fo...
def relabel_based_on_majority_labels(predicted_labels,ground_truth, transform=True): unique_predicted_labels = np.unique(predicted_labels) bool_array_list = [] most_frequent_label_list = [] for cluster_id in unique_predicted_labels: bool_array_list.append(predicted_labels == cluster_id) for bool_array ...
Python
nomic_cornstack_python_v1
comment https://atcoder.jp/contests/dp/tasks/dp_c set N = integer input set dp = list 0 * 3 for i in range N begin set tuple a b c = map int split input set x = max dp at 1 + a dp at 2 + a set y = max dp at 2 + b dp at 0 + b set z = max dp at 0 + c dp at 1 + c set dp = list x y z end print max dp
# https://atcoder.jp/contests/dp/tasks/dp_c N = int(input()) dp = [0] * 3 for i in range(N): a, b, c = map(int, input().split()) x = max(dp[1] + a, dp[2] + a) y = max(dp[2] + b, dp[0] + b) z = max(dp[0] + c, dp[1] + c) dp = [x, y, z] print(max(dp))
Python
zaydzuhri_stack_edu_python
function initialize_target trans_id sid did scid func_id begin comment Create asynchronous connection using random connection id. set conn_id = string random integer 1 9999999 try begin set manager = call connection_manager sid set conn = call connection did=did conn_id=conn_id end except Exception as e begin return ca...
def initialize_target(trans_id, sid, did, scid, func_id): # Create asynchronous connection using random connection id. conn_id = str(random.randint(1, 9999999)) try: manager = get_driver(PG_DEFAULT_DRIVER).connection_manager(sid) conn = manager.connection(did=did, conn...
Python
nomic_cornstack_python_v1
function REDS mode begin comment configurations comment whether real all images to memory with multiprocessing set read_all_imgs = false comment Set False for use limited memory comment After BATCH images, lmdb commits, if read_all_imgs = False set BATCH = 5000 if mode == string train_sharp begin set img_folder = strin...
def REDS(mode): #### configurations read_all_imgs = False # whether real all images to memory with multiprocessing # Set False for use limited memory BATCH = 5000 # After BATCH images, lmdb commits, if read_all_imgs = False if mode == 'train_sharp': img_folder = '../../datasets/REDS/train_...
Python
nomic_cornstack_python_v1
from user_creator.abstract_factory import AbstractUserFactory import requests import twitter from utils.config import TwitterConfig as Config class TwitterUserFactory extends AbstractUserFactory begin function __init__ self begin call __init__ set authenticate_info = dict set consumer_key = consumer_key set consumer_s...
from user_creator.abstract_factory import AbstractUserFactory import requests import twitter from utils.config import TwitterConfig as Config class TwitterUserFactory(AbstractUserFactory): def __init__(self): super().__init__() self.authenticate_info = {} self.consumer_key = Config.consumer...
Python
zaydzuhri_stack_edu_python
string Method - DP dp[i][j]: the largest square in [0][0] --> [i][j] Steps: 1. build a dp table, the size of table is len(matrix) * len(matrix[0]) 2. scan dp table from left to right and up to down dp[i][j] = min(dp[i-1][j],dp[i−1][j−1],dp[i][j−1])+1, matrix[i][j] == '1' base case: dp[i][0] = 1, matrix[i][0] == '1' dp[...
''' Method - DP dp[i][j]: the largest square in [0][0] --> [i][j] Steps: 1. build a dp table, the size of table is len(matrix) * len(matrix[0]) 2. scan dp table from left to right and up to down dp[i][j] = min(dp[i-1][j],dp[i−1][j−1],dp[i][j−1])+1, matrix[i][j] == '1' base case: ...
Python
zaydzuhri_stack_edu_python
comment !/usr/bin/env python comment Object representation of an image - from the data provided in the files class Image begin function __init__ self line_str begin set temp_arr = split line_str comment Integer ID set id = temp_arr at 0 comment Integer orientation set temp_arr = list comprehension integer i for i in te...
#!/usr/bin/env python #Object representation of an image - from the data provided in the files class Image: def __init__(self, line_str): temp_arr = line_str.split() self.id = temp_arr[0] # Integer ID temp_arr = [int(i) for i in temp_arr[1:]] # Integer orientation self.orientation =...
Python
zaydzuhri_stack_edu_python
comment ! /usr/bin/env python function big_child_or_year str_arg begin call right_child str_arg print string few_time end function function right_child str_arg begin print str_arg end function if __name__ == string __main__ begin call big_child_or_year string leave_hand end
#! /usr/bin/env python def big_child_or_year(str_arg): right_child(str_arg) print('few_time') def right_child(str_arg): print(str_arg) if __name__ == '__main__': big_child_or_year('leave_hand')
Python
zaydzuhri_stack_edu_python
function setup self begin pass end function
def setup(self): pass
Python
nomic_cornstack_python_v1
string Input: a stringified object as follows { 'vocabulary': [str] , 'sizeOfCorpus': int , 'sizeOfBatch': int, 'numberOfTopics': int, 'iteration': int, 'lambda': [[float]] 'articles': [str] } Outputs: a stringified object as follows { 'gamma': [float], 'lambda': [float] } Error: If there is an error it will return typ...
''' Input: a stringified object as follows { 'vocabulary': [str] , 'sizeOfCorpus': int , 'sizeOfBatch': int, 'numberOfTopics': int, 'iteration': int, 'lambda': [[float]] 'articles': [str] } Outputs: a stringified...
Python
zaydzuhri_stack_edu_python
from lxml import etree from sys import stdout , stdin import os function print_TRIAS FileTRIAS begin comment used namespaces print string File = FileTRIAS set NS3 = dict string ns3 string http://www.vdv.de/trias ; string coactive string http://shift2rail.org/project/coactive set parser = call XMLParser remove_blank_tex...
from lxml import etree from sys import stdout, stdin import os def print_TRIAS(FileTRIAS): # used namespaces print("File = ", FileTRIAS) NS3 = {'ns3': "http://www.vdv.de/trias", 'coactive': 'http://shift2rail.org/project/coactive'} parser = etree.XMLParser(remove_blank_text=True, recover=Tru...
Python
zaydzuhri_stack_edu_python
function app request begin global fixture if fixture is none begin set fixture = call WebApplication end return fixture end function
def app(request) -> Application: global fixture if fixture is None: fixture = WebApplication() return fixture
Python
nomic_cornstack_python_v1
function aux_split data begin comment idx = np.bool_(np.zeros(len(data['track_id']))) comment for track in np.unique(data['track_id']): comment idx |= data['segment_id']==(data['segment_id'][data['track_id'] == track][:3]) set idx = call bool_ zeros length data at string track_id for track in unique data at string trac...
def aux_split(data): # idx = np.bool_(np.zeros(len(data['track_id']))) # for track in np.unique(data['track_id']): # idx |= data['segment_id']==(data['segment_id'][data['track_id'] == track][:3]) idx = np.bool_(np.zeros(len(data['track_id']))) for track in np.unique(data['track_id']): seg_lst = (data['segment...
Python
nomic_cornstack_python_v1
import threading import socket import json import AWSIoTPythonSDK.MQTTLib as AWSIoTPyMQTT set HOST = string 0.0.0.0 comment [DONE] 166XX, XX is your tool box number set PORT = 16631 set s = call socket AF_INET SOCK_STREAM call setsockopt SOL_SOCKET SO_REUSEADDR 1 call bind tuple HOST PORT call listen 5 set tSocket = li...
import threading import socket import json import AWSIoTPythonSDK.MQTTLib as AWSIoTPyMQTT HOST = '0.0.0.0' # [DONE] 166XX, XX is your tool box number PORT = 16631 s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) s.bind((HOST, PORT)) s.listen(5) tSocket=[] ...
Python
zaydzuhri_stack_edu_python
function convert_df_to_data_format df data_format begin if data_format in list EMPTY PANDAS_DATAFRAME SNOWPARK_OBJECT PYSPARK_OBJECT PANDAS_INDEX PANDAS_STYLER begin return df end else if data_format == NUMPY_LIST begin comment It's a 1-dimensional array, so we only return comment the first column as numpy array commen...
def convert_df_to_data_format( df: DataFrame, data_format: DataFormat ) -> Union[ DataFrame, Series[Any], pa.Table, np.ndarray[Any, np.dtype[Any]], Tuple[Any], List[Any], Set[Any], Dict[str, Any], ]: if data_format in [ DataFormat.EMPTY, DataFormat.PANDAS_DATAFRAM...
Python
nomic_cornstack_python_v1
function ht_bib_full console cache_path=none output_path=none merge_version=none force=false begin set debug_start_time = now debug format string Started: {} debug_start_time comment LOAD: environment, configuration set default_root_dir = join path directory name path __file__ string .. set APP = call AppEnv name=strin...
def ht_bib_full( console, cache_path=None, output_path=None, merge_version=None, force=False ): debug_start_time = datetime.datetime.now() console.debug("Started: {}".format(debug_start_time)) # LOAD: environment, configuration default_root_dir = os.path.join(os.path.dirname(__file__), "..") A...
Python
nomic_cornstack_python_v1
comment ============================================================================ comment Pessoa comment ============================================================================ string @apiDefine ObjetoPessoa @apiParam {String} nome Nome da pessoa @apiParam {String} email Email da pessoa @apiParam {String} [tele...
# ============================================================================ # Pessoa # ============================================================================ """ @apiDefine ObjetoPessoa @apiParam {String} nome Nome da pessoa @apiParam {String} email Email da pessoa @apiParam {String} [telefone] Telefone da p...
Python
zaydzuhri_stack_edu_python
import os import csv comment Path to collect data from the folder set pybank = join path string budget_data.csv comment Read in the CSV file with open pybank string r newline=string as csvfile begin set csvreader = reader csvfile delimiter=string , comment This skips the first row of the CSV file. next csvreader none s...
import os import csv # Path to collect data from the folder pybank = os.path.join('budget_data.csv') # Read in the CSV file with open(pybank, 'r', newline = '') as csvfile: csvreader = csv.reader(csvfile, delimiter=',') #This skips the first row of the CSV file. next(csvreader, None) ...
Python
zaydzuhri_stack_edu_python
from moeda import * print string Se quiser o número formatado para valor monetário coloque o parâmetro "formatação = True" set n = decimal input string Digite um número: print call aumenta n formatação=false
from moeda import * print('Se quiser o número formatado para valor monetário coloque o parâmetro "formatação = True"' ) n = float(input('Digite um número: ')) print(aumenta(n,formatação=False))
Python
zaydzuhri_stack_edu_python
function test_n_steps_interval_3 self begin set n = 3 set scheduler = call n_step_scheduler step_interval=n assert true call scheduler none assert false call scheduler none assert false call scheduler none assert true call scheduler none assert false call scheduler none assert false call scheduler none end function
def test_n_steps_interval_3(self): n = 3 scheduler = schedulers.n_step_scheduler(step_interval=n) self.assertTrue(scheduler(None)) self.assertFalse(scheduler(None)) self.assertFalse(scheduler(None)) self.assertTrue(scheduler(None)) self.assertFalse(scheduler(None)) self.assertFalse(sched...
Python
nomic_cornstack_python_v1
function output_processing_status outfile status begin write outfile join string list call get_subject_id call get_resource_name string call get_resource_present string call get_data_present write outfile string end function
def output_processing_status(outfile, status): outfile.write('\t'.join([status.get_subject_id(), status.get_resource_name(), str(status.get_resource_present()), str(status.get_data_present())])) outfile.write('\n')
Python
nomic_cornstack_python_v1
function inline_keyboards_list request bot_id begin if method == string GET begin set keyboards = all set serializer = call InlineKeyboardSerializer keyboards many=true comment print(serializer) comment print(serializer.data) return call JsonResponse data safe=false end else if method == string POST begin set serialize...
def inline_keyboards_list(request, bot_id): if request.method == 'GET': keyboards = InlineKeyboard.objects.filter(bot_id=bot_id).all() serializer = InlineKeyboardSerializer(keyboards, many=True) # print(serializer) # print(serializer.data) return JsonResponse(serializer.data,...
Python
nomic_cornstack_python_v1
from pathlib import Path import pandas as pd from PIL import Image import get_frame import numpy as np class FaceMatcher begin string Class to match ground truth images. The image file are stored in gt_images/images/ The image metadata are stored in gt_images/gt_info.csv function __init__ self begin set gt_root = paren...
from pathlib import Path import pandas as pd from PIL import Image import get_frame import numpy as np class FaceMatcher: """ Class to match ground truth images. The image file are stored in gt_images/images/ The image metadata are stored in gt_images/gt_info.csv """ def __init__(self): ...
Python
zaydzuhri_stack_edu_python
set numbers = list comprehension integer i for i in split input string , set indexed = list comprehension index for tuple index value in enumerate numbers if value % 2 == 0 print indexed
numbers = [int(i) for i in input().split(', ')] indexed = [index for index,value in enumerate(numbers) if value % 2 == 0] print(indexed)
Python
zaydzuhri_stack_edu_python
from typing import List from abc import ABCMeta , abstractmethod from twisted.internet.defer import Deferred class DiagramImportApiABC begin decorator abstractmethod function importDisps self modelSetKey coordSetKey importGroupHash dispsEncodedPayload begin string Import Disps Add or replace display items in a model :p...
from typing import List from abc import ABCMeta, abstractmethod from twisted.internet.defer import Deferred class DiagramImportApiABC(metaclass=ABCMeta): @abstractmethod def importDisps(self, modelSetKey: str, coordSetKey: str, importGroupHash: str, dispsEncodedPayload: bytes) -> Deferred...
Python
zaydzuhri_stack_edu_python
function CFN_RESOURCE_TYPE_NAME cls begin return call sget cls string CFN_RESOURCE_TYPE_NAME end function
def CFN_RESOURCE_TYPE_NAME(cls) -> str: return jsii.sget(cls, "CFN_RESOURCE_TYPE_NAME")
Python
nomic_cornstack_python_v1
function step_infer self action begin set old_bb = copy bb set a_x = integer action_threshold * bb at 3 set a_y = integer action_threshold * bb at 2 if action == 0 begin comment Horizontal - left set bb at 1 = bb at 1 - a_x if bb at 1 < 0 begin set bb at 1 = 0 end end else if action == 1 begin comment Horizontal - righ...
def step_infer(self, action): old_bb = self.bb.copy() a_x = int(self.action_threshold * self.bb[3]) a_y = int(self.action_threshold * self.bb[2]) if(action == 0): #Horizontal - left self.bb[1] -= a_x if(self.bb[1] < 0): self.bb[1] = 0 ...
Python
nomic_cornstack_python_v1
string 2721 : 순환 문자열 영어 소문자로 구성된 단어 S1, S2, S3가 있을때, S1의 마지막 문자가 S2의 첫 글자와 같고, S2의 마지막 글자가 S3의 첫 글자와 같고, S3의 마지막 글자가 S1의 첫 글자와 같으면 순환 문자열이라고 한다. 예를 들어 turtle error robot 인 경우 순환 문자열이다. 세 단어가 주어졌을 때 순환 문자열이면 good을 출력, 아니면 bad를 출력하시오. set S1 = input set S2 = input set S3 = input if S1 at - 1 == S2 at 0 and S2 at - 1 == S...
''' 2721 : 순환 문자열 영어 소문자로 구성된 단어 S1, S2, S3가 있을때, S1의 마지막 문자가 S2의 첫 글자와 같고, S2의 마지막 글자가 S3의 첫 글자와 같고, S3의 마지막 글자가 S1의 첫 글자와 같으면 순환 문자열이라고 한다. 예를 들어 turtle error robot 인 경우 순환 문자열이다. 세 단어가 주어졌을 때 순환 문자열이면 good을 출력, 아니면 bad를 출력하시오. ''' S1 = input() S2 = input() S3 = input() if(S1[-1]==S2[0] and S2[-1]==S3[0] and S3[-1]...
Python
zaydzuhri_stack_edu_python
comment real signature unknown function __new__ *args **kwargs begin pass end function
def __new__(*args, **kwargs): # real signature unknown pass
Python
nomic_cornstack_python_v1
function autonomous self begin call putString string mode string auto call putBoolean string is_ds_attached call isDSAttached call _on_mode_enable_components run control_loop_wait_time _execute_components onException call _on_mode_disable_components end function
def autonomous(self): self.__nt.putString('mode', 'auto') self.__nt.putBoolean('is_ds_attached', self.ds.isDSAttached()) self._on_mode_enable_components() self._automodes.run(self.control_loop_wait_time, self._execute_components, ...
Python
nomic_cornstack_python_v1
import pandas as pd import numpy as np string df['scrore']=df['instance_id'].map(lambda x:random.uniform(0,0.3)) function set_value s begin comment RandomState生成随机数种子 set random = call RandomState 0 comment 随机数范围 set a = uniform 0 0.31 set x = round a 9 return x end function function load_csv begin comment RandomState生...
import pandas as pd import numpy as np """ df['scrore']=df['instance_id'].map(lambda x:random.uniform(0,0.3)) """ def set_value(s): random = np.random.RandomState(0) # RandomState生成随机数种子 a = random.uniform(0, 0.31) # 随机数范围 x = round(a,9) return x def load_csv(): random = np.random.RandomSta...
Python
zaydzuhri_stack_edu_python