code
stringlengths
10
2.58M
original_code
stringlengths
3
3.18M
original_language
stringclasses
1 value
source
stringclasses
7 values
import torch import torch.optim as optim import torch.nn as nn import torch.nn.functional as F import numpy as np from pytorch_pretrained_bert import BertModel try begin from layers.att_flow import AttFlow from layers.char_cnn import CharCNN from layers.pred_layer import PredictionLayer end except ModuleNotFoundError b...
import torch import torch.optim as optim import torch.nn as nn import torch.nn.functional as F import numpy as np from pytorch_pretrained_bert import BertModel try: from layers.att_flow import AttFlow from layers.char_cnn import CharCNN from layers.pred_layer import PredictionLayer except ModuleNotFoundErro...
Python
zaydzuhri_stack_edu_python
function init_output_formatters output_verbosity=string normal stderr=stderr logfile=none debug_logfile=none begin string Initialize the CLI logging scheme. :param output_verbosity: 'quiet','normal','verbose', or 'debug' controls the output to stdout and its format :param stderr: stream for stderr output, default=stder...
def init_output_formatters(output_verbosity='normal', stderr=sys.stderr, logfile=None, debug_logfile=None): """ Initialize the CLI logging scheme. :param output_verbosity: 'quiet','normal','verbose', or 'debug' controls the output to stdout and its format :param stderr: stream for stderr output, defaul...
Python
jtatman_500k
import random set lst = list string rock string paper string scissors print string hello world print string let's play rock, paper, scissors function fun s begin if s == string n begin return end print call center 50 print call center 50 print call center 50 print call center 50 print call center 50 set player1 = input...
import random lst= ['rock', 'paper', 'scissors'] print("hello world") print("let's play rock, paper, scissors") def fun(s): if(s=='n'): return print("***************************".center(50)) print("1".center(50)) print("2".center(50)) print("GO".center(50)) print("***************************".center(50)) ...
Python
zaydzuhri_stack_edu_python
function format_date date format begin set string = string format time call localtime date format return sub string (^|(?<=[^\w]))0+ string string end function
def format_date(date, format): string = timezone.localtime(date).strftime(format) return re.sub(r"(^|(?<=[^\w]))0+", "", string)
Python
nomic_cornstack_python_v1
import pandas as pd from beemeteo.stations.coordinates import Coordinates class PostalCode begin function __init__ self country postal_code begin set country = country set postal_code = postal_code set data = call _get set latitude = values at 0 set longitude = values at 0 end function function __str__ self begin retur...
import pandas as pd from beemeteo.stations.coordinates import Coordinates class PostalCode: def __init__(self, country, postal_code): self.country = country self.postal_code = postal_code self.data = self._get() self.latitude = self.data["latitude"].values[0] self.longitud...
Python
zaydzuhri_stack_edu_python
import xlsxwriter import re comment from progress.spinner import Spinner comment xlsxwriter comment workbook = xlsxwriter.Workbook('gcmsgs.xlsx') function allgchistory sk gcid begin set filename = call getfilename comment workbook set workbook = call getworkbook filename set ln = length gcid set history = true set rece...
import xlsxwriter import re # from progress.spinner import Spinner # xlsxwriter # workbook = xlsxwriter.Workbook('gcmsgs.xlsx') def allgchistory(sk, gcid): filename = getfilename() workbook = getworkbook(filename) # workbook ln = len(gcid) history = True recentprevious = messageoptions() ...
Python
zaydzuhri_stack_edu_python
function get_links_to_scrape selection_type launch_date flat_type=none town=none begin set flats_available = call get_available_flats selection_type set links = list if flats_available begin set launch_list = list comprehension x for x in flats_available if x at string launch_date == launch_date if length launch_list ...
def get_links_to_scrape(selection_type, launch_date, flat_type=None, town=None): flats_available = get_available_flats(selection_type) links = [] if flats_available: launch_list = [x for x in flats_available if x["launch_date"] == launch_date] if len(launch_list) == 1: launch = l...
Python
nomic_cornstack_python_v1
import csv class Node extends object begin string 节点数据信息 function __init__ self data=dict begin comment ID set id = get data string id string comment 姓名 set name = get data string name string comment 内网账号 set inter = get data string inter string comment 性别 set sex = get data string sex string comment 生日 set birthday = ...
import csv class Node(object): ''' 节点数据信息 ''' def __init__(self, data = {}): self.id = data.get('id', '') #ID self.name = data.get('name', '') #姓名 self.inter = data.get('inter', '') #内网账号 self.sex = d...
Python
zaydzuhri_stack_edu_python
string Distinct powers set comb = list for a in range 2 101 begin for b in range 2 101 begin append comb a ^ b end end
'''Distinct powers''' comb = [] for a in range(2,101): for b in range(2,101): comb.append(a**b)
Python
zaydzuhri_stack_edu_python
function __init__ self config=dict **kwargs begin update self config update self kwargs end function
def __init__(self, config={}, **kwargs): self.update(config) self.update(kwargs)
Python
nomic_cornstack_python_v1
import numpy as np from sklearn import datasets , tree function load_data begin set dataset = call load_iris set iris_data = data set iris_label = target return tuple iris_data iris_label end function function train_test_split iris_data iris_label begin set indices = call permutation length iris_data set split_threshol...
import numpy as np from sklearn import datasets, tree def load_data(): dataset = datasets.load_iris() iris_data = dataset.data iris_label = dataset.target return iris_data, iris_label def train_test_split(iris_data, iris_label): indices = np.random.permutation(len(iris_data)) split_threshold =...
Python
zaydzuhri_stack_edu_python
function get_orthology_sources_from_zebrafishmine self begin comment For further documentation you can visit: comment http://www.intermine.org/wiki/PythonClient comment The following two lines will be needed in every python script: set service = call Service string http://zebrafishmine.org/service comment Get a new que...
def get_orthology_sources_from_zebrafishmine(self): # For further documentation you can visit: # http://www.intermine.org/wiki/PythonClient # The following two lines will be needed in every python script: service = Service("http://zebrafishmine.org/service") # Get a new qu...
Python
nomic_cornstack_python_v1
from pydantic import BaseModel from fastapi import Depends , FastAPI , HTTPException import pymysql from sqlalchemy import create_engine from sqlalchemy.ext.declarative import declarative_base from sqlalchemy.orm import sessionmaker , Session from sqlalchemy import Boolean , Column , Integer , String call install_as_My...
from pydantic import BaseModel from fastapi import Depends, FastAPI, HTTPException import pymysql from sqlalchemy import create_engine from sqlalchemy.ext.declarative import declarative_base from sqlalchemy.orm import sessionmaker, Session from sqlalchemy import Boolean, Column, Integer, String pymysql.install_as_MyS...
Python
zaydzuhri_stack_edu_python
import conf from game_logic import GameLogic from games_result import GameResults import logging as log class SceneGame begin function __init__ self app begin set app = app set next = sceneToday comment узнать номер игры set gameCount = length todayGamesData end function function getScene self begin return next end fun...
import conf from game_logic import GameLogic from games_result import GameResults import logging as log class SceneGame: def __init__(self, app) -> None: self.app = app self.next = app.sceneToday self.gameCount = len(conf.todayGamesData) # узнать номер игры def getScene(self): ...
Python
zaydzuhri_stack_edu_python
function test_models_course_run_field_languages_three_invalid self begin with assert raises ValidationError as context begin call CourseRunFactory languages=list string fr string zzzzz string yyyyy string xxxxx end assert equal messages at 0 string Values zzzzz, yyyyy and xxxxx are not valid choices. end function
def test_models_course_run_field_languages_three_invalid(self): with self.assertRaises(ValidationError) as context: CourseRunFactory(languages=["fr", "zzzzz", "yyyyy", "xxxxx"]) self.assertEqual( context.exception.messages[0], "Values zzzzz, yyyyy and xxxxx are not va...
Python
nomic_cornstack_python_v1
function skip_test n begin return k > 0 and magic * n * k ^ 0.5 >= t4_ref end function
def skip_test(n): return k > 0 and magic * n * k**0.5 >= t4_ref
Python
nomic_cornstack_python_v1
string Constants defining xp allocated for each action class XP_Constants extends object begin function __init__ self begin set verified_xp = 100000 set action_xps = dict string star_project 1 ; string earn_star 50 ; string send_collab 5 ; string recieve_collab 10 ; string add_task 30 ; string complete_task 50 ; string...
''' Constants defining xp allocated for each action ''' class XP_Constants(object): def __init__(self): self.verified_xp = 100000 self.action_xps = { ## stars ## 'star_project' : 1, 'earn_star' : 50, ## collab ## 'send_co...
Python
zaydzuhri_stack_edu_python
comment -*- coding: utf-8 -*- import requests import sys from pymongo import MongoClient import time call reload sys call setdefaultencoding string utf8 comment 设置mongo数据库连接 set client = call MongoClient host=string localhost port=27017 set db = mongo function get_json url page lang_name begin set data = dict string fi...
# -*- coding: utf-8 -*- import requests import sys from pymongo import MongoClient import time reload(sys) sys.setdefaultencoding('utf8') # 设置mongo数据库连接 client = MongoClient(host='localhost', port=27017) db = client.mongo def get_json(url, page, lang_name): data = { 'first':'True', 'pn':page, 'kd':...
Python
zaydzuhri_stack_edu_python
from peewee import CharField , SqliteDatabase , Model , TextField , IntegerField , OperationalError , IntegrityError set db = call SqliteDatabase string artwork.db class Artwork extends Model begin set name = call CharField max_length=1000 unique=true set description = call TextField default=string Good image set thumb...
from peewee import (CharField, SqliteDatabase, Model, TextField, IntegerField, OperationalError, IntegrityError) db = SqliteDatabase("artwork.db") class Artwork(Model): name = CharField(max_l...
Python
zaydzuhri_stack_edu_python
function scale_branch_capacity self zone_name=none branch_id=none begin set anticipated_branch = call _get_df_with_new_elements string branch if boolean zone_name or boolean branch_id is true begin if string branch not in ct begin set ct at string branch = dict end if zone_name is not none begin try begin call _check_...
def scale_branch_capacity(self, zone_name=None, branch_id=None): anticipated_branch = self._get_df_with_new_elements("branch") if bool(zone_name) or bool(branch_id) is True: if "branch" not in self.ct: self.ct["branch"] = {} if zone_name is not None: ...
Python
nomic_cornstack_python_v1
comment !/usr/bin/env python import numpy as np from matplotlib import pyplot as plt set Nmajors = array list 61 65 91 string f set years = array list 2013 2014 2015 string f figure plot years Nmajors string gs markersize=20 x label string Year fontsize=22 y label string Number of Physics Majors fontsize=22 call xticks...
#!/usr/bin/env python import numpy as np from matplotlib import pyplot as plt Nmajors = np.array([61,65,91],'f') years = np.array([2013,2014,2015],'f') plt.figure() plt.plot(years,Nmajors,'gs',markersize=20) plt.xlabel('Year',fontsize=22) plt.ylabel('Number of Physics Majors',fontsize=22) plt.xticks(years,['2013','2...
Python
zaydzuhri_stack_edu_python
comment !/usr/bin/env python3 comment -*- coding: utf-8 -*- string Created on Tue Apr 3 12:10:48 2018 @author: stevedeng from pylab import figure , axes , pie , title , show , savefig comment Make a square figure and axes figure 1 figsize=tuple 6 6 set ax = call axes list 0.1 0.1 0.8 0.8 set labels = tuple string Frogs...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Tue Apr 3 12:10:48 2018 @author: stevedeng """ from pylab import figure, axes, pie, title, show, savefig # Make a square figure and axes figure(1, figsize=(6, 6)) ax = axes([0.1, 0.1, 0.8, 0.8]) labels = 'Frogs', 'Hogs', 'Dogs', 'Logs' fracs = [15, 30, ...
Python
zaydzuhri_stack_edu_python
comment python 3 comment sections pending completion, code will not function import sys , os change directory string C:\ append path string C:\\PyEnviron\\Steveenviron\\Lib\\site-packages from bs4 import BeautifulSoup import tkinter as tk from tkinter import * from tkinter import messagebox as box from tkinter import f...
#python 3 #sections pending completion, code will not function import sys, os os.chdir("C:\\") sys.path.append(r"C:\\PyEnviron\\Steveenviron\\Lib\\site-packages") from bs4 import BeautifulSoup import tkinter as tk from tkinter import * from tkinter import messagebox as box from tkinter import filedialog from ...
Python
zaydzuhri_stack_edu_python
function import_image image_path begin set img = call imread image_path set img = call cvtColor img COLOR_BGR2RGB return img end function
def import_image(image_path): img = cv2.imread(image_path) img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB) return img
Python
nomic_cornstack_python_v1
from flask import Flask , request set app = call Flask name decorator call route string /minmax methods=list string POST function minmax begin set data = call get_json set nums = data at string nums set minVal = min nums set maxVal = max nums return dict string min minVal ; string max maxVal end function if name == str...
from flask import Flask, request app = Flask(name) @app.route('/minmax', methods=['POST']) def minmax(): data = request.get_json() nums = data['nums'] minVal = min(nums) maxVal = max(nums) return {'min': minVal, 'max': maxVal} if name == 'main': app.run()
Python
jtatman_500k
function _parse_location self response begin set loc_parts = list comprehension strip sub string \s+ string part for part in extract call css string #contact-info .right-col-content .content *::text if strip part return dict string name loc_parts at 3 ; string address strip replace join string loc_parts at slice 4 : ...
def _parse_location(self, response): loc_parts = [ re.sub(r"\s+", " ", part).strip() for part in response.css( "#contact-info .right-col-content .content *::text" ).extract() if part.strip() ] return { "name": loc_parts[...
Python
nomic_cornstack_python_v1
from tkinter import * class CheckBox extends Frame begin function __init__ self master begin call __init__ master grid call create_fields end function function create_fields self begin set init_label = grid row=0 column=0 sticky=W set check_footbal = call BooleanVar grid row=1 column=0 sticky=W set check_basketball = c...
from tkinter import * class CheckBox(Frame): def __init__(self, master): super(CheckBox, self).__init__(master) self.grid() self.create_fields() def create_fields(self): self.init_label = Label(self, text=" Wybierz swoje ulubione dyscypliny sportowe:").grid(row=0, column=0, ...
Python
zaydzuhri_stack_edu_python
from collections import defaultdict import itertools import sys from math import log from decimal import Decimal function bi_gram_generator train_data vocab gram=1 weight=tuple 1 0 0 begin set window = gram - 1 set start_sequence = string * * window set end_sequence = string & set count_dict = default dictionary lambda...
from collections import defaultdict import itertools import sys from math import log from decimal import Decimal def bi_gram_generator(train_data,vocab,gram=1,weight=(1,0,0)): window = (gram-1) start_sequence = '*' * window end_sequence = '&' count_dict=defaultdict(lambda : defaultdict(lambda : defaul...
Python
zaydzuhri_stack_edu_python
function add_project_tag gateway tag_text project_id description=none begin set data_manager = call getFacility DataManagerFacility set user = call getLoggedInUser set ctx = call SecurityContext call getGroupId comment Arrange the data set tag_data = call TagAnnotationData tag_text if description begin call setTagDescr...
def add_project_tag(gateway, tag_text, project_id, description=None): data_manager = gateway.getFacility(DataManagerFacility) user = gateway.getLoggedInUser() ctx = SecurityContext(user.getGroupId()) # Arrange the data tag_data = TagAnnotationData(tag_text) if description: tag_data.setT...
Python
nomic_cornstack_python_v1
function DeleteNodeFromContactsPath node begin call _ModifyCSPSearchPathForPath string delete node string /Search/Contacts end function
def DeleteNodeFromContactsPath(node): _ModifyCSPSearchPathForPath('delete', node, '/Search/Contacts')
Python
nomic_cornstack_python_v1
function get_ppm self begin return PARA * power call get_resistance / RZERO - PARB end function
def get_ppm(self): return self.PARA * math.pow((self.get_resistance()/ self.RZERO), -self.PARB)
Python
nomic_cornstack_python_v1
function form_for_model model begin set parts = split __module__ string . set parts at index parts string models = string forms set module_name = join string . parts set form_name = __name__ + string Form set module = call try_import module_name if module is not none begin set form = get attribute module form_name none...
def form_for_model(model): parts = model.__module__.split(".") parts[parts.index("models")] = "forms" module_name = ".".join(parts) form_name = model.__name__ + "Form" module = try_import(module_name) if module is not None: form = getattr(module, form_name, None) ...
Python
nomic_cornstack_python_v1
comment !/usr/bin/env python3 comment -*- coding: utf-8 -*- comment The above encoding declaration is required and the file must be saved as UTF-8 import random comment Этапы работы: comment 1) написать массивы comment 2) написать вывод первых значений вопроса и ответа. Обосновать, что сначало надо задача чтоб работала...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # The above encoding declaration is required and the file must be saved as UTF-8 import random # Этапы работы: # 1) написать массивы # 2) написать вывод первых значений вопроса и ответа. Обосновать, что сначало надо задача чтоб работала, потом украшать. # 3) Написать цикл...
Python
zaydzuhri_stack_edu_python
set tmp = set literal 1 2 3 4 print tmp
tmp = {1,2,3,4} print(tmp)
Python
zaydzuhri_stack_edu_python
import time import string import random import numpy as np function bytes_to_bits byte_array begin string Name: bytes_to_bits Description: Converts byte array to bit array Arguments: - byte_array: Array of bytes, where elements in array in [0,255] Returns: - bit_array: Array of bits, where elements in array are 0 or 1 ...
import time import string import random import numpy as np def bytes_to_bits(byte_array): """ Name: bytes_to_bits Description: Converts byte array to bit array Arguments: - byte_array: Array of bytes, where elements in array in [0,255] Returns: - bit_array: Array of bits, where ...
Python
zaydzuhri_stack_edu_python
comment !/usr/bin/env python comment ***** BEGIN LICENSE BLOCK ***** comment Version: MPL 1.1/GPL 2.0/LGPL 2.1 comment The contents of this file are subject to the Mozilla Public License Version comment 1.1 (the "License"); you may not use this file except in compliance with comment the License. You may obtain a copy o...
#!/usr/bin/env python # ***** BEGIN LICENSE BLOCK ***** # Version: MPL 1.1/GPL 2.0/LGPL 2.1 # # The contents of this file are subject to the Mozilla Public License Version # 1.1 (the "License"); you may not use this file except in compliance with # the License. You may obtain a copy of the License at # http://www.mozil...
Python
zaydzuhri_stack_edu_python
comment !/usr/bin/env python3 import sys import math import os function usage exit_code=0 begin set progname = base name path argv at 0 print string usage: { progname } numValues sizeLowestMean lowestMean sizeNextLowestMean nextLowestMean sizeNextLowestMean nextLowestMean ... sizeHighestMean highestMean MSE Q exit exit...
#!/usr/bin/env python3 import sys import math import os def usage(exit_code=0): progname = os.path.basename(sys.argv[0]) print( f'usage: {progname} numValues sizeLowestMean lowestMean sizeNextLowestMean nextLowestMean sizeNextLowestMean nextLowestMean ... sizeHighestMean highestMean MSE Q') sys.ex...
Python
zaydzuhri_stack_edu_python
comment -*- coding: utf-8 -*- string Created on Sun Mar 29 16:55:45 2020 @author: Sathwik Matcha function next_collatz n begin if n % 2 == 0 begin return n // 2 end if n % 2 == 1 begin return 3 * n + 1 end if n == 1 begin return 1 end end function function len_collatz N begin set cnt = 0 while true begin if N == 1 begi...
# -*- coding: utf-8 -*- """ Created on Sun Mar 29 16:55:45 2020 @author: Sathwik Matcha """ def next_collatz(n): if(n%2==0): return n//2 if(n%2==1): return 3*n+1 if(n==1): return 1 def len_collatz(N): cnt=0 while(True): if(N==1): cnt=0 break ...
Python
zaydzuhri_stack_edu_python
function get_count self club begin set count = call aggregate count string id return integer count at string id__count end function
def get_count (self, club): count = self.filter (club=club) \ .aggregate (Count ('id')) return int (count['id__count'])
Python
nomic_cornstack_python_v1
string TO-DO: Write a description of what this XBlock is. import pkg_resources from xblock.core import XBlock from xblock.fields import Integer , Scope , String from xblock.fragment import Fragment class TestVideoXBlock extends XBlock begin string TO-DO: document what your XBlock does. comment Fields are defined on the...
"""TO-DO: Write a description of what this XBlock is.""" import pkg_resources from xblock.core import XBlock from xblock.fields import Integer, Scope ,String from xblock.fragment import Fragment class TestVideoXBlock(XBlock): """ TO-DO: document what your XBlock does. """ # Fields are defined on the...
Python
zaydzuhri_stack_edu_python
comment 进程之间数据隔离 comment 进程之间通信(IPC) Inter Process Communication comment 基于文件:同一台机器上的多个进程之间的通信 Queue comment # 基于网络:同一台机器或者多态机器上的多进程通信 comment from multiprocessing import Queue, Process comment def son(q): comment q.put('hello') comment if __name__ == '__main__': comment q = Queue() comment Process(target=son, args=(q,...
# 进程之间数据隔离 # 进程之间通信(IPC) Inter Process Communication # 基于文件:同一台机器上的多个进程之间的通信 Queue # # 基于网络:同一台机器或者多态机器上的多进程通信 # from multiprocessing import Queue, Process # # def son(q): # q.put('hello') # # if __name__ == '__main__': # q = Queue() # Process(target=son, args=(q, )).start() # print(q.get()) #...
Python
zaydzuhri_stack_edu_python
function not_in_both l l2 begin set tuple seta setb = tuple set l set l2 return sorted call symmetric_difference setb end function if __name__ == string __main__ begin set _ = input set l = map int split call raw_input set _ = input set l2 = map int split call raw_input end
def not_in_both(l, l2): seta, setb = set(l), set(l2) return sorted(seta.symmetric_difference(setb)) if __name__ == "__main__": _ = input() l = map(int, raw_input().split()) _ = input() l2 = map(int, raw_input().split())
Python
zaydzuhri_stack_edu_python
function makemap filenames sourcedir targetdir=none begin string Return an OrderedDict (to preserve script run order) which maps filenames coming from a single local source directory to a single target directory. Most useful for scripts, whose location when run is often unimportant, and so can all be placed in common d...
def makemap(filenames, sourcedir, targetdir=None): """Return an OrderedDict (to preserve script run order) which maps filenames coming from a single local source directory to a single target directory. Most useful for scripts, whose location when run is often unimportant, and so can all be placed in c...
Python
jtatman_500k
function _build_experiment_seq_embedded_list begin set antibody_embeds = call embed_defaults_for_type base_path=string antibody t=string antibody return embedded_list + antibody_embeds end function
def _build_experiment_seq_embedded_list(): antibody_embeds = DependencyEmbedder.embed_defaults_for_type( base_path='antibody', t='antibody') return ( Experiment.embedded_list + antibody_embeds )
Python
nomic_cornstack_python_v1
function test_get self begin assert equal status_code 200 end function
def test_get(self): self.assertEqual(self.response.status_code, 200)
Python
nomic_cornstack_python_v1
import sys import csv comment Stores the values of STR from dna sequence into a dictionary set dnaDict = dict function main begin comment Checks proper usage and stores the cmd line arguments set length = length argv if length != 3 begin print string Usage: python dna.py data.csv sequence.txt end set database = argv a...
import sys import csv # Stores the values of STR from dna sequence into a dictionary dnaDict = {} def main(): # Checks proper usage and stores the cmd line arguments length = len(sys.argv) if length != 3: print("Usage: python dna.py data.csv sequence.txt") database = sys.argv[1] sequence...
Python
zaydzuhri_stack_edu_python
function checkIndex key begin if not is instance key tuple int float begin raise TypeError end if key < 0 begin raise IndexError end end function
def checkIndex(key): if not isinstance(key, (int, float)): raise TypeError if key<0: raise IndexError
Python
nomic_cornstack_python_v1
function testTreeUnshare self begin set _UNSHARE_LIMIT = 7 for i in call xrange 2 begin set tuple vp_id ep_ids = call ShareNew _cookie list tuple _new_ep_id _photo_ids list user_id for j in call xrange 1 begin call ShareNew _cookie2 list tuple ep_ids at 0 _photo_ids list user_id end end call Unshare _cookie _new_vp_id ...
def testTreeUnshare(self): UnshareOperation._UNSHARE_LIMIT = 7 for i in xrange(2): vp_id, ep_ids = self._tester.ShareNew(self._cookie, [(self._new_ep_id, self._photo_ids)], [self._user2.user_id]) for j in x...
Python
nomic_cornstack_python_v1
function sampling_volume self val begin string Sets sampling volume. if instrument == string Vectrino and type val is float begin if val == 2.5 begin set SamplingVolume = 0 end else if val == 4.0 begin set SamplingVolume = 1 end else if val == 5.5 begin set SamplingVolume = 2 end else if val == 7.0 begin set SamplingVo...
def sampling_volume(self, val): """Sets sampling volume.""" if self.instrument == "Vectrino" and type(val) is float: if val == 2.5: self.pdx.SamplingVolume = 0 elif val == 4.0: self.pdx.SamplingVolume = 1 elif val == 5.5: ...
Python
jtatman_500k
comment !/usr/bin/env python3 set X = integer split input at 0 set ans = if expression X == 0 or X % 100 != 0 then string No else string Yes print ans
#!/usr/bin/env python3 X = int(input().split()[0]) ans = "No" if X == 0 or X % 100 != 0 else "Yes" print(ans)
Python
zaydzuhri_stack_edu_python
function set_radio_buttons self buttons begin if length buttons < 2 begin raise call IndexError string At least two buttons required. end for button in buttons begin if button not in keys _buttons begin raise call ValueError string Button { button } not in button list. end set button_str = if expression button != 1 the...
def set_radio_buttons(self, buttons: Iterable): if len(buttons) < 2: raise IndexError("At least two buttons required.") for button in buttons: if button not in self._buttons.keys(): raise ValueError(f"Button {button} not in button list.") button_str =...
Python
nomic_cornstack_python_v1
function test_dlatch self begin set circ = call DLatch size=2 call pulse call assertSigEq q 0 set d = 3 call assertSigEq q 0 set call assertSigEq q 3 set d = 2 call assertSigEq q 2 end function
def test_dlatch(self): circ = DLatch(size=2) circ.clk.pulse() self.assertSigEq(circ.q, 0) circ.d = 3 self.assertSigEq(circ.q, 0) circ.clk.set() self.assertSigEq(circ.q, 3) circ.d = 2 self.assertSigEq(circ.q, 2)
Python
nomic_cornstack_python_v1
comment Minha solução set matriz = list list list list for x in range 3 begin for y in range 3 begin append matriz at x integer input string Digite: end end print string =- * 30 print matriz at 0 at 0 matriz at 0 at 1 matriz at 0 at 2 print matriz at 1 at 0 matriz at 1 at 1 matriz at 1 at 2 print matriz at 2 at 0 ma...
# Minha solução matriz = [[], [], []] for x in range(3): for y in range(3): matriz[x].append(int(input('Digite: '))) print('=-' * 30) print(matriz[0][0], matriz[0][1], matriz[0][2]) print(matriz[1][0], matriz[1][1], matriz[1][2]) print(matriz[2][0], matriz[2][1], matriz[2][2]) print('=-' * 30) # Solução...
Python
zaydzuhri_stack_edu_python
function read_stats self begin string Read current statistics from chassis. :return: dictionary {stream: {tx: {stat name: stat value}} rx: {tpld: {stat group {stat name: value}}}} set tx_statistics = call TgnObjectsDict for port in values ports begin for stream in values streams begin set tx_statistics at stream = call...
def read_stats(self): """ Read current statistics from chassis. :return: dictionary {stream: {tx: {stat name: stat value}} rx: {tpld: {stat group {stat name: value}}}} """ self.tx_statistics = TgnObjectsDict() for port in self.session.ports.values(): for stream in p...
Python
jtatman_500k
function getDataTypes self name begin Ellipsis end function
def getDataTypes(self, name: unicode) -> List[ghidra.program.model.data.DataType]: ...
Python
nomic_cornstack_python_v1
comment https://github.com/jcjohnson/pytorch-examples comment Code in file tensor/two_layer_net_numpy.py import numpy as np comment N is batch size; D_in is input dimension; comment H is hidden dimension; D_out is output dimension. set tuple N D_in H D_out = tuple 64 1000 100 10 comment Create random input and output d...
# https://github.com/jcjohnson/pytorch-examples ############################################################################### # Code in file tensor/two_layer_net_numpy.py import numpy as np # N is batch size; D_in is input dimension; # H is hidden dimension; D_out is output dimension. N, D_in, H, D_out = 64, 1000, ...
Python
zaydzuhri_stack_edu_python
comment Jude AND Max class MyDictionary begin function __init__ self begin set keyList = list set valuesList = list end function function put self key value begin for i in range length keyList begin if key == keyList at i begin print string ERROR end end append keyList key append valuesList value end function functio...
#Jude AND Max class MyDictionary: def __init__(self): self.keyList = [] self.valuesList = [] def put(self, key, value): for i in range(len(self.keyList)): if key == self.keyList[i]: print('ERROR') self.keyList.append(key) self.valuesList.appe...
Python
zaydzuhri_stack_edu_python
function verify_election_partial_key_backup verifier_id backup auxiliary_key_pair decrypt=rsa_decrypt begin set decrypted_value = call decrypt encrypted_value secret_key if decrypted_value is none begin return call ElectionPartialKeyVerification owner_id designated_id verifier_id false end set value = call get_optional...
def verify_election_partial_key_backup( verifier_id: GUARDIAN_ID, backup: ElectionPartialKeyBackup, auxiliary_key_pair: AuxiliaryKeyPair, decrypt: AuxiliaryDecrypt = rsa_decrypt, ) -> ElectionPartialKeyVerification: decrypted_value = decrypt(backup.encrypted_value, auxiliary_key_pair.secret_key) ...
Python
nomic_cornstack_python_v1
function test_is_traveling self begin set travelcalculator = call TravelCalculator 25 50 with patch string time.time as mock_time begin set return_value = 1580000000.0 assert not call is_traveling assert call position_reached call set_position 80 assert not call is_traveling assert call position_reached set return_valu...
def test_is_traveling(self): travelcalculator = TravelCalculator(25, 50) with patch("time.time") as mock_time: mock_time.return_value = 1580000000.0 assert not travelcalculator.is_traveling() assert travelcalculator.position_reached() travelcalculator.set...
Python
nomic_cornstack_python_v1
function is_public_group_type context group_type_id begin set group_type = call group_type_get context group_type_id return group_type at string is_public end function
def is_public_group_type(context, group_type_id): group_type = db.group_type_get(context, group_type_id) return group_type['is_public']
Python
nomic_cornstack_python_v1
comment 2x^2 + 6x -20 find the roots. set a = 2 set b = 6 set c = - 20 set root1 = - 1 * b + b ^ 2 - 4 * a * c ^ 0.5 / 2 * a set root2 = - 1 * b - b ^ 2 - 4 * a * c ^ 0.5 / 2 * a print string Roots are root1 root2
# 2x^2 + 6x -20 find the roots. a = 2 b = 6 c = -20 root1 = ((-1*b) + (((b**2) - (4*a*c))**0.5)) / (2*a) root2 = ((-1*b) - (((b**2) - (4*a*c))**0.5)) / (2*a) print("Roots are", root1, root2)
Python
zaydzuhri_stack_edu_python
function random_skokka_title stringLength=1 begin set title = string set justDigits = digits set lettersAndDigits = ascii_letters + digits set justLetters = ascii_letters set wordNo = 0 while wordNo <= 4 begin set wordNo = integer join string generator expression random choice justDigits for i in range stringLength e...
def random_skokka_title(stringLength=1): title = '' justDigits = string.digits lettersAndDigits = string.ascii_letters + string.digits justLetters = string.ascii_letters wordNo = 0 while wordNo <= 4: wordNo = int(''.join(random.choice(justDigits) for i in range(stringLength))) wor...
Python
nomic_cornstack_python_v1
function propagate w b X Y begin set m = shape at 1 set A = sigmoid dot T X + b set cost = - sum Y * log A + 1 - Y * log 1 - A / m comment backpropagation set dw = dot X T / m set db = sum A - Y / m assert shape == shape assert dtype == float set cost = squeeze np cost assert shape == tuple set grad = dict string dw d...
def propagate(w,b,X,Y): m = X.shape[1] A = sigmoid(np.dot(w.T,X) + b) cost = -np.sum(Y*np.log(A)+(1-Y)*np.log(1-A))/m #backpropagation dw = np.dot(X,(A-Y).T) / m db = np.sum(A-Y) / m assert (dw.shape == w.shape) assert (db.dtype == float) cost = np.squeeze(cost) assert (cost.s...
Python
nomic_cornstack_python_v1
function connections self cxns begin if cxns is none begin set _connections = array tuple tuple 0 0 1 tuple 0 0 - 1 tuple 0 1 0 tuple 0 - 1 0 tuple 1 0 0 tuple - 1 0 0 dtype=int end else begin set _connections = array tuple generator expression tuple generator expression integer c for c in cxn for cxn in cxns type=int ...
def connections(self, cxns): if cxns is None: self._connections = np.array(((0, 0, 1), (0, 0, -1), (0, 1, 0), (0, -1, 0), (1, 0, 0), (-1, 0, 0)), dtype=int) else: self._connections = np.array(tupl...
Python
nomic_cornstack_python_v1
from cgear import cgear import sys function print_gear gear begin set prnt1 = call ret_data set sprnt0 = format string {:0.2f} cp set sprnt1 = format string {:0.2f} prnt1 at 0 set sprnt2 = format string {:0.2f} prnt1 at 1 set sprnt3 = format string {:0.2f} prnt1 at 2 set sprnt4 = format string {:0.2f} prnt1 at 3 set sp...
from cgear import cgear import sys def print_gear(gear): prnt1 = gear.ret_data() sprnt0 = "{:0.2f}".format(cp) sprnt1 = "{:0.2f}".format(prnt1[0]) sprnt2 = "{:0.2f}".format(prnt1[1]) sprnt3 = "{:0.2f}".format(prnt1[2]) sprnt4 = "{:0.2f}".format(prnt1[3]) sprnt5 = "{:0.2f}".format(prnt1[4])...
Python
zaydzuhri_stack_edu_python
function encoding_onehot df target=none begin if not target begin set target = list string user_type string city end for col in target begin comment Following is exactily the df.join() but is inplace. set one_hot = call get_dummies df at col for item in one_hot begin set df at item = one_hot at item end drop df list co...
def encoding_onehot(df, target=None): if not target: target = ['user_type', 'city'] for col in target: # Following is exactily the df.join() but is inplace. one_hot = pandas.get_dummies(df[col]) for item in one_hot: df[item] = one_hot[item] df.drop([col], axis...
Python
nomic_cornstack_python_v1
comment ----------------- comment animal.py comment ----------------- comment Animal Class class Animal begin function __init__ self name begin set name = name end function function eat self begin print string { name } is eating end function function drink self begin print string { name } is drinking end function end c...
# ----------------- # animal.py # ----------------- # Animal Class class Animal: def __init__(self, name): self.name = name def eat(self): print(f"{self.name} is eating") def drink(self): print(f"{self.name} is drinking") # Frog Class class Frog(Animal): def jump(self): ...
Python
zaydzuhri_stack_edu_python
comment !/usr/bin/env python import mysql.connector import json from collections import Counter import cgi
#!/usr/bin/env python import mysql.connector import json from collections import Counter import cgi
Python
zaydzuhri_stack_edu_python
from datetime import date set ano = integer input string Em que ano você nasceu? set idade = year - ano set categoria = string if idade < 10 begin set categoria = string MIRIM end else if idade < 15 begin set categoria = string INFANTIL end else if idade < 20 begin set categoria = string JUNIOR end else if idade < 26 ...
from datetime import date ano = int(input('Em que ano você nasceu? ')) idade = date.today().year - ano categoria = '' if idade < 10: categoria = 'MIRIM' elif idade < 15: categoria = 'INFANTIL' elif idade < 20: categoria = 'JUNIOR' elif idade < 26: categoria = 'SÊNIOR' else: categoria = 'MASTER' prin...
Python
zaydzuhri_stack_edu_python
import collections set N = integer input set a = list map int split input set c = counter a set ans = 0 set tmp = call most_common at 0 at 1 set tmp2 = call most_common 999999 for i in range length tmp2 begin set tmp3 = tmp2 at i at 1 + c at tmp2 at i at 0 + 1 + c at tmp2 at i at 0 + 2 set tmp4 = tmp2 at i at 1 + c at ...
import collections N = int(input()) a = list(map(int,input().split())) c = collections.Counter(a) ans = 0 tmp = c.most_common()[0][1] tmp2 = c.most_common(999999) for i in range(len(tmp2)): tmp3 = tmp2[i][1] + c[tmp2[i][0] + 1] + c[tmp2[i][0] + 2] tmp4 = tmp2[i][1] + c[tmp2[i][0] - 1] + c[tmp2[i][0] - 2] a...
Python
zaydzuhri_stack_edu_python
class Solution begin comment Principal, if the letter can be swap, it should only be swapped ONCE comment in case you need to swap twice, because a->c->b->a, some letter will be affected comment by other swap, so we need a tmp char for swap, such as, a->tmp, b->a, c->b, tmp->c comment with different order, we can break...
class Solution: # Principal, if the letter can be swap, it should only be swapped ONCE # in case you need to swap twice, because a->c->b->a, some letter will be affected # by other swap, so we need a tmp char for swap, such as, a->tmp, b->a, c->b, tmp->c # with different order, we can break the lo...
Python
zaydzuhri_stack_edu_python
function __repr__ self begin return call to_str end function
def __repr__(self): return self.to_str()
Python
nomic_cornstack_python_v1
function get_items self recursive=false begin if not recursive begin return _block end set res = list for item in _block begin append res item if is instance item Menu begin extend res call get_items true end else if is instance item Choice begin extend res call get_items end end return res end function
def get_items(self, recursive=False): if not recursive: return self._block res = [] for item in self._block: res.append(item) if isinstance(item, Menu): res.extend(item.get_items(True)) elif isinstance(item, Choice): ...
Python
nomic_cornstack_python_v1
import pandas as pd comment use specic column names set df = read csv string Log_May182019_061448.csv usecols=list string Latitude string Longitude comment you can specify new column names while writing to a new file to csv df string Log_May182019_061448_stripped.csv header=list string Latitude string Longitude
import pandas as pd #use specic column names df = pd.read_csv('Log_May182019_061448.csv', usecols = ['Latitude','Longitude']) #you can specify new column names while writing to a new file df.to_csv('Log_May182019_061448_stripped.csv', header = ['Latitude', 'Longitude'])
Python
zaydzuhri_stack_edu_python
set mark1 = integer input string enter the mark of subject 1 set mark2 = integer input string enter the mark of subject 2 set mark3 = integer input string enter the mark of subject 3 set total = mark1 + mark2 + mark3 if total > 140 begin print string A+ end else if total > 130 ? total <= 140 begin print string A end el...
mark1=int(input("enter the mark of subject 1")) mark2=int(input("enter the mark of subject 2")) mark3=int(input("enter the mark of subject 3")) total=mark1+mark2+mark3 if(total>140): print("A+") elif(total>130) & (total<=140): print("A") elif(total>120) & (total<=130): print("B+") else: print("failed") ...
Python
zaydzuhri_stack_edu_python
comment Find the fibonacci number corresponding the given index comment Fibonaci: 0, 1, 1, 2, 3, 5, 8, 13 comment Ex: index: 4 -> 3 function fibonacciIterative index begin set fibonacci = list 0 1 for i in range 1 index begin set number = fibonacci at i + fibonacci at i - 1 append fibonacci number end return fibonacci ...
# Find the fibonacci number corresponding the given index # Fibonaci: 0, 1, 1, 2, 3, 5, 8, 13 # Ex: index: 4 -> 3 def fibonacciIterative(index): fibonacci = [0, 1] for i in range(1, index): number = fibonacci[i] + fibonacci[i-1] fibonacci.append(number) return fibonacci[index] def fibonac...
Python
zaydzuhri_stack_edu_python
function save_frequency count_table input_file begin comment Opens new file to output to with open string { input_file } .out string w as text begin comment Total sum of every word's occurrence in the file. set totalCount = sum values count_table comment Loop through each key and corresponding value in the dictionary f...
def save_frequency(count_table, input_file): # Opens new file to output to with open(f"{input_file}.out", "w") as text: # Total sum of every word's occurrence in the file. totalCount = sum(count_table.values()) # Loop through each key and corresponding value in the dictionary fo...
Python
nomic_cornstack_python_v1
comment !/usr/bin/env python comment encoding: utf-8 string The main file for controlling the audio book reader through a numpad. set __version_info__ = tuple 0 0 1 set __version__ = join string . map str __version_info__ set __author__ = string Andreas Söderlund from main import BookReader from threading import Thread...
#!/usr/bin/env python # encoding: utf-8 """ The main file for controlling the audio book reader through a numpad. """ __version_info__ = (0, 0, 1) __version__ = '.'.join(map(str, __version_info__)) __author__ = "Andreas Söderlund" from main import BookReader from threading import Thread, currentThread try: # Pyth...
Python
zaydzuhri_stack_edu_python
function condition self begin if _now_weather_data begin return CONDITION_MAP at _now_weather_data at string cond at string code end else begin return _msg end end function
def condition(self): if self._now_weather_data: return CONDITION_MAP[self._now_weather_data["cond"]["code"]] else: return self._msg
Python
nomic_cornstack_python_v1
function userInfo self begin comment auth/authenticated is helpful for debugging set auth = string role in session set ret = dict string authenticated auth if auth begin for k in tuple string role string email string projectNumbers begin set ret at k = session at k end end comment ret is a JSON object containing role a...
def userInfo(self): # auth/authenticated is helpful for debugging auth = 'role' in cherrypy.session ret = {'authenticated': auth} if auth: for k in ('role', 'email', 'projectNumbers'): ret[k] = cherrypy.session[k] # ret is a JSON object containing r...
Python
nomic_cornstack_python_v1
import numpy as np comment 1. Steepest Descent function steepest_descent_2d func gradx grady x0 MaxIter=10 learning_rate=0.25 begin for i in range MaxIter begin set grad = array list call gradx *x0 call grady *x0 set x1 = x0 - learning_rate * grad set x0 = x1 end return x0 end function set f = lambda x y -> 3 * x - 2 ^...
import numpy as np # 1. Steepest Descent def steepest_descent_2d(func, gradx, grady, x0, MaxIter=10, learning_rate=0.25): for i in range(MaxIter): grad = np.array([gradx(*x0), grady(*x0)]) x1 = x0 - learning_rate * grad x0 = x1 return x0 f = lambda x,y : 3 * (x - 2)**2 + (y - 2)**2 grad...
Python
zaydzuhri_stack_edu_python
comment !/usr/bin/env python3 comment python ./scripts/feedback_marks.py comment chris.browne@anu.edu.au - all care and no responsibility :) comment =========================================================== string turns the marks spreadsheet into pdf feedback string expects one submission per row import os import con...
#!/usr/bin/env python3 # python ./scripts/feedback_marks.py # # # chris.browne@anu.edu.au - all care and no responsibility :) # =========================================================== '''turns the marks spreadsheet into pdf feedback''' '''expects one submission per row''' import os import config as c import funct...
Python
zaydzuhri_stack_edu_python
function frame self frame_reference begin comment type: (FrameReference) -> None set frame = call FrameResolver frame_reference _driver call will_switch_to_frame eyes_webelement call frame webelement end function
def frame(self, frame_reference): # type: (FrameReference) -> None frame = FrameResolver(frame_reference, self._driver) self.will_switch_to_frame(frame.eyes_webelement) self._switch_to.frame(frame.webelement)
Python
nomic_cornstack_python_v1
comment /*********************************************************************************** comment * This program is free software; you can redistribute it and/or comment * modify it under the terms of the GNU General Public License comment * as published by the Free Software Foundation; either version 2 comment * of...
# /*********************************************************************************** # * This program is free software; you can redistribute it and/or # * modify it under the terms of the GNU General Public License # * as published by the Free Software Foundation; either version 2 # * of the License, or (at y...
Python
zaydzuhri_stack_edu_python
function masahat arz tool vahed begin set vahed1 = string metr set result1 = arz * tool if vahed == string mm begin set result = result1 * 10 ^ - 3 end else if vahed == string cm begin set result = result1 * 10 ^ - 2 end else if vahed == string m begin set result = result1 end else begin set result = result1 print stri...
def masahat(arz, tool, vahed) : vahed1 = 'metr' result1 = arz * tool if vahed == 'mm': result = result1 * 10 ** -3 elif vahed == 'cm': result = result1 * 10 ** -2 elif vahed == 'm': result = result1 else : result = result1 print('vaahed shoma esshtbeh ast ...
Python
zaydzuhri_stack_edu_python
set strings = list string Ready string Set string go string Hello string Pizza string Book string goat string mango set new_list = list comprehension string for string in strings if length string < 6 and any generator expression is upper char for char in string sort new_list key=lambda x -> tuple - length x x print new...
strings = ['Ready', 'Set', 'go', 'Hello', 'Pizza', 'Book', 'goat', 'mango'] new_list = [string for string in strings if len(string) < 6 and any(char.isupper() for char in string)] new_list.sort(key=lambda x: (-len(x), x)) print(new_list)
Python
jtatman_500k
import random comment Generating a random no. set n = integer random * 50 print string Enter any guess between 1 and 50 print string You are having only 5 guesses so choose smartly: comment No.of guesses left set x = 4 while x >= 0 begin comment Taking input set inp = integer input set i = 0 comment Checking conditions...
import random n=int( random.random()*50 ) #Generating a random no. print('Enter any guess between 1 and 50') print('You are having only 5 guesses so choose smartly:') x=4 #No.of guesses left while(x>=0): inp=int(input()) #Ta...
Python
zaydzuhri_stack_edu_python
function test_top self begin set top3 = call top 3 set actual = list dict string systemname string Sleepy ; string lifetimeperformance 1.18652810676406 dict string systemname string Happy ; string lifetimeperformance 1.11151164379285 dict string systemname string Doc ; string lifetimeperformance 1.10329187448733 assert...
def test_top(self): top3 = self.spc.top(3) actual = [{'systemname': 'Sleepy', 'lifetimeperformance': 1.18652810676406}, {'systemname': 'Happy', 'lifetimeperformance': 1.11151164379285}, {'systemname': 'Doc', 'l...
Python
nomic_cornstack_python_v1
comment A Hunter is derived from a Mobile_Simulton and a Pulsator; it updates comment like a Pulsator, but it also moves (either in a straight line comment or in pursuit of Prey), and displays as a Pulsator. from pulsator import Pulsator from mobilesimulton import Mobile_Simulton from prey import Prey from math import ...
# A Hunter is derived from a Mobile_Simulton and a Pulsator; it updates # like a Pulsator, but it also moves (either in a straight line # or in pursuit of Prey), and displays as a Pulsator. from pulsator import Pulsator from mobilesimulton import Mobile_Simulton from prey import Prey from math import atan2 clas...
Python
zaydzuhri_stack_edu_python
function apply self data begin raise NotImplementedError end function
def apply(self, data): raise NotImplementedError
Python
nomic_cornstack_python_v1
from math import * import numpy as np import os string 求出所有topo的路由矩阵 comment 无穷大 set _ = decimal string inf comment 遍历文件夹中的某类文件 function findAllFile base begin for tuple root ds fs in walk base begin for f in fs begin if ends with f string .txt begin set fullname = join path root f yield fullname end end end end functi...
from math import* import numpy as np import os """ 求出所有topo的路由矩阵 """ _=float('inf') #无穷大 def findAllFile(base): #遍历文件夹中的某类文件 for root, ds, fs in os.walk(base): for f in fs: if f.endswith('.txt'): fullname = os.path.join(root, f) yield fullnam...
Python
zaydzuhri_stack_edu_python
from tkinter import * from data import * from file_management import save_an_object , read_an_object function get_owned_var_name begin for k in keys owned_var_name begin set list_owned_units at k = get owned_var_name at k end call save_an_object list_owned_units string owned_units end function function get_add_var_name...
from tkinter import * from data import * from file_management import save_an_object, read_an_object def get_owned_var_name(): for k in owned_var_name.keys(): list_owned_units[k] = owned_var_name[k].get() save_an_object(list_owned_units, "owned_units") def get_add_var_name(): for k in add_var_n...
Python
zaydzuhri_stack_edu_python
import math import os function ReadSampleData dir_path begin set InputSamples = list set SpeedSamples = list set DirectionSamples = list set Fitness = list set files = list directory dir_path for sample_file in files begin if sample_file at slice - 4 : : != string .csv begin continue end set file_path = dir_path ...
import math import os def ReadSampleData(dir_path): InputSamples = [] SpeedSamples = [] DirectionSamples = [] Fitness = [] files = os.listdir(dir_path) for sample_file in files: if sample_file[-4:] != '.csv': continue file_path = dir_path + '/' + sample_file f = open(file_path,'r') if...
Python
zaydzuhri_stack_edu_python
from selenium import webdriver from selenium.webdriver.common.keys import Keys set driver = call Chrome get driver string https://example.com/form set first_name = call find_element_by_name string first_name set last_name = call find_element_by_name string last_name call send_keys string John call send_keys string Doe ...
from selenium import webdriver from selenium.webdriver.common.keys import Keys driver = webdriver.Chrome() driver.get('https://example.com/form') first_name = driver.find_element_by_name('first_name') last_name = driver.find_element_by_name('last_name') first_name.send_keys('John') last_name.send_keys('Doe') last_name....
Python
flytech_python_25k
function run_forever self *args **kwargs begin sleep random * interval while true begin set begin = time info call _ string Begin object audit sweep call run_once *args keyword kwargs set elapsed = time - begin info call _ string Object audit sweep completed: %.02fs elapsed call dump_recon_cache dict string object_audi...
def run_forever(self, *args, **kwargs): time.sleep(random.random() * self.interval) while True: begin = time.time() self.logger.info(_('Begin object audit sweep')) self.run_once(*args, **kwargs) elapsed = time.time() - begin self.logger.info(_(...
Python
nomic_cornstack_python_v1
function deep_copy self begin set size = _size set regions = list set tys = list for reg in _regions begin set interval = list for i in range length reg begin append interval reg at i end append regions interval end for x in _types begin append tys x end return call Dimension size regions tys end function
def deep_copy(self): size = self._size regions = [] tys = [] for reg in self._regions: interval = [] for i in range(len(reg)): interval.append(reg[i]) regions.append(interval) for x in self._types: tys.append(x) ...
Python
nomic_cornstack_python_v1
import os import re from pathlib import Path from flask import Flask , request from flask_restful import Api , Resource from flask_restful.utils import cors from pytube import YouTube set app = call Flask __name__ set api = call Api app set youtube_pattern = compile string (https?\:\/\/)?(www\.youtube\.com|youtu\.?be)\...
import os import re from pathlib import Path from flask import Flask, request from flask_restful import Api, Resource from flask_restful.utils import cors from pytube import YouTube app = Flask(__name__) api = Api(app) youtube_pattern = re.compile(r'(https?\:\/\/)?(www\.youtube\.com|youtu\.?be)\/.+') outer_dir = P...
Python
zaydzuhri_stack_edu_python
function calculate_hex self hex_string begin set hex_conv = split hex_string string : set converted_hex = integer hex_conv at 0 16 + integer hex_conv at 1 16 / 8192 return converted_hex end function
def calculate_hex(self, hex_string): hex_conv = hex_string.split(':') converted_hex = (int(hex_conv[0], 16) + int(hex_conv[1], 16))/8192 return converted_hex
Python
nomic_cornstack_python_v1
import random set HANGMAN = tuple string ------ | | | | | | | | | ---------- string ------ | | | O | | | | | | ---------- string ------ | | | O | -+- | | | | | ---------- string ------ | | | O | /-+- | | | | | ---------- string ------ | | | O | /-+-/ | | | | | ---------- string ------ | | | O | /-+-/ | | | | | | ------...
import random HANGMAN = ( """ ------ | | | | | | | | | ---------- """, """ ------ | | | O | | | | | | ---------- """, """ ------ | | | O | -+- | ...
Python
zaydzuhri_stack_edu_python
function parse_args argv=none begin set parser = call ArgumentParser description=__doc__ call add_argument string key call add_argument string value call add_argument string -o dest=string filepath help=string Save the file to the specified path. call add_argument string -p dest=string percentage_mode action=string sto...
def parse_args(argv=None): parser = argparse.ArgumentParser(description=__doc__) parser.add_argument('key') parser.add_argument('value') parser.add_argument('-o', dest='filepath', help='Save the file to the specified path.') parser.add_argument('-p', dest='percentage_mode',...
Python
nomic_cornstack_python_v1