code
stringlengths
10
2.58M
original_code
stringlengths
3
3.18M
original_language
stringclasses
1 value
source
stringclasses
7 values
function _compute_pd_power raw_vals begin set pd_powers = list set constants_list = list 0.202 3.912 for i in list 0 1 begin append pd_powers raw_vals at i / 1638.0 * constants_list at i end return pd_powers end function
def _compute_pd_power(raw_vals): pd_powers = [] constants_list = [0.202, 3.912] for i in [0, 1]: pd_powers.append(raw_vals[i]/1638.*constants_list[i]) return pd_powers
Python
nomic_cornstack_python_v1
function __init__ __self__ cluster_identifier endpoint_name subnet_group_name resource_owner=none vpc_security_group_ids=none begin set __self__ string cluster_identifier cluster_identifier set __self__ string endpoint_name endpoint_name set __self__ string subnet_group_name subnet_group_name if resource_owner is not n...
def __init__(__self__, *, cluster_identifier: pulumi.Input[str], endpoint_name: pulumi.Input[str], subnet_group_name: pulumi.Input[str], resource_owner: Optional[pulumi.Input[str]] = None, vpc_security_group_ids: Optional[pulumi.Input[...
Python
nomic_cornstack_python_v1
function test_edit_empty sp tempfile setup_edit_patches cleandir fake_db funk_dict begin set edited_cmd_string = string assert is file path FUNKY_DB_FILENAME for tuple i funk in enumerate funk_dict begin call setup_edit_patches sp tempfile edited_cmd_string set cmd = call Edit list funk assert length funk_dict == leng...
def test_edit_empty(sp, tempfile, setup_edit_patches, cleandir, fake_db, funk_dict): edited_cmd_string = '' assert os.path.isfile(commands.Command.FUNKY_DB_FILENAME) for i, funk in enumerate(funk_dict): setup_edit_patches(sp, tempfile, edited_cmd_string) cmd = commands.Edit([funk]) ...
Python
nomic_cornstack_python_v1
function _check_v2 self start_here=false begin if start_here begin info string Validating configuration data... end set data at string compose_files = call _check_for_compose_file set ret = true set compose_override_list = list comprehension file for file in data at string compose_files if string override in file if le...
def _check_v2(self, start_here: bool = False) -> bool: if start_here: self.console.info("Validating configuration data...") self.data["compose_files"] = self._check_for_compose_file() ret = True compose_override_list = [ file for file in self.data["compose_file...
Python
nomic_cornstack_python_v1
from loader import load_data from sklearn.preprocessing import MinMaxScaler from pprint import pprint from sklearn.cluster import KMeans , MiniBatchKMeans from sklearn.model_selection import train_test_split import pandas as pd class Model begin function __init__ self file_name begin set __file_name = file_name set __d...
from loader import load_data from sklearn.preprocessing import MinMaxScaler from pprint import pprint from sklearn.cluster import KMeans, MiniBatchKMeans from sklearn.model_selection import train_test_split import pandas as pd class Model: def __init__(self, file_name): self.__file_name = file_name ...
Python
zaydzuhri_stack_edu_python
import numpy as np import pandas as pd import matplotlib.pyplot as plt import seaborn as sns comment Importar datos de pydataset comment Checar bases de datos comment data() comment df = data('iris') comment Cargar base de datos set df = call load_dataset string iris head df describe df columns value counts df at strin...
import numpy as np import pandas as pd import matplotlib.pyplot as plt import seaborn as sns #Importar datos de pydataset #Checar bases de datos #data() #df = data('iris') #Cargar base de datos df = sns.load_dataset('iris') df.head() df.describe() df.columns df['species'].value_counts() sns.countplot(x = 'species', da...
Python
zaydzuhri_stack_edu_python
function map self layers=none interactive=true zoom=none lat=none lng=none size=tuple 800 400 ax=none begin string Produce a CARTO map visualizing data layers. Examples: Create a map with two data :py:class:`Layer <cartoframes.layer.Layer>`\s, and one :py:class:`BaseMap <cartoframes.layer.BaseMap>` layer:: import carto...
def map(self, layers=None, interactive=True, zoom=None, lat=None, lng=None, size=(800, 400), ax=None): """Produce a CARTO map visualizing data layers. Examples: Create a map with two data :py:class:`Layer <cartoframes.layer.Layer>`\s, and one :py:class:`B...
Python
jtatman_500k
import types from scipy.optimize import minimize from import core as coreHelp function decoObjFunctCallToCatchCalledProcessError objFunctObj retVal begin string Decorates an instance of ObjFunctCalculatorStandard class such that when CalledProcessError is encountered the objective function returns retVal (instead of t...
import types from scipy.optimize import minimize from . import core as coreHelp def decoObjFunctCallToCatchCalledProcessError(objFunctObj, retVal): """ Decorates an instance of ObjFunctCalculatorStandard class such that when CalledProcessError is encountered the objective function returns retVal (instead of the pro...
Python
zaydzuhri_stack_edu_python
function __bool__ self begin set it = iterate line for tab in it begin set code = next it if strip code begin return true end end return false end function
def __bool__(self): it = iter(self.line) for tab in it: code = next(it) if code.strip(): return True return False
Python
nomic_cornstack_python_v1
function users2Neo db renderedTwits begin set started = now set right_now = call isoformat for twit in renderedTwits begin set twit at string last_scraped = right_now end set data = list comprehension dict string screen_name get twit string screen_name false ; string props twit for twit in renderedTwits if get twit str...
def users2Neo(db, renderedTwits): started = datetime.now() right_now = started.isoformat() for twit in renderedTwits: twit['last_scraped'] = right_now data = [{'screen_name': twit.get('screen_name', False), 'props':twit} for twit in renderedTwits if twit.get('screen_nam...
Python
nomic_cornstack_python_v1
comment pylint: disable=unused-argument function calculate_kolmogorov_smirnov p q num_samples=100 _random_state=none begin comment pragma: no cover warning string This function is deprecated, please use `calculate_goodness_of_fit` end function
def calculate_kolmogorov_smirnov(p, q, num_samples=100, _random_state=None): # pylint: disable=unused-argument logging.warning("This function is deprecated, please use `calculate_goodness_of_fit`") # pragma: no cover
Python
nomic_cornstack_python_v1
comment !/usr/bin/env python string coding=utf-8 Code Template import inspect import logging import os import sys import pandas import spacy from matplotlib import pyplot as plt comment Collections import collections from collections import Counter comment NLTK from nltk.tokenize import word_tokenize from nltk.corpus i...
#!/usr/bin/env python """ coding=utf-8 Code Template """ import inspect import logging import os import sys import pandas import spacy from matplotlib import pyplot as plt # Collections import collections from collections import Counter # NLTK from nltk.tokenize import word_tokenize from nltk.corpus import stopwo...
Python
zaydzuhri_stack_edu_python
comment !/usr/bin/env python import sys import GmailFilters set input = open argv at 1 set filters = call GmailFilters read input set allproperties = dict for filter in filters begin for key in keys properties begin if not call has_key key begin set allproperties at key = set list end add allproperties at key properti...
#!/usr/bin/env python import sys import GmailFilters input = open(sys.argv[1]) filters = GmailFilters.GmailFilters(input.read()) allproperties = {} for filter in filters: for key in filter.properties.keys(): if not allproperties.has_key(key): allproperties[key] = set([]) allproperties[key].add(filter...
Python
zaydzuhri_stack_edu_python
function sevens_in_a_row arr n begin set result = false for i in range length arr - n begin if arr at i == 7 begin set result = true for j in range i + 1 i + n begin if arr at j != 7 begin set result = false end end if result begin break end end end return result end function function main begin print call sevens_in_a_...
def sevens_in_a_row(arr, n): result = False for i in range(len(arr) - n): if arr[i] == 7: result = True for j in range(i+1, i+n): if arr[j] != 7: result = False if result: break return result def main(): pr...
Python
zaydzuhri_stack_edu_python
function _is_lis_output_missing curdate model_forcing begin for model in list string SURFACEMODEL string ROUTING begin set filename = string lis_fcst set filename = filename + string / { model_forcing } set filename = filename + string / { model } set filename = filename + string / { year } { month } set filename = fil...
def _is_lis_output_missing(curdate, model_forcing): for model in ["SURFACEMODEL", "ROUTING"]: filename = f"lis_fcst" filename += f"/{model_forcing}" filename += f"/{model}" filename += f"/{curdate.year:04d}{curdate.month:02d}" filename += "/LIS_HIST_" filename += f"{c...
Python
nomic_cornstack_python_v1
from tkinter import * import tkinter.font from gpiozero import LED import RPi.GPIO call setmode BCM set led = call LED 14 set win = call Tk title win string LED Toggler set myFont = call Font family=string Helvetica size=12 weight=string bold function ledToggle begin if is_lit begin call off set ledButton at string tex...
from tkinter import * import tkinter.font from gpiozero import LED import RPi.GPIO RPi.GPIO.setmode(RPi.GPIO.BCM) led=LED(14) win=Tk() win.title('LED Toggler') myFont=tkinter.font.Font(family='Helvetica', size = 12, weight = 'bold') def ledToggle(): if led.is_lit: led.off() ledButton['text']='Tu...
Python
zaydzuhri_stack_edu_python
function connect_samdb_ex samdb_url lp=none session_info=none credentials=none flags=0 ldb_options=none ldap_only=false begin set sam_db = call connect_samdb samdb_url lp session_info credentials flags ldb_options ldap_only comment fetch RootDse set res = search base=string expression=string scope=SCOPE_BASE attrs=li...
def connect_samdb_ex(samdb_url, lp=None, session_info=None, credentials=None, flags=0, ldb_options=None, ldap_only=False): sam_db = connect_samdb(samdb_url, lp, session_info, credentials, flags, ldb_options, ldap_only) # fetch RootDse res = sam_db.search(base=...
Python
nomic_cornstack_python_v1
from bamboo.macro.utils import get_residue_labels function extract_scores scores label begin string Pull out the score specified by 'label' comment Validate label (NAME-CHAIN-NUMBER-INSCODE) if label at 3 == string begin set label = list label set label at 3 = string set label = tuple label end comment Extract Scores...
from bamboo.macro.utils import get_residue_labels def extract_scores(scores, label): """Pull out the score specified by 'label'""" # Validate label (NAME-CHAIN-NUMBER-INSCODE) if label[3] == '': label = list(label) label[3] = ' ' label = tuple(label) # Extract Scores try: ...
Python
zaydzuhri_stack_edu_python
string 生成器是返回迭代器的函数(使用yield关键字的函数) yield返回一个值,并且记住这个返回的位置,下次迭代时,代码从yield的下一条语句开始执行 .send() 和next()一样,都能让生成器继续往下走一步(下次遇到yield停),但send()能传一个值,这个值作为yield表达式整体的结果 yield 表达式的值,作为send()函数的返回值 列表解析式: li=[x*x for x in range(10)] 生成器表达式: ge=(x*x for x in range(10)) function generator begin print string start yield 2 print strin...
''' 生成器是返回迭代器的函数(使用yield关键字的函数) yield返回一个值,并且记住这个返回的位置,下次迭代时,代码从yield的下一条语句开始执行 .send() 和next()一样,都能让生成器继续往下走一步(下次遇到yield停),但send()能传一个值,这个值作为yield表达式整体的结果 yield 表达式的值,作为send()函数的返回值 列表解析式: li=[x*x for x in range(10)] 生成器表达式: ge=(x*x for x in range(10)) ''' def generator(): print("start") yield 2 print...
Python
zaydzuhri_stack_edu_python
function connect self gateway_name begin set dialog = get connect_dialogs gateway_name none if not dialog begin set dialog = call ConnectDialog main_engine gateway_name end call exec_ end function
def connect(self, gateway_name: str) -> None: dialog = self.connect_dialogs.get(gateway_name, None) if not dialog: dialog = ConnectDialog(self.main_engine, gateway_name) dialog.exec_()
Python
nomic_cornstack_python_v1
function childNames self begin if _object begin return list comprehension nodeName for child in childNodes if is instance child Element end return list end function
def childNames( self ): if ( self._object ): return [ child.nodeName for child in self._object.childNodes if isinstance( child, xml.dom.minidom.Element ) ] return []
Python
nomic_cornstack_python_v1
function acceptance_required self begin return get pulumi self string acceptance_required end function
def acceptance_required(self) -> pulumi.Output[bool]: return pulumi.get(self, "acceptance_required")
Python
nomic_cornstack_python_v1
function close_session self begin string Close tensorflow session. Exposes for memory management. with call as_default begin close _sess set _sess = none end end function
def close_session(self): """ Close tensorflow session. Exposes for memory management. """ with self._graph.as_default(): self._sess.close() self._sess = None
Python
jtatman_500k
comment !/usr/bin/python comment -*- coding: utf-8 -*- string # soluction 广度优先遍历, 利用循环的思想去遍历即可。基于以构建的上层连接关系,去遍历链接下一层节点 comment Definition for a binary tree node class TreeNode begin function __init__ self x begin set val = x set left = none set right = none set next = none end function end class class Solution begin co...
#!/usr/bin/python # -*- coding: utf-8 -*- """ # soluction 广度优先遍历, 利用循环的思想去遍历即可。基于以构建的上层连接关系,去遍历链接下一层节点 """ # Definition for a binary tree node class TreeNode: def __init__(self, x): self.val = x self.left = None self.right = None self.next = None class Solution: # @param r...
Python
zaydzuhri_stack_edu_python
async function receive self text_data=none begin set packet = loads text_data comment print('Receive:', packet) comment 0: Create / Update; 1: Delete await call deserialize_comment packet at string data packet at string event_type try begin await call group_send room_group_name dict string type string forum_message end...
async def receive(self, text_data=None): packet = json.loads(text_data) # print('Receive:', packet) await self.deserialize_comment(packet['data'], packet['event_type']) # 0: Create / Update; 1: Delete try: await self.channel_layer.group_send( self.roo...
Python
nomic_cornstack_python_v1
function build_license scanned_file begin comment TODO: filter based on license scores and/or add warnings and or detailed comments with that info set license_expressions = get scanned_file string license_expressions list if not license_expressions begin return end comment TODO: use either Debian license symbols or SPD...
def build_license(scanned_file): # TODO: filter based on license scores and/or add warnings and or detailed comments with that info license_expressions = scanned_file.get('license_expressions', []) if not license_expressions: return # TODO: use either Debian license symbols or SPDX # TODO: ...
Python
nomic_cornstack_python_v1
function test_list_empty self begin set returns = list list set expectedData = dict string tenantId string 123 ; string limit 100 set expectedCql = string SELECT "tenantId", "groupId", group_config, active, pending, "groupTouched", "policyTouched", paused, desired, created_at, status, error_reasons, suspended FROM sca...
def test_list_empty(self): self.returns = [[]] expectedData = {'tenantId': '123', 'limit': 100} expectedCql = ( 'SELECT "tenantId", "groupId", group_config, active, pending, ' '"groupTouched", "policyTouched", paused, desired, ' 'created_at, status, error_rea...
Python
nomic_cornstack_python_v1
function update self *args **kwargs begin update _curr *args keyword kwargs if not CASE_SENSITIVE begin for tuple k v in list items _curr begin set _curr at upper k = v end end call _update_path end function
def update(self, *args, **kwargs): self._curr.update(*args, **kwargs) if not self.CASE_SENSITIVE: for k, v in list(self._curr.items()): self._curr[k.upper()] = v self._update_path()
Python
nomic_cornstack_python_v1
comment !/usr/bin/env python from characterset import CharacterSet , distinctCharacterSets from fsm import State , StateMachine class NFAState extends State begin pass end class class NFA extends StateMachine begin decorator classmethod function fnmatch klass s begin string create an NFA state machine representing the ...
#!/usr/bin/env python from characterset import CharacterSet, distinctCharacterSets from fsm import State, StateMachine class NFAState(State): pass class NFA(StateMachine): @classmethod def fnmatch(klass, s): '''create an NFA state machine representing the fnmatch pattern @s''' nfa = NFA(NFAState()) ...
Python
zaydzuhri_stack_edu_python
function metadata self df begin return dict end function
def metadata(self, df): return {}
Python
nomic_cornstack_python_v1
function support_attachments self begin return _support_attachments end function
def support_attachments(self) -> ConfigNodePropertyBoolean: return self._support_attachments
Python
nomic_cornstack_python_v1
function encrypt plaintext keyword begin comment Preparing variables for later set plaintext = call prepare_string plaintext set keyword = call prepare_string keyword set keyword = list comprehension ordinal x - 64 for x in keyword set encrypted = string set key = 0 for char in plaintext begin comment If keyword ends ...
def encrypt(plaintext: str, keyword: str): # Preparing variables for later plaintext = prepare_string(plaintext) keyword = prepare_string(keyword) keyword = [ord(x) - 64 for x in keyword] encrypted = '' key = 0 for char in plaintext: # If keyword ends go to the begin if key...
Python
nomic_cornstack_python_v1
string Author : Yi-Chieh Wu, Ka Ki Fung, Jasmine Seo, Anya Wallace Class : HMC CS 121 Date : 2018 Sep 13 Description : Utility functions import os from collections import Counter import numpy as np import pandas as pd import cv2 as cv from sklearn import metrics import matplotlib.pyplot as plt comment functions functio...
""" Author : Yi-Chieh Wu, Ka Ki Fung, Jasmine Seo, Anya Wallace Class : HMC CS 121 Date : 2018 Sep 13 Description : Utility functions """ import os from collections import Counter import numpy as np import pandas as pd import cv2 as cv from sklearn import metrics import matplotlib.pyplot as plt ###...
Python
zaydzuhri_stack_edu_python
import sys set N = 8 set s = 0 set g = list comprehension none for _ in range N + 1 set g at 0 = list tuple 1 1 tuple 3 2 set g at 1 = list tuple 0 1 tuple 2 4 tuple 3 3 tuple 4 1 tuple 5 6 set g at 2 = list tuple 1 4 tuple 5 1 tuple 6 1 tuple 7 2 set g at 3 = list tuple 0 2 tuple 1 3 tuple 4 5 set g at 4 = list tuple ...
import sys N = 8 s = 0 g = [None for _ in range(N+1)] g[0] = [(1,1), (3,2)] g[1] = [(0,1), (2,4), (3,3), (4,1), (5,6)] g[2] = [(1,4), (5,1), (6,1), (7,2)] g[3] = [(0,2), (1,3), (4,5)] g[4] = [(1,1), (3,5), (6,2)] g[5] = [(1,6), (2,1), (7,9)] g[6] = [(2,1), (4,2), (7,1)] g[7] = [(2,2), (5,9), (6,1)] visited = [False fo...
Python
zaydzuhri_stack_edu_python
from typing import Any class Item begin function __init__ self value begin set value = value set next = none end function end class class CustomList begin function __init__ self *data node=none begin set __head = none for a in data at slice : : - 1 begin print string appended: a set node = item a set next = __head se...
from typing import Any class Item: def __init__(self, value): self.value = value self.next = None class CustomList: def __init__(self, *data, node=None): self.__head = None for a in data[::-1]: print('appended: ', a) node = Item(a) node.nex...
Python
zaydzuhri_stack_edu_python
function test_fasttrakg begin set test_path = make dir temp set tuple x_train metadata = call fasttrakg test_path try begin assert shape == tuple 15 9 end except any begin remove tree test_path raise tuple end end function
def test_fasttrakg(): test_path = tempfile.mkdtemp() x_train, metadata = fasttrakg(test_path) try: assert x_train.shape == (15, 9) except: shutil.rmtree(test_path) raise()
Python
nomic_cornstack_python_v1
async function removejoinchannel self ctx channel begin set db_session = call create_db_session try begin set existing = call one set joinable = false end except NoResultFound begin await call send string There was no record for { mention } . The channel is not currently joinable. return end commit db_session close db_...
async def removejoinchannel(self, ctx: commands.Context, channel: discord.TextChannel): db_session = self.bot.create_db_session() try: existing = db_session.query(Channel).filter(Channel.id == channel.id).one() existing.joinable = False except NoResultFound: ...
Python
nomic_cornstack_python_v1
function get_message_ids self debug=false begin call _ensure_connection end function comment Make sure there are messages in the inbox
def get_message_ids(self, debug=False): self._ensure_connection() # Make sure there are messages in the inbox
Python
nomic_cornstack_python_v1
comment coding:UTF-8 comment Author:Winyn string 定义一个列表的操作类:Listinfo 包括的方法: 1 列表元素添加: add_key(keyname) [keyname:字符串或者整数类型] 2 列表元素取值:get_key(num) [num:整数类型] 3 列表合并:update_list(list) [list:列表类型] 4 删除并且返回最后一个元素:del_key() list_info = Listinfo([44,222,111,333,454,'sss','333']) class Listinfo begin function __init__ self lis...
#coding:UTF-8 #Author:Winyn ''' 定义一个列表的操作类:Listinfo 包括的方法: 1 列表元素添加: add_key(keyname) [keyname:字符串或者整数类型] 2 列表元素取值:get_key(num) [num:整数类型] 3 列表合并:update_list(list) [list:列表类型] 4 删除并且返回最后一个元素:del_key() list_info = Listinfo([44,222,111,333,454,'sss','333']) ''' class Listinfo(): def __init__(self,list1): self...
Python
zaydzuhri_stack_edu_python
comment -*- coding:utf-8 -*- from __future__ import unicode_literals from django.db import models set WEEKDAYS = tuple tuple 0 string 日曜日 tuple 1 string 月曜日 tuple 2 string 火曜日 tuple 3 string 水曜日 tuple 4 string 木曜日 tuple 5 string 金曜日 tuple 6 string 土曜日 comment JavaScriptのDateオブジェクトの曜日IDなのでPython datetimeモジュールのweekdayとは1...
# -*- coding:utf-8 -*- from __future__ import unicode_literals from django.db import models WEEKDAYS = ( # JavaScriptのDateオブジェクトの曜日IDなのでPython datetimeモジュールのweekdayとは1ずれる(isoweekday()に近い) (0, '日曜日'), (1, '月曜日'), (2, '火曜日'), (3, '水曜日'), (4, '木曜日'), (5, '金曜日'), (6, '土曜日'), ) SHORTWEEKDAY...
Python
zaydzuhri_stack_edu_python
comment !/usr/bin/python3 comment encoding: utf-8 comment Version:1.0 by Caesar in 2/10 2020 comment 功能:使用python3分析nmea数据,统计GGA总条数,固定比,均值±2cm占比,均值±1cm占比,高程值极差 import pynmea2 import time function read filename begin comment 解析列表 set records = list comment gga语句总统计值 set gga_sumcount = 0 comment gga有效语句统计值(固定且差分延迟小于20秒) ...
#!/usr/bin/python3 # encoding: utf-8 #Version:1.0 by Caesar in 2/10 2020 #功能:使用python3分析nmea数据,统计GGA总条数,固定比,均值±2cm占比,均值±1cm占比,高程值极差 import pynmea2 import time def read(filename): records = [] #解析列表 gga_sumcount = 0 #gga语句总统计值 gga_validcount = 0 #gga有效语句统计值(固定且差分延迟小于20秒) hgts...
Python
zaydzuhri_stack_edu_python
comment -- ass4 -- use map to extract all alphabets from each string in a list. Use map and a function function ext_alpha word_str begin set new_word = string for c in word_str begin if is alpha c begin set new_word = new_word + c end end return new_word end function set words = list string Ab12c string x12y2 string s...
# -- ass4 -- use map to extract all alphabets from each string in a list. Use map and a function def ext_alpha(word_str): new_word = '' for c in word_str: if c.isalpha(): new_word += c return new_word words = ['Ab12c','x12y2','sdfds33&'] for word in words: alpha_extract =...
Python
zaydzuhri_stack_edu_python
comment -*- coding: utf-8 -*- string https://leetcode.com/problems/find-all-anagrams-in-a-string/ comment Solution 1 from collections import defaultdict class Solution extends object begin function findAnagrams self s p begin string :type s: str :type p: str :rtype: List[int] if length s < length p begin return list e...
# -*- coding: utf-8 -*- ''' https://leetcode.com/problems/find-all-anagrams-in-a-string/ ''' # Solution 1 from collections import defaultdict class Solution(object): def findAnagrams(self, s, p): """ :type s: str :type p: str :rtype: List[int] """ if len(s) < len(p)...
Python
zaydzuhri_stack_edu_python
comment !/usr/bin/python comment -*- coding: utf-8 -*- comment ### sorted() string sorted() 运行原理: 把可迭代数据里面的元素,一个一个的取出来,放到key这个函数中进行处理, 并按照函数中return的结果进行排序,返回一个新的列表 功能: 排序 参数: iterable 可迭代的数据 (容器类型数据,range数据序列,迭代器) reverse 可选,是否反转,默认为False,不反转, True反转 key 可选, 函数,可以是自定义函数,也可以是内置函数 返回值: 排序后的结果 set arr = list 3 7 1 - 9 20 ...
#!/usr/bin/python # -*- coding: utf-8 -*- # ### sorted() ''' sorted() 运行原理: 把可迭代数据里面的元素,一个一个的取出来,放到key这个函数中进行处理, 并按照函数中return的结果进行排序,返回一个新的列表 功能: 排序 参数: iterable 可迭代的数据 (容器类型数据,range数据序列,迭代器) reverse 可选,是否反转,默认为False,不反转, True反转 key 可选, 函数,可以是自定义函数,也可以是内置函数 返回值: 排序后的结果 ''' arr = [3,7,1,-9,20...
Python
zaydzuhri_stack_edu_python
function refresh request driver_config driver_secrets begin call log_debug string refresh set path = call request_path request set file_path = call path_join string / path call clear_cache file_path set cmd = none set sem = semaphore acquire sem if not exists fs file_path begin comment delete call log_debug string No l...
def refresh(request, driver_config, driver_secrets): gateway.log_debug("refresh") path = gateway.request_path(request) file_path = gateway.path_join("/", path) fs.clear_cache(file_path) cmd = None sem = threading.Semaphore() sem.acquire() if not fs.exists(file_path): # delete ...
Python
nomic_cornstack_python_v1
import sys import pkg_resources from PyQt5 import uic from PyQt5.QtWidgets import QApplication , QWidget from dto.dto_dept import Department class DepartmentContent extends QWidget begin function __init__ self parent=none begin call __init__ parent set ui_path = call resource_filename string ui string designer/content_...
import sys import pkg_resources from PyQt5 import uic from PyQt5.QtWidgets import QApplication, QWidget from dto.dto_dept import Department class DepartmentContent(QWidget): def __init__(self, parent=None): super(DepartmentContent, self).__init__(parent) ui_path = pkg_resources.resource_filenam...
Python
zaydzuhri_stack_edu_python
import queue as q set customQueue = queue maxsize=3 print call qsize put 100 put 256 put 180 print call qsize print call full print get customQueue print call qsize
import queue as q customQueue = q.Queue(maxsize=3) print(customQueue.qsize()) customQueue.put(100) customQueue.put(256) customQueue.put(180) print(customQueue.qsize()) print(customQueue.full()) print(customQueue.get()) print(customQueue.qsize())
Python
zaydzuhri_stack_edu_python
function is_ssh_enabled begin set webserver_node = call get_webserver_node info string Providing ssh enabled as response try begin comment Check SSH status if find execute utility string /bin/systemctl --no-pager status ssh shlex_split=true at 1 string active (running) > - 1 begin comment Check UFW status set stdout = ...
def is_ssh_enabled(): webserver_node = webserver_publisher_node.get_webserver_node() webserver_node.get_logger().info("Providing ssh enabled as response") try: # Check SSH status if utility.execute("/bin/systemctl --no-pager status ssh", shlex_split=True)[1].find("active (running)") > -1: ...
Python
nomic_cornstack_python_v1
function grayscale pic1 begin set pixel = list call getdata set newImg = list for i in pixel begin set grayscale = tuple integer i at 0 + i at 1 + i at 2 / 3 integer i at 0 + i at 1 + i at 2 / 3 integer i at 0 + i at 1 + i at 2 / 3 append newImg grayscale end set newImage = call new string RGB tuple 736 1189 i call pu...
def grayscale(pic1): pixel = list(pic1.getdata()) newImg = [] for i in pixel: grayscale = (int((i[0] + i[1] + i[2])/3), int((i[0] + i[1] + i[2])/3), int((i[0] + i[1] + i[2])/3)) newImg.append(grayscale) newImage = Image.new("RGB", (736, 1189), i) newImage.putdata(newImg) return n...
Python
zaydzuhri_stack_edu_python
import sys function is_sum_of n array begin set size = length array for i in range 0 size begin for j in range i + 1 size begin if n == array at i + array at j begin return 1 end end end return 0 end function function part_a filename count begin set array = list with open filename string r as f begin for line in f beg...
import sys def is_sum_of(n, array): size = len(array) for i in range(0, size): for j in range(i+1, size): if n == array[i] + array[j]: return 1 return 0 def part_a(filename, count): array = [] with open(filename, 'r') as f: for line in f: a...
Python
zaydzuhri_stack_edu_python
import unittest from sympy import Rational from peano.base_maps import BaseMap , Spec from peano.curves import Curve from peano.subsets import Point , Gate from examples import * comment some additional curves for testing function get_rev_curves begin set chain = string jiJ set bases_list = list list string ji string I...
import unittest from sympy import Rational from peano.base_maps import BaseMap, Spec from peano.curves import Curve from peano.subsets import Point, Gate from .examples import * # some additional curves for testing def get_rev_curves(): chain = 'jiJ' bases_list = [ ['ji','Ij~','ij','JI'], # time r...
Python
zaydzuhri_stack_edu_python
comment -*- coding: UTF-8 -*- import Hello import os set a = call fun1 10 20 30
# -*- coding: UTF-8 -*- import Hello import os a = Hello.fun1(10, 20, 30)
Python
zaydzuhri_stack_edu_python
comment !/usr/bin/env python3 comment -*- coding: utf-8 -*- string Created on Mon Feb 12 16:46:05 2018 @author: josharnold from data import preprocessing from model import nn comment Load data set tuple X_train y_train X_test y_test = call load_data load_char_set=false pad=25 file_name=string 9.smi comment Define model...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Mon Feb 12 16:46:05 2018 @author: josharnold """ from data import preprocessing from model import nn # Load data X_train, y_train, X_test, y_test = preprocessing.load_data(load_char_set=False, pad=25, file_name = "9.smi") # Define model model = nn(X_trai...
Python
zaydzuhri_stack_edu_python
for _ in range N begin set tuple x y = map int split input append XYs at 0 x - y append XYs at 1 x + y end print max max XYs at 0 - min XYs at 0 max XYs at 1 - min XYs at 1
for _ in range(N): x,y = map(int, input().split()) XYs[0].append(x-y) XYs[1].append(x+y) print(max(max(XYs[0])-min(XYs[0]), max(XYs[1])-min(XYs[1])))
Python
zaydzuhri_stack_edu_python
function connect_emr aws_access_key_id=none aws_secret_access_key=none **kwargs begin string :type aws_access_key_id: string :param aws_access_key_id: Your AWS Access Key ID :type aws_secret_access_key: string :param aws_secret_access_key: Your AWS Secret Access Key :rtype: :class:`boto.emr.EmrConnection` :return: A co...
def connect_emr(aws_access_key_id=None, aws_secret_access_key=None, **kwargs): """ :type aws_access_key_id: string :param aws_access_key_id: Your AWS Access Key ID :type aws_secret_access_key: string :param aws_secret_access_key: Your AWS Secret Access Key :rtype: :class:`boto.emr.EmrConnectio...
Python
jtatman_500k
function show_images images cols=1 titles=none begin assert titles is none or length images == length titles set n_images = length images if titles is none begin set titles = list comprehension string Image (%d) % i for i in range 1 n_images + 1 end set fig = figure for tuple n tuple image title in enumerate zip images...
def show_images(images, cols = 1, titles = None): assert((titles is None)or (len(images) == len(titles))) n_images = len(images) if titles is None: titles = ['Image (%d)' % i for i in range(1,n_images + 1)] fig = plt.figure() for n, (image, title) in enumerate(zip(images, titles)): a = fig.a...
Python
nomic_cornstack_python_v1
function update self input **kwargs begin set init_value = get kwargs string init_value false set match = match input if match begin debug string BinaryParameterDictVal.update(): match=<%s>, init_value=%s encode call group 1 string hex init_value set value = call f_getval match if init_value begin set init_value = valu...
def update(self, input, **kwargs): init_value = kwargs.get('init_value', False) match = self.regex.match(input) if match: log.debug('BinaryParameterDictVal.update(): match=<%s>, init_value=%s', match.group(1).encode('hex'), init_value) value = self.f_getval(match) ...
Python
nomic_cornstack_python_v1
comment encoding: utf-8 import math import Image import ImageDraw import ImageColor comment Propriétés de la scène set width = 500 comment Déformation due à la perspective set perspective = width comment Recul de la caméra set cameraZ = - width comment « Calque » pour gérer les points superposés set zBuffer = dict com...
#encoding: utf-8 import math import Image import ImageDraw import ImageColor # Propriétés de la scène width = 500 perspective = width # Déformation due à la perspective cameraZ = -width # Recul de la caméra zBuffer = {} # « Calque » pour gérer les points superposés # Création d'un objet image vide où dess...
Python
zaydzuhri_stack_edu_python
function verify_password self password begin comment Check that we're in a state to check a password. if not call check_self begin return false end set test_hash = password set true_hash = password_hash for i in range length algorithms begin set algorithm = algorithms at i set rounds = rounds at i set salt = salts at i...
def verify_password(self, password): # Check that we're in a state to check a password. if not self.check_self(): return False test_hash = password true_hash = self.password_hash for i in range(len(self.algorithms)): algorithm = self.algorithms[i] rounds = self.rounds[i] sal...
Python
nomic_cornstack_python_v1
function post_drawing_dxf self request begin set HttpRequest = call to_http_info configuration return call __make_request HttpRequest string POST string file end function
def post_drawing_dxf(self, request): HttpRequest = request.to_http_info(self.api_client.configuration) return self.__make_request(HttpRequest, 'POST', 'file')
Python
nomic_cornstack_python_v1
function verify_files folder_path begin for dataset_file in list directory folder_path begin call verify_file folder_path + dataset_file end end function
def verify_files(folder_path): for dataset_file in listdir(folder_path): verify_file(folder_path + dataset_file)
Python
nomic_cornstack_python_v1
from Vote import Vote from STV import STV import random class Tests begin function removeCandidate self input person begin set retVotes = list for vote in input begin append retVotes call Vote vote end for vote in retVotes begin set i = 0 while i < length call getList begin set j = 0 set rank = call getList at i while...
from Vote import Vote from STV import STV import random class Tests: def removeCandidate(self, input, person): retVotes = [] for vote in input: retVotes.append(Vote(vote)) for vote in retVotes: i = 0 while i < len(vote.getList()): ...
Python
zaydzuhri_stack_edu_python
from django.core.management.base import BaseCommand from vehicles.models import Manufacturer class Command extends BaseCommand begin set help = string simple command demo function add_arguments self parser begin call add_argument string number nargs=string + type=int help=string give some number(s) call add_argument st...
from django.core.management.base import BaseCommand from vehicles.models import Manufacturer class Command(BaseCommand): help = 'simple command demo' def add_arguments(self, parser): parser.add_argument('number', nargs='+', type= int, help= 'give some number(s)') parser.add_argument('--mesg...
Python
zaydzuhri_stack_edu_python
import pygame as pg comment print ('\n\n hola bebe, se que contigo no sirve la labia \n') comment a=12 comment b=2.5 comment c=a+b comment print (c) call init set pantalla = call set_mode list 600 300 comment fin = False comment while not fin: comment a= a+1 comment if a>1000: comment fin = True set fin = false set NEG...
import pygame as pg # # print ('\n\n hola bebe, se que contigo no sirve la labia \n') # a=12 # b=2.5 # c=a+b # print (c) pg.init() pantalla=pg.display.set_mode([600,300]) # fin = False # while not fin: # a= a+1 # if a>1000: # fin = True fin = False NEGRO=[0,0,0] AZUL=[0,0,255] p=[200,200] reloj=pg.time.C...
Python
zaydzuhri_stack_edu_python
comment !/bin/ipython import numpy import numpy as _np from minimalvariance import * comment quick test of limit cases should be close to 0.2 except the last one: print call minimal_variances_3 0.2 0.2 0.2 print call minimal_variances_3 0.2 0.2 10 print call minimal_variances_3 0.2 10 10 print call minimal_variances_3 ...
#!/bin/ipython import numpy import numpy as _np from minimalvariance import * #quick test of limit cases should be close to 0.2 except the last one: print(minimal_variances_3(0.2, 0.2, 0.2)) print(minimal_variances_3(0.2, 0.2, 10)) print(minimal_variances_3(0.2, 10, 10)) print(minimal_variances_3( 10, 10, 0.2)...
Python
zaydzuhri_stack_edu_python
function get self *args **kwargs begin try begin if length args not in tuple 2 3 begin raise call ValueError string Invalid URL end set module_name = string args at 1 set worker = call __get_worker module_name if not worker begin raise call KeyError string Unable to find module %s % module_name end set tenant_id = uuid...
def get(self, *args, **kwargs): try: if len(args) not in (2, 3): raise ValueError("Invalid URL") module_name = str(args[1]) worker = self.__get_worker(module_name) if not worker: raise KeyError("Unable to find module %s" % modul...
Python
nomic_cornstack_python_v1
comment Python-based application for handling a city # from CitySimulator.Building import Building from CitySimulator.Person import Person from CitySimulator.CityConf import CityConf from CitySimulator.CDC import CDC from JanusAPI.JanusServer import JanusServer import math import itertools import random import numpy as...
############################################################### #Python-based application for handling a city # ############################################################### from CitySimulator.Building import Building from CitySimulator.Person import Person from CitySimulator.CityConf import CityConf ...
Python
zaydzuhri_stack_edu_python
function fullGrid state begin return not any end function
def fullGrid(state): return not ((state[:, :, 0] + state[:, :, 1]) == 0).any()
Python
nomic_cornstack_python_v1
function use_test begin global _casda_query_base_url _casda_anon_query_base_url _casda_soda_base_url set _casda_query_base_url = _casda_base_url_vo_test set _casda_anon_query_base_url = _casda_base_url_anon_vo_test set _casda_soda_base_url = _casda_base_url_soda_test end function
def use_test(): global _casda_query_base_url, _casda_anon_query_base_url, _casda_soda_base_url _casda_query_base_url = _casda_base_url_vo_test _casda_anon_query_base_url = _casda_base_url_anon_vo_test _casda_soda_base_url = _casda_base_url_soda_test
Python
nomic_cornstack_python_v1
function _detect_by_color self blocks begin set lower_blue = array list 110 100 100 dtype=uint8 set upper_blue = array list 130 255 255 dtype=uint8 set sensitivity = 135 set lower_white = array list 0 0 255 - sensitivity set upper_white = array list 255 sensitivity 255 set hsv = call cvtColor img COLOR_BGR2HSV set prop...
def _detect_by_color(self, blocks): lower_blue = np.array([110, 100, 100], dtype=np.uint8) upper_blue = np.array([130, 255, 255], dtype=np.uint8) sensitivity = 135 lower_white = np.array([0, 0, 255 - sensitivity]) upper_white = np.array([255, sensitivity, 255]) hsv = cv...
Python
nomic_cornstack_python_v1
comment !/usr/bin/env python comment -*- coding: utf-8 -*- comment Python 2/3 compatibility imports from __future__ import print_function comment standard library imports comment for working with data file import json from threading import Thread from time import sleep comment local module imports from blinker import s...
# !/usr/bin/env python # -*- coding: utf-8 -*- # Python 2/3 compatibility imports from __future__ import print_function # standard library imports import json # for working with data file from threading import Thread from time import sleep # local module imports from blinker import signal import gv # Get access to...
Python
zaydzuhri_stack_edu_python
function RevComp seq begin set seq_dict = dict string A string T ; string T string A ; string G string C ; string C string G return join string list comprehension seq_dict at base for base in reversed strip seq end function with open string D:/python/input.txt as input_data begin set sets = list comprehension strip li...
def RevComp(seq): seq_dict = {'A':'T','T':'A','G':'C','C':'G'} return "".join([seq_dict[base] for base in reversed(seq.strip())]) with open('D:/python/input.txt') as input_data: sets = [line.strip() for line in input_data.readlines()] edges = set() for i in sets: edges.add(i) edges.add(RevComp(i))...
Python
zaydzuhri_stack_edu_python
import sys import json import datetime from urllib.request import Request , urlopen from urllib.parse import urlencode function main port username begin set args = dict set args at string timestamp = call isoformat set args at string username = username set args at string arguments = dumps args set data = url encode a...
import sys import json import datetime from urllib.request import Request, urlopen from urllib.parse import urlencode def main(port, username): args = {} args["timestamp"] = datetime.datetime.utcnow().isoformat() args["username"] = username args['arguments'] = json.dumps(args) data = urlencode(ar...
Python
zaydzuhri_stack_edu_python
comment HD map import numpy as np import os import sys import cv2 import collections import pandas as pd import argparse from traj_ext.utils import mathutil from traj_ext.tracker.cameramodel import CameraModel class RoadMark extends object begin string Raod Mark structure. Holds a list on points defining a road mark fu...
################################################################################# # # HD map # ################################################################################# import numpy as np import os import sys import cv2 import collections import pandas as pd import argparse from traj_ext.utils import mathuti...
Python
zaydzuhri_stack_edu_python
function require_consistent self begin return get pulumi self string require_consistent end function
def require_consistent(self) -> Optional[bool]: return pulumi.get(self, "require_consistent")
Python
nomic_cornstack_python_v1
for i in lst begin set total = total + i set count = count + 1 end print string list = lst print string mean = total / count comment print("mean = %f" % (total / count)) comment print("mean = %f" % (sum(lst) / len(lst)))
for i in lst: total += i count += 1 print("list = ", lst) print("mean = ", total / count) #print("mean = %f" % (total / count)) #print("mean = %f" % (sum(lst) / len(lst)))
Python
zaydzuhri_stack_edu_python
function shrink self begin comment We assume that if an all-zero block of bytes is an interesting comment example then we're not going to do better than that. comment This might not technically be true: e.g. for integers() | booleans() comment the simplest example is actually [1, 0]. Missing this case is fairly comment...
def shrink(self): # We assume that if an all-zero block of bytes is an interesting # example then we're not going to do better than that. # This might not technically be true: e.g. for integers() | booleans() # the simplest example is actually [1, 0]. Missing this case is fairly ...
Python
nomic_cornstack_python_v1
function delta self delta begin set _delta = delta end function
def delta(self, delta): self._delta = delta
Python
nomic_cornstack_python_v1
import random set desen = list string Karo string Maça string Sinek string Kupa set rakam = list range 1 14 print string ************************************ şans oyunlarına hoşgeldin 1. zar atmak 2. iskambil kağıdı seçmek 3. çıkış ************************************ while true begin set secim = input string Seçiminiz...
import random desen=["Karo","Maça","Sinek","Kupa"] rakam=list(range(1,14)) print(""" ************************************ şans oyunlarına hoşgeldin 1. zar atmak 2. iskambil kağıdı seçmek 3. çıkış ************************************ """) while True: secim=input("Seçiminiz: ") if secim...
Python
zaydzuhri_stack_edu_python
function check_value arr val begin for i in arr begin if i == val begin return true end end return false end function set arr = list 2 3 7 8 set val = 7 if call check_value arr val begin print string Array contains number + string val end else begin print string Array does not contain number + string val end
def check_value(arr, val): for i in arr: if i == val: return True return False arr = [2, 3, 7, 8] val = 7 if(check_value(arr, val)): print("Array contains number " + str(val)) else: print("Array does not contain number " + str(val))
Python
flytech_python_25k
function sector_wipeout radar field_sector sector begin set sector_wipeout = ones tuple nrays ngates dtype=int comment check for altitude limits if sector at string hmin is not none begin set sector_wipeout at gate_altitude at string data < sector at string hmin = 0 end if sector at string hmax is not none begin set se...
def sector_wipeout(radar, field_sector, sector): sector_wipeout = np.ma.ones((radar.nrays, radar.ngates), dtype=int) # check for altitude limits if sector['hmin'] is not None: sector_wipeout[radar.gate_altitude['data'] < sector['hmin']] = 0 if sector['hmax'] is not None: sector_wipeou...
Python
nomic_cornstack_python_v1
function rename_key cell_dict begin for table_name in keys cell_dict begin set cell_dict at table_name at string cells_list = pop cell_dict at table_name string bbox_predictions end return cell_dict end function
def rename_key(cell_dict): for table_name in cell_dict.keys(): cell_dict[table_name]["cells_list"] = cell_dict[table_name].pop( "bbox_predictions") return cell_dict
Python
nomic_cornstack_python_v1
import sys from urllib2 import Request , urlopen , URLError , HTTPError import time import re comment Class will get the html doc file listing for a URL and then allow a file by file pulling down of the comment data. Can be made "smart" by using the fetch log which will keep track of what files have been pulled and com...
import sys from urllib2 import Request, urlopen, URLError, HTTPError import time import re #################################################################################################################### # Class will get the html doc file listing for a URL and then allow a file by file pulling down of the # data....
Python
zaydzuhri_stack_edu_python
function create_connection db_file begin set conn = none try begin set conn = call connect db_file set db_name = split db_file string \ at - 1 print string Connected to { db_name } 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) db_name = db_file.split("\\")[-1] print(f"Connected to {db_name}") except Error as e: print(e) return conn
Python
nomic_cornstack_python_v1
function Overlap a b min_length=3 begin set start = 0 while true begin comment look for b's prefix in a comment Python Docs: string.find(value, start, end) set start = find a b at slice : min_length : start if start == - 1 begin return 0 end if starts with b a at slice start : : begin return length a - start end set...
def Overlap(a, b, min_length=3): start = 0 while True: # look for b's prefix in a start = a.find(b[:min_length], start) # Python Docs: string.find(value, start, end) if start == -1: return 0 if b.startswith(a[start:]): return len(a) - start start...
Python
nomic_cornstack_python_v1
function printMyname x y z begin print string Einat print x y z end function function run begin return 0 end function
def printMyname(x, y , z): print('Einat') print (x, y, z) def run(): return 0
Python
zaydzuhri_stack_edu_python
comment !/usr/bin/env python3 import tkinter as tk from tkinter import simpledialog as sd from tkinter import messagebox as mb from json import dump from json import loads function agregar begin set datos = dict set datos at string nombre = call askstring string Datos Personales string Ingrese su nombre set datos at s...
#!/usr/bin/env python3 import tkinter as tk from tkinter import simpledialog as sd from tkinter import messagebox as mb from json import dump from json import loads def agregar(): datos = {} datos["nombre"] = sd.askstring("Datos Personales", "Ingrese su nombre") datos["apellido"] = sd.askstring("Datos Personal...
Python
zaydzuhri_stack_edu_python
function learn_denoising_model num_res_blocks=5 quick_mode=false begin function corruption_func im begin return call add_gaussian_noise im LDN_MIN_SIG LDN_MAX_SIG end function set images = call images_for_denoising set model = call build_nn_model LDN_PATCH_SIZE LDN_PATCH_SIZE LDN_CHANNELS num_res_blocks if quick_mode b...
def learn_denoising_model(num_res_blocks=5, quick_mode=False): def corruption_func(im): return add_gaussian_noise(im, LDN_MIN_SIG, LDN_MAX_SIG) images = sol5_utils.images_for_denoising() model = build_nn_model(LDN_PATCH_SIZE, LDN_PATCH_SIZE, LDN_CHANNELS, num_res_blocks) if quick_mode: train_m...
Python
nomic_cornstack_python_v1
string Task 4 We took a little look on os module. Write a small script which will print a string using all the types of string formatting which were considered during the lecture with the following context: This script has the following PID: <ACTUAL_PID_HERE>. It was ran by <ACTUAL_USERNAME_HERE> to work happily on <AC...
""" Task 4 We took a little look on os module. Write a small script which will print a string using all the types of string formatting which were considered during the lecture with the following context: This script has the following PID: <ACTUAL_PID_HERE>. It was ran by <ACTUAL_USERNAME_HERE> to work happily on <ACTUA...
Python
zaydzuhri_stack_edu_python
function _get_host_qat_device_config self pci_device_list begin set device_config = dict set qat_c62x_devices = pci_device_list at NOVA_PCI_ALIAS_QAT_C62X_PF_DEVICE if length qat_c62x_devices != 0 begin for tuple idx device in enumerate qat_c62x_devices begin set name = string pci-%s % pciaddr set dev = dict string qa...
def _get_host_qat_device_config(self, pci_device_list): device_config = {} qat_c62x_devices = pci_device_list[constants.NOVA_PCI_ALIAS_QAT_C62X_PF_DEVICE] if len(qat_c62x_devices) != 0: for idx, device in enumerate(qat_c62x_devices): name = 'pci-%s' % device.pciaddr ...
Python
nomic_cornstack_python_v1
function info rom begin set rom = call ROM rom detect=true end function
def info(rom): rom = ROM(rom, detect=True)
Python
nomic_cornstack_python_v1
function __le__ self other begin return min timestamps <= min timestamps end function
def __le__(self, other): return min(self.timestamps) <= min(other.timestamps)
Python
nomic_cornstack_python_v1
comment ObliqueTriangle Connect Anti-ObliqueTriangle comment Input:3 comment |OUTPUT| comment |* | comment |** | comment |*** | comment | ** | comment | * | set ipt = integer input for i in range ipt begin for j in range i + 1 begin print string * end=string end print end for i in range ipt - 1 begin for j in range i +...
#ObliqueTriangle Connect Anti-ObliqueTriangle # #Input:3 # #|OUTPUT| #|* | #|** | #|*** | #| ** | #| * | ipt = int(input()) for i in range (ipt): for j in range (i+1): print("*",end = "") print() for i in range (ipt-1): for j in range (i+1): print(" ",end = "") for j in range (ipt-(i+1)): print(...
Python
zaydzuhri_stack_edu_python
function verifyTradeRecord3 self record begin comment there should be 10 fields assert equal length record 10 assert equal string COH4 Comdty record at string BloombergTicker assert equal string Cover record at string Side assert equal 1 record at string Quantity call assertAlmostEqual 106.95 record at string Price ass...
def verifyTradeRecord3(self, record): self.assertEqual(len(record), 10) # there should be 10 fields self.assertEqual('COH4 Comdty', record['BloombergTicker']) self.assertEqual('Cover', record['Side']) self.assertEqual(1, record['Quantity']) self.assertAlmostEqual(106.95, record...
Python
nomic_cornstack_python_v1
function _format_line self line begin set bi_reg = compile string ([^\\]|^)(\*{3}.*?[^ \\]\*{3}) set bd_reg = compile string ([^\\]|^)(\*{2}.*?[^ \\]\*{2}) set it_reg = compile string ([^\\]|^)(\*.*[^ \\]\*) set ul_reg = compile string ([^\\]|^)(_.*[^ \\]_) set regs = list bi_reg bd_reg it_reg ul_reg set subs = list li...
def _format_line(self, line): bi_reg = re.compile(r"([^\\]|^)(\*{3}.*?[^ \\]\*{3})") bd_reg = re.compile(r"([^\\]|^)(\*{2}.*?[^ \\]\*{2})") it_reg = re.compile(r"([^\\]|^)(\*.*[^ \\]\*)") ul_reg = re.compile(r"([^\\]|^)(_.*[^ \\]_)") regs = [bi_reg, bd_reg, it_reg, ul_reg] ...
Python
nomic_cornstack_python_v1
comment Создайте класс Pizza, который принимает список ингредиентов. comment Класс поддерживает: comment атрибут order_number, который возвращает текущий номер заказа comment (подсказка: используйте статический атрибут в качестве сквозного счётчика) comment атрибут ingredients, который возвращает список, принятый в кон...
# Создайте класс Pizza, который принимает список ингредиентов. # Класс поддерживает: # атрибут order_number, который возвращает текущий номер заказа # (подсказка: используйте статический атрибут в качестве сквозного счётчика) # атрибут ingredients, который возвращает список, принятый в конструкторе # функции (gard...
Python
zaydzuhri_stack_edu_python
import requests import pprint import flask import flask_sqlalchemy import flask_restless from io import StringIO comment http://127.0.0.1:5000/api/v1/news comment Create the Flask application and the Flask-SQLAlchemy object. set app = call Flask __name__ set config at string DEBUG = true set config at string SQLALCHEMY...
import requests import pprint import flask import flask_sqlalchemy import flask_restless from io import StringIO # http://127.0.0.1:5000/api/v1/news # Create the Flask application and the Flask-SQLAlchemy object. app = flask.Flask(__name__) app.config['DEBUG'] = True app.config['SQLALCHEMY_DATABASE_URI'] = 'mysql+py...
Python
zaydzuhri_stack_edu_python
function clearCache *args allNodes=true computed=true dirty=true **kwargs begin pass end function
def clearCache(*args, allNodes: bool=True, computed: bool=True, dirty: bool=True, **kwargs)->int: pass
Python
nomic_cornstack_python_v1
from tkinter import * import wikipedia from tkinter.font import Font function get_data begin set srch_data = get data delete 1.0 END try begin set ans_val = call summary srch_data insert ans INSERT ans_val end except any begin insert ans INSERT string Please check your string or internet connection end end function set...
from tkinter import * import wikipedia from tkinter.font import Font def get_data(): srch_data = data.get() ans.delete(1.0, END) try: ans_val = wikipedia.summary(srch_data) ans.insert(INSERT, ans_val) except: ans.insert(INSERT,"Please check your string or internet connection") ...
Python
zaydzuhri_stack_edu_python
function nombres1 begin global v call withdraw set n = call Toplevel v set canvas2 = call Canvas n width=800 height=630 set nombres = call PhotoImage file=string N1.png call create_image 400 315 image=nombres call focus_set call pack function juego2 begin string esta funcion inicia el juego en el modo un jugador set no...
def nombres1(): global v m.withdraw() n=tkinter.Toplevel(v) canvas2 = tkinter.Canvas(n,width=800,height=630) nombres=tkinter.PhotoImage(file='N1.png') canvas2.create_image(400,315, image=nombres) canvas2.focus_set() canvas2.pack() def jueg...
Python
nomic_cornstack_python_v1