code
stringlengths
10
2.58M
original_code
stringlengths
3
3.18M
original_language
stringclasses
1 value
source
stringclasses
7 values
comment noqa: E501 # noqa: E501 function __init__ self _configuration=none **kwargs begin if _configuration is none begin set _configuration = call Configuration end set _configuration = _configuration set _allow_envelope_publish = none set _allow_salesforce_publish = none set _all_users = none set _configuration_type ...
def __init__(self, _configuration=None, **kwargs): # noqa: E501 # noqa: E501 if _configuration is None: _configuration = Configuration() self._configuration = _configuration self._allow_envelope_publish = None self._allow_salesforce_publish = None self._all_users =...
Python
nomic_cornstack_python_v1
function configure self cnf=dict **kw begin return call tuple _w string configure + call _options cnf kw end function
def configure(self, cnf={}, **kw): return self.tk.call((self._w, "configure") + self._options(cnf, kw))
Python
nomic_cornstack_python_v1
function post self server_type server_id begin set form = payload set server_group_id = call get_group_id server_type server_id if first filter by query server_group_id=server_group_id name=form at string name is not none begin call abort 400 string Alias { form at string name } already exists end set alias = call Alia...
def post(self, server_type, server_id): form = ns.payload server_group_id = get_group_id(server_type, server_id) if ( Alias.query.filter_by( server_group_id=server_group_id, name=form["name"] ).first() is not None ): abort(...
Python
nomic_cornstack_python_v1
comment -*- coding: utf-8 -*- string Usage: main generate <config_file> main (-h | --help) main --version Options: -h --help Show this screen. --version Show version. comment 根据数据表创建语句生成java对象类 comment 在数据库 show create table table_name; comment 复制创建表语句并保存进文本文件, 如: comment CREATE TABLE `tbl_test` ( comment `id` int(10) ...
# -*- coding: utf-8 -*- """ Usage: main generate <config_file> main (-h | --help) main --version Options: -h --help Show this screen. --version Show version. """ # 根据数据表创建语句生成java对象类 # 在数据库 show create table table_name; # 复制创建表语句并保存进文本文件, 如: # # CREATE TABLE `tbl_test` ( # `id` int(10) unsigned N...
Python
zaydzuhri_stack_edu_python
function Bubble_sort sort order=string ascending begin set swaped = false for i in range length sort - 1 begin for j in range length sort - 1 - i begin if sort at j > sort at j + 1 begin set tuple sort at j sort at j + 1 = call swap sort at j sort at j + 1 set swaped = true end end if not swaped begin break end end ret...
def Bubble_sort(sort,order = 'ascending'): swaped = False for i in range(len(sort)-1): for j in range(len(sort)-1-i): if sort[j] > sort[j+1]: sort[j],sort[j+1] = swap(sort[j],sort[j+1]) swaped = True if not swaped: break return sort
Python
nomic_cornstack_python_v1
function physical_to_logical_map lut_bel bel_pins begin set phys_to_log = dictionary for pin in pins begin set phys_to_log at pin = none for bel_pin in bel_pins begin if bel_pin == pin begin set phys_to_log at pin = cell_pin break end end end return phys_to_log end function
def physical_to_logical_map(lut_bel, bel_pins): phys_to_log = dict() for pin in lut_bel.pins: phys_to_log[pin] = None for bel_pin in bel_pins: if bel_pin.bel_pin == pin: phys_to_log[pin] = bel_pin.cell_pin ...
Python
nomic_cornstack_python_v1
function serialize self buff begin try begin set _x = self write buff call pack seq secs nsecs set _x = frame_id set length = length _x if python3 or type _x == unicode begin set _x = encode _x string utf-8 set length = length _x end if python3 begin write buff call pack string <I%sB % length length *_x end else begin ...
def serialize(self, buff): try: _x = self buff.write(_struct_3I.pack(_x.request.workspace_parameters.header.seq, _x.request.workspace_parameters.header.stamp.secs, _x.request.workspace_parameters.header.stamp.nsecs)) _x = self.request.workspace_parameters.header.frame_id length = len(_x) ...
Python
nomic_cornstack_python_v1
function __str__ self begin set s = string Human Cone Mosaic: + name + string set s = s + string [Height, Width]: [%.4g % height * 1000 + string , %.4g % width * 1000 + string ] mm set s = s + string Field of view: %.4g % fov + string deg set s = s + string Cone diameter: %.4g % cone_diameter * 1000000.0 + string um s...
def __str__(self): s = "Human Cone Mosaic: " + self.name + "\n" s += " [Height, Width]: [%.4g" % (self.height*1000) + ", %.4g" % (self.width*1000) + "] mm\n" s += " Field of view: %.4g" % self.fov + " deg\n" s += " Cone diameter: %.4g" % (self.cone_diameter*1e6) + " um\n" s +=...
Python
nomic_cornstack_python_v1
function saveScaling self begin debug string Entered saveScaling() set name = call text set description = call text call setUnitsOfTime call value call setUnitsOfPrice call value call setViewScalingX call value call setViewScalingY call value debug string Exiting saveScaling() end function
def saveScaling(self): self.log.debug("Entered saveScaling()") self.priceBarChartScaling.name = self.nameLineEdit.text() self.priceBarChartScaling.description = \ self.descriptionLineEdit.text() self.priceBarChartScaling.\ setUnitsOfTime(self.unitsOfTimeSpin...
Python
nomic_cornstack_python_v1
function __call__ self epoch begin set exp = floor 1 + epoch / dropEvery set alpha = initAlpha * factor ^ exp return decimal alpha end function
def __call__(self, epoch: int) -> float: exp = np.floor((1 + epoch) / self.dropEvery) alpha = self.initAlpha * (self.factor ** exp) return float(alpha)
Python
nomic_cornstack_python_v1
import numpy as np import pyswarms as ps from pyswarms.utils.decorators import cost from pyswarms.utils.search import GridSearch from utils import generate_permuted_population , get_state_fitness comment n must be at least 4 set n = 8 set swarm_size = 20 if __name__ == string __main__ begin comment Set-up hyperparamete...
import numpy as np import pyswarms as ps from pyswarms.utils.decorators import cost from pyswarms.utils.search import GridSearch from utils import generate_permuted_population, get_state_fitness n = 8 # n must be at least 4 swarm_size = 20 if __name__ == '__main__' : # Set-up hyperparameters options = {'c1'...
Python
zaydzuhri_stack_edu_python
string Author : Arun Pottekat Domain : Data Mining Problem : Fuzzy C Means Clustering import numpy as np import pandas as pd import timeit comment [ Load training data into memory ] set training_data = read csv string 29000.csv usecols=list 0 1 names=list string Nature string Interval header=0 comment [ initialize glob...
""" Author : Arun Pottekat Domain : Data Mining Problem : Fuzzy C Means Clustering """ import numpy as np import pandas as pd import timeit # [ Load training data into memory ] training_data = pd.read_csv("29000.csv", usecols=[0,1], names=["Nature","Interval"], header=0) # [ initialize global variables ] centroids =...
Python
zaydzuhri_stack_edu_python
comment http://tryhelloworld.co.kr/challenge_codes/23 comment seungdols code function caesar s n begin set result = string set alp_list = list s for alpabet in alp_list begin if alpabet == string begin set result = result + string end else begin set temp = ordinal alpabet if 65 <= temp and temp <= 90 begin set temp ...
# http://tryhelloworld.co.kr/challenge_codes/23 # seungdols code def caesar(s, n): result = "" alp_list = list(s) for alpabet in alp_list: if ( alpabet == ' ' ): result += ' ' else: temp = ord(alpabet) if( 65 <= temp and temp <= 90 ): ...
Python
zaydzuhri_stack_edu_python
comment !/usr/bin/env python import gmpy2 import math function to_int a K begin set s = 0 set m = 1 for x in a begin set s = s + m * x set m = m * K end return s end function set T = integer call raw_input
#!/usr/bin/env python import gmpy2 import math def to_int(a, K): s = 0 m = 1 for x in a: s += m * x m *= K return s T = int(raw_input())
Python
zaydzuhri_stack_edu_python
comment -*- coding:utf-8 -*- import cv2 import numpy as np function rotate image angle begin comment grab the dimensions of the image and then determine the comment center set tuple h w = shape at slice : 2 : set tuple cX cY = tuple w // 2 h // 2 comment grab the rotation matrix (applying the negative of the comment ...
# -*- coding:utf-8 -*- import cv2 import numpy as np def rotate(image, angle): # grab the dimensions of the image and then determine the # center (h, w) = image.shape[:2] (cX, cY) = (w // 2, h // 2) # grab the rotation matrix (applying the negative of the # angle to rotate clockwise),...
Python
zaydzuhri_stack_edu_python
import sqlite3 comment to open a data base on sql set hello = call connect string world.db comment to create a table in sql function table1 begin comment row creation set row_factory = Row comment creation of admin in the form of rows execute hello string create table if not exists Admin(Name text,Age int) commit hello...
import sqlite3 # to open a data base on sql hello=sqlite3.connect("world.db") # to create a table in sql def table1(): # row creation hello.row_factory=sqlite3.Row # creation of admin in the form of rows hello.execute("create table if not exists Admin(Name text,Age int)") hello.commit() # to ad...
Python
zaydzuhri_stack_edu_python
string Script to visualize attention maps using a pre-trained model. Usage: python visualize_attention.py --load=checkpoints/h10-bs16 import os import pdb import sys import argparse import pickle as pkl import numpy as np import torch comment Local imports import utils comment words = ['roomba', comment 'a', comment 'a...
"""Script to visualize attention maps using a pre-trained model. Usage: python visualize_attention.py --load=checkpoints/h10-bs16 """ import os import pdb import sys import argparse import pickle as pkl import numpy as np import torch # Local imports import utils # words = ['roomba', # 'a', # ...
Python
zaydzuhri_stack_edu_python
while quest1 != string stop copying me begin print quest1 set quest1 = input end print string UGH FINE YOU WIN
while quest1 != "stop copying me": print(quest1) quest1 = input() print("UGH FINE YOU WIN")
Python
zaydzuhri_stack_edu_python
function generate_randomkey length begin set chars = letters + digits return join string list comprehension random choice chars for i in range length end function
def generate_randomkey(length): chars = string.letters + string.digits return ''.join([choice(chars) for i in range(length)])
Python
nomic_cornstack_python_v1
import main import unittest class TestSumEqualsProduct extends TestCase begin function test_1 self begin set total = 4.0 set count = 2 set expected = list 2.0 2.0 set answer = call slurp total count assert equal answer expected end function function test_2 self begin set total = 6.0 set count = 3 set expected = list 1....
import main import unittest class TestSumEqualsProduct(unittest.TestCase): def test_1(self): total = 4.0 count = 2 expected = [2.0, 2.0] answer = main.slurp(total, count) self.assertEqual(answer, expected) def test_2(self): total = 6.0 count = 3 ...
Python
zaydzuhri_stack_edu_python
comment i/usr/bin/python import numpy as np class BoxPlotTechnique begin function refineDeltaArray dayArray deltaArray travelTimeArray begin set npDeltaArray = array deltaArray set q1 = decimal call percentile npDeltaArray 25 set q3 = decimal call percentile npDeltaArray 75 set iq = q3 - q1 set upperBound = q3 + decima...
#i/usr/bin/python import numpy as np class BoxPlotTechnique: def refineDeltaArray(dayArray, deltaArray, travelTimeArray): npDeltaArray = np.array(deltaArray) q1 = float(np.percentile(npDeltaArray, 25)) q3 = float(np.percentile(npDeltaArray, 75)) iq = q3 - q1 upper...
Python
zaydzuhri_stack_edu_python
function author self begin return get _data string author none end function
def author(self): return self._data.get('author', None)
Python
nomic_cornstack_python_v1
function model_test attack begin set mnist = call MNIST train_start=TRAIN_START train_end=TRAIN_END test_start=TEST_START test_end=TEST_END set tuple x_train y_train = call get_set string train set tuple x_test y_test = call get_set string test print string ORIGINAL MNIST TEST call model_testing string mnist_defense_ +...
def model_test(attack): mnist = MNIST(train_start=TRAIN_START, train_end=TRAIN_END, test_start=TEST_START, test_end=TEST_END) x_train, y_train = mnist.get_set('train') x_test, y_test = mnist.get_set('test') print("ORIGINAL MNIST TEST") model_testing("mnist_defense_" + attack + ".joblib", x_train,...
Python
nomic_cornstack_python_v1
comment This Source Code Form is subject to the terms of the Mozilla Public comment License, v. 2.0. If a copy of the MPL was not distributed with this comment file, You can obtain one at http://mozilla.org/MPL/2.0/. import IPy import bisect comment IPy's IP seems sufficient set IP = IP function combine_names name1 nam...
# This Source Code Form is subject to the terms of the Mozilla Public # License, v. 2.0. If a copy of the MPL was not distributed with this # file, You can obtain one at http://mozilla.org/MPL/2.0/. import IPy import bisect # IPy's IP seems sufficient IP = IPy.IP def combine_names(name1, name2): """Combine rule...
Python
zaydzuhri_stack_edu_python
set n = integer input set a = integer input set d = integer input
n=int(input()) a=int(input()) d=int(input())
Python
zaydzuhri_stack_edu_python
function __init__ self person company shift begin call __init__ person=person company=company shift=shift comment Work accomplishments set body_interments = set end function
def __init__(self, person, company, shift): super(Mortician, self).__init__(person=person, company=company, shift=shift) # Work accomplishments self.body_interments = set()
Python
nomic_cornstack_python_v1
function train self X y lr=0.5 n_epochs=10 batch_size=10 seed=1701 begin raise call NotImplementedError end function
def train(self, X, y, lr=0.5, n_epochs=10, batch_size=10, seed=1701): raise NotImplementedError()
Python
nomic_cornstack_python_v1
import pymysql , time from phone_data import sms from phone_data import yunduanxin comment 实例化爬取数据函数 set sms_data = call sms set yunduanxin_data = call yunduanxin comment 两个list合并一个list print sms_data print yunduanxin_data set phone_list = sms_data at 1 + yunduanxin_data at 1 set Area_code_list = sms_data at 0 + yundua...
import pymysql,time from phone_data import sms from phone_data import yunduanxin #实例化爬取数据函数 sms_data=sms() yunduanxin_data=yunduanxin() #两个list合并一个list print(sms_data) print(yunduanxin_data) phone_list=sms_data[1]+yunduanxin_data[1] Area_code_list=sms_data[0]+yunduanxin_data[0] country_url_list=sms_data[2]+yunduanxin...
Python
zaydzuhri_stack_edu_python
string BOX Object implementation import controller class Box extends Object begin string BOX function __init__ self gm manager name size begin call __init__ gm manager name set size = size call set_random_position set type = - 1 end function function draw self begin call drawRectangle tuple position tuple position at 0...
""" BOX Object implementation """ import controller class Box(controller.Object): """ BOX """ def __init__(self, gm, manager, name, size): super().__init__(gm, manager, name) self.size = size self.set_random_position() self.type = -1 def draw(self): self.g...
Python
zaydzuhri_stack_edu_python
function elf_storage_policy self elf_storage_policy begin set _elf_storage_policy = elf_storage_policy end function
def elf_storage_policy(self, elf_storage_policy): self._elf_storage_policy = elf_storage_policy
Python
nomic_cornstack_python_v1
function run self config data_store signal_server workflow_id begin set _workflow_id = workflow_id set _celery_app = call create_app config comment pre-fill the data store with supplied arguments set args = call consolidate _provided_arguments for tuple key value in items args begin set key value end comment start all ...
def run(self, config, data_store, signal_server, workflow_id): self._workflow_id = workflow_id self._celery_app = create_app(config) # pre-fill the data store with supplied arguments args = self._parameters.consolidate(self._provided_arguments) for key, value in args.items(): ...
Python
nomic_cornstack_python_v1
import math function pad l begin set l = l - 1 set counter = 0 while l != 0 begin set l = l ? 1 set counter = counter + 1 end return 2 ^ counter end function function fft a m w begin if m == 1 begin return a end set ae = list comprehension a at 2 * i for i in range m / 2 set ao = list comprehension a at 2 * i + 1 for i...
import math def pad (l): l -= 1 counter = 0 while l != 0: l = l >> 1 counter += 1 return 2**counter def fft (a,m,w): if m == 1: return a ae = [a[2*i] for i in range (m/2)] ao = [a[2*i+1] for i in range (m/2)] fe = fft (ae, m/2, w*w) fo = fft (ao, m/2, w...
Python
zaydzuhri_stack_edu_python
import socket from threading import Thread from auto_brightness import AutoLED from time import sleep class Server begin function __init__ self ip=string 192.168.0.92 port=5001 buffer_size=100 amount=1 begin set buffer_size = 1024 set socket = call socket AF_INET SOCK_STREAM call bind tuple ip port set conn = list set...
import socket from threading import Thread from auto_brightness import AutoLED from time import sleep class Server: def __init__(self, ip="192.168.0.92", port=5001, buffer_size = 100, amount = 1): self.buffer_size = 1024 self.socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) ...
Python
zaydzuhri_stack_edu_python
function isValid s begin set stack = list set right_to_left = dict string ) string ( ; string ] string [ ; string } string { for c in s begin comment c is right parenthese if stack and c in keys right_to_left and pop stack != right_to_left at c begin return false end else comment c is left parenthese if c in values ri...
def isValid(s): stack = [] right_to_left = {')':'(',']':'[','}':'{'} for c in s: if stack and c in right_to_left.keys() and stack.pop() != right_to_left[c]: # c is right parenthese return False elif c in right_to_left.values(): # c is left parenthese stack.append(c)...
Python
zaydzuhri_stack_edu_python
comment coding: utf-8 set string = input set result = string for tuple i char in enumerate string begin if i % 2 == 0 begin set result = result + char end end print result
# coding: utf-8 string = input() result = "" for i , char in enumerate(string): if i % 2 == 0: result += char print(result)
Python
zaydzuhri_stack_edu_python
comment !/bin/python2.7 string @author: Rafal Maselek Main file of the scipt package from __future__ import print_function import plotter import data_loader as dl import classification as cf import numpy as np import math function event_check events begin string Checks if distance between two points is larger than 400 ...
#!/bin/python2.7 """ @author: Rafal Maselek Main file of the scipt package """ from __future__ import print_function import plotter import data_loader as dl import classification as cf import numpy as np import math def event_check(events): """ Checks if distance between two points is larger than 400 mm :...
Python
zaydzuhri_stack_edu_python
function get_inner_types annotation begin return __args__ end function
def get_inner_types(annotation): return annotation.__args__[0].__args__
Python
nomic_cornstack_python_v1
function mel_gff_list begin set mod_gff3 = argv at 1 with open mod_gff3 string r as f begin set gff = list comprehension split strip line string for line in f close f end return gff end function comment gff_list ex/: comment ['2L', 'FlyBase', 'gene', '7529', '9484', '.', '+', '.', 'ID=FBgn0031208;Name=CG11023;Ontology_...
def mel_gff_list(): mod_gff3 = sys.argv[1] with open(mod_gff3, 'r') as f: gff = [line.strip().split('\t') for line in f] f.close() return gff #gff_list ex/: #['2L', 'FlyBase', 'gene', '7529', '9484', '.', '+', '.', 'ID=FBgn0031208;Name=CG11023;Ontology_term=SO:0000010,SO:0000087,GO:0016929,GO:0016926;Dbxref=Fl...
Python
nomic_cornstack_python_v1
function apply_sub1 self method url_template *args **kwargs begin set url_suffix = replace url_template string {1} string args at 0 return read call url_call method url_suffix kwargs end function
def apply_sub1(self, method, url_template, *args, **kwargs): url_suffix = url_template.replace('{1}', str(args[0])) return self.url_call(method, url_suffix, kwargs).read()
Python
nomic_cornstack_python_v1
function _remove_lock self lock begin try begin comment Ignore exceptions and do not raise for status. comment If necessary the curator will clean up the orphaned lock. delete _locks_collection call _get_lock_collection_key collection key lock_ref end except any begin pass end end function
def _remove_lock(self, lock): try: # Ignore exceptions and do not raise for status. # If necessary the curator will clean up the orphaned lock. super(self.__class__, self).delete(_locks_collection, Job._get_lock_collection_key(lock.collection, lock.key), ...
Python
nomic_cornstack_python_v1
function abc begin set l1 = list string a 123 string list string hello 765 print string the list is l1 end function call abc comment generate random numbers from 1 to 100 import random set mylist = list for i in range 0 100 begin set x = random integer 1 10 append mylist x end print mylist comment importing sys module...
def abc(): l1 = ['a', 123, 'list', 'hello', 765] print("the list is", l1) abc() # generate random numbers from 1 to 100 import random mylist = [] for i in range(0, 100): x = random.randint(1, 10) mylist.append(x) print(mylist) # importing sys module import sys # appending a path
Python
zaydzuhri_stack_edu_python
function _check_keys_exist_for_provider self secret_key provider_id begin comment Accounts for old way of storing provider key if secret_key is none begin set msg = format string Could not retrieve secret key for credit provider [{}]. Unable to validate requests from provider. provider_id error msg raise call Permissio...
def _check_keys_exist_for_provider(self, secret_key, provider_id): # Accounts for old way of storing provider key if secret_key is None: msg = 'Could not retrieve secret key for credit provider [{}]. ' \ 'Unable to validate requests from provider.'.format(provider_id) ...
Python
nomic_cornstack_python_v1
function check_if_project_privacity_can_be_changed project current_memberships=none current_private_projects=none current_public_projects=none begin if owner is none begin return dict string can_be_updated false ; string reason ERROR_PROJECT_WITHOUT_OWNER end if current_memberships is none begin set current_memberships...
def check_if_project_privacity_can_be_changed( project, current_memberships=None, current_private_projects=None, current_public_projects=None): if project.owner is None: return {'can_be_updated': False, 'reason': ERROR_PROJECT_WITHOUT_OWNER} if current_memberships is Non...
Python
nomic_cornstack_python_v1
function get self request *args **kwargs begin set object = get objects pk=kwargs at string pk set form_class = call get_form_class set form = call get_form form_class set instrumento_linea_form = call Instrumento_LineaFormSet instance=object return call render_to_response call get_context_data form=form instrumento_li...
def get(self, request, *args, **kwargs): self.object = Presupuesto.objects.get(pk=kwargs['pk']) form_class = self.get_form_class() form = self.get_form(form_class) instrumento_linea_form = Instrumento_LineaFormSet(instance=self.object) return self.render_to_response( ...
Python
nomic_cornstack_python_v1
function build self begin set catdict = cat_corr at string catalog set corrdict = cat_corr at string correction comment cosmoslogy set cosmo = call cosmo set f_peak = corrdict at string fpeak comment survey redshift limits set tuple survey_zmin survey_zmax = call survey_zlimits set survey_comdis_min = call comoving_dis...
def build(self): catdict = (self.cat_corr)['catalog'] corrdict = (self.cat_corr)['correction'] cosmo = self.cosmo() # cosmoslogy f_peak = corrdict['fpeak'] # survey redshift limits survey_zmin, survey_zmax = self.survey_zlimits() survey_comdis_min =...
Python
nomic_cornstack_python_v1
while S begin if starts with S string hi begin set S = S at slice 2 : : end else begin set ans = string No break end end print ans
while S: if S.startswith('hi'): S = S[2:] else: ans = 'No' break print(ans)
Python
zaydzuhri_stack_edu_python
comment !/usr/bin/python3 string island_perimeter module function island_perimeter grid begin string Calculating the perimeter of an island grid is a list of list of integers: 0 represents a water zone 1 represents a land zone One cell is a square with side length 1 Grid cells are connected horizontally/vertically (not...
#!/usr/bin/python3 """ island_perimeter module """ def island_perimeter(grid): """ Calculating the perimeter of an island grid is a list of list of integers: 0 represents a water zone 1 represents a land zone One cell is a square with side length 1 Grid cells are connected horizontally/ve...
Python
zaydzuhri_stack_edu_python
function is_empty self begin return size == 0 end function
def is_empty(self): return self.size == 0
Python
nomic_cornstack_python_v1
for i in range 0 10001 begin if i % N == 2 begin print i end end
for i in range(0,10001): if (i%N==2): print(i)
Python
zaydzuhri_stack_edu_python
function buildNewPage self pagestr begin debug format string building page {0}... totalPages set page = call PageCreate call Rect 0 0 612 794 call Begin page call Reset comment begin writing text elements to the current page set element = call CreateTextBegin courierNew 8 comment last two digits are x, y coords on page...
def buildNewPage(self, pagestr): self.logger.debug("building page {0}...".format(self.totalPages)) page = self.pdf_doc.PageCreate(Rect(0, 0, 612, 794)) self.writer.Begin(page) self.eb.Reset() # begin writing text elements to the current page element = self.eb.CreateTextBegin(self.courierNew, 8) element.S...
Python
nomic_cornstack_python_v1
function test_tests_detect_bad_ordering self hge_ctx begin call check_query_f hge_ctx string test_tests/select_query_author_by_pkey_bad_ordering.yaml string http end function comment E AssertionError: comment E expected: comment E data: comment E author_by_pk: comment E name: Author 1 comment E id: 1 comment E diff: (r...
def test_tests_detect_bad_ordering(self, hge_ctx): check_query_f(hge_ctx, 'test_tests/select_query_author_by_pkey_bad_ordering.yaml', 'http') # # E AssertionError: # E expected: # E data: # E author_by_pk: # E ...
Python
nomic_cornstack_python_v1
function solution s begin string This function takes in a string s, and finds the maximum equal splits of s Example, s = abcabcabcab, pattern = abc, max_eqal_split = 3 s = aaaaaaaaaaaaaaabbbbbbaaaaaaaaaaaaaaabbbbbb, pattern = aaaaaaaaaaaaaaabbbbbb, max_equal_split = 2 comment collect index positions of first unique let...
def solution(s): """ This function takes in a string s, and finds the maximum equal splits of s Example, s = abcabcabcab, pattern = abc, max_eqal_split = 3 s = aaaaaaaaaaaaaaabbbbbbaaaaaaaaaaaaaaabbbbbb, pattern = aaaaaaaaaaaaaaabbbbbb, max_equal_split = 2 """ #collect index positions of first ...
Python
zaydzuhri_stack_edu_python
string Consider the fraction, n/d, where n and d are positive integers. If n<d and HCF(n,d)=1, it is called a reduced proper fraction. If we list the set of reduced proper fractions for d ≤ 8 in ascending order of size, we get: 1/8, 1/7, 1/6, 1/5, 1/4, 2/7, 1/3, 3/8, 2/5, 3/7, 1/2, 4/7, 3/5, 5/8, 2/3, 5/7, 3/4, 4/5, 5/...
""" Consider the fraction, n/d, where n and d are positive integers. If n<d and HCF(n,d)=1, it is called a reduced proper fraction. If we list the set of reduced proper fractions for d ≤ 8 in ascending order of size, we get: 1/8, 1/7, 1/6, 1/5, 1/4, 2/7, 1/3, 3/8, 2/5, 3/7, 1/2, 4/7, 3/5, 5/8, 2/3, 5/7, 3/4, 4/5, 5...
Python
zaydzuhri_stack_edu_python
function _find_embeddings snlp begin set embs = none for proc in values processors begin if has attribute proc string pretrain and is instance pretrain Pretrain begin set embs = pretrain break end end return embs end function
def _find_embeddings(snlp): embs = None for proc in snlp.processors.values(): if hasattr(proc, "pretrain") and isinstance(proc.pretrain, Pretrain): embs = proc.pretrain break return embs
Python
nomic_cornstack_python_v1
function pop_message self wait=SECOND till=none begin string RETURN TUPLE (message, payload) CALLER IS RESPONSIBLE FOR CALLING message.delete() WHEN DONE if till is not none and not is instance till Signal begin error string Expecting a signal end set message = read queue wait_time_seconds=floor seconds if not message ...
def pop_message(self, wait=SECOND, till=None): """ RETURN TUPLE (message, payload) CALLER IS RESPONSIBLE FOR CALLING message.delete() WHEN DONE """ if till is not None and not isinstance(till, Signal): Log.error("Expecting a signal") message = self.queue.read(wait_ti...
Python
jtatman_500k
import socket import threading function recv sock addr content begin print string Accept new connection from %s:%s... % addr if content at string flag == 1 begin call send bytes content at string data string utf-8 end else begin call send bytes string Welcome! string utf-8 end print call recv 1024 while true begin set ...
import socket import threading def recv(sock, addr, content): print ('Accept new connection from %s:%s...' % addr) if content["flag"] == 1: sock.send(bytes(content["data"], "utf-8")) else: sock.send(bytes('Welcome!', 'utf-8')) print(sock.recv(1024)) while True: data = sock....
Python
zaydzuhri_stack_edu_python
function shortest_path G source dest begin comment Check that source exists within G and that source != dest if source not in call vertices or source == dest begin return end comment Get the spanning tree from this node set tree = call spanning_tree G source comment Make sure that the dest is in the sources' spanning t...
def shortest_path(G, source, dest): # Check that source exists within G and that source != dest if source not in G.vertices() or source == dest: return # Get the spanning tree from this node tree = spanning_tree(G, source) # Make sure that the dest is in the sources' spanning tree if dest not...
Python
nomic_cornstack_python_v1
function save self begin info string Saving all student information to disk... call to_disk end function
def save(self): logger.info('Saving all student information to disk...') self.students.to_disk()
Python
nomic_cornstack_python_v1
from selenium import webdriver from selenium.webdriver.common.keys import Keys import time class WhatsappBot begin function __init__ self begin comment Parte 1 - A mensagem que você quer enviar set mensagem = string KOE !! comment Parte 2 - Nome dos grupos ou pessoas a quem você deseja enviar a mensagem set grupos_ou_p...
from selenium import webdriver from selenium.webdriver.common.keys import Keys import time class WhatsappBot: def __init__(self): # Parte 1 - A mensagem que você quer enviar self.mensagem = "KOE !!" # Parte 2 - Nome dos grupos ou pessoas a quem você deseja enviar a mensagem self.gr...
Python
zaydzuhri_stack_edu_python
comment !/usr/bin/env python3 comment -*- coding: utf-8 -*- string Created on Tue Apr 24 21:44:48 2018 @author: tauro function fitness password test_word begin if length test_word != length password begin print string Confucius say: This password no good return end else begin set score = 0 for i in range length passwor...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Tue Apr 24 21:44:48 2018 @author: tauro """ def fitness(password, test_word): if len(test_word) != len(password): print("Confucius say: This password no good") return else: score = 0 for i in range...
Python
zaydzuhri_stack_edu_python
function multiply num1 num2 begin if num2 == 0 begin return 0 end set first1 = call get_first1 num2 set first_prod = num1 ? first1 return first_prod + call multiply num1 num2 ? num2 - 1 end function function get_first1 num begin set index = 0 while num begin if num ? 1 begin return index end set num = num ? 1 set index...
def multiply(num1, num2): if num2 == 0: return 0 first1 = get_first1(num2) first_prod = num1 << first1 return first_prod + multiply(num1, num2 & (num2 - 1)) def get_first1(num): index = 0 while num: if num & 1: return index num >>= 1 index += 1
Python
zaydzuhri_stack_edu_python
function solution S C begin string :param S: takes a string of the same many letters eg. 'aabbccc' :param C: add price/point to each letter :return: removes the highest price from the duplicates and returns sum of the lowest price of letters. set many = list set cost = 0 set previous = none comment We can use "C.appen...
def solution(S, C): """ :param S: takes a string of the same many letters eg. 'aabbccc' :param C: add price/point to each letter :return: removes the highest price from the duplicates and returns sum of the lowest price of letters. """ many = [] cost = 0 previous = None # We can use...
Python
zaydzuhri_stack_edu_python
import cv2 , time set img = call imread string shapes.jpg set img2 = img set tuple height width channels = shape comment Number of pieces Horizontally set CROP_W_SIZE = 3 comment Number of pieces Vertically to each Horizontal set CROP_H_SIZE = 2 for ih in range CROP_H_SIZE begin for iw in range CROP_W_SIZE begin set x ...
import cv2,time img = cv2.imread('shapes.jpg') img2 = img height, width, channels = img.shape # Number of pieces Horizontally CROP_W_SIZE = 3 # Number of pieces Vertically to each Horizontal CROP_H_SIZE = 2 for ih in range(CROP_H_SIZE ): for iw in range(CROP_W_SIZE ): x = int(width/CROP_W_SIZE * iw) ...
Python
zaydzuhri_stack_edu_python
function extract_slitlet2d image_2k2k sltlim begin string Extract slitlet 2d image from image with original EMIR dimensions. Parameters ---------- image_2k2k : 2d numpy array, float Original image (dimensions NAXIS1 * NAXIS2) sltlim : instance of SlitLimits class Object containing relevant information concerning the sl...
def extract_slitlet2d(image_2k2k, sltlim): """Extract slitlet 2d image from image with original EMIR dimensions. Parameters ---------- image_2k2k : 2d numpy array, float Original image (dimensions NAXIS1 * NAXIS2) sltlim : instance of SlitLimits class Object containing relevant info...
Python
jtatman_500k
from flask import Flask , render_template , session , request , redirect , url_for from datetime import timedelta import pandas as pd import json import sqlite3 from urllib.request import urlopen set app = call Flask __name__ comment same as fb set permanent_session_lifetime = time delta days=13 set secret_key = string...
from flask import Flask, render_template,session,request,redirect,url_for from datetime import timedelta import pandas as pd import json import sqlite3 from urllib.request import urlopen app = Flask(__name__) app.permanent_session_lifetime= timedelta(days= 13) #same as fb app.secret_key = "keyyyyy" #...
Python
zaydzuhri_stack_edu_python
function _check_output *popenargs **kwargs begin if string stdout in kwargs begin raise call ValueError string stdout argument not allowed, it will be overridden. end set process = popen *popenargs stdout=PIPE keyword kwargs set tuple output unused_err = communicate process set retcode = poll process if retcode begin s...
def _check_output(*popenargs, **kwargs): if 'stdout' in kwargs: raise ValueError('stdout argument not allowed, it will be overridden.') process = subprocess.Popen(stdout=subprocess.PIPE, *popenargs, **kwargs) output, unused_err = process.communicate() retcode = process.poll() if retcode: ...
Python
nomic_cornstack_python_v1
comment Day : 12 class Solution begin function singleNonDuplicate self nums begin if length nums == 1 begin return nums at 0 end for i in range 0 length nums 2 begin if i == length nums - 1 begin return nums at i end if not nums at i == nums at i + 1 begin return nums at i end end return 0 end function end class
# Day : 12 class Solution: def singleNonDuplicate(self, nums: List[int]) -> int: if len(nums)==1: return nums[0] for i in range(0,len(nums),2): if i == len(nums)-1: return nums[i] if not nums[i]==nums[i+1]: return nums[i] ...
Python
zaydzuhri_stack_edu_python
function get_exported_bundle_archive_stream self bundle_id begin return call _perform_raw string GET string /projects/%s/bundles/exported/%s/archive % tuple project_key bundle_id end function
def get_exported_bundle_archive_stream(self, bundle_id): return self.client._perform_raw("GET", "/projects/%s/bundles/exported/%s/archive" % (self.project_key, bundle_id))
Python
nomic_cornstack_python_v1
function getmask self mask inverse=false begin set output = list for tuple data cond in zip data mask begin if inverse begin append output data at ? cond end else begin append output data at cond end end return output end function
def getmask( self, mask: Union[List[dd.Series], UserList], inverse: bool = False ) -> List[dd.Series]: output = [] for data, cond in zip(self.data, mask): if inverse: output.append(data[~cond]) else: output.append(data[cond]) r...
Python
nomic_cornstack_python_v1
import os from requests import get , put , post import json from item import ToDoItem set _todo_list = string 5f140cd74e0efa661d85d545 set _done_list = string 5f14102775f3e65db1615d81 set _auth_params = dict string key call getenv string API_KEY ; string token call getenv string USER_TOKEN function _make_item trello_co...
import os from requests import get, put, post import json from item import ToDoItem _todo_list='5f140cd74e0efa661d85d545' _done_list='5f14102775f3e65db1615d81' _auth_params = { 'key': os.getenv('API_KEY'), 'token': os.getenv('USER_TOKEN') } def _make_item(trello_content, status): return ToDoItem(trello_c...
Python
zaydzuhri_stack_edu_python
import sys append path string .. import numpy as np import line plot list 1 2 3 list 4 5 6 xlabel=string t ylabel=string xy_nodesc plot list 1 2 3 list 4.1 5.1 6.1 string mx xlabel=string t ylabel=string xy_desc set l1 = plot list 1 2 3 string gs xlabel=string 123 ylabel=string xy_single_nodesc set l2 = plot list 1.2 2...
import sys sys.path.append('..') import numpy as np import line line.plot([1,2,3], [4,5,6], xlabel='t', ylabel='xy_nodesc') line.plot([1,2,3], [4.1,5.1,6.1], 'mx', xlabel='t', ylabel='xy_desc') l1 = line.plot([1,2,3], 'gs', xlabel='123', ylabel='xy_single_nodesc') l2 = line.plot([1.2,2.2,3.2], xlabel='t', ylabel='xy_...
Python
zaydzuhri_stack_edu_python
function set_num_format_n self num_format_n begin set num_format_n = num_format_n end function
def set_num_format_n(self, num_format_n): self.num_format_n = num_format_n
Python
nomic_cornstack_python_v1
import numpy as np import torch import torch.nn.functional as F from sklearn.metrics import roc_auc_score function get_node_degree adj_matrix node begin return sum adj_matrix at tuple node slice : : end function string For heterogeneous networks and homogeneous networks, the function to compute acc and recall is as f...
import numpy as np import torch import torch.nn.functional as F from sklearn.metrics import roc_auc_score def get_node_degree(adj_matrix, node): return torch.sum(adj_matrix[node,:]) ''' For heterogeneous networks and homogeneous networks, the function to compute acc and recall is as foll...
Python
zaydzuhri_stack_edu_python
function test_decoratePreservesSuite self begin set test = test case set suite = call DestructiveTestSuite list test set decorated = call decorate suite TestDecorator call assertSuitesEqual decorated call DestructiveTestSuite list call TestDecorator test end function
def test_decoratePreservesSuite(self): test = self.TestCase() suite = runner.DestructiveTestSuite([test]) decorated = unittest.decorate(suite, unittest.TestDecorator) self.assertSuitesEqual( decorated, runner.DestructiveTestSuite([unittest.TestDecorator(test)]) )
Python
nomic_cornstack_python_v1
from collections import defaultdict set user_words = default dictionary list set word_users_count = default dictionary int set word_count = default dictionary int set n = integer input for i in range n begin set s = split input set user_words at s at 0 = user_words at s at 0 + s at slice 1 : : end for tuple u ws in i...
from collections import defaultdict user_words = defaultdict(list) word_users_count = defaultdict(int) word_count = defaultdict(int) n = int(input()) for i in range(n): s = input().split() user_words[s[0]] += s[1:] for u, ws in user_words.items(): w_thisuser = defaultdict(int) for w in ws: ...
Python
zaydzuhri_stack_edu_python
async function on_socket_response self data begin try begin set key = data at string t set body = data at string d end except KeyError begin return end if key != string VOICE_SERVER_UPDATE begin return end set guild_id = integer body at string guild_id set ws = call get_discord_websocket discord_client guild_id set ses...
async def on_socket_response(self, data: Dict[str, Any]) -> None: try: key = data["t"] body = data["d"] except KeyError: return if key != "VOICE_SERVER_UPDATE": return guild_id = int(body["guild_id"]) ws = get_discord_websocket(se...
Python
nomic_cornstack_python_v1
import pandas as pd import numpy as np import scipy as sci import statsmodels.api as sm import matplotlib.pyplot as plt import sklearn as sk import seaborn as sns import math from sklearn import model_selection from sklearn import metrics from model import data_merging from model import data_modification from model imp...
import pandas as pd import numpy as np import scipy as sci import statsmodels.api as sm import matplotlib.pyplot as plt import sklearn as sk import seaborn as sns import math from sklearn import model_selection from sklearn import metrics from model import data_merging from model import data_modification from model i...
Python
zaydzuhri_stack_edu_python
function expose action begin append api_methods __name__ return action end function
def expose(action): api_methods.append(action.__name__) return action
Python
nomic_cornstack_python_v1
comment 英小文字 c が与えられるので、cが母音であるか判定してください。 comment c が母音であるとき、vowel と、そうでないとき consonant と出力せよ。 if c in tuple string a string e string i string o string u begin print string vowel end else begin print string consonant end
# 英小文字 c が与えられるので、cが母音であるか判定してください。 # c が母音であるとき、vowel と、そうでないとき consonant と出力せよ。 if c in ("a", "e", "i", "o", "u"): print("vowel") else: print("consonant")
Python
zaydzuhri_stack_edu_python
function test_no_files_created self begin assert equal list directory STATIC_ROOT list end function
def test_no_files_created(self): self.assertEqual(os.listdir(settings.STATIC_ROOT), [])
Python
nomic_cornstack_python_v1
comment install cv2 with this command $ pip install opencv-python (21,21),0 import cv2 set b = 34 set c = 5 set f = 80 for i in range b begin set image = call imread string ImagesDataSet/barcelona_0 { i } .png set grey_img = call cvtColor image COLOR_BGR2GRAY set invert = call bitwise_not grey_img set blur = call Gauss...
#install cv2 with this command $ pip install opencv-python (21,21),0 import cv2 b=34 c=5 f=80 for i in range(b): image = cv2.imread(f'ImagesDataSet/barcelona_0{i}.png') grey_img = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) invert = cv2.bitwise_not(grey_img) blur = cv2.GaussianBlur(invert, (31,31),6) i...
Python
zaydzuhri_stack_edu_python
function filter_packs self packs begin return list comprehension pack for pack in packs if length pack < pack_size_threshold end function
def filter_packs(self, packs): return [ pack for pack in packs if len(pack) < self.model.pack_size_threshold ]
Python
nomic_cornstack_python_v1
function test_delete_volumes self volumes_count volumes_steps create_volumes begin set volume_names = list call generate_ids string volume count=volumes_count call create_volumes volume_names end function
def test_delete_volumes(self, volumes_count, volumes_steps, create_volumes): volume_names = list(generate_ids('volume', count=volumes_count)) create_volumes(volume_names)
Python
nomic_cornstack_python_v1
function fact self head begin set symbol = if expression has attribute head string symbol then call symbol else head write out string %s. % string symbol set atom = call add_atom symbol comment Only functions relevant for constructing bug reports for bad error messages comment are assumptions, and only when using cores...
def fact(self, head): symbol = head.symbol() if hasattr(head, "symbol") else head self.out.write("%s.\n" % str(symbol)) atom = self.backend.add_atom(symbol) # Only functions relevant for constructing bug reports for bad error messages # are assumptions, and only when using cor...
Python
nomic_cornstack_python_v1
function __init__ self top left alinecolor afillcolor begin assert alinecolor == afillcolor set xpoint = left + BRICK_WIDTH / 2.0 set ypoint = top - BRICK_HEIGHT / 2.0 call __init__ self x=xpoint y=ypoint linecolor=alinecolor fillcolor=afillcolor width=BRICK_WIDTH height=BRICK_HEIGHT set _collision_status = false end f...
def __init__(self,top,left,alinecolor,afillcolor): assert alinecolor == afillcolor xpoint = left+BRICK_WIDTH/2.0 ypoint = top-BRICK_HEIGHT/2.0 GRectangle.__init__(self,x=xpoint,y=ypoint,linecolor=alinecolor,fillcolor=afillcolor, width=BRICK_WIDTH,height=BRICK_...
Python
nomic_cornstack_python_v1
class User begin function __init__ self username password begin set username = username set password = password set is_authenticated = false end function function authenticate self username password begin if username == username and password == password begin set is_authenticated = true end end function function logout...
class User: def __init__(self, username, password): self.username = username self.password = password self.is_authenticated = False def authenticate(self, username, password): if (username == self.username and password == self.password): self.is_authenticated = True ...
Python
jtatman_500k
function parent self parent begin set _parent = parent end function
def parent(self, parent): self._parent = parent
Python
nomic_cornstack_python_v1
comment !/usr/bin/env python import sys import markovify from scraper import Scraper set NUM_TRIAL_RUNS = 100 set MAX_PROBABLE_KMER = 10 set STATE_SIZE_THRESHOLD = 0.05 set TWEET_LENGTH = 140 class TweetModel extends object begin string A tweet model can be a model generated based on one or multiple twitter corpus sour...
#!/usr/bin/env python import sys import markovify from scraper import Scraper NUM_TRIAL_RUNS = 100 MAX_PROBABLE_KMER = 10 STATE_SIZE_THRESHOLD = 0.05 TWEET_LENGTH = 140 class TweetModel(object): """A tweet model can be a model generated based on one or multiple twitter corpus sources Twitter Model can be...
Python
zaydzuhri_stack_edu_python
function run_executable cmd env stdoutfile=none use_openbox=true use_xcompmgr=true begin comment It might seem counterintuitive to support a --no-xvfb flag in a script comment whose only job is to start xvfb, but doing so allows us to consolidate comment the logic in the layers of buildbot scripts so that we *always* u...
def run_executable( cmd, env, stdoutfile=None, use_openbox=True, use_xcompmgr=True): # It might seem counterintuitive to support a --no-xvfb flag in a script # whose only job is to start xvfb, but doing so allows us to consolidate # the logic in the layers of buildbot scripts so that we *always* use # xvfb...
Python
nomic_cornstack_python_v1
import random import os import warnings filter warnings string ignore import numpy as np import torch function collate batch begin set tuple inputs labels = batch at 0 return tuple call FloatTensor inputs call LongTensor labels end function class DefaultDataset begin function __init__ self feature_name label_name data_...
import random import os import warnings warnings.filterwarnings("ignore") import numpy as np import torch def collate(batch): inputs, labels = batch[0] return torch.FloatTensor(inputs), torch.LongTensor(labels) class DefaultDataset: def __init__(self, feature_name, label_name, data_dir, train_p, test_p,...
Python
zaydzuhri_stack_edu_python
import psutil import numpy as np import pandas as pd from sklearn.ensemble import RandomForestClassifier from sklearn import tree from sklearn.feature_extraction import DictVectorizer from sklearn import metrics from sklearn.decomposition import PCA from sklearn.preprocessing import StandardScaler from sklearn.model_se...
import psutil import numpy as np import pandas as pd from sklearn.ensemble import RandomForestClassifier from sklearn import tree from sklearn.feature_extraction import DictVectorizer from sklearn import metrics from sklearn.decomposition import PCA from sklearn.preprocessing import StandardScaler from sklearn.model_se...
Python
zaydzuhri_stack_edu_python
function n_points self begin return dictionary comprehension obs : shape for tuple obs pts in items self end function
def n_points(self): return {obs: pts.shape for obs, pts in self.items()}
Python
nomic_cornstack_python_v1
comment define a function to draw the board function draw_board begin print string print string --- | --- | --- print string 7 | 8 | 9 print string --- | --- | --- print string 4 | 5 | 6 print string --- | --- | --- print string 1 | 2 | 3 print string --- | --- | --- end function comment define a function to check if p...
# define a function to draw the board def draw_board(): print("\n") print(" --- | --- | --- ") print(" 7 | 8 | 9 ") print(" --- | --- | --- ") print(" 4 | 5 | 6 ") print(" --- | --- | --- ") print(" 1 | 2 | 3 ") print(" --- | --- | --- ") # ...
Python
jtatman_500k
function get_nearest_atom_inds self begin comment Create empty data structure set closest_ats = zeros tuple natom natom - 1 dtype=int comment Get and sort distances set all_at_inds = array range natom for iat in range natom begin set at_inds = all_at_inds at all_at_inds != iat set dist = all_dist at tuple iat at_inds s...
def get_nearest_atom_inds(self): # Create empty data structure self.closest_ats = np.zeros((self.natom, self.natom-1), dtype=int) # Get and sort distances all_at_inds = np.arange(self.natom) for iat in range(self.natom): at_inds = all_at_inds[all_at_inds != iat] ...
Python
nomic_cornstack_python_v1
function reguid zpool begin string Generates a new unique identifier for the pool .. warning:: You must ensure that all devices in this pool are online and healthy before performing this action. zpool : string name of storage pool .. versionadded:: 2016.3.0 CLI Example: .. code-block:: bash salt '*' zpool.reguid myzpoo...
def reguid(zpool): ''' Generates a new unique identifier for the pool .. warning:: You must ensure that all devices in this pool are online and healthy before performing this action. zpool : string name of storage pool .. versionadded:: 2016.3.0 CLI Example: .. c...
Python
jtatman_500k
comment Реализуйте класс MoneyBox, для работы с виртуальной копилкой. comment Каждая копилка имеет ограниченную вместимость, которая выражается целым числом comment – количеством монет, которые можно положить в копилку. Класс должен comment поддерживать comment информацию о количестве монет в копилке, предоставлять воз...
#Реализуйте класс MoneyBox, для работы с виртуальной копилкой. #Каждая копилка имеет ограниченную вместимость, которая выражается целым числом #– количеством монет, которые можно положить в копилку. Класс должен #поддерживать #информацию о количестве монет в копилке, предоставлять возможность добавлять #монеты #в копи...
Python
zaydzuhri_stack_edu_python
from airdata.datasource import Airports set countries = list function getcountrybyname name begin return list comprehension x for x in countries if starts with lower x at string name name or lower x at string code == name end function function sortbyairportsqty top calc maxelements begin if calc begin for country in c...
from airdata.datasource import Airports countries = [] def getcountrybyname(name): return [x for x in countries if x['name'].lower().startswith(name) or x['code'].lower() == name] def sortbyairportsqty(top, calc, maxelements): if(calc): for country in countries: country['qty'] = Airpor...
Python
zaydzuhri_stack_edu_python
function test_healer_not_confirmed self begin call signup string healer set response = get rest_client reverse string provider_setup_intro assert equal status_code 200 comment check if any other page except setup is available set response = get rest_client reverse string notes assert equal status_code 302 end function
def test_healer_not_confirmed(self): self.signup('healer') response = self.rest_client.get(reverse('provider_setup_intro')) self.assertEqual(response.status_code, 200) # check if any other page except setup is available response = self.rest_client.get(reverse('notes')) self.assertEqual(response.status_cod...
Python
nomic_cornstack_python_v1
function main begin comment 抓取新浪网中国军情 set path = string sina_china.csv set sina_china = call sina_crawler path list string sina string china call get_link_list get text sina_china comment 抓取新浪网国际军情 set path = string sina_international.csv set sina_inter = call sina_crawler path list string sina string international cal...
def main(): # 抓取新浪网中国军情 path = 'sina_china.csv' sina_china = mc.sina_crawler(path, ['sina', 'china']) sina_china.get_link_list() sina_china.get_text() # 抓取新浪网国际军情 path = 'sina_international.csv' sina_inter = mc.sina_crawler(path, ['sina', 'international']) sina_inter.get_link_list()...
Python
nomic_cornstack_python_v1
comment -*- coding: utf-8 -*- string Created on Sun Jan 6 18:46:47 2019 @author: Ricardo Nunes function evaluate a x begin set result = list comprehension ele * x ^ i for tuple i ele in enumerate a return sum result end function
# -*- coding: utf-8 -*- """ Created on Sun Jan 6 18:46:47 2019 @author: Ricardo Nunes """ def evaluate(a, x): result= [ele*x**i for i,ele in enumerate(a)] return sum(result)
Python
zaydzuhri_stack_edu_python