code
stringlengths
10
2.58M
original_code
stringlengths
3
3.18M
original_language
stringclasses
1 value
source
stringclasses
7 values
function analyze_file self file_name begin try begin set file = open file_name end except FileNotFoundError begin print format string {} not found file_name end try else begin with file begin set function_count = 0 set classes_count = 0 set characters = read file set lines = split strip characters string string for lin...
def analyze_file(self, file_name): try: file = open(file_name) except FileNotFoundError: print('{} not found'.format(file_name)) else: with file: function_count = 0 classes_count = 0 characters = file.read() ...
Python
nomic_cornstack_python_v1
function select_tokens begin set r = json get requests string https://api.totle.com/data/pairs if r at string success begin comment filters out DAI pairs and low-volume tokens return list comprehension base for tuple base quote in r at string response if quote == string ETH and base not in LOW_VOLUME_TOKENS end else be...
def select_tokens(): r = requests.get('https://api.totle.com/data/pairs').json() if r['success']: return [ base for base, quote in r['response'] if quote == 'ETH' and base not in LOW_VOLUME_TOKENS ] # filters out DAI pairs and low-volume tokens else: raise ValueError(f"{r['name']} ({r['code'...
Python
nomic_cornstack_python_v1
import hashlib , re comment 4.1 starts with 5 zeros - 282749 set pattern = compile string [0]{5,}\w+ comment 4.2 starts with 6 zeros - 9962624 set pattern = compile string [0]{6,}\w+ function getHash key num begin set inputStr = key + string num set m = md5 update m encode str inputStr return hex digest m end function ...
import hashlib, re #4.1 starts with 5 zeros - 282749 pattern = re.compile('[0]{5,}\w+') #4.2 starts with 6 zeros - 9962624 pattern = re.compile('[0]{6,}\w+') def getHash(key, num): inputStr = key + str(num) m = hashlib.md5() m.update(str.encode(inputStr)) return m.hexdigest() def ch...
Python
zaydzuhri_stack_edu_python
import random import time function is_prime n begin if n <= 1 begin return false end for i in range 2 integer n ^ 0.5 + 1 begin if n % i == 0 begin return false end end return true end function function bubble_sort arr begin set swaps = 0 set n = length arr for i in range n begin for j in range n - i - 1 begin if arr a...
import random import time def is_prime(n): if n <= 1: return False for i in range(2, int(n**0.5) + 1): if n % i == 0: return False return True def bubble_sort(arr): swaps = 0 n = len(arr) for i in range(n): for j in range(n - i - 1): if arr[j] > ...
Python
jtatman_500k
comment coding:utf-8 import collections import hashlib import time import random import re import importlib set jieba = call import_module string jieba call initialize class PreProcessor extends object begin function __init__ self labeling_task paragraphs tokenization_dict=none begin comment tokenizer = jieba.Tokenizer...
#coding:utf-8 import collections import hashlib import time import random import re import importlib jieba = importlib.import_module("jieba") jieba.initialize() class PreProcessor(object): def __init__(self,labeling_task,paragraphs,tokenization_dict=None): # tokenizer = jieba.Tokenizer() #tokenizer....
Python
zaydzuhri_stack_edu_python
from itertools import permutations comment Bord grootte set SIZE = 8 function toon_bord kols begin for i in kols begin for j in range length kols begin if i == j begin print string K end=string end else begin print string - end=string end end print end end function function is_oplossing kols begin for rij in range leng...
from itertools import permutations SIZE = 8 # Bord grootte def toon_bord( kols ): for i in kols : for j in range( len( kols ) ): if i == j: print( 'K', end=" " ) else: print( '-', end=" " ) print() def is_oplossing( kols ): for rij in ra...
Python
zaydzuhri_stack_edu_python
function _predefined_cluster_topics self begin set clusters = list string Doesnt fit string Weight changes string Mood and behavioral changes string Vision changes string Headaches string Body aches and pain string Memory and concentration issues string Menstrual changes string Sleep issues and drowsiness string Balanc...
def _predefined_cluster_topics(self): self.clusters = ['Doesnt fit', 'Weight changes', 'Mood and behavioral changes', 'Vision changes', 'Headaches', 'Body aches and pain', ...
Python
nomic_cornstack_python_v1
function uint64v self addr begin return call uint64 call readv addr 8 end function
def uint64v(self, addr): return uint64(self.readv(addr, 8))
Python
nomic_cornstack_python_v1
function test_asymmetric_error quantile default_solver begin set n_samples = 1000 set rng = call RandomState 42 set X = concatenate tuple absolute randn n_samples at tuple slice : : none - random integer 2 size=tuple n_samples 1 axis=1 set intercept = 1.23 set coef = array list 0.5 - 2 comment Take care that X @ coe...
def test_asymmetric_error(quantile, default_solver): n_samples = 1000 rng = np.random.RandomState(42) X = np.concatenate( ( np.abs(rng.randn(n_samples)[:, None]), -rng.randint(2, size=(n_samples, 1)), ), axis=1, ) intercept = 1.23 coef = np.array([...
Python
nomic_cornstack_python_v1
comment RaspEasy6.py import RPi.GPIO as GPIO import time comment Button A set COUNT_BUTTON = 12 comment Button B set EXIT_BUTTON = 13 function onCountButtonEvent channel begin global count btnReady if btnReady and input COUNT_BUTTON == HIGH begin set btnReady = false set count = count + 1 end else begin set btnReady = ...
# RaspEasy6.py import RPi.GPIO as GPIO import time COUNT_BUTTON = 12 # Button A EXIT_BUTTON = 13 # Button B def onCountButtonEvent(channel): global count, btnReady if btnReady and GPIO.input(COUNT_BUTTON) == GPIO.HIGH: btnReady = False count += 1 else: btnReady = True time.sle...
Python
zaydzuhri_stack_edu_python
function btu_to_kwh BTU begin return BTU / KWH_PER_BTU end function
def btu_to_kwh(BTU): return BTU / KWH_PER_BTU
Python
nomic_cornstack_python_v1
function max_position_limit self value begin call _write MX_MAX_POSITION_LIMIT value end function
def max_position_limit(self, value): self._write(MX_MAX_POSITION_LIMIT, value)
Python
nomic_cornstack_python_v1
function solution gems begin set answer = list set visited = dict set type_nums = length set gems set min_dist = length gems + 1 set tuple _left _right = tuple 0 0 while _right < length gems begin if gems at _right in visited begin set visited at gems at _right = visited at gems at _right + 1 end else begin set visit...
def solution(gems): answer = [] visited = {} type_nums = len(set(gems)) min_dist = len(gems)+1 _left, _right = 0, 0 while _right < len(gems): if gems[_right] in visited: visited[gems[_right]] += 1 else: visited[gems[_right]] = 1 _right += 1 ...
Python
zaydzuhri_stack_edu_python
function getncVars cls ncfile begin set dset = call Dataset ncfile string r return variables end function
def getncVars(cls, ncfile): dset = ncpy.Dataset(ncfile, 'r') return dset.variables
Python
nomic_cornstack_python_v1
string Double Q-Learning agent. import torch as T import torch.nn as nn import torch.nn.functional as F import torch.optim as optim import numpy as np import random import copy import os import sys class ReplayBuffer begin string The replay buffer used to store state transitions and to draw batches for computing the lo...
""" Double Q-Learning agent. """ import torch as T import torch.nn as nn import torch.nn.functional as F import torch.optim as optim import numpy as np import random import copy import os import sys class ReplayBuffer: """ The replay buffer used to store state transitions and to draw batches for computing th...
Python
zaydzuhri_stack_edu_python
string 숫자 맞추기 게임 1. 컴퓨터가 난수를 실행한다. (범위는 1~100) 2. 사용자 부터 숫자를 입력받는다. 3. 입력받은 숫자가 난수와 같은지 비교한다. 4. 문제가 맞출 수 있는 기회만을 반복한다.(기회5편) 5-1 틀렸을 경우 힌트를 제공한다. 5-2 사용자가 입력한 숫자가 정답보다 큰지,작은지를 알려준다. 6. 기회를 다썻다면 종료 7. 정답을 맞췄을떄도 종 import random as rd set answer = random integer 1 100 set try_cnt = 5 while true begin if try_cnt == 0 begi...
""" 숫자 맞추기 게임 1. 컴퓨터가 난수를 실행한다. (범위는 1~100) 2. 사용자 부터 숫자를 입력받는다. 3. 입력받은 숫자가 난수와 같은지 비교한다. 4. 문제가 맞출 수 있는 기회만을 반복한다.(기회5편) 5-1 틀렸을 경우 힌트를 제공한다. 5-2 사용자가 입력한 숫자가 정답보다 큰지,작은지를 알려준다. 6. 기회를 다썻다면 종료 7. 정답을 맞췄을떄도 종 """ import random as rd answer = rd.randint(1,100) try_cnt = 5 while True: if try_cnt == 0: prin...
Python
zaydzuhri_stack_edu_python
from nose.tools import assert_equals from enum_ipoly import * import util import itertools function test_enum_umonomials1 begin set xs = call mkVars list string x string y string z set ums = call enum_umonomials xs 1 call assert_equals length ums 4 call assert_equals set ums set list 1 + xs end function function test_e...
from nose.tools import assert_equals from enum_ipoly import * import util import itertools def test_enum_umonomials1(): xs = util.mkVars(["x", "y", "z"]) ums = enum_umonomials(xs, 1) assert_equals(len(ums), 4) assert_equals(set(ums), set([1] + xs)) def test_enum_umonomials2(): xs = util.mkVars(["x...
Python
zaydzuhri_stack_edu_python
function load_scans_filter img_org filterdata begin comment check which filter will be used and apply that one set filter = filterdata at string filtername if filter == string gaussian begin set sigma = filterdata at string parameters at 0 set smoothed_img = call calc_gaussian img_org sigma=sigma end else if filter == ...
def load_scans_filter(img_org, filterdata): # check which filter will be used and apply that one filter = filterdata['filtername'] if filter == 'gaussian': sigma = filterdata['parameters'][0] smoothed_img = calc_gaussian(img_org, sigma=sigma) elif filter == 'median': radius = fi...
Python
nomic_cornstack_python_v1
function __init__ self *args begin if __class__ == TimeEvent begin set _self = none end else begin set _self = self end set this = call new_TimeEvent _self *args try begin append this this end except any begin set this = this end end function
def __init__(self, *args): if self.__class__ == TimeEvent: _self = None else: _self = self this = _fife.new_TimeEvent(_self, *args) try: self.this.append(this) except: self.this = this
Python
nomic_cornstack_python_v1
function Blur clip amountH=1.0 amountV=none planes=none begin set funcName = string Blur if not is instance clip VideoNode begin raise call TypeError funcName + string : "clip" is not a clip! end if amountH < - 1 or amountH > 1.5849625 begin raise call ValueError funcName + string : 'amountH' have not a correct value! ...
def Blur(clip: vs.VideoNode, amountH: float = 1.0, amountV: Optional[float] = None, planes: PlanesType = None ) -> vs.VideoNode: funcName = 'Blur' if not isinstance(clip, vs.VideoNode): raise TypeError(funcName + ': \"clip\" is not a clip!') if amountH < -1 or amountH > 1.584962...
Python
nomic_cornstack_python_v1
comment -*- coding: utf-8 -*- comment @Author: Guillaume Viejo comment @Date: 2022-05-06 15:59:38 comment @Last Modified by: Guillaume Viejo comment @Last Modified time: 2022-05-13 14:26:33 import numpy as np import pandas as pd import pynapple as nap import os , sys function loadXML path begin string path should be th...
# -*- coding: utf-8 -*- # @Author: Guillaume Viejo # @Date: 2022-05-06 15:59:38 # @Last Modified by: Guillaume Viejo # @Last Modified time: 2022-05-13 14:26:33 import numpy as np import pandas as pd import pynapple as nap import os, sys def loadXML(path): """ path should be the folder session containing ...
Python
zaydzuhri_stack_edu_python
import math function solve begin set tuple N D = list comprehension integer x for x in split input set ans = 0 for _ in range N begin set tuple X Y = list comprehension integer x for x in split input if square root X ^ 2 + Y ^ 2 <= D begin set ans = ans + 1 end end print ans end function if __name__ == string __main__ ...
import math def solve(): N, D = [int(x) for x in input().split()] ans = 0 for _ in range(N): X, Y = [int(x) for x in input().split()] if math.sqrt(X**2 + Y**2) <= D: ans += 1 print(ans) if __name__ == "__main__": solve()
Python
zaydzuhri_stack_edu_python
function write_ground_truth self begin set total_instance = 0 set n_ary_instance = 0 set all_files = list train dev test with open ground_truth string w as fw begin for input_file in all_files begin with open input_file string r as fr begin for line in read lines fr begin write fw strip line string + string set total_i...
def write_ground_truth(self): total_instance = 0 n_ary_instance = 0 all_files = [self.train, self.dev, self.test] with open(self.ground_truth, "w") as fw: for input_file in all_files: with open(input_file, "r") as fr: for line in fr.readlin...
Python
nomic_cornstack_python_v1
comment Integrantes del equipo comment Cipriano Sebastian comment Hernández Alvarado Abraham comment Arellano Munguia Jose Alejandro import string import random import os import math import base64 from bitstring import BitArray comment Global Variables set abc = string ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_` set alphabet = li...
#Integrantes del equipo #Cipriano Sebastian #Hernández Alvarado Abraham #Arellano Munguia Jose Alejandro import string import random import os import math import base64 from bitstring import BitArray #Global Variables ##################################################################### abc = "ABCDEFGHIJKLMNOPQR...
Python
zaydzuhri_stack_edu_python
function count_greater_than_ten nums begin return length list comprehension n for n in nums if n > 10 end function
def count_greater_than_ten(nums): return len([n for n in nums if n > 10])
Python
flytech_python_25k
function provide_categorized_dataset tfds_name batch_size patch_size split=string train color_labeled=0 num_parallel_calls=none shuffle=true download=true data_dir=none begin print format string [**] Load tf data source: {tfdata_source} tfdata_source=tfds_name set tuple ds info = load tfds tfds_name split=split shuffle...
def provide_categorized_dataset(tfds_name, batch_size, patch_size, split='train', color_labeled=0, num_parallel_calls=None, shuf...
Python
nomic_cornstack_python_v1
comment Naming convention: https://www.python.org/dev/peps/pep-0008/#:~:text=Use%20the%20function%20naming%20rules,invoke%20Python's%20name%20mangling%20rules. function binary_search list_1 item begin set low = 0 set high = length list_1 - 1 while low <= high begin set mid = integer low + high / 2 set guess = list_1 at...
# Naming convention: https://www.python.org/dev/peps/pep-0008/#:~:text=Use%20the%20function%20naming%20rules,invoke%20Python's%20name%20mangling%20rules. def binary_search(list_1, item): low = 0 high = len(list_1)-1 while low <= high: mid = int((low + high)/2) guess = list_1[mid] i...
Python
zaydzuhri_stack_edu_python
function to_one_hot y n_dims begin if is_cuda begin set dtype = FloatTensor set long_dtype = LongTensor end else begin set dtype = FloatTensor set long_dtype = LongTensor end set scatter_dim = length size y set y_tensor = view type long_dtype *y.size() - 1 set zeros = type dtype set y_one_hot = scatter zeros scatter_di...
def to_one_hot(y, n_dims): if y.is_cuda: dtype = torch.cuda.FloatTensor long_dtype = torch.cuda.LongTensor else: dtype = torch.FloatTensor long_dtype = torch.LongTensor scatter_dim = len(y.size()) y_tensor = y.type(long_dtype).view(*y.size(), -1) zeros = torch.zeros(...
Python
nomic_cornstack_python_v1
comment !/usr/bin/env python comment -*- coding: utf-8 -*- comment Author: Junjie Bian comment File Name: pro55.py comment Description: function isPalin num begin set strnum = string num set l = length strnum end function
#!/usr/bin/env python # -*- coding: utf-8 -*- # Author: Junjie Bian # File Name: pro55.py # Description: def isPalin(num): strnum=str(num) l=len(strnum)
Python
zaydzuhri_stack_edu_python
function _get_all_children_with_details self node tagname attributes=none startswith=none begin set result = list for childnode in call getchildren begin if tag == tagname begin set doesMatch = true if attributes begin for tuple attrname attrvalue in items attributes begin if get childnode attrname != attrvalue begin ...
def _get_all_children_with_details(self, node, tagname, attributes=None, startswith=None): result = [] for childnode in node.getchildren(): if childnode.tag == tagname: doesMatch = True if attributes: for attrname, attrvalue in attributes.i...
Python
nomic_cornstack_python_v1
comment !/usr/bin/env python comment --------------------------------------# comment The minor modification comment --------------------------------------# function get_integer begin return integer call raw_input string Please enter a number: end function function primality num begin if num <= 1 begin print string Inva...
#!/usr/bin/env python #--------------------------------------# #The minor modification #--------------------------------------# def get_integer(): return int(raw_input("Please enter a number: ")) def primality(num): if num <= 1: print("Invalid input") else: primes = range(2,(num-1)) ...
Python
zaydzuhri_stack_edu_python
function add_joint joint x1 y1 x2 y2 begin return joint end function
def add_joint(joint: str, x1: int, y1: int, x2: int, y2: int) -> str: return joint
Python
nomic_cornstack_python_v1
for name in names begin print name end=string end print
for name in names: print(name, end=" ") print()
Python
zaydzuhri_stack_edu_python
function getMaxandMinProduct A Q N M begin if length A == 0 or length Q == 0 begin raise exception end if A is none or Q is none begin raise exception end set retVals = list for idx in range 0 M begin set counter = 0 for jidx in range 0 N begin if Q at idx % 2 == 0 begin if A at jidx % 2 == 0 begin try begin if A at ji...
def getMaxandMinProduct( A, Q, N, M): if len(A) == 0 or len(Q) == 0: raise Exception() if A is None or Q is None: raise Exception() retVals = list() for idx in range(0, M): counter = 0 for jidx in range(0, N): if Q[idx] % 2 == 0: if A[jidx] % 2 == 0: ...
Python
zaydzuhri_stack_edu_python
function _del_ begin call system string rm *.log call system string rm -rf __pycache__/ call system string rm -rf algorithms/__pycache__/ call system string rm -rf algorithms/extra/__pycache__/ call system string rm -rf algorithms/sdalgo/__pycache__/ call system string rm -rf skillset/__pycache__/ return end function
def _del_(): os.system("rm *.log") os.system("rm -rf __pycache__/") os.system("rm -rf algorithms/__pycache__/") os.system("rm -rf algorithms/extra/__pycache__/") os.system("rm -rf algorithms/sdalgo/__pycache__/") os.system("rm -rf skillset/__pycache__/") return
Python
nomic_cornstack_python_v1
function count_island row col island begin set count = 0 for i in range row begin for j in range col begin set count = count + call floodfill i j row col island end end return count end function
def count_island(row, col, island): count = 0 for i in range(row): for j in range(col): count = count + floodfill(i, j, row, col, island) return count
Python
nomic_cornstack_python_v1
function land begin set resp = call mode_service custom_mode=string 9 end function comment disarm()
def land(): resp = mode_service(custom_mode="9") #disarm()
Python
nomic_cornstack_python_v1
import pyshark comment File capture object set cap = call FileCapture string test.pcapng comment Finding the number of packets in cap set i = 0 for p in cap begin set i = i + 1 end print string Total packets in this capture: i set tx_rate_array = list set RSSI_array = list set j = 0 for j in range i begin set packet ...
import pyshark cap = pyshark.FileCapture('test.pcapng') # File capture object # Finding the number of packets in cap i = 0 for p in cap: i = i + 1 print ("Total packets in this capture:", i) tx_rate_array = [] RSSI_array = [] j = 0 for j in range(i): packet = cap[j] # print(packet.number) try: wlan_info = pac...
Python
zaydzuhri_stack_edu_python
function findMatchingBracket self event=none begin set tuple c p = tuple self p if batchMode begin call notValidInBatchMode string Match Brackets return end set language = call getLanguageAtPosition c p if language == string perl begin call es string match-brackets not supported for language end else begin run end end ...
def findMatchingBracket(self: Self, event: Event = None) -> None: c, p = self, self.p if g.app.batchMode: c.notValidInBatchMode("Match Brackets") return language = g.getLanguageAtPosition(c, p) if language == 'perl': g.es('match-brackets not supported for', language) else: ...
Python
nomic_cornstack_python_v1
comment !/usr/bin/env python comment -*- coding: utf-8 -*- comment Author: 'longjh' time: 2018/12/14 string 61. 旋转链表 string 题目: 一个机器人位于一个 m x n 网格的左上角 (起始点在下图中标记为“Start” )。 机器人每次只能向下或者向右移动一步。机器人试图达到网格的右下角(在下图中标记为“Finish”)。 问总共有多少条不同的路径? 例如,上图是一个7 x 3 的网格。有多少可能的路径? 说明:m 和 n 的值均不超过 100。 示例 1: 输入: m = 3, n = 2 输出: 3 解释: 从...
#!/usr/bin/env python # -*- coding: utf-8 -*- # Author: 'longjh' time: 2018/12/14 """ 61. 旋转链表 """ """ 题目: 一个机器人位于一个 m x n 网格的左上角 (起始点在下图中标记为“Start” )。 机器人每次只能向下或者向右移动一步。机器人试图达到网格的右下角(在下图中标记为“Finish”)。 问总共有多少条不同的路径? 例如,上图是一个7 x 3 的网格。有多少可能的路径? 说明:m 和 n 的值均不超过 100。 示例 1: 输入: m = 3, n = 2 输出: 3 解释: 从左上角开始,总共有 3 条路...
Python
zaydzuhri_stack_edu_python
function _process_interactions self row begin string Process row of CTD data from CTD_chemicals_diseases.tsv.gz and generate triples. Only create associations based on direct evidence (not using the inferred-via-gene), and unambiguous relationships. (Ambiguous ones will be processed in the sister method using the disam...
def _process_interactions(self, row): """ Process row of CTD data from CTD_chemicals_diseases.tsv.gz and generate triples. Only create associations based on direct evidence (not using the inferred-via-gene), and unambiguous relationships. (Ambiguous ones will be processed in the ...
Python
jtatman_500k
function has_diminutive_suffix word suffixes set_name=none begin comment normalization set word = lower word comment do checking for suffix in suffixes begin if ends with word suffix begin if set_name begin debug string -> Matched against %s set_name end return true end end if set_name begin debug string -> Not matched...
def has_diminutive_suffix(word: str, suffixes: Set[str], set_name: Optional[str] = None) -> bool: # normalization word = word.lower() # do checking for suffix in suffixes: if word.endswith(suffix): if set_name: L.debug(' -> Matched against %s', set_name) ...
Python
nomic_cornstack_python_v1
function forms self begin set seen = set set saw = add set forms = chain list form1 form2 tolerances set unique_forms = generator expression x for x in forms if x and not x in seen or call saw x return tuple sorted unique_forms key=len reverse=true end function
def forms(self): seen = set() saw = seen.add forms = chain([self.form1, self.form2], self.tolerances) unique_forms = (x for x in forms if x and not (x in seen or saw(x))) return tuple(sorted(unique_forms, key=len, reverse=True))
Python
nomic_cornstack_python_v1
import re from scripts.handle_mysql import HandleMysql from scripts.handle_yaml import HandleYaml from scripts.handle_path import USER_ACCOUNT_FILE_PATH class Parameterize begin string 参数化 comment 未注册的手机号 set not_existed_tel_pattern = string {not_existed_tel} comment 不存在的id set not_existed_id_pattern = string {not_exis...
import re from scripts.handle_mysql import HandleMysql from scripts.handle_yaml import HandleYaml from scripts.handle_path import USER_ACCOUNT_FILE_PATH class Parameterize: ''' 参数化 ''' not_existed_tel_pattern = r'{not_existed_tel}' # 未注册的手机号 not_existed_id_pattern = r'{not_existed_id}' # 不存在的id ...
Python
zaydzuhri_stack_edu_python
function get_comments self card_id begin string Returns an iterator for the comments on a certain card. set params = dict string filter string commentCard ; string memberCreator_fields string username set comments = call api_request format string /1/cards/{card_id}/actions card_id=card_id keyword params for comment in ...
def get_comments(self, card_id): """ Returns an iterator for the comments on a certain card. """ params = {'filter': 'commentCard', 'memberCreator_fields': 'username'} comments = self.api_request( "/1/cards/{card_id}/actions".format(card_id=card_id), **params) for...
Python
jtatman_500k
function __init__ __self__ config_id failure=none name=none project=none request_id=none success=none timeout=none begin set __self__ string config_id config_id if failure is not none begin set __self__ string failure failure end if name is not none begin set __self__ string name name end if project is not none begin s...
def __init__(__self__, *, config_id: pulumi.Input[str], failure: Optional[pulumi.Input['EndConditionArgs']] = None, name: Optional[pulumi.Input[str]] = None, project: Optional[pulumi.Input[str]] = None, request_id: Optional[pulumi.Inpu...
Python
nomic_cornstack_python_v1
function reverse n begin if n < 10 begin return n end else begin return call combine n % 10 reverse n // 10 end end function
def reverse(n): if n < 10: return n else: return combine(n % 10 , reverse(n // 10))
Python
nomic_cornstack_python_v1
function test_remove_from_blacklist_with_string self begin set email = string example@example.com call add_to_blacklist email call remove_from_blacklist email assert false email in blacklist end function
def test_remove_from_blacklist_with_string(self): email = 'example@example.com' self.feature_test.add_to_blacklist(email) self.feature_test.remove_from_blacklist(email) self.assertFalse(email in Feature("testing").blacklist)
Python
nomic_cornstack_python_v1
comment TODO: draw the different images for the current conditions - I have not started this yet. comment ! python comment Lets import some required libraries that will be used to gather and display the information. import urllib comment from urllib.request import urlopen import json comment Import the libraries for th...
#TODO: draw the different images for the current conditions - I have not started this yet. #! python # Lets import some required libraries that will be used to gather and display the information. import urllib # from urllib.request import urlopen import json # Import the libraries for the Waveshare 2.7" ePa...
Python
zaydzuhri_stack_edu_python
function get_targets self df begin return iloc at tuple slice : : target_col end function
def get_targets(self, df): return df.iloc[:, self.target_col]
Python
nomic_cornstack_python_v1
comment !/usr/bin/env python string CracklyePop.py: FizzBuzz equivalent for Hacker School application. set __author__ = string Orlando Ferrer set __copyright__ = string Copyright 2013, Hacker School application comment A flow diagram for this program can be comment found at: http://www.gliffy.com/go/publish/5148322 com...
#!/usr/bin/env python """CracklyePop.py: FizzBuzz equivalent for Hacker School application.""" __author__ = "Orlando Ferrer" __copyright__ = "Copyright 2013, Hacker School application" ################################################################################### #A flow diagram for this program can be ...
Python
zaydzuhri_stack_edu_python
function __sub__ self other begin if type other is Transfer begin info string __sub__ set tuple invTvec invRvec = call _inversePerspective set tuple orgTvec orgRvec = call _inversePerspective set rvec = reshape rvec tuple 3 1 set tvec = reshape tvec tuple 3 1 set info = call composeRT rvec tvec invRvec at 0 invTvec set...
def __sub__(self, other): if type(other) is Transfer: log.info("__sub__") invTvec, invRvec = other._inversePerspective() orgTvec, orgRvec = self._inversePerspective() rvec = self.rvec.reshape((3,1)) tvec = self.tvec.reshape((3,1)) info = cv...
Python
nomic_cornstack_python_v1
function main begin comment Parse the arguments set argparser = call ArgumentParser call add_argument string --dataset string -i type=str required=true help=string Path to the dataset in csv format call add_argument string --output string -o type=str help=string Path where to write the json metadata file set args = cal...
def main(): # Parse the arguments argparser = ArgumentParser() argparser.add_argument('--dataset', '-i', type=str, required=True, help='Path to the dataset in csv format') argparser.add_argument('--output', '-o', type=str, help='Path where to write t...
Python
nomic_cornstack_python_v1
comment Michael Dean comment CSCI157 comment 2-20-17 import unittest class User begin function __init__ self username email ss password begin set username = username set email = call Email email set ss_num = call SS ss set hash = call Hash password set password = password end function function check_password self passw...
# Michael Dean # CSCI157 # 2-20-17 import unittest class User: def __init__(self, username, email, ss, password): self.username = username self.email = Email(email) self.ss_num = SS(ss) self.hash = Hash(password) self.password = password def check_password(self, passwor...
Python
zaydzuhri_stack_edu_python
function audio_bottom x model_hparams vocab_size begin comment unused arg del vocab_size set inputs = x with call variable_scope string audio_modality begin comment TODO(aidangomez): Will need to sort out a better audio pipeline function xnet_resblock x filters res_relu name begin string Xception block. with call varia...
def audio_bottom(x, model_hparams, vocab_size): del vocab_size # unused arg inputs = x with tf.variable_scope("audio_modality"): # TODO(aidangomez): Will need to sort out a better audio pipeline def xnet_resblock(x, filters, res_relu, name): """Xception block.""" with tf.variable_scope(name):...
Python
nomic_cornstack_python_v1
function wait_for_and_select_from_list_by_value self locator target begin call wait_for_and_focus_on_element locator call select_from_list_by_value locator target end function
def wait_for_and_select_from_list_by_value(self, locator, target): self.wait_for_and_focus_on_element(locator) self.select_from_list_by_value(locator, target)
Python
nomic_cornstack_python_v1
comment -------------------------# import pygame import random import time import numpy as np import csv comment -------------------------# set NAME = string ./data/points set screen = call set_mode tuple 800 600 set color = tuple 255 255 255 set radius = 2 set running = true set drawn = false set points_collector = li...
# -------------------------# import pygame import random import time import numpy as np import csv # -------------------------# NAME = "./data/points" screen = pygame.display.set_mode((800, 600)) color = (255, 255, 255) radius = 2 running = True drawn = False points_collector = [] lines_collector = [] cr = csv.rea...
Python
zaydzuhri_stack_edu_python
string Validate postal codes A valid postal code P have to fulfill both requirements: 1. P must be a number in range from 100000 to 999999 inclusive. 2. P must not contain more than one alternating repetitive digit pair. Alternating repetitive digits are digits which repeat immediately after the next digit. In other wo...
""" Validate postal codes A valid postal code P have to fulfill both requirements: 1. P must be a number in range from 100000 to 999999 inclusive. 2. P must not contain more than one alternating repetitive digit pair. Alternating repetitive digits are digits which repeat immediately after the next digit. In o...
Python
zaydzuhri_stack_edu_python
import requests from datetime import date comment get the KCRW tracklist for the date and start time function get_playlist starttime=string 09:00 begin set t = today set playlist_url = format string https://tracklist-api.kcrw.com/Simulcast/date/{}/{}/{} year month day set tracklist = json get requests playlist_url set ...
import requests from datetime import date # get the KCRW tracklist for the date and start time def get_playlist(starttime = "09:00"): t = date.today() playlist_url = r'https://tracklist-api.kcrw.com/Simulcast/date/{}/{}/{}'.format(t.year, t.month, t.day) tracklist = requests.get(playlist_url).json() ...
Python
zaydzuhri_stack_edu_python
import curses from entity import EntitySymbol from wall import Wall class Field begin function __init__ self width=60 height=30 begin set width = width set height = height set screen = list comprehension list comprehension i for i in range height for j in range width clear self end function function clear self begin fo...
import curses from entity import EntitySymbol from wall import Wall class Field: def __init__(self, width = 60, height = 30): self.width = width self.height = height self.screen = [[i for i in range(height)] for j in range(width)] self.clear() def clear(self): for y in...
Python
zaydzuhri_stack_edu_python
function parse_user_arguments *args **kwds begin set parser = call ArgumentParser description=string Generate the profiles of the input drug epilog=string @oliva's lab 2017 call add_argument string -cr string --crossings_file dest=string crossings_file action=string store help=string Define the file where the drug cros...
def parse_user_arguments(*args, **kwds): parser = argparse.ArgumentParser( description = "Generate the profiles of the input drug", epilog = "@oliva's lab 2017") parser.add_argument('-cr','--crossings_file',dest='crossings_file',action = 'store', help = """Define th...
Python
nomic_cornstack_python_v1
string 787. Cheapest Flights Within K Stops https://leetcode.com/problems/cheapest-flights-within-k-stops/ There are n cities connected by m flights. Each fight starts from city u and arrives at v with a price w. Now given all the cities and flights, together with starting city src and the destination dst, your task is...
''' 787. Cheapest Flights Within K Stops https://leetcode.com/problems/cheapest-flights-within-k-stops/ There are n cities connected by m flights. Each fight starts from city u and arrives at v with a price w. Now given all the cities and flights, together with starting city src and the destination dst, your task is ...
Python
zaydzuhri_stack_edu_python
comment inverted index import csv import pycountry function file_reader filename begin set csv_reader = reader open filename return list comprehension line for line in csv_reader end function function build_inverted_index filename keyindex textindex begin set d = dict set f = call file_reader filename for line in f be...
#inverted index import csv import pycountry def file_reader(filename): csv_reader = csv.reader(open(filename)) return [line for line in csv_reader] def build_inverted_index(filename,keyindex,textindex): d = {} f = file_reader(filename) for line in f: document = line[keyindex] ...
Python
zaydzuhri_stack_edu_python
string Comment model that only includes data columns. Author: Andrew Jarombek Date: 10/8/2019 from Comment import Comment class CommentData begin function __init__ self comment begin string Create a comment object without any auditing fields. :param comment: The original Comment object with auditing fields. if comment ...
""" Comment model that only includes data columns. Author: Andrew Jarombek Date: 10/8/2019 """ from .Comment import Comment class CommentData: def __init__(self, comment: Comment): """ Create a comment object without any auditing fields. :param comment: The original Comment object with au...
Python
zaydzuhri_stack_edu_python
import numpy as np set data1 = list 1 2 3 4 5 set data2 = list 2 4 6 8 10 set correlation = call corrcoef data1 data2 at 0 at 1 print correlation comment Output 0.98198050606
import numpy as np data1 = [1,2,3,4,5] data2 = [2,4,6,8,10] correlation = np.corrcoef(data1, data2)[0][1] print(correlation) # Output 0.98198050606
Python
iamtarun_python_18k_alpaca
comment !/usr/bin/python comment -*- coding: UTF-8 -*- import pymysql comment 创建数据库与创建数据表 function create_table begin comment 连接customer data 数据库 set cd = call connect host=string 127.0.0.1 port=3306 user=string CIM password=string pingan1234 comment 创建游标 set cursor = call cursor comment 使用execute()执行SQL try begin exec...
#!/usr/bin/python # -*- coding: UTF-8 -*- import pymysql #创建数据库与创建数据表 def create_table(): #连接customer data 数据库 cd=pymysql.connect(host="127.0.0.1",port=3306,user="CIM",password="pingan1234") #创建游标 cursor=cd.cursor() #使用execute()执行SQL try: cursor.execute("""CREATE DATABASE ...
Python
zaydzuhri_stack_edu_python
import time import traceback import pyautogui function game_state begin string 判断游戏界面属于什么状态 if call pic_exits string pic/游戏未开判断0.png string 未开标志图片0 begin print string 游戏未开状态 return 0 end else if call pic_exits string pic/游戏中判断1.png string 游戏中图片1 begin print string 云顶游戏中状态 return 1 end else begin print string 没找到对应的状态图片...
import time import traceback import pyautogui def game_state(): """ 判断游戏界面属于什么状态 """ if pic_exits('pic/游戏未开判断0.png', '未开标志图片0'): print('游戏未开状态') return 0 elif pic_exits('pic/游戏中判断1.png', '游戏中图片1'): print('云顶游戏中状态') return 1 else: print('没找到对应的状态图片') ...
Python
zaydzuhri_stack_edu_python
function _process_aux_data self vocabulary_list begin set weld_program = string result(for(_inp0, dictmerger[vec[i8], i64, +], | bs: dictmerger[vec[i8], i64, +], i: i64, word: vec[i8] | merge(bs, {word, i}) )) import willump.evaluation.willump_executor as wexec set module_name = call compile_weld_program weld_program t...
def _process_aux_data(self, vocabulary_list) -> List[Tuple[int, WeldType]]: weld_program = \ """ result(for(_inp0, dictmerger[vec[i8], i64, +], | bs: dictmerger[vec[i8], i64, +], i: i64, word: vec[i8] | merge(bs, {word, i}) ...
Python
nomic_cornstack_python_v1
comment !/usr/bin/env python3 import sys import os.path as osp from os import mkdir append path absolute path osp __name__ import matplotlib.pyplot as plt import numpy as np import scipy.stats as st import seaborn as sns from utils import Cauchy , Normal , ImportanceSampler function eval_importance_sampling target_dist...
#!/usr/bin/env python3 import sys import os.path as osp from os import mkdir sys.path.append(osp.abspath(__name__)) import matplotlib.pyplot as plt import numpy as np import scipy.stats as st import seaborn as sns from utils import Cauchy, Normal, ImportanceSampler def eval_importance_sampling(target_dist, ...
Python
zaydzuhri_stack_edu_python
function block_public_policy self begin return get _values string block_public_policy end function
def block_public_policy(self) -> typing.Optional[bool]: return self._values.get('block_public_policy')
Python
nomic_cornstack_python_v1
import requests post string http://<coffee_maker_ip>/start_brew json=dict string brew_type string regular
import requests requests.post("http://<coffee_maker_ip>/start_brew", json={"brew_type": "regular"})
Python
flytech_python_25k
function LeftOf *args **kwargs begin return call IndividualLayoutConstraint_LeftOf *args keyword kwargs end function
def LeftOf(*args, **kwargs): return _core_.IndividualLayoutConstraint_LeftOf(*args, **kwargs)
Python
nomic_cornstack_python_v1
function _get_event_handlers module_found_handler begin import os import importlib set event_handlers = dict string on_ready list ; string on_resume list ; string on_error list ; string on_message list ; string on_socket_raw_receive list ; string on_socket_raw_send list ; string on_message_delete list ; string o...
def _get_event_handlers(module_found_handler): import os import importlib event_handlers = { "on_ready": [], "on_resume": [], "on_error": [], "on_message": [], "on_socket_raw_receive": [], "on_socket_raw_send": [], "on_message_delete": [], "o...
Python
nomic_cornstack_python_v1
function computeActionFromValues self state begin if call isTerminal state begin return none end if length list keys policy == 0 begin return string exit end return policy at state end function
def computeActionFromValues(self, state): if self.mdp.isTerminal(state): return None if len(list(self.policy.keys())) == 0: return 'exit' return self.policy[state]
Python
nomic_cornstack_python_v1
comment !/usr/bin/env python comment -*- coding: utf-8 -*- comment @Time : 2019/1/24 22:36 comment @Author : alison comment @File : list02.py comment list与str的区别 comment 相同点 comment 所谓序列类型的数据,就是说它的每一个元素都可以通过指定一个编号,行话叫做“偏移量”的方式得到,而要想一次得到多个元素,可以使用切片。偏移量从0开始,总元素数减1结束 comment 区别 comment ist和str的最大区别是:list是可以改变的,str不可变。这个怎么...
#!/usr/bin/env python # -*- coding: utf-8 -*- # @Time : 2019/1/24 22:36 # @Author : alison # @File : list02.py # list与str的区别 # 相同点 # 所谓序列类型的数据,就是说它的每一个元素都可以通过指定一个编号,行话叫做“偏移量”的方式得到,而要想一次得到多个元素,可以使用切片。偏移量从0开始,总元素数减1结束 # 区别 # ist和str的最大区别是:list是可以改变的,str不可变。这个怎么理解呢? # 多维list # 这个也应该算是两者的区别了,虽然有点牵强。在str中,里面的每个元...
Python
zaydzuhri_stack_edu_python
function user_reset username password begin set dn = string uid=%s,ou=People,dc=cluster % username call passwd_s dn none password end function
def user_reset(username, password): dn = 'uid=%s,ou=People,dc=cluster' % username conn.passwd_s(dn, None, password)
Python
nomic_cornstack_python_v1
function delete self begin if item is not none begin comment Fetch Initiative Collaboration group set _collab_groupId = properties at string groupId set _collab_group = get groups _collab_groupId comment Fetch Open Data Group set _od_groupId = properties at string openDataGroupId set _od_group = get groups _od_groupId ...
def delete(self): if self.item is not None: #Fetch Initiative Collaboration group _collab_groupId = self.item.properties['groupId'] _collab_group = self._gis.groups.get(_collab_groupId) #Fetch Open Data Group _od_groupId = self.item.properties['o...
Python
nomic_cornstack_python_v1
comment Definition for a binary tree node. comment class TreeNode(object): comment def __init__(self, x): comment self.val = x comment self.left = None comment self.right = None class Solution extends object begin function deleteNode self root key begin string :type root: TreeNode :type key: int :rtype: TreeNode functi...
# Definition for a binary tree node. # class TreeNode(object): # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution(object): def deleteNode(self, root, key): """ :type root: TreeNode :type key: int :rty...
Python
zaydzuhri_stack_edu_python
comment Name: PyDict.py comment Author: Richard ROSALION comment Date: March, 2011 comment Notes: Takes a text file dictionary (one word/phrase per line) and comment generates a hybrid dictionary to use for password cracking comment Revisions: comment 1.0 4/03/2011 Initial Version comment 1.1 7/03/2011 Now saves to SQL...
# Name: PyDict.py # Author: Richard ROSALION # Date: March, 2011 # Notes: Takes a text file dictionary (one word/phrase per line) and # generates a hybrid dictionary to use for password cracking # # Revisions: # 1.0 4/03/2011 Initial Version # 1.1 7/03/2011 Now saves to SQLite DB, includin...
Python
zaydzuhri_stack_edu_python
function policy_type self begin return get pulumi self string policy_type end function
def policy_type(self) -> str: return pulumi.get(self, "policy_type")
Python
nomic_cornstack_python_v1
comment !/usr/bin/python2.7 class Tree begin function __init__ self data begin set value = data set children = list end function function add_child self obj begin append children obj end function end class
#!/usr/bin/python2.7 class Tree: def __init__(self, data): self.value = data self.children = [] def add_child(self, obj): self.children.append(obj)
Python
zaydzuhri_stack_edu_python
from math import sqrt function factors x begin set fin = list set i = 2 while i <= square root x begin if x % i == 0 begin append fin i while x % i == 0 begin set x = x / i end end set i = i + 1 end if x != 1 begin append fin x end return fin end function function primes x begin return call factors x at - 1 end functi...
from math import sqrt def factors(x): fin = [] i = 2 while i <= sqrt(x): if (x % i == 0): fin.append(i) while (x % i == 0): x = x / i i += 1 if x != 1: fin.append(x) return fin def primes(x): return factors(x)[-1]
Python
zaydzuhri_stack_edu_python
function generateParser calling_parser_group begin if calling_parser_group is none begin set parser = call ArgumentParser prog=__prog__ description=__description__ epilog=__epilog__ end else begin set parser = call add_parser split string __prog__ string . at - 1 help=__description__ end call add_argument string -g str...
def generateParser(calling_parser_group): if calling_parser_group is None: parser = argparse.ArgumentParser( prog=__prog__, description=__description__, epilog=__epilog__ ) else: parser = calling_parser_group.add_parser( str(__prog__).split(".")[-1], help=__description__ ) parser.add_argument( ...
Python
nomic_cornstack_python_v1
function nic_num_in self nic_num_in begin set _nic_num_in = nic_num_in end function
def nic_num_in(self, nic_num_in): self._nic_num_in = nic_num_in
Python
nomic_cornstack_python_v1
function almost_equal1 s1 s2 begin set diffs = 0 set length = length s1 for i in range length begin if s1 at i != s2 at i begin comment too many inversions if diffs >= 2 begin return false end set diffs = diffs + 1 for j in range length begin if s2 at j == s1 at i and s2 at i == s1 at j begin comment found inversion, c...
def almost_equal1(s1, s2): diffs = 0 length = len(s1) for i in range(length): if s1[i] != s2[i]: if diffs >= 2: # too many inversions return False diffs += 1 for j in range(length): if s2[j] == s1[i] and s2[i] == s1[j]: ...
Python
nomic_cornstack_python_v1
comment !/usr/bin/python comment This script design to take screenshot of current screen comment Loading libararies in the script from sikuli import * import os from datetime import datetime import shutil from time import sleep function takeScreenshot imagename begin set capscreen = string ScreenShots set screenshot_di...
#!/usr/bin/python #This script design to take screenshot of current screen #Loading libararies in the script from sikuli import * import os from datetime import datetime import shutil from time import sleep def takeScreenshot(imagename): capscreen = 'ScreenShots' screenshot_dir_loc = os.path.join(os.getcwd(...
Python
zaydzuhri_stack_edu_python
import numpy as np import scipy.special as sp import matplotlib.pyplot as plt function S_int A B Rab2 begin string Calculates the overlap between two gaussian functions return pi / A + B ^ 1.5 * exp - A * B * Rab2 / A + B end function function T_int A B Rab2 begin string Calculates the kinetic energy integrals for un-n...
import numpy as np import scipy.special as sp import matplotlib.pyplot as plt def S_int(A, B, Rab2): """ Calculates the overlap between two gaussian functions """ return (np.pi / (A + B)) ** 1.5 * np.exp(-A * B * Rab2 / (A + B)) def T_int(A, B, Rab2): """ Calculates the kinetic energy inte...
Python
zaydzuhri_stack_edu_python
comment Matius Celcius Sinaga comment Ubuntu 14.0 | 32 bit comment Python 2.7 comment matplotlib-1.4.0 import numpy as np import matplotlib.pyplot as plt import matplotlib.animation as animation comment perulangan yang dilakukan function data_gen begin set t = t set hitung = 0 while hitung < 1000 begin set hitung = hit...
# Matius Celcius Sinaga # Ubuntu 14.0 | 32 bit # Python 2.7 # matplotlib-1.4.0 import numpy as np import matplotlib.pyplot as plt import matplotlib.animation as animation #perulangan yang dilakukan def data_gen(): t = data_gen.t hitung = 0 while hitung < 1000: hitung+=1 t += 0.05 ...
Python
zaydzuhri_stack_edu_python
set temp = decimal input string Informe a temperatura em °C: set convert = 9 * temp / 5 + 32 print format string A temperatura de {:.1f}°C corresponde a {:.1f}F! temp convert
temp = float(input('Informe a temperatura em °C: ')) convert = ((9*(temp/5))+32) print('A temperatura de {:.1f}°C corresponde a {:.1f}F!' .format(temp, convert))
Python
zaydzuhri_stack_edu_python
import os import csv comment Path to collect data from the Resources folder set election_csv = join path string Resources string election_data.csv comment files to load and output set file_to_output = join path string analysis string election_analysis.txt set total_votes = 0 set candidates = dict comment Read in the C...
import os import csv # Path to collect data from the Resources folder election_csv = os.path.join('Resources', 'election_data.csv') # files to load and output file_to_output = os.path.join("analysis", "election_analysis.txt") total_votes = 0 candidates = {} # Read in the CSV file with open(election_csv, 'r') as csv...
Python
zaydzuhri_stack_edu_python
function test_metadata self begin set result = call calculate_uv_index cube_uv_up cube_uv_down assert equal string standard_name string ultraviolet_index assert is none var_name assert is none long_name assert equal units call Unit string 1 end function
def test_metadata(self): result = calculate_uv_index(self.cube_uv_up, self.cube_uv_down) self.assertEqual(str(result.standard_name), 'ultraviolet_index') self.assertIsNone(result.var_name) self.assertIsNone(result.long_name) self.assertEqual((result.units), Unit("1"))
Python
nomic_cornstack_python_v1
from enigma.rotors.rotor import Rotor from enigma.plugboard import Plugboard from enigma.machine import EnigmaMachine comment Rotors set r1 = call Rotor string my rotor1 string EKMFLGDQVZNTOWYHXUSPAIBRCJ ring_setting=0 stepping=string Q set r2 = call Rotor string my rotor2 string AJDKSIRUXBLHWTMCQGZNPYFVOE ring_setting...
from enigma.rotors.rotor import Rotor from enigma.plugboard import Plugboard from enigma.machine import EnigmaMachine #Rotors r1 = Rotor('my rotor1', 'EKMFLGDQVZNTOWYHXUSPAIBRCJ', ring_setting=0, stepping='Q') r2 = Rotor('my rotor2', 'AJDKSIRUXBLHWTMCQGZNPYFVOE', ring_setting=5, stepping='E') r3 = Rotor('my rotor3', '...
Python
zaydzuhri_stack_edu_python
comment Et program komuniserer med en bruker. Brukeren tar inn et navn og et bosted fra terminalen. comment Prosedyren repeteres 3 ganger og derfor faar vi informasjon om 3 personer. function navnsted begin set navn = input string Skriv inn navn: set sted = input string Hvor kommer du fra? print string Hei, + navn + st...
#Et program komuniserer med en bruker. Brukeren tar inn et navn og et bosted fra terminalen. #Prosedyren repeteres 3 ganger og derfor faar vi informasjon om 3 personer. def navnsted(): navn = input("Skriv inn navn: ") sted = input("Hvor kommer du fra? ") print ("Hei, " + navn + "! " "Du er fra " + sted...
Python
zaydzuhri_stack_edu_python
function disconnect self begin info string Shutting down and disconnect from engine try begin call disconnect end except Exception as ex begin pass info string disconnect from engine failed + message end finally begin call shutdown end end function
def disconnect(self): logging.info('Shutting down and disconnect from engine') try: self.connection.disconnect() except Exception as ex: pass logging.info('disconnect from engine failed\n' + ex.message) finally: logging.shutdown()
Python
nomic_cornstack_python_v1
import matplotlib.pyplot as plt import math function graphfunction xmin xmax xres function *args begin string takes a given mathematical function and graphs it-how it works is not important set tuple x y = tuple list list set i = 0 while xmin + i * xres <= xmax begin append x xmin + i * xres append y call function x ...
import matplotlib.pyplot as plt import math def graphfunction(xmin,xmax,xres,function,*args): "takes a given mathematical function and graphs it-how it works is not important" x,y = [],[] i=0 while xmin+i*xres<=xmax: x.append(xmin+i*xres) y.append(function(x[i],*args)) i+=1 ...
Python
zaydzuhri_stack_edu_python
class Solution begin comment Time: O(logn) comment Space: O(1) function binarySearchLargestK self A k begin set tuple l r res = tuple 0 length A - 1 - 1 while l <= r begin set mid = l + r - l ? 1 if A at mid > k begin set tuple res r = tuple mid mid - 1 end else begin set l = mid + 1 end end return res end function fun...
class Solution: # Time: O(logn) # Space: O(1) def binarySearchLargestK(self, A, k): l, r, res = 0, len(A) - 1, -1 while l <= r: mid = l + ((r - l) >> 1) if A[mid] > k: res, r = mid, mid - 1 else: l = mid + 1 return res def binarySearchForARange(self, A, k): ...
Python
zaydzuhri_stack_edu_python
function wheel self pos begin if pos < 85 begin return call Color pos * 3 255 - pos * 3 0 end else if pos < 170 begin set pos = pos - 85 return call Color 255 - pos * 3 0 pos * 3 end else begin set pos = pos - 170 return call Color 0 pos * 3 255 - pos * 3 end end function
def wheel(self,pos): if pos < 85: return Color(pos * 3, 255 - pos * 3, 0) elif pos < 170: pos -= 85 return Color(255 - pos * 3, 0, pos * 3) else: pos -= 170 return Color(0, pos * 3, 255 - pos * 3)
Python
nomic_cornstack_python_v1
from sklearn.feature_extraction.text import TfidfVectorizer from sklearn.naive_bayes import MultinomialNB from sklearn.pipeline import make_pipeline from sklearn.datasets import fetch_20newsgroups set categories = list string talk.religion.misc string soc.religion.christian string sci.space string comp.graphics functio...
from sklearn.feature_extraction.text import TfidfVectorizer from sklearn.naive_bayes import MultinomialNB from sklearn.pipeline import make_pipeline from sklearn.datasets import fetch_20newsgroups categories = ['talk.religion.misc','soc.religion.christian','sci.space','comp.graphics'] def predict_category(s, train=fe...
Python
zaydzuhri_stack_edu_python
function explanation self index extra begin string >>> d = DistanceAlphabet('D', NPOSTFIX=2, NDIRECT=10) >>> d[55].explanation(13) '11[1101]01-5: [0]+240' set extraBits = call extraBits index set extraString = format string [{:0{}b}] extra extraBits return format string {0}: [{1[0]}]{1[1]:+d} replace call mnemonic inde...
def explanation(self, index, extra): """ >>> d = DistanceAlphabet('D', NPOSTFIX=2, NDIRECT=10) >>> d[55].explanation(13) '11[1101]01-5: [0]+240' """ extraBits = self.extraBits(index) extraString = '[{:0{}b}]'.format(extra, extraBits) return '{0}: [{1[0]}]{...
Python
jtatman_500k
function gen_df row_num col_num lb=0 ub=100 begin set shape = tuple row_num col_num set data = random integer lb ub shape set cols = list ascii_lowercase at slice : col_num : set df = call DataFrame data columns=cols print string shape: shape print head df 2 return df end function
def gen_df(row_num: int, col_num: int, lb: int = 0, ub: int = 100): shape = (row_num, col_num) data = np.random.randint(lb, ub, shape) cols = list(ascii_lowercase[:col_num]) df = pd.DataFrame(data, columns=cols) print("shape:", df.shape) print(df.head(2)) return df
Python
nomic_cornstack_python_v1