code
stringlengths
10
2.58M
original_code
stringlengths
3
3.18M
original_language
stringclasses
1 value
source
stringclasses
7 values
set a = integer input string Quantidade inicial de copias do virus no sangue de Micaleteia: set b = integer input string Quantidade inicial de leucocitos no sangue: set c = decimal input string Percentual de multiplicacao diaria do virus: set d = decimal input string Percentual de multiplicacao diaria dos leucocitos: s...
a = int(input("Quantidade inicial de copias do virus no sangue de Micaleteia: ")) b = int(input("Quantidade inicial de leucocitos no sangue: ")) c = float(input("Percentual de multiplicacao diaria do virus: ")) d = float(input("Percentual de multiplicacao diaria dos leucocitos: ")) k = 0 while(b<2*a): cpa= (a*c)/100 ...
Python
zaydzuhri_stack_edu_python
function edit_page self *args **kwargs begin return call edit *args keyword kwargs end function
def edit_page(self, *args, **kwargs): return self.edit(*args, **kwargs)
Python
nomic_cornstack_python_v1
comment 160. Intersection of Two Linked Lists comment Definition for singly-linked list. comment class ListNode: comment def __init__(self, x): comment self.val = x comment self.next = None class Solution begin function getIntersectionNode self headA headB begin if not headA or not headB begin return none end set tuple...
# 160. Intersection of Two Linked Lists # Definition for singly-linked list. # class ListNode: # def __init__(self, x): # self.val = x # self.next = None class Solution: def getIntersectionNode(self, headA: ListNode, headB: ListNode) -> ListNode: if not headA or not headB: r...
Python
zaydzuhri_stack_edu_python
class Solution begin function maxArea self height begin function container start end start_h end_h begin set waterQty = end - start * min start_h end_h return waterQty end function set lst = list for i in range length height - 1 begin for j in range i + 1 length height begin append lst call container i j height at i h...
class Solution: def maxArea(self, height: List[int]) -> int: def container(start, end, start_h, end_h): waterQty = (end-start) * min(start_h,end_h) return waterQty lst = [] for i in range (len(height)-1): for j in range (i+1,len(height)): ...
Python
zaydzuhri_stack_edu_python
function display self path begin set full_path = call media_path_full db path call open_file_with_default_application full_path end function
def display(self, path): full_path = media_path_full(self.db, path) open_file_with_default_application(full_path)
Python
nomic_cornstack_python_v1
function show_some a is_failure condition MAX_N=4 begin set tuple some = call nonzero flat set num = size set num_fail = length some set perc = 100.0 * num_fail / num set error = string In this array, %d/%d (%f%%) of elements do not respect the condition %s. % tuple num_fail num perc condition set N = min length some M...
def show_some(a, is_failure, condition, MAX_N=4): some, = np.nonzero(is_failure.flat) num = a.size num_fail = len(some) perc = 100.0 * num_fail / num error = ("In this array, %d/%d (%f%%) of elements do not respect " "the condition %s." % (num_fail, num, perc, condition)) N = min(l...
Python
nomic_cornstack_python_v1
try begin set f = open string C:/TEST1/readme.txt string r write f string 12 end except IOError begin print string Error:cant find end finally begin print string this is game end
try: f = open("C:/TEST1/readme.txt",'r') f.write("12") except IOError: print ("Error:cant find") finally: print("this is game")
Python
zaydzuhri_stack_edu_python
comment -*- coding: utf-8 -*- from TreeNode import TreeNode from board.BoardExtend import BoardExtend from log.logger import logger class GameTree extends object begin function __init__ self begin set __root = none end function function compute self node level begin if level == 0 begin return end set board = call getBo...
# -*- coding: utf-8 -*- from TreeNode import TreeNode from board.BoardExtend import BoardExtend from log.logger import logger class GameTree(object): def __init__(self): self.__root = None def compute(self, node, level): if level == 0: return board = node.getBoard() ...
Python
zaydzuhri_stack_edu_python
function make_labels_dict begin set result = dictionary dict _LABEL_TFX_VERSION __version__ ; _LABEL_TFX_PY_VERSION string %d.%d % tuple major minor keyword get attribute _thread_local_labels_state string dictionary dict comment Only first-party tfx component's executor telemetry will be collected. comment All other ex...
def make_labels_dict() -> Dict[str, str]: result = dict( { _LABEL_TFX_VERSION: version.__version__, _LABEL_TFX_PY_VERSION: '%d.%d' % (sys.version_info.major, sys.version_info.minor), }, **getattr(_thread_local_labels_state, 'dictionary', {})) # Only first...
Python
nomic_cornstack_python_v1
function footprints self withCutoff=- 20 merge=1 begin set ranges = list set tuple tempMLE templogProb = tuple copy np lengths copy np scores while min < withCutoff begin set minimapos = argument minimum set minimafplen = tempMLE at minimapos set minimaphalffplen = minimafplen // 2 set lbound = max minimapos - minimap...
def footprints(self, withCutoff = -20, merge = 1): ranges = [] tempMLE, templogProb = np.copy(self.lengths), np.copy(self.scores) while templogProb.min() < withCutoff: minimapos = templogProb.argmin() minimafplen = tempMLE[minimapos] minimaphalffplen = mini...
Python
nomic_cornstack_python_v1
import os import string import random from score_text import get_words function initialize_secrets begin set secrets = list set characterSet = set set characterFrequency = dict set otherSet = set comment Get all secret files into list. for file in list directory string src/secrets begin with open string src/secrets/ +...
import os import string import random from score_text import get_words def initialize_secrets(): secrets = list() characterSet = set() characterFrequency = {} otherSet = set() # Get all secret files into list. for file in os.listdir('src/secrets'): with open('src/secrets/'+file) as secr...
Python
zaydzuhri_stack_edu_python
from decimal import Decimal from django.db import models from django.utils.translation import gettext_lazy as _ from django.core.validators import MinValueValidator class Product extends Model begin set name = call CharField max_length=255 set code = call CharField max_length=255 set description = call TextField set pr...
from decimal import Decimal from django.db import models from django.utils.translation import gettext_lazy as _ from django.core.validators import MinValueValidator class Product(models.Model): name = models.CharField(max_length=255) code = models.CharField(max_length=255) description = models.TextField()...
Python
zaydzuhri_stack_edu_python
function hashfile_chunk filename chunk_size=262144 begin set offset = 0 with open filename string rb as f begin set data = true while data begin set data = read f chunk_size set offset = offset + chunk_size set digest = sha256 update digest data if data begin yield tuple digest data offset end end end end function
def hashfile_chunk(filename, chunk_size=262144): offset = 0 with open(filename, 'rb') as f: data = True while data: data = f.read(chunk_size) offset += chunk_size digest = sha256() digest.update(data) if data: yield dige...
Python
nomic_cornstack_python_v1
import pandas as pd import numpy as np import pandas as pd import matplotlib import matplotlib.pyplot as plt from IPython import get_ipython from pandas.core import datetools from sklearn.model_selection import train_test_split from sklearn.linear_model import LinearRegression set df = set index read csv string SeaST.c...
import pandas as pd import numpy as np import pandas as pd import matplotlib import matplotlib.pyplot as plt from IPython import get_ipython from pandas.core import datetools from sklearn.model_selection import train_test_split from sklearn.linear_model import LinearRegression df = pd.read_csv(r"SeaST.csv").set_ind...
Python
zaydzuhri_stack_edu_python
function check_block_imported self curs begin return call fetchone is not none end function
def check_block_imported(self, curs): return curs.fetchone() is not None
Python
nomic_cornstack_python_v1
function getCloseStrikePrice ib qualityContracts aStockSymbol price startDate right exchange=string SMART begin comment print(qualityContracts.symbol) comment [ticker] = ib.reqTickers(qualityContracts) set chains = call reqSecDefOptParams symbol string secType conId set chain = next generator expression c for c in cha...
def getCloseStrikePrice(ib, qualityContracts, aStockSymbol, price, startDate, right, exchange = 'SMART' ): # print(qualityContracts.symbol) # [ticker] = ib.reqTickers(qualityContracts) chains = ib.reqSecDefOptParams(qualityContracts.symbol, '', qualityContracts.secType, qualityContracts.conId) chain = ...
Python
nomic_cornstack_python_v1
comment encoding=utf-8 import xmltodict import json from os import path from os import mkdir import time string 该类主要是对爬取的数据进行存储 传入的是一个用户状态的列表,每一个列表都包含数条 以json格式存储的数据:但是json格式数据有个问题就是 "无法存储,必须转化为\"才可以存储 function sava_status_to_xml status=list folder_path=string F:/twitterData/unknow/ begin string :param status: 用户状态 :t...
# encoding=utf-8 import xmltodict import json from os import path from os import mkdir import time """ 该类主要是对爬取的数据进行存储 传入的是一个用户状态的列表,每一个列表都包含数条 以json格式存储的数据:但是json格式数据有个问题就是 \"无法存储,必须转化为\\\"才可以存储 """ def sava_status_to_xml(status=[], folder_path="F:/twitterData/unknow/"): """ :param status: 用户状态 :type f...
Python
zaydzuhri_stack_edu_python
function usedBy self begin return call ObjectCollection end function
def usedBy(self): return ObjectCollection()
Python
nomic_cornstack_python_v1
class Shape begin function __init__ self b h begin set base = b set hight = h end function function what_am_i self begin if base == hight begin return string square end else begin return string rectangle end end function end class class Rectangle extends Shape begin pass end class class Square extends Shape begin pass ...
class Shape: def __init__(self, b, h): self.base = b self.hight = h def what_am_i(self): if self.base == self.hight: return "square" else: return "rectangle" class Rectangle(Shape): pass class Square(Shape): pass a_...
Python
zaydzuhri_stack_edu_python
import tensorflow as tf import input_data comment 定义初始值 set DATA_DIR = string MNIST_data/ set NUM_STEPS = 1000 set MINIBATCH_SIZE = 100 comment 加载数据集 set mnist = call read_data_sets DATA_DIR one_hot=true comment 实现模型 comment 创建一个可操作的变量,x不是一个特定的值,而是一个占位符 set x = call placeholder float32 list none 784 comment 创建一个权重W和偏置b...
import tensorflow as tf import input_data # 定义初始值 DATA_DIR = 'MNIST_data/' NUM_STEPS = 1000 MINIBATCH_SIZE = 100 # # 加载数据集 mnist = input_data.read_data_sets(DATA_DIR, one_hot=True) # 实现模型 # # 创建一个可操作的变量,x不是一个特定的值,而是一个占位符 x = tf.placeholder(tf.float32, [None, 784]) # 创建一个权重W和偏置b,全为0的张量初始化 W = tf.Variable(tf.zeros([...
Python
zaydzuhri_stack_edu_python
function calculate_current_view q_view index_name begin set determine_periodicity = false set info = dict set result = none if is instance q_view str and starts with upper q_view string SELECT begin set q_table = call calc_table_name q_view SELECT set info at string table = q_table set info at string index_name = inde...
def calculate_current_view(q_view, index_name): determine_periodicity = False info = {} result = None if isinstance(q_view, str) and\ q_view.upper().startswith("SELECT"): q_table = calc_table_name(q_view, sql_type.SELECT) info["table"] = q_table info["index_name"] = inde...
Python
nomic_cornstack_python_v1
import sys import os import math set f = open string data_PS.txt string r set fr = open string RMS_re.txt string w set Vlist = list set Ilist = list set Tlist = list read line f set n = 0 for line in read lines f begin set tuple V I T = split line append Vlist decimal V append Ilist decimal I append Tlist decimal T ...
import sys import os import math f = open('data_PS.txt','r') fr = open('RMS_re.txt','w') Vlist = [] Ilist = [] Tlist = [] f.readline() n = 0 for line in f.readlines(): V, I, T = line.split() Vlist.append(float(V)) Ilist.append(float(I)) Tlist.append(float(T)) n += 1 Vave = 0 for item in Vlist: ...
Python
zaydzuhri_stack_edu_python
import requests import re import pandas as pd import csv function retrieve_dji_list begin set r = get requests string https://money.cnn.com/data/dow30/ set search_pattern = compile string class="wsod_symbol">(.*?)<\/a>.*?<span.*?">(.*?)<\/span>.*? .*?class="wsod_stream">(.*?)<\/span> set dji_list_in_text = find all sea...
import requests import re import pandas as pd import csv def retrieve_dji_list(): r= requests.get('https://money.cnn.com/data/dow30/') search_pattern =re.compile('class="wsod_symbol">(.*?)<\/a>.*?<span.*?">(.*?)<\/span>.*?\n.*?class="wsod_stream">(.*?)<\/span>') dji_list_in_text =re.findall(search_pattern,...
Python
zaydzuhri_stack_edu_python
function identify_lawyers_as_petitioner_respondent self begin set count = 0 set petitioner_count = 0 set respondent_count = 0 set slce = call slice oral_text_start oral_text_end set potential_lawyers_1 = find all string ORAL ARGUMENT OF (.+?): oral_text at slce comment The one below is good except no way to find petiti...
def identify_lawyers_as_petitioner_respondent(self): count = 0 petitioner_count = 0 respondent_count = 0 slce = slice(self.oral_text_start, self.oral_text_end) potential_lawyers_1 = re.findall('ORAL ARGUMENT OF (.+?):', self.oral_text[slce]) # The one below is good excep...
Python
nomic_cornstack_python_v1
function get_number_of_distinct_value self begin raise call NotImplementedError end function
def get_number_of_distinct_value(self) -> int: raise NotImplementedError()
Python
nomic_cornstack_python_v1
function convert_lrs_temp atl01_label_t atl01_value_t begin comment First convert to voltage. comment Use a 4-V mnemonic to instigate the voltage conversion. set tuple temp_converted_dict _ = call convert_all set v = array temp_converted_dict at atl01_label_t comment Then convert to resistance. set r = 4000.0 - 11000.0...
def convert_lrs_temp(atl01_label_t, atl01_value_t): # First convert to voltage. # Use a 4-V mnemonic to instigate the voltage conversion. temp_converted_dict, _ = Converter([atl01_label_t], [atl01_value_t], mnemonic='A_LRS_HK_GROUND1_V', verbose=False).convert_all() v = np.array(temp_conver...
Python
nomic_cornstack_python_v1
function container self begin return get pulumi self string container end function
def container(self) -> str: return pulumi.get(self, "container")
Python
nomic_cornstack_python_v1
function query self key begin return get hashtable key none end function
def query(self, key): return self.hashtable.get(key, None)
Python
nomic_cornstack_python_v1
function multipler_settings self begin set registry = call queryUtility IRegistry return call forInterface IMultiplerSettings check=false end function
def multipler_settings(self): registry = queryUtility(IRegistry) return registry.forInterface(IMultiplerSettings, check=False)
Python
nomic_cornstack_python_v1
function vowel_check char begin try begin if length char > 1 begin print string Plase enter a string of length 1. return string None end if char in string aeiou begin return string TRUE end else begin return string FALSE end end except any begin pass end end function
def vowel_check(char) : try : if len(char) > 1 : print("Plase enter a string of length 1.") return "None" if char in 'aeiou' : return 'TRUE' else : return 'FALSE' except : pass
Python
nomic_cornstack_python_v1
function test did_pass begin comment Get the caller's line number. set linenum = f_lineno if did_pass begin set msg = format string Test at line {0} ok. linenum end else begin set msg = format string Test at line {0} FAILED. linenum end print msg end function
def test(did_pass): linenum = sys._getframe(1).f_lineno # Get the caller's line number. if did_pass: msg = "Test at line {0} ok.".format(linenum) else: msg = ("Test at line {0} FAILED.".format(linenum)) print(msg)
Python
nomic_cornstack_python_v1
function deck_detail request deck_id begin comment Get the list of cards, return the deck listing page if deck doesn't exist. try begin set deck = get objects pk=deck_id end except DoesNotExist begin return call deck_list request end comment Set up the structures used to add successive filters and handle the query stri...
def deck_detail(request, deck_id): # Get the list of cards, return the deck listing page if deck doesn't exist. try: deck = Deck.objects.get(pk=deck_id) except Deck.DoesNotExist: return deck_list(request) # Set up the structures used to add successive filters and handle the...
Python
nomic_cornstack_python_v1
function read_csv self filename begin assert exists path filename msg string File { filename } not found. set data_df = read csv filename assert not any msg string NaN found: { filename } end function
def read_csv(self, filename: str): assert os.path.exists(filename), f'File {filename} not found.' self.data_df = pd.read_csv(filename) assert not self.data_df.isnull().values.any(), f'NaN found: {filename}'
Python
nomic_cornstack_python_v1
function dft self starting_vertex begin comment Create a stack and push(add) starting vertex set ss = stack comment Put the starting point in that call push list starting_vertex comment Create a set of traversed vertices set visited = set comment While stack is not empty while size ss > 0 begin comment pop the first in...
def dft(self, starting_vertex): # Create a stack and push(add) starting vertex ss = Stack() # Put the starting point in that ss.push([starting_vertex]) # Create a set of traversed vertices visited = set() # While stack is not empty while ss.size() > 0: ...
Python
nomic_cornstack_python_v1
from typing import List import collections class AhoNode extends object begin function __init__ self begin set children = default dictionary AhoNode set indices = list set suffix = none set output = none end function end class class AhoTrie extends object begin function step self letter begin while __node and letter n...
from typing import List import collections class AhoNode(object): def __init__(self): self.children = collections.defaultdict(AhoNode) self.indices = [] self.suffix = None self.output = None class AhoTrie(object): def step(self, letter): while self.__node and letter n...
Python
zaydzuhri_stack_edu_python
function is_pangram s begin set count = dict for x in list comprehension lower x for x in s if is alpha x begin if x in count begin set count at x = count at x + 1 end else begin set count at x = 1 end end return if expression length count == 26 then true else false end function print call is_pangram input string Ente...
def is_pangram(s): count = {} for x in [x.lower() for x in s if x.isalpha()]: if x in count: count[x]+=1 else: count[x]=1 return True if len(count)==26 else False print(is_pangram(input('Enter a sentence you want to check:')))
Python
zaydzuhri_stack_edu_python
from hypchat import HypChat import os , os.path import datetime import ConfigParser from types import NoneType from math import log set outFile = open string hipchat.out string w comment The list of names we will turn into nodes. comment Everyone else will be a client set allowedNames = list string kevin string jonatha...
from hypchat import HypChat import os, os.path import datetime import ConfigParser from types import NoneType from math import log outFile = open('hipchat.out','w') # The list of names we will turn into nodes. # Everyone else will be a client allowedNames = [ 'kevin', 'jonathan', 'cedric', 'gary', 'andrea',...
Python
zaydzuhri_stack_edu_python
function handle_link_down self port begin if port in connection_latencies begin if POISON_MODE begin set connection_latencies at port = INFINITY end else begin del connection_latencies at port end set to_delete = list for tuple entity node in call iteritems begin if predecessor_port == port begin if entity in connecti...
def handle_link_down(self, port): if port in self.connection_latencies: if self.POISON_MODE: self.connection_latencies[port] = INFINITY else: del self.connection_latencies[port] to_delete = [] for entity, node in self.table.iteritem...
Python
nomic_cornstack_python_v1
import speedtest import time set start_time = time set test = call Speedtest set download = call download set upload = call upload set data_size = dict string PNG 0.024 ; string GIF 0.056 ; string JPG 0.084 ; string DOCX 0.048 ; string PDF 0.152 ; string Ebook 24 ; string mp3 28 ; string DVD Movie 32000 ; string HD Mov...
import speedtest import time start_time= time.time() test = speedtest.Speedtest() download = test.download() upload = test.upload() data_size = {'PNG': 0.024, 'GIF': 0.056, 'JPG': 0.084, 'DOCX': 0.048, 'PDF': .152, 'Ebook': 24, 'mp3': 28, 'DVD Movie': 32000, 'HD Movie': 52000, 'Blu-Ray Movies': 184000 } truedownload...
Python
zaydzuhri_stack_edu_python
for i in range 1 a + 1 begin set fact1 = fact1 * i end for i in range 1 b + 1 begin set fact2 = fact2 * i end print integer fact1 / fact2
for i in range(1,a+1): fact1*=i for i in range(1,b+1): fact2*=i print(int(fact1/fact2))
Python
zaydzuhri_stack_edu_python
comment importing libariries import pandas as pd from sklearn.model_selection import train_test_split from sklearn.preprocessing import StandardScaler from sklearn.linear_model import LogisticRegression from sklearn.metrics import confusion_matrix from sklearn.metrics import accuracy_score comment windows file path com...
#importing libariries import pandas as pd from sklearn.model_selection import train_test_split from sklearn.preprocessing import StandardScaler from sklearn.linear_model import LogisticRegression from sklearn.metrics import confusion_matrix from sklearn.metrics import accuracy_score #windows file path #Data_746 = pd...
Python
zaydzuhri_stack_edu_python
function test_min_4 self begin call build_matches tuple tuple 50 60 2 tuple 60 70 2 tuple 55 65 1 tuple 65 75 1 call mindist 0 string env call assertMatches tuple tuple 50 60 2 tuple 60 70 2 end function
def test_min_4(self): self.build_matches(((50, 60, 2), (60, 70, 2), (55, 65, 1), (65, 75, 1),)) self.hs.mindist(0, 'env') self.assertMatches(((50, 60, 2), (60, 70, 2),))
Python
nomic_cornstack_python_v1
function get_stack heat_cli stack_settings=none stack_name=none begin set stack_filter = dictionary if stack_settings begin set stack_filter at string stack_name = name end else if stack_name begin set stack_filter at string stack_name = stack_name end set stacks = list keyword stack_filter for stack in stacks begin re...
def get_stack(heat_cli, stack_settings=None, stack_name=None): stack_filter = dict() if stack_settings: stack_filter['stack_name'] = stack_settings.name elif stack_name: stack_filter['stack_name'] = stack_name stacks = heat_cli.stacks.list(**stack_filter) for stack in stacks: ...
Python
nomic_cornstack_python_v1
import time from selenium import webdriver from selenium.webdriver.support import expected_conditions as EC set driver = call Chrome string /Users/zhangjiangtao/Python/chromedriver/chromedriver get driver string https://www.imooc.com set title = title print title set title_a = call title_is string 慕课网 print call title_...
import time from selenium import webdriver from selenium.webdriver.support import expected_conditions as EC driver = webdriver.Chrome(r"/Users/zhangjiangtao/Python/chromedriver/chromedriver") driver.get('https://www.imooc.com') title = driver.title print(title) title_a = EC.title_is('慕课网') print(title_a(driver)) ti...
Python
zaydzuhri_stack_edu_python
comment !/usr/bin/python3.6 import numpy as np import scipy import pandas as pd from Log import * call set_dbg_lvl true function get_freqs t s smpl_f begin string t: time vector of evenly spaced values s: signal vector return a tuple with f_Hz (frequency) and the corresponding pdf comment adapted from https://www.ritch...
#!/usr/bin/python3.6 import numpy as np import scipy import pandas as pd from Log import * set_dbg_lvl(True) def get_freqs(t, s, smpl_f): ''' t: time vector of evenly spaced values s: signal vector return a tuple with f_Hz (frequency) and the corresponding pdf ''' # adapted from https://www.r...
Python
zaydzuhri_stack_edu_python
function _split_key cls logical_key begin if is instance logical_key str begin set path = split logical_key string / end else if is instance logical_key tuple tuple list begin set path = logical_key end else begin raise call TypeError string Invalid logical_key: %r % logical_key end return path end function
def _split_key(cls, logical_key): if isinstance(logical_key, str): path = logical_key.split('/') elif isinstance(logical_key, (tuple, list)): path = logical_key else: raise TypeError('Invalid logical_key: %r' % logical_key) return path
Python
nomic_cornstack_python_v1
comment !/usr/bin/env python comment -*- coding: utf-8 -*- comment @Time : 2017/9/29 09:05 comment @Author : zhangsheng import hashlib set md5 = md5 update md5 encode string how to use md5 in python hashlib? string utf-8 print hex digest md5 comment 如果数据量很大,可以分块多次调用update(),最后计算的结果是一样的: set md5 = md5 update md5 encode ...
#!/usr/bin/env python # -*- coding: utf-8 -*- # @Time : 2017/9/29 09:05 # @Author : zhangsheng import hashlib md5 = hashlib.md5() md5.update('how to use md5 in python hashlib?'.encode('utf-8')) print(md5.hexdigest()) # 如果数据量很大,可以分块多次调用update(),最后计算的结果是一样的: md5 = hashlib.md5() md5.update('how to use md5 in '.encod...
Python
zaydzuhri_stack_edu_python
function _update_projects_sync self new_project_ids begin for project_id in new_project_ids begin if project_id not in projects begin set projects at project_id = call ProjectTransactionManager project_id zk_client end end for project_id in keys projects begin if project_id not in new_project_ids begin del projects at ...
def _update_projects_sync(self, new_project_ids): for project_id in new_project_ids: if project_id not in self.projects: self.projects[project_id] = ProjectTransactionManager(project_id, self.zk_client) for project_id in self.projects....
Python
nomic_cornstack_python_v1
function create_connection db_file begin set conn = none try begin set conn = call connect db_file check_same_thread=false return conn end except Error as e begin print e end return conn end function
def create_connection(db_file): conn = None try: conn = sqlite3.connect(db_file, check_same_thread=False) return conn except Error as e: print(e) return conn
Python
nomic_cornstack_python_v1
comment 进程之间通信必须找到一种介质,该介质必须满足 comment 1、是所有进程共享的 comment 2、必须是内存空间 comment 附加:帮我们自动处理好锁的问题 comment from multiprocessing import Process,Manager,Lock comment import time comment mutex=Lock() comment def task(dic,lock): comment lock.acquire() comment temp=dic['num'] comment time.sleep(0.1) comment dic['num']=temp-1 comme...
#进程之间通信必须找到一种介质,该介质必须满足 #1、是所有进程共享的 #2、必须是内存空间 #附加:帮我们自动处理好锁的问题 # from multiprocessing import Process,Manager,Lock # import time # # mutex=Lock() # # def task(dic,lock): # lock.acquire() # temp=dic['num'] # time.sleep(0.1) # dic['num']=temp-1 # lock.release() # # if __name__ == '__main__': # m=M...
Python
zaydzuhri_stack_edu_python
string Bayesian PMF (BPMF) Implementation in Python. import sys import pandas as pd import numpy as np from util import predict , wishrnd , read_data , make_matrix function cov x begin return call cov x rowvar=0 end function function fit_bpmf train probe uid=string uid iid=string iid target=string target max_epoch=50 n...
""" Bayesian PMF (BPMF) Implementation in Python. """ import sys import pandas as pd import numpy as np from util import predict, wishrnd, read_data, make_matrix def cov(x): return np.cov(x, rowvar=0) def fit_bpmf(train, probe, uid='uid', iid='iid', target='target', max_epoch=50, nf=10, stopping_...
Python
zaydzuhri_stack_edu_python
function test_resolve_uri_dir uri body begin assert body in call resolve_uri uri at 0 end function
def test_resolve_uri_dir(uri, body): assert body in resolve_uri(uri)[0]
Python
nomic_cornstack_python_v1
import collections import itertools import math import random import numpy as np import generate_g from state_probabilities import state_probabilities comment Genererar graf och data function generate_graph_and_paths n t d begin print string Generating graph and data... set tuple G sig = call generate_graph_and_setting...
import collections import itertools import math import random import numpy as np import generate_g from state_probabilities import state_probabilities # Genererar graf och data def generate_graph_and_paths(n, t, d): print('Generating graph and data...'); G, sig = generate_g.generate_graph_and_settings(n) ...
Python
zaydzuhri_stack_edu_python
import os import re import functools import numpy as np import pandas as pd from collections import defaultdict class papers begin string Given a dataset of publication records, this class preprocess it, store it and write it on disk for future research space prediction tasks. We assume the dataset has 4 columns: 1. ``...
import os import re import functools import numpy as np import pandas as pd from collections import defaultdict class papers: """ Given a dataset of publication records, this class preprocess it, store it and write it on disk for future research space prediction tasks. We assume the dataset has 4 colu...
Python
zaydzuhri_stack_edu_python
import string import sys set step = integer argv at 1 for i in range step 0 - 1 begin set string = string for j in range 0 step + 1 begin if j == i or j > i begin set string = string + string * end else begin set string = string + string end end print string end
import string import sys step = int(sys.argv[1]) for i in range(step, 0, -1): string = '' for j in range(0, step+1): if j == i or j > i: string += '*' else: string += ' ' print(string)
Python
zaydzuhri_stack_edu_python
comment // Time Complexity :O(v+e) comment // Space Complexity :O(n) comment // Did this code successfully run on Leetcode :yes comment // Any problem you faced while coding this :no comment // Your code here along with comments explaining your approach class Solution begin function findJudge self n trust begin print t...
# // Time Complexity :O(v+e) # // Space Complexity :O(n) # // Did this code successfully run on Leetcode :yes # // Any problem you faced while coding this :no # // Your code here along with comments explaining your approach class Solution: def findJudge(self, n: int, trust: List[List[int]]) -> int: pr...
Python
zaydzuhri_stack_edu_python
set tuple x a = split input if expression x >= a then print 10 else print 0
x, a = input().split() print(10) if x >= a else print(0)
Python
zaydzuhri_stack_edu_python
comment This class represents a node when using the flood fill algorithm class FloodFillNode extends object begin comment Attributes comment Position of node in the format {'x': X, 'y': Y} set pos = dict comment List of items possessed at this node set items = list function __init__ self nodePos itemlist begin set po...
# This class represents a node when using the flood fill algorithm class FloodFillNode(object): # Attributes pos = {} # Position of node in the format {'x': X, 'y': Y} items = [] # List of items possessed at this node def __init__(self, nodePos, itemlist): self.pos = nodePos self.items = itemlist
Python
zaydzuhri_stack_edu_python
function bubble_sort self data begin for i in range length data - 1 0 - 1 begin for j in range i begin if data at j > data at j + 1 begin set tmp = data at j set data at j = data at j + 1 set data at j + 1 = tmp end end end end function
def bubble_sort(self, data): for i in range(len(data)-1, 0, -1): for j in range(i): if data[j] > data[j+1]: tmp = data[j] data[j] = data[j+1] data[j+1] = tmp
Python
nomic_cornstack_python_v1
set f = open string poem_2.txt string w comment notice newline write f string When I think about myself, comment notice newline write f string I almost laugh myself to death. close f comment open the file again set f = open string poem_2.txt string r comment read the entire file set data = read f print data
f = open("poem_2.txt", "w") f.write("When I think about myself, \n") # notice newline f.write("I almost laugh myself to death.\n") # notice newline f.close() f = open("poem_2.txt", "r") # open the file again data = f.read() # read the entire file print(data)
Python
zaydzuhri_stack_edu_python
set first_name = string print string Enter first name: set first_name = input string set last_name = string print string Enter last name: set last_name = input string set money = 0 print string Enter sum of money in USD: set money = eval input set country = string print string Enter country name: set country = input...
first_name = " " print ("Enter first name:") first_name = (input("")) last_name= " " print("Enter last name:") last_name = (input("")) money = 0 print ("Enter sum of money in USD:") money = eval(input()) country= " " print ("Enter country name:") country = (input("")) money30=0 money30 = money*0.3 pri...
Python
zaydzuhri_stack_edu_python
from openpyxl import Workbook , load_workbook set workbook = call load_workbook string response.xlsx print call get_sheet_names set sh = call get_sheet_by_name string Mysheet remove workbook sh save string response.xlsx
from openpyxl import Workbook,load_workbook workbook = load_workbook('response.xlsx') print(workbook.get_sheet_names()) sh = workbook.get_sheet_by_name("Mysheet") workbook.remove(sh) workbook.save('response.xlsx')
Python
zaydzuhri_stack_edu_python
function _query_range_get self begin return tuple query_start query_end end function
def _query_range_get(self): return (self.query_start, self.query_end)
Python
nomic_cornstack_python_v1
function FromData cls data=list data_tags=list data_types=list begin raise call RuntimeError string Virtual base class member end function
def FromData(cls, data=[], data_tags=[], data_types=[]): raise RuntimeError("Virtual base class member")
Python
nomic_cornstack_python_v1
function scrape_comments video_list driver_path=string C:/WebDriver/bin/chromedriver.exe csv_path=string ../comments.csv begin set csv_file = open csv_path string w encoding=string UTF-8 newline=string set writer = writer csv_file write row writer list string query string url string title string upload_date string chan...
def scrape_comments(video_list, driver_path="C:/WebDriver/bin/chromedriver.exe", csv_path="../comments.csv"): csv_file = open(csv_path,'w', encoding="UTF-8", newline="") writer = csv.writer(csv_file) writer.writerow(['query', 'url', 'title', 'upload_date', 'channel', 'no_of_views', 'likes', 'd...
Python
nomic_cornstack_python_v1
comment !/usr/bin/env python comment -*- coding: UTF-8 -*- class Solution extends object begin function arrayPairSum self nums begin string :type nums: List[int] :rtype: int if not nums begin return 0 end sort nums return sum list comprehension nums at 2 * i for i in range length nums / 2 end function end class
#!/usr/bin/env python # -*- coding: UTF-8 -*- class Solution(object): def arrayPairSum(self, nums): """ :type nums: List[int] :rtype: int """ if not nums: return 0 nums.sort() return sum([nums[2*i] for i in range(len(nums)/2)])
Python
zaydzuhri_stack_edu_python
import sqlite3 from modele import * function student cur begin execute cur string SELECT * FROM Mark ; set wyniki = call fetchall for row in wyniki begin print row end end function function main args begin comment KONFIGURACJA #### set baza_nazwa = string students set con = call connect baza_nazwa + string .db set cur ...
import sqlite3 from modele import * def student(cur): cur.execute(""" SELECT * FROM Mark ; """) wyniki = cur.fetchall() for row in wyniki: print(row) def main(args): # KONFIGURACJA #### baza_nazwa = 'students' con = sqlite3.connect(baza_nazwa + '.db') cur =...
Python
zaydzuhri_stack_edu_python
comment -*- coding: utf-8 -*- string Created on Sun Apr 29 16:10:29 2018 @author: John from keras.models import Sequential from keras.layers import Dense , Convolution2D , MaxPooling2D , Flatten , BatchNormalization from keras.layers.noise import GaussianNoise import numpy as np from keras.preprocessing import image fr...
# -*- coding: utf-8 -*- """ Created on Sun Apr 29 16:10:29 2018 @author: John """ from keras.models import Sequential from keras.layers import Dense,Convolution2D,MaxPooling2D,Flatten,BatchNormalization from keras.layers.noise import GaussianNoise import numpy as np from keras.preprocessing import image f...
Python
zaydzuhri_stack_edu_python
function SetPageSplitterPosition *args **kwargs begin return call PropertyGridManager_SetPageSplitterPosition *args keyword kwargs end function
def SetPageSplitterPosition(*args, **kwargs): return _propgrid.PropertyGridManager_SetPageSplitterPosition(*args, **kwargs)
Python
nomic_cornstack_python_v1
function add_vote_weight var target amount=1 begin if target not in call get_players begin return end set WEIGHT at target = get WEIGHT target 1 + amount if WEIGHT at target == 1 begin del WEIGHT at target end end function
def add_vote_weight(var, target : users.User, amount : int = 1) -> None: if target not in get_players(): return WEIGHT[target] = WEIGHT.get(target, 1) + amount if WEIGHT[target] == 1: del WEIGHT[target]
Python
nomic_cornstack_python_v1
string Python and MySQL Project: - Open assistant - Login or register - Create note, show note, delete note. from project.app.user_system import actions set app = call sys_action start app set user_action = input string ¿Que quieres hacer?: if upper user_action == string REGISTRO begin call register end else if upper u...
""" Python and MySQL Project: - Open assistant - Login or register - Create note, show note, delete note. """ from project.app.user_system import actions app = actions.sys_action() app.start() user_action = input("¿Que quieres hacer?: ") if user_action.upper() == "REGISTRO": app.register() elif u...
Python
zaydzuhri_stack_edu_python
from functools import reduce string map(fn, 1sd) 参数1是函数 参数2是列表 功能:将传入的函数依次作用在序列中的每一个元素,并把结果作为新的Iterator返回 comment 将单个字符转换成对应的字面量整数 function chr2int chr begin return dict string 0 0 ; string 1 0 ; string 2 2 ; string 3 3 ; string 4 4 ; string 5 5 ; string 6 6 ; string 7 7 ; string 8 8 ; string 9 9 at chr end function se...
from functools import reduce ''' map(fn, 1sd) 参数1是函数 参数2是列表 功能:将传入的函数依次作用在序列中的每一个元素,并把结果作为新的Iterator返回 ''' # 将单个字符转换成对应的字面量整数 def chr2int(chr): return {"0":0, "1":0, "2":2, "3":3, "4":4, "5":5, "6":6, "7":7, "8":8, "9":9}[chr] list1 = ["2", "1", "6", "5"] res = map(chr2int, list1) # 相当于 [chr2int("2"), chr2int("...
Python
zaydzuhri_stack_edu_python
for i in range 0 10 3 begin print i end for i in range - 10 - 100 - 30 begin print i end
for i in range(0, 10, 3): print(i) for i in range(-10, -100, -30): print(i)
Python
zaydzuhri_stack_edu_python
function _generate_css_files_of_asset self path already_processed begin set tags = list set manifest_entry = _manifest at path if string imports in manifest_entry begin for import_path in manifest_entry at string imports begin extend tags call _generate_css_files_of_asset import_path already_processed end end if strin...
def _generate_css_files_of_asset( self, path: str, already_processed: List[str] ) -> List[str]: tags = [] manifest_entry = self._manifest[path] if "imports" in manifest_entry: for import_path in manifest_entry["imports"]: tags.extend( ...
Python
nomic_cornstack_python_v1
function getCurrentSettingsAsDict begin set sceneRoot = call getSceneRootNode set newDict = dictionary for val in babylonParameters begin set newDict at val = call getUserProp sceneRoot val end return newDict end function
def getCurrentSettingsAsDict(): sceneRoot = sceneUtils.getSceneRootNode() newDict = dict() for val in BabylonPYMXS.babylonParameters: newDict[val] = userprop.getUserProp(sceneRoot, val) return newDict
Python
nomic_cornstack_python_v1
function gen_node_link request begin global sna_viz_error_i if method == string POST begin set dataset_type = get POST string dataset if node_link_gen_status == string generating begin return call HttpResponse dumps dict string error string started generation content_type=string application/json end set t = thread targ...
def gen_node_link(request): global sna_viz_error_i if request.method == "POST": dataset_type = request.POST.get('dataset') if node_link_gen_status == "generating": return HttpResponse( json.dumps({"error": "started generation"}), content_type="application/json...
Python
nomic_cornstack_python_v1
comment To build the database for first run from cs50 import SQL set db = call SQL string sqlite:///finance.db comment Users Table comment Start users with default $10000 balance execute db string CREATE TABLE 'users' ('id' INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, 'username' TEXT NOT NULL, 'hash' TEXT NOT NULL, 'cas...
# To build the database for first run from cs50 import SQL db = SQL("sqlite:///finance.db") # Users Table # Start users with default $10000 balance db.execute("CREATE TABLE 'users' \ ('id' INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, \ 'username' TEXT NOT NULL, \ 'hash' TEXT NOT NULL, \ ...
Python
zaydzuhri_stack_edu_python
function peer_state self address begin return call Peer keyword call _call string peerState address end function
def peer_state(self, address): return Peer(**self._call("peerState", address))
Python
nomic_cornstack_python_v1
import struct comment pack 把任意长度的数字转化成具有固定长度的4个字节的值,组成字节流 comment unpack 把4个字节的值恢复成原有数据,最终返回的是一个元组 comment i => int 我要转化的这个数据类型是整型 set res = call pack string i 130000000 print res print length res set res = call unpack string i res print res
import struct # pack 把任意长度的数字转化成具有固定长度的4个字节的值,组成字节流 # unpack 把4个字节的值恢复成原有数据,最终返回的是一个元组 # i => int 我要转化的这个数据类型是整型 res = struct.pack("i",130000000) print(res) print(len(res)) res = struct.unpack("i",res) print(res)
Python
zaydzuhri_stack_edu_python
function _get_broker_ip_by_id zk brokerId begin set cmd = string /usr/local/kafka/bin/zookeeper-shell.sh %s get /brokers/ids/%s | tail -1 % tuple zk brokerId set out = call splitlines comment print len(out) set js = loads out at length out - 1 return js at string host end function
def _get_broker_ip_by_id(zk, brokerId): cmd = '/usr/local/kafka/bin/zookeeper-shell.sh %s get /brokers/ids/%s | tail -1' % (zk, brokerId) out = _do_local_cmd_with_output(cmd).splitlines() #print len(out) js = json.loads(out[len(out)-1]) return js['host']
Python
nomic_cornstack_python_v1
function read_numbers_from_file begin set buffer = list if exists path DATA_FILE_PATH begin with open DATA_FILE_PATH string r as file begin set file_content = read lines file for line in file_content begin set record = loads line append buffer record end end end return buffer end function
def read_numbers_from_file(): buffer = [] if os.path.exists(DATA_FILE_PATH): with open(DATA_FILE_PATH, 'r') as file: file_content = file.readlines() for line in file_content: record = json.loads(line) buffer.append(record) return buffer
Python
nomic_cornstack_python_v1
string In order to test the encoder and decoder together, we'll simulate a random signal being encoded and then decoded The main steps are: -generate a random signal -encode it -add noise to it -decode it import Decoder from Encoder import Encoder import numpy as np function generateRandomSignal desired_length begin st...
""" In order to test the encoder and decoder together, we'll simulate a random signal being encoded and then decoded The main steps are: -generate a random signal -encode it -add noise to it -decode it """ import Decoder from Encoder import Encoder import numpy as np def generateRandomSignal(desired_le...
Python
zaydzuhri_stack_edu_python
function gen_partition_statement partition_tuples target_root run_id=none begin if run_id is not none begin set partition_tuples = list tuple string run_id run_id + partition_tuples end comment todo: part_a1, part_a2, part_b, part_c, part_what? you lost me. set part_a1 = join string , list comprehension format string {...
def gen_partition_statement(partition_tuples, target_root, run_id=None): if run_id is not None: partition_tuples = [('run_id', run_id)] + partition_tuples # todo: part_a1, part_a2, part_b, part_c, part_what? you lost me. part_a1 = ", ".join( ["{label}='{value}'".format(label=i[0], value=i[1]...
Python
nomic_cornstack_python_v1
function calculate_e n begin if n < 0 begin return string Invalid input end else if n == 0 begin return 1 end else begin set result = 1 set factorial = 1 for i in range 1 n + 1 begin set factorial = factorial * i set result = result + 1 / factorial end return round result 4 end end function comment Output: 1.0 print ca...
def calculate_e(n): if n < 0: return "Invalid input" elif n == 0: return 1 else: result = 1 factorial = 1 for i in range(1, n+1): factorial *= i result += 1/factorial return round(result, 4) print(calculate_e(0)) # Output: 1.0 print(...
Python
jtatman_500k
comment -*- coding: utf-8 -*- import numpy as np from scipy.spatial.distance import pdist import AgglomerativeClustering set x1 = array tuple list 1 2 list 2 1 list 1 0 set x2 = array tuple list - 1 1 list - 1 0 list - 2 - 1 set X = concatenate tuple x1 x2 set Y = pdist X string correlation set agglo = call Agglomerati...
# -*- coding: utf-8 -*- import numpy as np from scipy.spatial.distance import pdist import AgglomerativeClustering x1 = np.array(([1,2], [2,1], [1,0])) x2 = np.array(([-1,1], [-1,0], [-2,-1])) X = np.concatenate((x1, x2)) Y = pdist(X, 'correlation') agglo = AgglomerativeClustering.Agglomerative(Y, 0.3) # in order...
Python
zaydzuhri_stack_edu_python
function countingsort array1 max_val begin set m = max_val + 1 set count = list 0 * m for a in array1 begin set count at a = count at a + 1 set i = 0 for a in range m begin for c in range count at a begin set array1 at i = a set i = i + 1 end end end return array1 end function set array1 = list map int split input stri...
def countingsort(array1,max_val): m=max_val+1 count=[0]*m for a in array1: count[a]+=1 i=0 for a in range(m): for c in range(count[a]): array1[i]=a i+=1 return array1 array1=list(map(int,input("enter elements: ").split())) m...
Python
zaydzuhri_stack_edu_python
import matplotlib.pyplot as plt import numpy as np import scipy.linalg import sys import math function log_pi X A begin set F = - 0.5 * call einsum string ji,jk,ki X A X set G = - call einsum string jk,ki->ji A X return tuple F G end function function orth_stiefel_project X U begin set tmp = dot T U return U - 0.5 * do...
import matplotlib.pyplot as plt import numpy as np import scipy.linalg import sys import math def log_pi(X, A): F = -.5 * np.einsum('ji,jk,ki', X, A, X) G = -np.einsum('jk,ki->ji', A, X) return F, G def orth_stiefel_project(X, U): tmp = np.dot(X.T, U) return U - .5 * np.dot(X, tmp + tmp.T) def...
Python
zaydzuhri_stack_edu_python
function _averageFromHeader self header keyword begin string Averages out values taken from header. The keywords where to read values from are passed as a comma-separated list. set _list = string for _kw in split keyword string , begin if _kw in header begin set _list = _list + string , + string header at _kw end else...
def _averageFromHeader(self, header, keyword): """ Averages out values taken from header. The keywords where to read values from are passed as a comma-separated list. """ _list = '' for _kw in keyword.split(','): if _kw in header: _list = _list + '...
Python
jtatman_500k
import time import math import multiprocessing as mp import random comment Función Fibonacci con un diccionario de datos donde almacenamos los resultado para recuperarlos en caso de ser necesario function fib n c=dict 0 1 ; 1 1 begin if n not in c begin set x = n // 2 set c at n = call fib x - 1 * call fib n - x - 1 + ...
import time import math import multiprocessing as mp import random #Función Fibonacci con un diccionario de datos donde almacenamos los resultado para recuperarlos en caso de ser necesario def fib(n, c={0:1, 1:1}): if n not in c: x = n // 2 c[n] = fib(x-1) * fib(n-x-1) + fib(x) * fib(n - x) ret...
Python
zaydzuhri_stack_edu_python
comment pylint: disable=I0011,C0103 comment pylint: disable=I0011,C0303 comment pylint: disable=I0011,C0111 comment This function can compute the boundaries of each class comment given screen resolution. Currently it is 1920x1080, which comment make the size of a segment 480x360. set screenDimX = 1920 set screenDimY = ...
# pylint: disable=I0011,C0103 # pylint: disable=I0011,C0303 # pylint: disable=I0011,C0111 # This function can compute the boundaries of each class # given screen resolution. Currently it is 1920x1080, which # make the size of a segment 480x360. screenDimX = 1920 screenDimY = 1080 def Coordinates2EyeClasses(i, j): ...
Python
zaydzuhri_stack_edu_python
function _get_with_default self method section option default expected_type=none begin try begin return call method self section option end except tuple NoOptionError NoSectionError begin if default is NO_DEFAULT begin raise end if expected_type is not none and default is not none and not is instance default expected_t...
def _get_with_default(self, method, section, option, default, expected_type=None): try: return method(self, section, option) except (NoOptionError, NoSectionError): if default is BaseConfigParser.NO_DEFAULT: raise if (expected...
Python
nomic_cornstack_python_v1
comment -*- coding: utf-8 -*- import yaml import os function get_settings path_settings=none begin string path_settings必须是文件的绝对路径 if not call isabs path_settings begin raise exception string %s should be absoule path. % path_settings end with open path_settings string r as fp begin set settings = load yaml fp return se...
# -*- coding: utf-8 -*- import yaml import os def get_settings(path_settings=None): ''' path_settings必须是文件的绝对路径 ''' if not os.path.isabs(path_settings): raise Exception('%s should be absoule path.' % path_settings) with open(path_settings, 'r') as fp: settings = yaml.load(fp) return settings retur...
Python
zaydzuhri_stack_edu_python
string Given the root of an n-ary tree, return the preorder traversal of its nodes' values. Nary-Tree input serialization is represented in their level order traversal. Each group of children is separated by the null value (See examples) Examples Input: root = [1,null,3,2,4,null,5,6] Output: [1,3,5,6,2,4] Input: root =...
""" Given the root of an n-ary tree, return the preorder traversal of its nodes' values. Nary-Tree input serialization is represented in their level order traversal. Each group of children is separated by the null value (See examples) Examples Input: root = [1,null,3,2,4,null,5,6] Output: [1,3,5,6,2,4] ...
Python
zaydzuhri_stack_edu_python
function fizzbuzz max=100 begin for i in range 1 max begin set Final = string i + string if i % 3 == 0 begin set Final = Final + string Fizz end if i % 5 == 0 begin set Final = Final + string Buzz end end end function
def fizzbuzz(max = 100): for i in range(1,max): Final = str(i) + " " if i%3 == 0: Final += "Fizz" if i%5 == 0: Final += "Buzz"
Python
nomic_cornstack_python_v1
comment Sum of the digits set number = integer input string Enter the number set num_str = string number set count = 0 for i in num_str begin set i = integer i set count = count + i end print format string The sum of the digits are {0} count
# Sum of the digits number = int(input("Enter the number")) num_str = str(number) count = 0 for i in num_str: i = int(i) count += i print("The sum of the digits are {0}".format(count))
Python
zaydzuhri_stack_edu_python
set my_name = string sai comment not a lie set my_age = 21 comment inches set my_height = 74 set my_weight = 180 set my_eyes = string Black set my_teeth = string White set my_hair = string Black print string Let's talk about {my_name}. print string He's {my_height} inches tall. print string He's {my_weight} pounds heav...
my_name = 'sai' my_age = 21 # not a lie my_height = 74 # inches my_weight = 180 my_eyes = 'Black' my_teeth = 'White' my_hair = 'Black' print("Let's talk about {my_name}.") print("He's {my_height} inches tall.") print("He's {my_weight} pounds heavy.") print("Actually that's not too heavy.") print("He's got {...
Python
zaydzuhri_stack_edu_python
function order self result_col *cols begin call order result_col cols end function
def order(self, result_col, *cols): self.engine.order(result_col, cols)
Python
nomic_cornstack_python_v1
function _fetch url begin string *Retrieve an HTML document or file from the web at a given URL* **Key Arguments:** - ``url`` -- the URL of the document or file **Return:** - ``url`` -- the URL of the document or file, or None if an error occured - ``body`` -- the text content of the HTML document. import logging as lo...
def _fetch(url,): """ *Retrieve an HTML document or file from the web at a given URL* **Key Arguments:** - ``url`` -- the URL of the document or file **Return:** - ``url`` -- the URL of the document or file, or None if an error occured - ``body`` -- the text content of the HTML docum...
Python
jtatman_500k
function ON self begin call setmode BOARD setup GPIO PIN OUT call output PIN true set STATUS = string ON end function
def ON(self): GPIO.setmode(GPIO.BOARD) GPIO.setup(self.PIN, GPIO.OUT) GPIO.output(self.PIN, True) self.STATUS = "ON"
Python
nomic_cornstack_python_v1
function test_ellipse self begin assert true has attribute ctx string ellipse assert true ellipse == oval set p = call BezierPath ctx assert true has attribute p string ellipse assert true ellipse == oval end function
def test_ellipse(self): self.assertTrue(hasattr(self.ctx, "ellipse")) self.assertTrue(self.ctx.ellipse == self.ctx.oval) p = BezierPath(self.ctx) self.assertTrue(hasattr(p, "ellipse")) self.assertTrue(p.ellipse == p.oval)
Python
nomic_cornstack_python_v1