code
stringlengths
10
2.58M
original_code
stringlengths
3
3.18M
original_language
stringclasses
1 value
source
stringclasses
7 values
set slist = list string 영어 string 국어 string Math 4 10 append slist 30 print slist print slist at 2
slist = ["영어", "국어", "Math", 4, 10] slist.append(30) print(slist) print(slist[2])
Python
zaydzuhri_stack_edu_python
function exec_in_context self arg begin comment contains elaborate scheme to detect what is specified by comment -s, and to warn about any replacement set current_ids = dictionary list comprehension tuple k call id v for tuple k v in items context end function
def exec_in_context(self,arg): ## contains elaborate scheme to detect what is specified by ## -s, and to warn about any replacement current_ids = dict([(k,id(v)) for k,v in self.context.items()])
Python
nomic_cornstack_python_v1
function check_bullet_ship_collisions ai_settings screen stats sb ship aliens bullets crash begin comment remove any bullets and aliens that have collided comment collisions = pygame.sprite.groupcollide(bullets, ship, True, True) set collisions = call spritecollide ship bullets true if collisions begin call ship_hit ai...
def check_bullet_ship_collisions(ai_settings, screen,stats, sb, ship, aliens, bullets,crash): #remove any bullets and aliens that have collided #collisions = pygame.sprite.groupcollide(bullets, ship, True, True) collisions = pygame.sprite.spritecollide(ship, bullets, True) if collisions: sh...
Python
nomic_cornstack_python_v1
function clear_temp_traject settings m=none k=none begin if m is none begin set m = range call count_morphs settings end if k is none begin set k = range length settings at string keyframes end for mm in m begin set search = join path settings at string temppath format string m{0:03d} mm + 1 string m*.* set hitlist = g...
def clear_temp_traject(settings, m=None, k=None): if m is None: m = range(count_morphs(settings)) if k is None: k = range(len(settings['keyframes'])) for mm in m: search = path.join(settings['temppath'], 'm{0:03d}'.format(mm + 1), 'm*.*') hitlist = glob(search...
Python
nomic_cornstack_python_v1
comment coding=utf-8 string Exposes a simple HTTP API to search a users Gists via a regular expression. Github provides the Gist service as a pastebin analog for sharing code and other develpment artifacts. See http://gist.github.com for details. This module implements a Flask server exposing two endpoints: a simple pi...
# coding=utf-8 """ Exposes a simple HTTP API to search a users Gists via a regular expression. Github provides the Gist service as a pastebin analog for sharing code and other develpment artifacts. See http://gist.github.com for details. This module implements a Flask server exposing two endpoints: a simple ping end...
Python
zaydzuhri_stack_edu_python
function get_folds X y k begin comment temporarily change the 1/-1 nature of y to 1/0 set _y = y + 1 / 2 comment partition the examples into postive and negative sets set positive_indices = where _y at 0 set negative_indices = where _y - 1 at 0 assert length positive_indices + length negative_indices == length y commen...
def get_folds(X, y, k): # temporarily change the 1/-1 nature of y to 1/0 _y = (y + 1) / 2 # partition the examples into postive and negative sets positive_indices = np.where(_y)[0] negative_indices = np.where(_y - 1)[0] assert len(positive_indices) + len(negative_indices) == len(y) # shuffl...
Python
nomic_cornstack_python_v1
import os import glob comment takes us into the folder set path = string fasta_problem
import os import glob path = 'fasta_problem' #takes us into the folder
Python
zaydzuhri_stack_edu_python
function calculate_feature eegs window_size step_size feature sensor1=- 1 sensor2=- 1 seizure=- 1 begin set feature_signals = list set signal2 = none if seizure != - 1 begin set eegs = list eegs at seizure end for seizure_eegs in eegs begin set seizure_feature_signals = list for eeg in seizure_eegs begin if sensor1 !...
def calculate_feature(eegs, window_size, step_size, feature, sensor1=-1, sensor2=-1, seizure=-1): feature_signals = [] signal2=None if seizure != -1: eegs = [eegs[seizure]] for seizure_eegs in eegs: seizure_feature_signals = [] for eeg in seizure_eegs: ...
Python
nomic_cornstack_python_v1
function print_txt txtfile path_type begin if path_type not in list string npc string room string misc string art begin raise call ValueError string Arg path_type must be either 'art', 'npc', 'room', 'misc' end else if path_type == string art begin set path = call resolve end else if path_type == string misc begin set ...
def print_txt(txtfile, path_type): if path_type not in ['npc', 'room', 'misc', 'art']: raise ValueError("Arg path_type must be either 'art', 'npc', 'room', 'misc'") elif path_type == 'art': path = Path_art_txt.joinpath(f'{txtfile}.txt').resolve() elif path_type == 'misc': p...
Python
nomic_cornstack_python_v1
class node begin function __init__ self begin set b = 0 set w = 0 set ub = 0 set item = 0 set path = list set left = none set right = none end function end class function upperBound item b w begin set WtR = CAP - w set BenT = b set WtT = w for i in range item length items_b begin if WtT >= CAP begin break end set frac...
class node: def __init__(self): self.b = 0 self.w = 0 self.ub = 0 self.item = 0 self.path = [] self.left = None self.right = None def upperBound(item,b,w): WtR = CAP - w BenT = b WtT = w for i in range(item,len(items_b)): ...
Python
zaydzuhri_stack_edu_python
function __init__ self in_channels conv_channels mlp_channels depth kernel_size=3 patch_size=2 dropout=0.0 activation=string SiLU begin call __init__ set tuple patch_w patch_h = if expression is instance patch_size int then tuple patch_size patch_size else patch_size set conv1_nxn = call Conv in_channels in_channels ke...
def __init__( self, in_channels: int, conv_channels: int, mlp_channels: int, depth: int, kernel_size: int = 3, patch_size: Union[int, Tuple[int, int]] = 2, dropout: float = 0.0, activation: Union[str, None] = "SiLU", ) -> None: super()....
Python
nomic_cornstack_python_v1
function env_prefix self path begin if is_default begin comment FIXME: Is this guaranteed to be the right one? return root end return join sep list path PROJECT_ENVS_FOLDER default_environment end function
def env_prefix(self, path): if self.is_default: return self.root # FIXME: Is this guaranteed to be the right one? return os.sep.join([path, PROJECT_ENVS_FOLDER, self.default_environment])
Python
nomic_cornstack_python_v1
import serial , time set arduino = call Serial string COM4 9600 sleep 2 set rawString = read line arduino print rawString close arduino
import serial, time arduino = serial.Serial('COM4', 9600) time.sleep(2) rawString = arduino.readline() print(rawString) arduino.close()
Python
zaydzuhri_stack_edu_python
function zabbix_server_get begin if url in keys ZABBIX_SERVERS begin return options at url end else begin error format string ERROR: No zabbix_server know to reload for {0}. url end end function
def zabbix_server_get(): if ( args.url in ZABBIX_SERVERS.keys() ): return options[args.url] else: logger.error('ERROR: No zabbix_server know to reload for {0}.'.format(args.url))
Python
nomic_cornstack_python_v1
comment -*- coding: utf-8 -*- comment import click comment import logging import requests import os import time import praw import json from pathlib import Path from dotenv import find_dotenv , load_dotenv comment @click.command() function main proj_root begin string Runs data downloading scripts to get raw data (../ra...
# -*- coding: utf-8 -*- # import click # import logging import requests import os import time import praw import json from pathlib import Path from dotenv import find_dotenv, load_dotenv # @click.command() def main(proj_root): """ Runs data downloading scripts to get raw data (../raw). """ print("========...
Python
zaydzuhri_stack_edu_python
function _generate_barcode_ids info_iter begin set bc_type = string SampleSheet set barcodes = list set list comprehension x at - 1 for x in info_iter sort barcodes set barcode_ids = dict for tuple i bc in enumerate barcodes begin set barcode_ids at bc = tuple bc_type i + 1 end return barcode_ids end function
def _generate_barcode_ids(info_iter): bc_type = "SampleSheet" barcodes = list(set([x[-1] for x in info_iter])) barcodes.sort() barcode_ids = {} for i, bc in enumerate(barcodes): barcode_ids[bc] = (bc_type, i+1) return barcode_ids
Python
nomic_cornstack_python_v1
function waitonwalk pidevice channels timeout=300 predelay=0 postdelay=0 polldelay=0.1 begin if not call isdeviceavailable list GCS2Commands GCS21Commands pidevice begin raise call TypeError string Type %s of pidevice is not supported! % __name__ end set channels = if expression is instance channels tuple list set tupl...
def waitonwalk(pidevice, channels, timeout=300, predelay=0, postdelay=0, polldelay=0.1): if not isdeviceavailable([GCS2Commands, GCS21Commands], pidevice): raise TypeError('Type %s of pidevice is not supported!' % type(pidevice).__name__) channels = channels if isinstance(channels, (list, set, tuple)) ...
Python
nomic_cornstack_python_v1
function default_option self begin set LIMIT_START_TAKE_ACTION = integer weapon_cost at 12 at 2 print string Limit to buy has been set to default { LIMIT_START_TAKE_ACTION } set chosen = buy_weapons_defence end function
def default_option(self): self.LIMIT_START_TAKE_ACTION = int(self.weapon_cost[12][2]) print(f"Limit to buy has been set to default {self.LIMIT_START_TAKE_ACTION}") self.chosen = self.buy_weapons_defence
Python
nomic_cornstack_python_v1
function getCorpusOfTweets self folderPath begin set tweets = list call getTweet folderPath set id2tweets = dictionary enumerate tweets call dumpJson join path folderPath string final string id2tweets_total.json id2tweets print string id2tweets_total.json has been saved. set tokens = list for tweet in tweets begin set...
def getCorpusOfTweets(self, folderPath): tweets = list(self.helper.getTweet(folderPath)) id2tweets = dict(enumerate(tweets)) self.helper.dumpJson(os.path.join(folderPath, "final"), "id2tweets_total.json", id2tweets) print("id2tweets_total.json has been saved.") tokens = [] ...
Python
nomic_cornstack_python_v1
function visit visitor node begin assert is instance visitor DocxTranslator assert is instance node Node if not p begin set p = call _add_paragraph style=p_style end if is instance parent list_item begin if is_first_list_item begin call _multilevel_list_numbering p p_level - 1 numIds at - 1 end else begin call _multile...
def visit(visitor: DocxTranslator, node: Node): assert isinstance(visitor, DocxTranslator) assert isinstance(node, Node) if not visitor.p: visitor.p = visitor._add_paragraph(style=visitor.p_style) if isinstance(node.parent, nodes.list_item): if visitor.is_first_list_item: v...
Python
nomic_cornstack_python_v1
set valor_uno = 10 set valor_dos = string codi set valor_tres = 10 * 20 print valor_uno print valor_dos print valor_tres
valor_uno = 10 valor_dos = "codi" valor_tres = 10 * 20 print(valor_uno) print(valor_dos) print(valor_tres)
Python
zaydzuhri_stack_edu_python
comment !/usr/bin/python comment Filename: chasanjiao.py from time import time import itertools set t1 = time set n = 5 set k = n * n + 1 / 2 function fun a begin set t = a for i in range n begin yield t set t = list comprehension absolute t at i - t at i - 1 for i in range 1 length t end end function function main beg...
#!/usr/bin/python #Filename: chasanjiao.py from time import time import itertools t1=time() n=5 k=n*(n+1)/2 def fun(a): t=a for i in range(n): yield t t=[abs(t[i]-t[i-1]) for i in range(1,len(t))] def main(): for i in itertools.permutations(range(1, k+1), n): t=list(fun(i)) ...
Python
zaydzuhri_stack_edu_python
comment !/usr/bin/python comment coding=UTF-8 from config import info import collections import itertools import operator from random import randint
#!/usr/bin/python # coding=UTF-8 from config import info import collections import itertools import operator from random import randint
Python
zaydzuhri_stack_edu_python
function test_crawl_repositories begin set params = input_values set params at string type = string repositories set raw = call get_raw_html search_type=get params string type search_keywords=params at string keywords gh_crawler=github_crawler assert is instance raw str set url_list = call get_url_list raw_search_html=...
def test_crawl_repositories(): params = input_values params['type'] = 'repositories' raw = get_raw_html(search_type=params.get('type'), search_keywords=params['keywords'], gh_crawler=github_crawler) assert isinstance(raw, str) url_list = get_url_list(raw...
Python
nomic_cornstack_python_v1
async function delete_user_ranking_admin_v3_async leaderboard_code user_id namespace=none x_additional_headers=none **kwargs begin if namespace is none begin set tuple namespace error = call get_services_namespace if error begin return tuple none error end end set request = call create leaderboard_code=leaderboard_code...
async def delete_user_ranking_admin_v3_async( leaderboard_code: str, user_id: str, namespace: Optional[str] = None, x_additional_headers: Optional[Dict[str, str]] = None, **kwargs ): if namespace is None: namespace, error = get_services_namespace() if error: return No...
Python
nomic_cornstack_python_v1
function _rotate img angle begin string angle [DEG] set s = shape if angle == 0 begin return img end else begin set M = call getRotationMatrix2D tuple s at 1 // 2 s at 0 // 2 angle 1 return call warpAffine img M tuple s at 1 s at 0 end end function
def _rotate(img, angle): ''' angle [DEG] ''' s = img.shape if angle == 0: return img else: M = cv2.getRotationMatrix2D((s[1] // 2, s[0] // 2), angle, 1) return cv2.warpAffine(img, M, (s...
Python
jtatman_500k
function zero_gradients architecture begin set grad_weights = dict set grad_bias = dict comment Initialising first and second moments for each gradient and bias matrix in each layer set m = dict set v = dict for layer in range length architecture begin set weightsi = architecture at format string layer{} layer + 1 ...
def zero_gradients(architecture): grad_weights = {} grad_bias = {} # Initialising first and second moments for each gradient and bias matrix in each layer m = {} v = {} for layer in range(len(architecture)): weightsi = architecture['layer{}'.format(layer+1)][2] biasi ...
Python
nomic_cornstack_python_v1
if total >= 24000 begin print string Total price is %.2f baht. % total print string You've got a discount of %.2f baht. % discount print string Your payment is %.2f baht. Thank you! % total - discount end else begin print string Total price is %.2f baht. % total print string Your payment is %.2f baht. Thank you! % tota...
if total >= 24000: print("Total price is %.2f baht." % total) print("You've got a discount of %.2f baht." % discount) print("Your payment is %.2f baht. Thank you!" % (total - discount)) else: print("Total price is %.2f baht." % total) print("Your payment is %.2f baht. Thank you!" % total)
Python
zaydzuhri_stack_edu_python
import os import pytest from mtg_draft_ai.brains import all_common_neighbors from mtg_draft_ai.api import * from import TEST_DATA_DIR decorator fixture comment Cards: comment Abzan Battle Priest, Ajani's Pridemate, Lightning Helix, "Ayli, Eternal Pilgrim", comment Tuskguard Captain, Swift Justice function cards begin ...
import os import pytest from mtg_draft_ai.brains import all_common_neighbors from mtg_draft_ai.api import * from .. import TEST_DATA_DIR # Cards: # Abzan Battle Priest, Ajani's Pridemate, Lightning Helix, "Ayli, Eternal Pilgrim", # Tuskguard Captain, Swift Justice @pytest.fixture def cards(): file_path = os.path....
Python
zaydzuhri_stack_edu_python
function write_output output_path out_lines begin if output_path is not none begin try begin set output_handle = open output_path string w end except OSError begin write stderr format string Error! Unable to open output file: {0} output_path exit 1 end write output_handle join string out_lines close output_handle end ...
def write_output(output_path, out_lines): if output_path is not None: try: output_handle = open(output_path, 'w') except OSError: sys.stderr.write('Error! Unable to open output file:\n{0}\n'.format(output_path)) sys.exit(1) output_handle.write('\n'.join(ou...
Python
nomic_cornstack_python_v1
string meetup.py: Program to calculate the date of meetups. import calendar from datetime import date set DAYS = dict string Monday 0 ; string Tuesday 1 ; string Wednesday 2 ; string Thursday 3 ; string Friday 4 ; string Saturday 5 ; string Sunday 6 set WEEKS = dict string 1st 0 ; string 2nd 1 ; string 3rd 2 ; string 4...
""" meetup.py: Program to calculate the date of meetups. """ import calendar from datetime import date DAYS = { 'Monday': 0, 'Tuesday': 1, 'Wednesday': 2, 'Thursday': 3, 'Friday': 4, 'Saturday': 5, 'Sunday': 6, } WEEKS = { '1st': 0, '2nd': 1, '3rd': 2, '4th': 3, } def mee...
Python
zaydzuhri_stack_edu_python
from dijkstra.inner_dijkstra import inner_dijkstra from dijkstra.graph import Graph from dijkstra.graph import default_destination_vertex_extract from dijkstra.graph import default_weight_extract from dijkstra.algo import default_add_edge_to_distance from dijkstra.algo import default_compare_distance from dijkstra.heap...
from dijkstra.inner_dijkstra import inner_dijkstra from dijkstra.graph import Graph from dijkstra.graph import default_destination_vertex_extract from dijkstra.graph import default_weight_extract from dijkstra.algo import default_add_edge_to_distance from dijkstra.algo import default_compare_distance from dijkstra.h...
Python
zaydzuhri_stack_edu_python
function edit_file_delete request code begin comment Decision of where to go back after or instead of removal set return_url = reverse string mdtui-home if string edit_return in session begin set return_url = session at string edit_return end if method == string POST begin set revision = get POST string revision false ...
def edit_file_delete(request, code): # Decision of where to go back after or instead of removal return_url = reverse('mdtui-home') if 'edit_return' in request.session: return_url = request.session['edit_return'] if request.method == 'POST': revision = request.POST.get('revision', False) ...
Python
nomic_cornstack_python_v1
import os , json from azureml.core import Workspace from azureml.core import Experiment from azureml.core.model import Model import azureml.core from azureml.core import Run from azureml.core.authentication import AzureCliAuthentication set cli_auth = call AzureCliAuthentication comment Get workspace set ws = call from...
import os, json from azureml.core import Workspace from azureml.core import Experiment from azureml.core.model import Model import azureml.core from azureml.core import Run from azureml.core.authentication import AzureCliAuthentication cli_auth = AzureCliAuthentication() # Get workspace ws = Workspace.from_config(auth...
Python
zaydzuhri_stack_edu_python
import requests from bs4 import BeautifulSoup set lookup = input string 输入代码: set headers = dict string User-Agent string Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/30.0.1599.101 Safari/537.36 set rs = get requests string https://finance.yahoo.com/quote/%s/history?p=%s % tuple loo...
import requests from bs4 import BeautifulSoup lookup = input("输入代码:") headers = { 'User-Agent':'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/30.0.1599.101 Safari/537.36', } rs = requests.get('https://finance.yahoo.com/quote/%s/history?p=%s' % (lookup,lookup), headers=headers)...
Python
zaydzuhri_stack_edu_python
function name self begin return _name end function
def name(self): return self._name
Python
nomic_cornstack_python_v1
function get_players_choices game_id begin set all_players = call get_all_players game_id set players_choice = dict for player_username in all_players begin set p_choice = call round_choices game_id string { player_username } _chosen if not p_choice begin set p_choice = string čaka na izbiro end else begin set p_choic...
def get_players_choices(game_id: int) -> dict: all_players = get_all_players(game_id) players_choice = {} for player_username in all_players: p_choice = RedisGetter.round_choices(game_id, f'{player_username}_chosen') if not p_choice: p_choice = 'čaka na izbiro' else: ...
Python
nomic_cornstack_python_v1
class Dog begin set tricks = list function __init__ self name begin set name = name end function function add_trick self trick begin append tricks trick end function end class set d1 = call Dog string Brave call add_trick string trick1 print tricks set d2 = call Dog string Shy call add_trick string trick2 print tricks...
class Dog: tricks = [] def __init__(self, name): self.name = name def add_trick(self, trick): self.tricks.append(trick) d1 = Dog('Brave') d1.add_trick("trick1") print(d1.tricks) d2 = Dog('Shy') d2.add_trick("trick2") print(d2.tricks) print(d1.tricks)
Python
zaydzuhri_stack_edu_python
import os from analyzer import analyze_and_respond function start update context begin print string [telegram_core][responder]Handling start command from: { id } call reply_text string Вітаю! Для отримання інформації відправте зображення. Бажано документом. end function function handle_image_as_picture update context b...
import os from analyzer import analyze_and_respond def start(update, context): print(f'[telegram_core][responder]Handling start command from: {update.effective_user.id}') update.message.reply_text('Вітаю! Для отримання інформації відправте зображення. Бажано документом.') def handle_image_as_picture(update...
Python
zaydzuhri_stack_edu_python
function genotype_code gt begin if gt is none begin set result = call Genotype list end else if any generator expression allele is none for allele in gt begin set result = call Genotype list end else begin comment type: ignore set result = call Genotype list comprehension allele for allele in gt end return result end f...
def genotype_code(gt: Optional[Tuple[Optional[int], ...]]) -> Genotype: if gt is None: result = Genotype([]) elif any(allele is None for allele in gt): result = Genotype([]) else: result = Genotype([allele for allele in gt]) # type: ignore return result
Python
nomic_cornstack_python_v1
comment -*- coding: utf-8 -*- string Created on Sun Jun 9 23:23:18 2019 @author: HP function isBalanced s begin set stack = list if s at 0 == string } or s at 0 == string ) or s at 0 == string ] begin return string NO end if s at - 1 == string { or s at - 1 == string [ or s at - 1 == string ( begin return string NO en...
# -*- coding: utf-8 -*- """ Created on Sun Jun 9 23:23:18 2019 @author: HP """ def isBalanced(s): stack = [] if(s[0] == '}' or s[0] == ')' or s[0] == ']'): return 'NO' if(s[-1] == '{' or s[-1] == '[' or s[-1] == '('): return 'NO' for char in s: if(char == '{' or char ==...
Python
zaydzuhri_stack_edu_python
function GetViewXform self begin return call _ApplyTypes_ 63 1 tuple 12 0 tuple string GetViewXform none end function
def GetViewXform(self): return self._ApplyTypes_(63, 1, (12, 0), (), u'GetViewXform', None,)
Python
nomic_cornstack_python_v1
comment collection of pre-embeddings available for use inside the model import os from register_embeddings import RegisterEmbedding from base_embedding import BaseEmbedding import numpy as np set SAVEFOLDER = string embeddings_data/ if not exists path SAVEFOLDER begin make directory os SAVEFOLDER end function download ...
# collection of pre-embeddings available for use inside the model import os from ..register_embeddings import RegisterEmbedding from ..base_embedding import BaseEmbedding import numpy as np SAVEFOLDER = 'embeddings_data/' if not os.path.exists(SAVEFOLDER): os.mkdir(SAVEFOLDER) def download(url, savelocation):...
Python
zaydzuhri_stack_edu_python
function authenticate_with_dopeauth email uid token strictAuth=true begin global DOPEAUTH_CACHE global DOPEAUTH_CACHE_STRICT if not strictAuth and uid + string ___ + token in DOPEAUTH_CACHE begin return email == DOPEAUTH_CACHE at uid + string ___ + token end if strictAuth and uid + string ___ + token in DOPEAUTH_CACHE_...
def authenticate_with_dopeauth(email, uid, token, strictAuth=True): global DOPEAUTH_CACHE global DOPEAUTH_CACHE_STRICT if (not strictAuth and uid + "___" + token in DOPEAUTH_CACHE): return email == DOPEAUTH_CACHE[uid + "___" + token] if (strictAuth and uid + "___" + token in DOPEAUTH_CACHE_STRI...
Python
nomic_cornstack_python_v1
from socket import * import sys import re comment 客户端登录部分 function do_login s begin while true begin set usrname = input string 请输入用户名: set passwd = input string 请输入密码: set l1 = find all string [^0-9A-Za-z] usrname set l2 = find all string [^0-9A-Za-z] passwd if l1 == list and l2 == list begin set msg = string #lgin#...
from socket import * import sys import re ## 客户端登录部分 def do_login(s): while True: usrname = input('请输入用户名:') passwd = input('请输入密码:') l1 = re.findall(r'[^0-9A-Za-z]', usrname) l2 = re.findall(r'[^0-9A-Za-z]', passwd) if l1 == [] and l2 == []: msg = '#lgin#%s$%s' ...
Python
zaydzuhri_stack_edu_python
function _Call self command retry=5 wait=5 **kwargs begin comment modules: import os import subprocess import time comment info ... info string call command: %s % string command comment run: set attempt = 1 while true begin comment info ... info string attempt %i ... % attempt comment run and obtain output and error: s...
def _Call( self, command, retry=5, wait=5, **kwargs ) : # modules: import os import subprocess import time # info ... self.info( 'call command: %s' % str(command) ) # run: attempt = 1 while True : # i...
Python
nomic_cornstack_python_v1
function embed_urls self urls model=none local_ids=none meta=none begin return call _multi_dataurl_op urls list string embed model=model local_ids=local_ids meta=meta end function
def embed_urls(self, urls, model=None, local_ids=None, meta=None): return self._multi_dataurl_op(urls, ['embed'], model=model, local_ids=local_ids, meta=meta)
Python
nomic_cornstack_python_v1
comment !/usr/bin/env python string Given pdb trajectories, perform FAST analysis. set __author__ = string Wang Zongan set __version__ = string 2016-09-05 import os import sys import string import numpy as np import pandas as pd import cPickle as cp import mdtraj as md import seaborn as sns call set_style style=string ...
#!/usr/bin/env python ''' Given pdb trajectories, perform FAST analysis. ''' __author__ = 'Wang Zongan' __version__ = '2016-09-05' import os import sys import string import numpy as np import pandas as pd import cPickle as cp import mdtraj as md import seaborn as sns sns.set_style(style='white') from matplotlib.pyplo...
Python
zaydzuhri_stack_edu_python
function __init__ self ha=none bufsize=1024 wlog=none begin set ha = ha set bs = bufsize set wlog = wlog comment Mailslot needs to be opened set ms = none set opened = false end function
def __init__(self, ha=None, bufsize=1024, wlog=None): self.ha = ha self.bs = bufsize self.wlog = wlog self.ms = None # Mailslot needs to be opened self.opened = False
Python
nomic_cornstack_python_v1
comment Author: Kyle White comment Class: CS460 - Machine Learning comment Date: 10/29/2021 import pandas as pd import numpy as np function getEntropy df begin string Helper function that returns the calculated entropy of a dataset. :param df: a pandas dataframe object containing a row of features and rows of values. :...
# Author: Kyle White # Class: CS460 - Machine Learning # Date: 10/29/2021 import pandas as pd import numpy as np def getEntropy(df): """ Helper function that returns the calculated entropy of a dataset. :param df: a pandas dataframe object containing a row of features and rows of values. :return: the ...
Python
zaydzuhri_stack_edu_python
import json string Algumas linha vão a mais de um campus, portanto, para modificar uma linha é necessário informat tanto o nome da linha, quanto o destino function registra_falhas lista_falhas begin try begin with open string falhas.json string r+ as falhas begin set falhas_lista = load json falhas extend falhas lista_...
import json ''' Algumas linha vão a mais de um campus, portanto, para modificar uma linha é necessário informat tanto o nome da linha, quanto o destino ''' def registra_falhas(lista_falhas): try: with open('falhas.json', 'r+') as falhas: falhas_lista = json.load(falhas) ...
Python
zaydzuhri_stack_edu_python
function _player_info player_name begin if type player_name != str begin return none end return call request string /lol/summoner/v4/summoners/by-name/%s % player_name end function
def _player_info(player_name: str) -> Opt[dict]: if type(player_name) != str: return None return request('/lol/summoner/v4/summoners/by-name/%s' % player_name)
Python
nomic_cornstack_python_v1
function test_update_comment_count self begin comment ensure comment count is 0 set node = get objects pk=1 assert equal 0 comment_count comment create a new comment set comment = call Comment node_id=1 user_id=1 text=string test comment save comment now should have incremented by 1 set node = get objects pk=1 assert e...
def test_update_comment_count(self): # ensure comment count is 0 node = Node.objects.get(pk=1) self.assertEqual(0, node.rating_count.comment_count) # create a new comment comment = Comment(node_id=1, user_id=1, text='test comment') comment.save() # now shou...
Python
nomic_cornstack_python_v1
function validate_response response begin set r = response try begin call raise_for_status end except HTTPError as e begin set message = dictionary status_code=status_code exception=e try begin set response = json r set message at string response = response end except JSONDecodeError as e begin set message at string re...
def validate_response(response): r = response try: r.raise_for_status() except HTTPError as e: message = dict(status_code=r.status_code, exception=e) try: response = r.json() message['response'] = response except JSONDecodeError as e: mes...
Python
nomic_cornstack_python_v1
function add_join self join begin append joins join end function comment self.sources_name[source.name] = source
def add_join(self, join): self.joins.append(join) #self.sources_name[source.name] = source
Python
nomic_cornstack_python_v1
function graph_init self sess=none begin if not sess begin set sess = sess end set saver = call Saver call global_variables max_to_keep=1 run call global_variables_initializer end function
def graph_init(self, sess=None): if not sess: sess = self.sess self.saver = tf.train.Saver(tf.global_variables(), max_to_keep=1) sess.run(tf.global_variables_initializer())
Python
nomic_cornstack_python_v1
function select_value alphabet show_text fail_text=string Please, insert only characters from the alphabet selected before begin while true begin set message = call raw_input show_text if not call check_text message alphabet begin print fail_text continue end return message end end function
def select_value(alphabet, show_text, fail_text="Please, insert only characters from the alphabet selected before"): while True: message = raw_input(show_text) if not check_text(message, alphabet): print(fail_text) continue return message
Python
nomic_cornstack_python_v1
comment !/bin/python3 import math import os import random import re import sys comment Complete the 'maxXorValue' function below. comment The function is expected to return a STRING. comment The function accepts following parameters: comment 1. STRING x comment 2. INTEGER k function maxXorValue x k begin set result = l...
#!/bin/python3 import math import os import random import re import sys # # Complete the 'maxXorValue' function below. # # The function is expected to return a STRING. # The function accepts following parameters: # 1. STRING x # 2. INTEGER k # def maxXorValue(x, k): result = ["0"] * len(x) for i, val in e...
Python
zaydzuhri_stack_edu_python
comment Import dependencies import numpy as np from qiskit import QuantumCircuit function map_gates qc_ori trans_id=true keep_H=false begin string Define new circuit of same # of qubits as circuit passed (no classical bits, but can be added): set qc_trans = call QuantumCircuit num_qubits string Loop through all gates o...
# Import dependencies import numpy as np from qiskit import QuantumCircuit def map_gates(qc_ori, trans_id = True, keep_H = False): """Define new circuit of same # of qubits as circuit passed (no classical bits, but can be added):""" qc_trans = QuantumCircuit(qc_ori.num_qubits) """Loop through all gat...
Python
zaydzuhri_stack_edu_python
function _download_and_clean_file filename url begin set tuple temp_file _ = url retrieve url with open temp_file string r as temp_eval_file begin with open filename string w as eval_file begin for line in temp_eval_file begin set line = strip line set line = replace line string , string , if not line or string , not i...
def _download_and_clean_file(filename, url): temp_file, _ = urllib.request.urlretrieve(url) with tf.gfile.Open(temp_file, 'r') as temp_eval_file: with tf.gfile.Open(filename, 'w') as eval_file: for line in temp_eval_file: line = line.strip() line = line.replac...
Python
nomic_cornstack_python_v1
comment !/usr/bin/env python import rospy from race.msg import pid_input from ackermann_msgs.msg import AckermannDrive set kp = 14.0 set kd = 0.09 comment zero correction offset in case servo is misaligned. set servo_offset = 0 set prev_error = 0.0 comment arbitrarily initialized. 25 is not a special value. This code c...
#!/usr/bin/env python import rospy from race.msg import pid_input from ackermann_msgs.msg import AckermannDrive kp = 14.0 kd = 0.09 servo_offset = 0 # zero correction offset in case servo is misaligned. prev_error = 0.0 vel_input = 25.0 # arbitrarily initialized. 25 is not a special value. This code can accept inpu...
Python
zaydzuhri_stack_edu_python
comment coding=utf-8 string The Asteroids Galaxy Tour Produce a _nightly_ list of observable asteroids brighter than 16 mag for the Robo-AO queue @autor: Dr Dmitry A. Duev [Caltech] from __future__ import print_function import os import numpy as np import datetime from astropy.table import Table from astropy import uni...
# coding=utf-8 """ The Asteroids Galaxy Tour Produce a _nightly_ list of observable asteroids brighter than 16 mag for the Robo-AO queue @autor: Dr Dmitry A. Duev [Caltech] """ from __future__ import print_function import os import numpy as np import datetime from astropy.table import Table from astropy import uni...
Python
zaydzuhri_stack_edu_python
function find self recording_id channel=none start_after=0 end_before=none adjust_offset=false tolerance=0.001 begin set segment_by_recording_id = call _index_by_recording_id_and_cache return generator expression if expression adjust_offset then call with_offset - start_after else segment for segment in get segment_by_...
def find( self, recording_id: str, channel: Optional[int] = None, start_after: Seconds = 0, end_before: Optional[Seconds] = None, adjust_offset: bool = False, tolerance: Seconds = 0.001, ) -> Iterable[SupervisionSegment]: segment_by_recording_id = self...
Python
nomic_cornstack_python_v1
function construction_costs_outdoor self year size begin try begin return __construction_cost_outdoor_db at year at integer size end except any begin raise call LookupError string No such tank found end end function
def construction_costs_outdoor(self,year, size): try: return self.__construction_cost_outdoor_db[year][int(size)] except: raise LookupError("No such tank found")
Python
nomic_cornstack_python_v1
function _index_to_date index begin set tuple i_year i_month i_day = split split index string - at 1 string . return call date integer i_year integer i_month integer i_day end function
def _index_to_date(index): (i_year, i_month, i_day) = index.split('-')[1].split('.') return date(int(i_year), int(i_month), int(i_day))
Python
nomic_cornstack_python_v1
comment /usr/bin/python string Purpose: asyncio working from python 3.7+ In Python 3.7, two new keywords (async and await) were introduced NOTE: If you lock coroutine synchronously — maybe you use time.sleep(10) instead of await asyncio.sleep(10) — you do not return control to the event loop — the whole process will be...
# /usr/bin/python """ Purpose: asyncio working from python 3.7+ In Python 3.7, two new keywords (async and await) were introduced NOTE: If you lock coroutine synchronously — maybe you use time.sleep(10) instead of await asyncio.sleep(10) — you do not return control to the event loop — the whole pro...
Python
zaydzuhri_stack_edu_python
comment python3.5 build_tagger.py <train_file_absolute_path> <model_file_absolute_path> import os import math import sys import datetime import torch import torch.nn as nn import torch.nn.functional as F import torch.optim as optim from torch.utils.data.dataset import Dataset from torch.utils.data import DataLoader fro...
# python3.5 build_tagger.py <train_file_absolute_path> <model_file_absolute_path> import os import math import sys import datetime import torch import torch.nn as nn import torch.nn.functional as F import torch.optim as optim from torch.utils.data.dataset import Dataset from torch.utils.data import DataLoader from tq...
Python
zaydzuhri_stack_edu_python
function _run_load_tests gateway_ip=string 192.168.60.142 begin set host = split hosts at 0 string : at 0 set port = split hosts at 0 string : at 1 set key = key_filename call local string ssh -i %s -o UserKnownHostsFile=/dev/null -o StrictHostKeyChecking=no -tt %s -p %s 'cd $MAGMA_ROOT/lte/gateway/python/load_tests; s...
def _run_load_tests(gateway_ip='192.168.60.142'): host = env.hosts[0].split(':')[0] port = env.hosts[0].split(':')[1] key = env.key_filename local( 'ssh -i %s -o UserKnownHostsFile=/dev/null' ' -o StrictHostKeyChecking=no -tt %s -p %s' ' \'cd $MAGMA_ROOT/lte/gateway/python/load...
Python
nomic_cornstack_python_v1
function unsaved_files self begin set save_state = get aug string /augeas/save set string /augeas/save string noop comment Existing Errors set ex_errs = match string /augeas//error try begin comment This is a noop save save end except tuple RuntimeError IOError begin call _log_save_errors ex_errs comment Erase Save Not...
def unsaved_files(self) -> Set[str]: save_state = self.aug.get("/augeas/save") self.aug.set("/augeas/save", "noop") # Existing Errors ex_errs = self.aug.match("/augeas//error") try: # This is a noop save self.aug.save() except (RuntimeError, IOErro...
Python
nomic_cornstack_python_v1
comment !/usr/bin/env python3 comment -*- coding: utf-8 -*- string Created on Sat Mar 27 23:14:11 2021 @author: icy import math function main begin set test_cases = integer input set n = integer input set q = integer input for iii in range test_cases begin set el = list append el 1 append el 2 append el 3 set curr = 3...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Sat Mar 27 23:14:11 2021 @author: icy """ import math def main(): test_cases = int(input()) n = int(input()) q=int(input()) for iii in range(test_cases): el = [] el.append(1) el.append(2) el.append(3) curr=3 ...
Python
zaydzuhri_stack_edu_python
function get_annotations cls __fn begin string Get the annotations of a given callable. if has attribute __fn string __func__ begin set __fn = __func__ end if has attribute __fn string __notes__ begin return __notes__ end raise call AttributeError format string {!r} does not have annotations __fn end function
def get_annotations(cls, __fn): """Get the annotations of a given callable.""" if hasattr(__fn, '__func__'): __fn = __fn.__func__ if hasattr(__fn, '__notes__'): return __fn.__notes__ raise AttributeError('{!r} does not have annotations'.format(__fn))
Python
jtatman_500k
comment -*- coding: utf-8 -*- string Created on Thu Jan 17 10:12:39 2019 @author: admin import csv function read_branchpoints f begin set data = open f string r set bp_reader = reader data delimiter=string , set sites = list for row in bp_reader begin set coords = list comprehension integer decimal x for x in row appe...
# -*- coding: utf-8 -*- """ Created on Thu Jan 17 10:12:39 2019 @author: admin """ import csv def read_branchpoints(f): data = open(f,"r") bp_reader = csv.reader(data,delimiter=',') sites = [] for row in bp_reader: coords = [int(float(x)) for x in row] sites.append(coords...
Python
zaydzuhri_stack_edu_python
function get_var self table var where=none begin set conn = call connect if where is none begin set where = string 1=1 end if string MAX not in var begin set var = string " + var + string " end set where_statement = string SELECT DISTINCT + var + string FROM + table + string WHERE + where set result = execute conn wher...
def get_var(self, table, var, where=None): conn = self.engine.connect() if where is None: where = "1=1" if "MAX" not in var: var = '"' + var + '"' where_statement = "SELECT DISTINCT " + \ var + " FROM " + table + " WHERE " + where ...
Python
nomic_cornstack_python_v1
function _get_releases begin set releases = none set response = get requests format PYPI_URL package=PYPI_PACKAGE_NAME if response begin set data = json response set releases = list set releases_dict = get data string releases dict if releases_dict begin for tuple version release in items releases_dict begin set relea...
def _get_releases(): releases = None response = requests.get(PYPI_URL.format(package=PYPI_PACKAGE_NAME)) if response: data = response.json() releases = [] releases_dict = data.get('releases', {}) if releases_dict: for version, release in releases_dict.items(): ...
Python
nomic_cornstack_python_v1
function put self sensor_id begin set parser = call RequestParser call add_argument string plant type=str call add_argument string alert_level type=int set args = call parse_args if not any list values args begin return call Response response=dumps dict string message string Both arguments are empty. Try checking your ...
def put(self, sensor_id): parser = reqparse.RequestParser() parser.add_argument("plant", type=str) parser.add_argument("alert_level", type=int) args = parser.parse_args() if not any(list(args.values())): return Response( response=json.dumps( ...
Python
nomic_cornstack_python_v1
function test_01_FindXml self begin assert equal tag string PyHouse assert equal tag string ButtonSection assert equal tag string Button end function
def test_01_FindXml(self): self.assertEqual(self.m_xml.root.tag, 'PyHouse') self.assertEqual(self.m_xml.button_sect.tag, 'ButtonSection') self.assertEqual(self.m_xml.button.tag, 'Button')
Python
nomic_cornstack_python_v1
string #4.4 2D densities: Now add a second characteristic feature of Iris, in order to have entries in d = 2 and produce 4 plots, each displaying the points of the subset of the data (with the plot function ), and the contour lines of the density estimated (using the contour function): (a) by the diagonal Gaussian para...
""" #4.4 2D densities: Now add a second characteristic feature of Iris, in order to have entries in d = 2 and produce 4 plots, each displaying the points of the subset of the data (with the plot function ), and the contour lines of the density estimated (using the contour function): (a) by the diagonal Gaussian p...
Python
zaydzuhri_stack_edu_python
function _filter_child self usage_key capa_type begin if block_type != string problem begin return false end set descriptor = call get_item usage_key depth=0 assert is instance descriptor ProblemBlock return capa_type in problem_types end function
def _filter_child(self, usage_key, capa_type): if usage_key.block_type != "problem": return False descriptor = self.store.get_item(usage_key, depth=0) assert isinstance(descriptor, ProblemBlock) return capa_type in descriptor.problem_types
Python
nomic_cornstack_python_v1
function plot_each_transcript self tids prefix indicate_dataset=false indicate_novel=false browser=false begin call check_plotting_args indicate_dataset indicate_novel browser comment loop through each transcript in the SwanGraph object for tid in tids begin call check_transcript tid end for tid in tids begin call init...
def plot_each_transcript(self, tids, prefix, indicate_dataset=False, indicate_novel=False, browser=False): self.check_plotting_args(indicate_dataset, indicate_novel, browser) # loop through each transcript in the SwanGraph object for tid in tids: self.check_transcript(tid) for tid in tid...
Python
nomic_cornstack_python_v1
function report_download self data token begin set response = call report_download data token set context = context if response is none begin return response end set requestcontent = loads data set url = requestcontent at 0 comment decoding the args represented in JSON set url_split = split url string ? set index = len...
def report_download(self, data, token): response = super(ReportController, self).report_download(data, token) context = request.context if response is None: return response requestcontent = simplejson.loads(data) url = requestcontent[0] # decoding the args r...
Python
nomic_cornstack_python_v1
from urllib.request import urlopen from urllib.error import HTTPError from bs4 import BeautifulSoup import socket import urllib comment get title by url function getBSObj url begin try begin comment proxy_support = urllib.request.ProxyHandler({'http':'http://213.136.77.246:80'}) comment opener = urllib.request.build_op...
from urllib.request import urlopen from urllib.error import HTTPError from bs4 import BeautifulSoup import socket import urllib # get title by url def getBSObj(url): try: # proxy_support = urllib.request.ProxyHandler({'http':'http://213.136.77.246:80'}) # opener = urllib.request.build_opener( proxy_s...
Python
zaydzuhri_stack_edu_python
function check_large_straight self dice_list begin sort dice_list comment checks for large straight 2 to 6 if length set dice_list == 5 and dice_list at 0 == 2 and dice_list at 4 == 6 begin return 35 end else comment checks for large straight 1 to 5 if length set dice_list == 5 and dice_list at 0 == 1 and dice_list at ...
def check_large_straight(self, dice_list): dice_list.sort() # checks for large straight 2 to 6 if len(set(dice_list)) == 5 \ and dice_list[0] == 2 and dice_list[4] == 6: return 35 # checks for large straight 1 to 5 elif len(set(dice_list)) == 5 \ ...
Python
nomic_cornstack_python_v1
comment noqa: PLR0913 function __init__ self name execution_engine=none data_connectors=none data_context_root_directory=none concurrency=none id=none begin set _name = name call __init__ name=name execution_engine=execution_engine data_context_root_directory=data_context_root_directory concurrency=concurrency id=id if...
def __init__( # noqa: PLR0913 self, name: str, execution_engine: Optional[dict] = None, data_connectors: Optional[dict] = None, data_context_root_directory: Optional[str] = None, concurrency: Optional[ConcurrencyConfig] = None, id: Optional[str] = None, ) -> ...
Python
nomic_cornstack_python_v1
function fitshduinfo ihdu begin set a = call qr_fitshdu ihdu 10 set b = call hduinfo set hdutype = a at 0 set naxis = a at 1 set naxes = a at 2 at slice : a at 1 : if naxis > 0 begin set nrows = naxes at 0 set nels = call prod naxes end else begin set nrows = 0 set nels = 0 end if naxis > 1 begin set ncols = naxes at...
def fitshduinfo(ihdu): a=qfitsfor.qr_fitshdu(ihdu,10) b=hduinfo() b.hdutype=a[0] b.naxis=a[1] b.naxes=a[2][:a[1]] if b.naxis>0: b.nrows=b.naxes[0] b.nels=np.prod(b.naxes) else: b.nrows=0 b.nels=0 if b.naxis>1: b.ncols=b.naxes[1] else: b...
Python
nomic_cornstack_python_v1
import sys comment import sys so we can use sys.stdout.write set pstartNum = integer input string Source Port number start: comment Asking to have the user (You) enter a start number. set q1 = string SELECT COUNT(*) AS Port_ comment Start of SQL Query, in this case we are getting a count, instead of a display of the va...
import sys # import sys so we can use sys.stdout.write pstartNum = int(input("Source Port number start: ")) # Asking to have the user (You) enter a start number. q1 = "SELECT COUNT(*) AS Port_" # Start of SQL Query, in this case we are getting a count, instead of a display of the values matching the query. ...
Python
zaydzuhri_stack_edu_python
function number_finder4 num_list begin set i = 0 while num_list at i <= 150 begin if num_list at i % 5 == 0 begin print num_list at i end set i = i + 1 end end function
def number_finder4(num_list): i = 0 while num_list[i] <= 150: if num_list[i] % 5 == 0: print(num_list[i]) i += 1
Python
nomic_cornstack_python_v1
comment !/usr/bin/env python from __future__ import division import sys import string set tweet_count = 0 set day = none set count = 0 set avg = dict for line in stdin begin set tuple key val = split strip line string if day != key begin if day begin set average_day = tweet_count / 52 set avg at average_day = day set ...
#!/usr/bin/env python from __future__ import division import sys import string tweet_count = 0 day = None count=0 avg={} for line in sys.stdin: (key,val) = line.strip().split('\t') if day != key: if day: average_day=tweet_count/52 avg[average_day]=day tweet_count = 0 day = key try: ...
Python
zaydzuhri_stack_edu_python
function sell begin if method == string POST begin comment ensure the stock symbol is valid set stock = get form string stock-symbol if not stock begin return call apology string This stock's symbol is not valid! end comment ensure the user inputs a valid number of shares to sell set uId = session at string user_id try...
def sell(): if request.method == "POST": # ensure the stock symbol is valid stock = request.form.get("stock-symbol") if not stock: return apology("This stock's symbol is not valid!") # ensure the user inputs a valid number of shares to sell uId = session["user_id...
Python
nomic_cornstack_python_v1
function model_spec x h=none init=false ema=none dropout_p=0.5 nr_resnet=5 nr_filters=160 nr_logistic_mix=10 resnet_nonlinearity=string concat_elu begin set counters = dict with call arg_scope list conv2d deconv2d gated_resnet dense nin counters=counters init=init ema=ema dropout_p=dropout_p begin comment parse resnet...
def model_spec(x, h=None, init=False, ema=None, dropout_p=0.5, nr_resnet=5, nr_filters=160, nr_logistic_mix=10, resnet_nonlinearity='concat_elu'): counters = {} with arg_scope([nn.conv2d, nn.deconv2d, nn.gated_resnet, nn.dense, nn.nin], counters=counters, init=init, ema=ema, dropout_p=dropout_p): # pa...
Python
nomic_cornstack_python_v1
if length set n_list == 1 begin print max n_list * 1000 + 10000 end else if length set n_list == 2 begin for n in n_list begin if count n_list n == 2 begin print 1000 + n * 100 exit end end end else begin print max n_list * 100 end
if len(set(n_list)) == 1: print(max(n_list)*1000+10000) elif len(set(n_list)) == 2: for n in n_list: if n_list.count(n) == 2: print(1000+n*100) exit() else: print(max(n_list)*100)
Python
zaydzuhri_stack_edu_python
comment -*- coding: utf-8 -*- string 百钱白鸡问题 鸡翁一值钱五,鸡母一值钱三,鸡雏三值钱一。百钱买百鸡,鸡翁、鸡母、鸡雏各几何? File Name: OneHundred Author : jing Date: 2019-05-22 string 数学列公式: x, y, z >= 0 x + y + z = 100 5x + 3y + z/3 = 100 --> 14x + 8y = 200 --> y = 25 - 7*x/4 for x in range 0 16 1 begin set y = 25 - 7 * x / 4 if y == integer y begin set z =...
# -*- coding: utf-8 -*- """ 百钱白鸡问题 鸡翁一值钱五,鸡母一值钱三,鸡雏三值钱一。百钱买百鸡,鸡翁、鸡母、鸡雏各几何? File Name: OneHundred Author : jing Date: 2019-05-22 """ """ 数学列公式: x, y, z >= 0 x + y + z = 100 5x + 3y + z/3 = 100 --> 14x + 8y = 200 --> y = 25 - 7*x/4 """ for x in range(0, 16, ...
Python
zaydzuhri_stack_edu_python
function get_children self instance begin set children = call order_by string created set serializer = call ChildCommentRetrieveSerializer children many=true read_only=true default=list context=context return data end function
def get_children(self, instance): children = instance.children.filter(is_valid=True).order_by('created') serializer = ChildCommentRetrieveSerializer( children, many=True, read_only=True, default=[], context=self.context, ) retur...
Python
nomic_cornstack_python_v1
function populateDatabaseChoices self begin set settings = call QSettings call beginGroup string PostgreSQL/connections call addItem call _fromUtf8 string call setItemText 0 call translate string dlg_DatabaseConnection string none for tuple i db in enumerate call childGroups begin call addItem call _fromUtf8 string ca...
def populateDatabaseChoices(self): settings = QSettings() settings.beginGroup('PostgreSQL/connections') self.cmbbx_conn.addItem(_fromUtf8("")) self.cmbbx_conn.setItemText(0, QApplication.translate( "dlg_DatabaseConnection", "", None )) ...
Python
nomic_cornstack_python_v1
string 下面的文件将会从csv文件中读取读取短信与电话记录, 你将在以后的课程中了解更多有关读取文件的知识。 import csv with open string texts.csv string r as f begin set reader = reader f set texts = list reader end with open string calls.csv string r as f begin set reader = reader f set calls = list reader end string 任务2: 哪个电话号码的通话总时间最长? 不要忘记,用于接听电话的时间也是通话时间的一部分。 输出信...
""" 下面的文件将会从csv文件中读取读取短信与电话记录, 你将在以后的课程中了解更多有关读取文件的知识。 """ import csv with open('texts.csv', 'r') as f: reader = csv.reader(f) texts = list(reader) with open('calls.csv', 'r') as f: reader = csv.reader(f) calls = list(reader) """ 任务2: 哪个电话号码的通话总时间最长? 不要忘记,用于接听电话的时间也是通话时间的一部分。 输出信息: "<telephone number>...
Python
zaydzuhri_stack_edu_python
import tkinter as tk import os from tkinter import filedialog from alphabetConverter import serbianLatinToLatin function startProgram begin set root = call Tk call withdraw set filepath = call askopenfilename set filename = input string Unesite naziv fajle koja ce se izgenerisati: call convertFile filepath filename end...
import tkinter as tk import os from tkinter import filedialog from alphabetConverter import serbianLatinToLatin def startProgram(): root = tk.Tk() root.withdraw() filepath = filedialog.askopenfilename() filename = input("Unesite naziv fajle koja ce se izgenerisati:") convertFile(filepath,filename) ...
Python
zaydzuhri_stack_edu_python
function collatz number begin if number % 2 == 0 begin comment print(str(number) + ' // 2') set number = number / 2 return number end else begin comment print('3 * ' + str(number) + ' + 1') set number = 3 * number + 1 return number end end function print string Type in a number try begin set spam = integer input while ...
def collatz(number): if number % 2 == 0: #print(str(number) + ' // 2') number = number / 2 return number else: #print('3 * ' + str(number) + ' + 1') number = 3 * number + 1 return number print('Type in a number') try: spam = int(input()) whil...
Python
zaydzuhri_stack_edu_python
function output_multiple self begin return call FreqOffCalc_sptr_output_multiple self end function
def output_multiple(self): return _ncofdm_swig.FreqOffCalc_sptr_output_multiple(self)
Python
nomic_cornstack_python_v1
comment what output will print? set x = - 10 if x * 2 > x begin print string Greater end else begin print string Less or Equal end comment Less or Equal comment What is the ouptup for this task? function foo x array begin if x in array begin return true end else begin return false end end function print call foo 1 list...
#what output will print? x = -10 if x * 2 > x: print("Greater") else: print("Less or Equal") #Less or Equal #What is the ouptup for this task? def foo(x, array): if x in array: return True else: return False print(foo(1, [1, 2, 3])) print(foo(1, [2, 3])) print(foo(1, ...
Python
zaydzuhri_stack_edu_python
from sklearn.feature_extraction.text import CountVectorizer set X = list string ciao ciao miao string miao string miao bao set vectorizer = call CountVectorizer fit vectorizer X set X = transform vectorizer X comment ['bao', 'ciao', 'miao'] print call get_feature_names comment Matrice densa print call todense comment M...
from sklearn.feature_extraction.text import CountVectorizer X = [ 'ciao ciao miao', 'miao', 'miao bao' ] vectorizer = CountVectorizer() vectorizer.fit(X) X = vectorizer.transform(X) print(vectorizer.get_feature_names()) # ['bao', 'ciao', 'miao'] print(X.todense()) # Matrice densa print(X)...
Python
zaydzuhri_stack_edu_python
function sensing_date self begin return string parse time _fragments at 2 string %Y%m%dT%H%M%S end function
def sensing_date(self) -> datetime: return datetime.strptime(self._fragments[2], '%Y%m%dT%H%M%S')
Python
nomic_cornstack_python_v1