code
stringlengths
10
2.58M
original_code
stringlengths
3
3.18M
original_language
stringclasses
1 value
source
stringclasses
7 values
function fp self groups=none ignore=none begin set ignore = if expression ignore is none then list else ignore set groups = if expression groups is none then list else groups set postfix = sorted set list comprehension x at string name for x in _options - set sum groups list - set ignore set groups = map _names_to_st...
def fp(self, groups=None, ignore=None): ignore = [] if ignore is None else ignore groups = [] if groups is None else groups postfix = sorted(set([x['name'] for x in self._options]) - set(sum(groups, [])) - set(ignore)) groups = map(self._names_to_str, groups) ...
Python
nomic_cornstack_python_v1
import random import math from classRobot import * from classArene import * from classCapteur import * class Controlleur begin string classe premettant de créer un controlleur function __init__ self begin set id = 1 end function function alea self capteur arene robot begin comment si le robot est à l'arret if call getV...
import random import math from classRobot import * from classArene import * from classCapteur import * class Controlleur: """ classe premettant de créer un controlleur""" def __init__(self): self.id=1 def alea(self,capteur,arene,robot): #si le robot est à l'arret if(robot.getVX() == 0.0 and robot.getVY()...
Python
zaydzuhri_stack_edu_python
function impute self imputer begin for i in range length methylation_arrays begin call impute imputer end end function
def impute(self, imputer): for i in range(len(self.methylation_arrays)): self.methylation_arrays[i].impute(imputer)
Python
nomic_cornstack_python_v1
function __len__ self begin return count self end function
def __len__(self): return self.count()
Python
nomic_cornstack_python_v1
set nombre = input string Ingrese el nombre: print 1000 * nombre + string
nombre = input("Ingrese el nombre: ") print(1000*(nombre+" "))
Python
zaydzuhri_stack_edu_python
comment !/usr/bin/env python3 comment -*- coding: utf-8 -*- string Created on Fri May 14 17:32:19 2021 @author: abby import pandas as pd import seaborn as sns import matplotlib.pyplot as plt set corr = read csv string correlations.csv set corr = drop corr 9 set rename = dict string Unnamed: 0 string Requirement set cor...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Fri May 14 17:32:19 2021 @author: abby """ import pandas as pd import seaborn as sns import matplotlib.pyplot as plt corr = pd.read_csv("correlations.csv") corr = corr.drop(9) rename = {"Unnamed: 0" : "Requirement"} corr = corr.rename(columns=rename) corr...
Python
zaydzuhri_stack_edu_python
import random import pandas as pd class Game begin set n_squares = 10 set winner = none function __init__ self bots use_trace=true verbose=false begin set bots = bots set use_trace = use_trace set verbose = verbose if use_trace begin set trace_df = call DataFrame call _save_trace end call _set_starting_positions end fu...
import random import pandas as pd class Game: n_squares = 10 winner = None def __init__(self, bots, use_trace=True, verbose=False): self.bots = bots self.use_trace = use_trace self.verbose = verbose if self.use_trace: self.trace_df = pd.DataFrame() ...
Python
zaydzuhri_stack_edu_python
comment with loop comment total = 0 comment count = 0 comment while True : comment inp = input('Enter a number: ') comment if inp == 'done' : break comment value = float(inp) comment total = total + value comment count = count + 1 comment average = total / count comment print('Average1 : ', average) comment with lists ...
#with loop #total = 0 #count = 0 #while True : # inp = input('Enter a number: ') # if inp == 'done' : break # value = float(inp) # total = total + value # count = count + 1 #average = total / count #print('Average1 : ', average) #with lists numlist = list() while True : inp = input('E...
Python
zaydzuhri_stack_edu_python
string Script downloads seasonal hindcast data from the ECMWF/EU Copernicus Climate Change Service Climate Data Store Note that the python package 'cdsapi' is needed and a cds api key must be installed locally in order for the forecast downloads to work. See following link for further details: https://cds.climate.coper...
''' Script downloads seasonal hindcast data from the ECMWF/EU Copernicus Climate Change Service Climate Data Store Note that the python package 'cdsapi' is needed and a cds api key must be installed locally in order for the forecast downloads to work. See following link for further details: https://cds.climate.coperni...
Python
zaydzuhri_stack_edu_python
import random string a=5.2 print(type(a)) b="hello" print(b[-4]) comment print("hello") set c = string asdfghu print length c print c at slice 2 : 6 : 2 print c at slice - 1 : : - 1 set d = list string hello string heyna print d append d string hey print d string print(d.pop(2)) print(d) sort d print d print 2 == 3 fo...
import random """a=5.2 print(type(a)) b="hello" print(b[-4])""" #print("hello") c="asdfghu" print(len(c)) print(c[2:6:2]) print(c[-1::-1]) d=['hello',"heyna"] print(d) d.append("hey") print(d) """print(d.pop(2)) print(d)""" d.sort() print(d) print(2==3) for i in range(-2,10): print(i) print(type(i)) x=[1,2,3,4,5,6,7] ...
Python
zaydzuhri_stack_edu_python
string This module is responsible for the Unbabel Translation API service. It fetches the authorization to make calls to the Unbabel API from a local config and defines the helper functions that make the calls to the API in sandbox mode. Unbabel API docs: https://developers.unbabel.com/v2/docs class UnbabelAPIError : E...
""" This module is responsible for the Unbabel Translation API service. It fetches the authorization to make calls to the Unbabel API from a local config and defines the helper functions that make the calls to the API in sandbox mode. Unbabel API docs: https://developers.unbabel.com/v2/docs class UnbabelAPIError ...
Python
zaydzuhri_stack_edu_python
comment !/usr/bin/env python comment coding:utf-8 import os , sys from cryptography.fernet import Fernet set victim = environ at string USERNAME set drive = environ at string SystemDrive set path = format string {}.key victim set file = open path string rb set key = read file close file function decrypt filename key be...
#!/usr/bin/env python #coding:utf-8 import os, sys from cryptography.fernet import Fernet victim = os.environ["USERNAME"] drive = os.environ["SystemDrive"] path = "{}.key".format(victim) file = open(path, 'rb') key = file.read() file.close() def decrypt(filename, key): """ Given a filename (...
Python
zaydzuhri_stack_edu_python
while length l > 1 begin if i % 2 == 0 begin set l = l at slice 0 : length l - 1 : end else begin set l = l at slice 1 : length l : end set i = i + 1 end print l at 0
while len(l) > 1: if i % 2 == 0: l = l[0:len(l) - 1] else: l = l[1:len(l)] i = i + 1 print(l[0])
Python
jtatman_500k
function puzzle_pieces a1 a2 begin if length a1 == length a2 begin return length set list comprehension a1 at i + a2 at i for i in range length a1 == 1 end else begin return false end end function
def puzzle_pieces(a1, a2): if len(a1) == len(a2): return len(set([a1[i] + a2[i] for i in range(len(a1))])) == 1 else: return False
Python
zaydzuhri_stack_edu_python
function shipping_system_name self shipping_system_name begin set _shipping_system_name = shipping_system_name end function
def shipping_system_name(self, shipping_system_name): self._shipping_system_name = shipping_system_name
Python
nomic_cornstack_python_v1
function update self map camera mpos aggro_list dt begin comment updates to look at the mouse call look_at_screen_point mpos camera update current_weapon self dt camera comment advance the attack animation timer set attack_anim_timer = attack_anim_timer + dt comment advance the movement animation timer set move_anim_ti...
def update(self, map, camera, mpos, aggro_list, dt): self.look_at_screen_point(mpos, camera) # updates to look at the mouse self.current_weapon.Update(self, dt, camera) self.attack_anim_timer += dt # advance the attack animation timer self.move_anim_timer += dt # advance the movem...
Python
nomic_cornstack_python_v1
string Script to generate table for the evaluation section of the measurement paper. The table has the following format: Topology | Term Size | ## Switches | Query1 | Query2 | Query3 | ... import csv import sys comment If true, this script creates a super big table. Otherwise, it creates a table comment that would fit ...
""" Script to generate table for the evaluation section of the measurement paper. The table has the following format: Topology | Term Size | ## Switches | Query1 | Query2 | Query3 | ... """ import csv import sys # If true, this script creates a super big table. Otherwise, it creates a table # that would fit in t...
Python
zaydzuhri_stack_edu_python
comment !/usr/bin/env python import roslib import rospy import cv2 import copy from sensor_msgs.msg import Image from cv_bridge import CvBridge , CvBridgeError from cmvision.msg import Blobs , Blob from std_msgs.msg import Int32 set colorImage = call Image set isColorImageReady = false set blobsInfo = call Blobs set is...
#!/usr/bin/env python import roslib import rospy import cv2 import copy from sensor_msgs.msg import Image from cv_bridge import CvBridge, CvBridgeError from cmvision.msg import Blobs, Blob from std_msgs.msg import Int32 colorImage = Image() isColorImageReady = False blobsInfo = Blobs() isBlobsInfoReady = False bigBlo...
Python
zaydzuhri_stack_edu_python
function cmd_set_origin self args begin string called when user selects "Set Origin (with height)" on map set tuple lat lon = tuple click_position at 0 click_position at 1 set alt = call GetElevation lat lon print string Setting origin to: lat lon alt call set_gps_global_origin_send target_system lat * 10000000 lon * 1...
def cmd_set_origin(self, args): '''called when user selects "Set Origin (with height)" on map''' (lat, lon) = (self.click_position[0], self.click_position[1]) alt = self.ElevationMap.GetElevation(lat, lon) print("Setting origin to: ", lat, lon, alt) self.master.mav.set_gps_global...
Python
jtatman_500k
function euler1 n begin string Sums all the integers that are multiple of 3 or 5 between 0 and n set u = 0 for i in range n begin if i % 3 == 0 or i % 5 == 0 begin set u = i + u end end print u end function call euler1 1000
def euler1(n): """Sums all the integers that are multiple of 3 or 5 between 0 and n""" u = 0 for i in range(n): if i % 3 == 0 or i % 5 == 0: u = i + u print(u) euler1(1000)
Python
zaydzuhri_stack_edu_python
function action_approve self reviewer=none begin if status == string in_review begin set status = string approved set is_published = true set reviewed_by = reviewer save comment Send email call send sender=self instance=self end else begin raise call ValueError string In order to approve an Report, it should be in 'in-...
def action_approve(self, reviewer=None): if self.status == 'in_review': self.status = 'approved' self.is_published = True self.reviewed_by = reviewer self.save() # Send email report_accepted.send(sender=self, instance=self) else: ...
Python
nomic_cornstack_python_v1
function addWeight self weight begin if not weight in weights begin append weights weight end else begin raise call RuntimeError string Weight %s already defined in sample %s % tuple weight name end for syst in values systDict begin if type == string weight begin if not weight in high begin append high weight end if no...
def addWeight(self, weight): if not weight in self.weights: self.weights.append(weight) else: raise RuntimeError("Weight %s already defined in sample %s" % (weight, self.name)) for syst in self.systDict.values(): if syst.type == "weight": if n...
Python
nomic_cornstack_python_v1
function performFilterXS self begin debug string filtering x data before aggregating and plotting debug string dataframe was %s rows % length dataframe set dataframe = dataframe at dataframe at xAxis > filterMinXs ? dataframe at xAxis < filterMaxXs debug string dataframe now %s rows % length dataframe end function
def performFilterXS(self): logger.debug("filtering x data before aggregating and plotting") logger.debug("dataframe was %s rows" % (len(self.dataframe))) self.dataframe = self.dataframe[(self.dataframe[self.xAxis]>self.filterMinXs) &(self.dataframe[self.xAxis]<self.filterMaxXs)] logger.d...
Python
nomic_cornstack_python_v1
function get_model_zoo_model_path workspace_path framework domain model_name model_dict begin if workspace_path is none begin return string end set model_dir = join path workspace_path string examples framework domain model_name set model_relative_path = get get model_dict string download dict string filename none if ...
def get_model_zoo_model_path( workspace_path: Optional[str], framework: str, domain: str, model_name: str, model_dict: Dict[str, Any], ) -> str: if workspace_path is None: return "" model_dir = os.path.join( workspace_path, "examples", framework, domai...
Python
nomic_cornstack_python_v1
function execute self args begin set all_args = list args try begin return call _cmd all_args end except OSError as e begin if E2BIG == errno begin set tuple args1 args2 = call _split_args all_args set result = execute self args1 if result != 0 begin return result end return execute self args2 end else begin raise e en...
def execute(self, args): all_args = list(args) try: return self._cmd(all_args) except OSError as e: if errno.E2BIG == e.errno: args1, args2 = self._split_args(all_args) result = self.execute(args1) if result != 0: return result return self.execute(args2)...
Python
nomic_cornstack_python_v1
function find_common var1 var2 begin comment if either of VAR is None if not var1 and var2 begin return 0 end set vars1 = list deep copy var1 deep copy var2 for vi in range 2 begin if is instance vars1 at vi int begin set vars1 at vi = set string vars1 at vi end if is instance vars1 at vi str begin set vars1 at vi = li...
def find_common(var1, var2) -> int: if not (var1 and var2): # if either of VAR is None return 0 vars1 = [copy.deepcopy(var1), copy.deepcopy(var2)] for vi in range(2): if isinstance(vars1[vi], int): vars1[vi] = set(str(vars1[vi])) if isinstance(vars1[vi], str): ...
Python
nomic_cornstack_python_v1
string DESCRIPTION This class controls the Transmitter and Receiver topologies. Currently, the array antennas could be allocated only along y axis and only the MT can move. Inputs: mode: 0 for Transmitter, 1 for Receiver nAntennas: Number of array antennas spacing: The spacing between the array antennas position: The v...
""" DESCRIPTION This class controls the Transmitter and Receiver topologies. Currently, the array antennas could be allocated only along y axis and only the MT can move. Inputs: mode: 0 for Transmitter, 1 for Receiver nAntennas: Number of array antennas spacing: The spacing betwee...
Python
zaydzuhri_stack_edu_python
function sum_array_elements arr begin set result = 0 for i in range length arr begin set result = result + arr at i end return result end function set arr = list 1 2 3 4 print call sum_array_elements arr
def sum_array_elements(arr): result = 0 for i in range(len(arr)): result += arr[i] return result arr = [1, 2, 3, 4] print(sum_array_elements(arr))
Python
jtatman_500k
string Write a function that sorts list while keeping the list structure. Numbers should be first then letters both in ascending order. ### Examples num_then_char([ [1, 2, 4, 3, "a", "b"], [6, "c", 5], [7, "d"], ["f", "e", 8] ]) ➞ [ [1, 2, 3, 4, 5, 6], [7, 8, "a"], ["b", "c"], ["d", "e", "f"] ] num_then_char([ [1, 2, 4...
""" Write a function that sorts list while keeping the list structure. Numbers should be first then letters both in ascending order. ### Examples num_then_char([ [1, 2, 4, 3, "a", "b"], [6, "c", 5], [7, "d"], ["f", "e", 8] ]) ➞ [ [1, 2, 3, 4, 5, 6], [7, 8, "a"], ["b", "c...
Python
zaydzuhri_stack_edu_python
comment !/usr/bin/python import numpy as np import csv import matplotlib as mpl import matplotlib.pyplot as plt import matplotlib.image as mpimg import palettable from palettable.colorbrewer.qualitative import Dark2_3 from argparse import ArgumentParser comment Global matplotlib parameters set params = dict string axes...
#!/usr/bin/python import numpy as np import csv import matplotlib as mpl import matplotlib.pyplot as plt import matplotlib.image as mpimg import palettable from palettable.colorbrewer.qualitative import Dark2_3 from argparse import ArgumentParser # Global matplotlib parameters params = { 'axes.labelsize': 16, 'axe...
Python
zaydzuhri_stack_edu_python
function create_account_from_email email begin set passwd = call make_random_password length=8 return tuple call create_account string string email passwd passwd end function
def create_account_from_email(email): passwd = User.objects.make_random_password(length=8) return create_account('', '', email, passwd), passwd
Python
nomic_cornstack_python_v1
function _set_value self v load=false begin if has attribute v string _utype begin set v = call _utype v end try begin set t = call YANGDynClass v base=call RestrictedClassType base_type=long restriction_dict=dict string range list string 0..4294967295 int_size=32 is_leaf=true yang_name=string value parent=self path_he...
def _set_value(self, v, load=False): if hasattr(v, "_utype"): v = v._utype(v) try: t = YANGDynClass(v,base=RestrictedClassType(base_type=long, restriction_dict={'range': ['0..4294967295']}, int_size=32), is_leaf=True, yang_name="value", parent=self, path_helper=self._path_helper, extmethods=self._ex...
Python
nomic_cornstack_python_v1
function get_file_storage self file_storage begin try begin return call get_file_volume_details file_storage end except SoftLayerAPIError as error begin return call resource_error faultCode faultString end end function
def get_file_storage(self, file_storage): try: return self.file.get_file_volume_details(file_storage) except sl.SoftLayer.SoftLayerAPIError as error: return resource_error(error.faultCode, error.faultString)
Python
nomic_cornstack_python_v1
comment https://www.geeksforgeeks.org/form-minimum-number-from-given-sequence/amp/ comment Form minimum number from given sequence function find_possible_smallest_number_matching_pattern pattern begin set n = length pattern if n >= 9 begin return string -1 end if not string I in pattern or string D in pattern begin ret...
# https://www.geeksforgeeks.org/form-minimum-number-from-given-sequence/amp/ # Form minimum number from given sequence def find_possible_smallest_number_matching_pattern(pattern): n = len(pattern) if n >= 9: return "-1" if not ('I' in pattern or 'D' in pattern): return "-1" result = ...
Python
zaydzuhri_stack_edu_python
comment INPUTS###### comment pary input###### set charnumber = integer input string Number of characters in the party? set count = 0 set charlevels = list 0 0 0 0 0 0 0 0 0 0 while count < charnumber and charnumber > 1 begin print string Character %d is what level? % count + 1 set charlevels at count = integer input st...
######INPUTS###### ######pary input###### charnumber = int(input("Number of characters in the party? ")) count = 0 charlevels = [0,0,0,0,0,0,0,0,0,0] while count < charnumber and charnumber > 1: print("Character %d is what level? " % (count +1)) charlevels[count] = int(input(" ")) count += 1 if cha...
Python
zaydzuhri_stack_edu_python
function test self obj begin pass end function
def test(self, obj): pass
Python
nomic_cornstack_python_v1
function millisecond_timestamp_to_utc_datetime self milliseconds begin return replace call utcfromtimestamp milliseconds / SECONDS_TO_MILLISECONDS tzinfo=tzinfo end function
def millisecond_timestamp_to_utc_datetime(self, milliseconds): return datetime.utcfromtimestamp(milliseconds/self.SECONDS_TO_MILLISECONDS).replace(tzinfo=self.tzinfo)
Python
nomic_cornstack_python_v1
function test_encrypt_fail client begin set response = post reverse string devoff:encrypt content_type=string application/json assert status_code == 422 assert string mensaje in json response assert string vueltas in json response end function
def test_encrypt_fail(client): response = client.post(reverse("devoff:encrypt"), content_type="application/json",) assert response.status_code == 422 assert "mensaje" in response.json() assert "vueltas" in response.json()
Python
nomic_cornstack_python_v1
function computeTrajectoryWithDecceleration self cmd_vel current_speed delay_time time_applied time_decc begin set accs = list acc_x acc_th dacc_x dacc_th comment project forwards in time set sim_interval = sim_interval set sim_interval_sq = sim_interval * sim_interval set cmd_vel = list cmd_vel set current_speed = lis...
def computeTrajectoryWithDecceleration(self, cmd_vel, current_speed, delay_time, time_applied, time_decc): accs = [self.robot.acc_x, self.robot.acc_th, self.robot.dacc_x,self.robot.dacc_th ] #project forwards in time sim_interval = self.sim_interval sim_interval_sq = sim_interval*sim_in...
Python
nomic_cornstack_python_v1
string Connection Module Handles put and get operations to the a REST API import sys import urllib import logging import simplejson from urlparse import urlparse from pprint import pprint , pformat from httplib import HTTPSConnection , HTTPException from xml.sax import parse , parseString from xml.sax.handler import Co...
""" Connection Module Handles put and get operations to the a REST API """ import sys import urllib import logging import simplejson from urlparse import urlparse from pprint import pprint, pformat from httplib import HTTPSConnection, HTTPException from xml.sax import parse, parseString from xml.sax.handler import Co...
Python
zaydzuhri_stack_edu_python
set REST_FRAMEWORK = dict string DEFAULT_AUTHENTICATION_CLASSES list string rest_framework.authentication.SessionAuthentication string rest_framework.authentication.TokenAuthentication ; string DEFAULT_PERMISSION_CLASSES list string rest_framework.permissions.IsAuthenticated set REST_FRAMEWORK = dict string DEFAULT_PAG...
REST_FRAMEWORK = { 'DEFAULT_AUTHENTICATION_CLASSES': [ 'rest_framework.authentication.SessionAuthentication', 'rest_framework.authentication.TokenAuthentication', ], 'DEFAULT_PERMISSION_CLASSES': [ 'rest_framework.permissions.IsAuthenticated', ], } REST_FRAMEWORK = { 'DEFAU...
Python
jtatman_500k
comment coding:utf-8 string Created on 2017/10/16 下午2:38 @author: liucaiquan comment import numpy as np comment my_array = np.array([[1., 3., 5., 7., 9.], comment [-2., 0., 2., 4., 6.], comment [-6., -3., 0., 3., 6.]]) comment x_vals = np.array([my_array, my_array + 1]) comment print x_vals import tensorflow as tf
# coding:utf-8 ''' Created on 2017/10/16 下午2:38 @author: liucaiquan ''' # import numpy as np # # my_array = np.array([[1., 3., 5., 7., 9.], # [-2., 0., 2., 4., 6.], # [-6., -3., 0., 3., 6.]]) # # x_vals = np.array([my_array, my_array + 1]) # # print x_vals import tensorflow a...
Python
zaydzuhri_stack_edu_python
function test_types begin set sb = call SchemaBuilder set schema = schema comment TODO: add this functionality to SchemaBuilder set t = call TypeDefinition string MyString description=string my string typeof=string string set types at name = t call _roundtrip schema TYPES_SPEC end function
def test_types(): sb = SchemaBuilder() schema = sb.schema # TODO: add this functionality to SchemaBuilder t = TypeDefinition('MyString', description='my string', typeof='string') schema.types[t.name] = t _roundtrip(schema, TYPES_SPEC)
Python
nomic_cornstack_python_v1
function plan_asgs asgs begin set asg_outdated_instance_dict = dict for asg in asgs begin set asg_name = asg at string AutoScalingGroupName info format string *** Checking autoscaling group {} *** asg_name set launch_type = string set asg_lc_name = string set asg_lt_name = string set asg_lt_version = string if str...
def plan_asgs(asgs): asg_outdated_instance_dict = {} for asg in asgs: asg_name = asg['AutoScalingGroupName'] logger.info('*** Checking autoscaling group {} ***'.format(asg_name)) launch_type = "" asg_lc_name = "" asg_lt_name = "" asg_lt_version = "" if 'La...
Python
nomic_cornstack_python_v1
function getInput begin try begin set infile = open string data.txt string r end except IOError begin print string File IO Error call quit end finally begin return read infile end end function function putOutput arr begin try begin set outfile = open string insert.out string w end except IOError begin print string File...
def getInput(): try: infile = open('data.txt', 'r') except IOError: print("File IO Error") quit() finally: return infile.read() def putOutput(arr): try: outfile = open('insert.out', 'w') except IOError: print("File IO Error") qui...
Python
zaydzuhri_stack_edu_python
function device_state_attributes self begin if _state is none or _attrs is none begin return none end set attributes = dict string max_usage _attrs at string limit at 0 ; string last_updated _attrs at string last_updated ; string used_percentage percentage_used ; string subscription_type _attrs at string subscription_t...
def device_state_attributes(self): if self._state is None or self._attrs is None: return None attributes = { 'max_usage': self._attrs['limit'][0], 'last_updated': self._attrs['last_updated'], 'used_percentage': self.percentage_used, 'subscript...
Python
nomic_cornstack_python_v1
import pandas as pd import numpy as np from scipy.stats import entropy import math class Node begin function __init__ self bools=none abClass=none begin set bools = bools set abClass = abClass end function end class function read begin set nodelist = list set filepath = string dtree-data with open filepath as fp begin...
import pandas as pd import numpy as np from scipy.stats import entropy import math class Node: def __init__(self, bools=None, abClass=None): self.bools = bools abClass = abClass def read(): nodelist = [] filepath = 'dtree-data' with open(filepath) as fp: line = fp.readline() ...
Python
zaydzuhri_stack_edu_python
comment import BeautifulSoup from bs4 import BeautifulSoup as bs import requests from selenium import webdriver from splinter import Browser import pandas as pd function init_browser begin comment @NOTE: Replace the path with your actual path to the chromedriver set executable_path = dict string executable_path string ...
#import BeautifulSoup from bs4 import BeautifulSoup as bs import requests from selenium import webdriver from splinter import Browser import pandas as pd def init_browser(): # @NOTE: Replace the path with your actual path to the chromedriver executable_path = {'executable_path': 'chromedriver.exe'} return ...
Python
zaydzuhri_stack_edu_python
function events time begin set event_list = call eventlist set idx = all time == event_list at tuple slice : : slice 0 : length time : axis=1 return event_list at tuple idx slice : : end function
def events(time): event_list = eventlist() idx = np.all(time == event_list[:, 0:len(time)], axis=1) return event_list[idx,:]
Python
nomic_cornstack_python_v1
function rife_interpolator_video_processor video_path output_path=none model=none exp=none dst_fps=none scale=0.5 skip=true out_ext=none png=false out_png_path=none UHD=true montage=false begin comment Ignore the parameter warnings from PyTorch. filter warnings string ignore comment Ensure that the video path exists. i...
def rife_interpolator_video_processor(video_path: AnyPath, output_path: AnyPath = None, model: MediaVisionModelBase = None, exp: int = None, dst_fps: int = None, scale: float = 0.5, skip: bool = True, ...
Python
nomic_cornstack_python_v1
import numpy as np import torch print string Computing Batch Norm Derivative set m = 4 set means = 0.8285777243 set variance = 0.000459415 set epsilon = 1e-05 set zin = call asarray list 0.864475136 0.8250697742 0.8099140393 0.8148519478 set zout = call asarray list 1.6568555953 - 0.1619104702 - 0.8614278725 - 0.633517...
import numpy as np import torch print( 'Computing Batch Norm Derivative ') m = 4 means = 0.8285777243 variance = 0.0004594150 epsilon = 1e-5 zin = np.asarray ( [ 0.8644751360 , 0.8250697742 , 0.8099140393 , 0.8148519478 ] ) zout = np.asarray( [ 1.6568555953 , -0.1619104702 , -0.8614278725 , -0.6335172527 ] ) rzi...
Python
zaydzuhri_stack_edu_python
function test_fma_invalid_param_intnum_intnum_bytes_none_908 self begin comment This version is expected to pass. call fma floatarrayx floatnumy floatarrayz comment This is the actual test. with assert raises TypeError begin call fma intnumx intnumy bytesz end end function
def test_fma_invalid_param_intnum_intnum_bytes_none_908(self): # This version is expected to pass. arrayfunc.fma(self.floatarrayx, self.floatnumy, self.floatarrayz) # This is the actual test. with self.assertRaises(TypeError): arrayfunc.fma(self.intnumx, self.intnumy, self.bytesz)
Python
nomic_cornstack_python_v1
comment vowels = {"a", "e", "i", "o", "u"} set finalSet = difference set sampleText vowels print finalSet set finalList = sorted finalSet print finalList
# vowels = {"a", "e", "i", "o", "u"} finalSet = set(sampleText).difference(vowels) print(finalSet) finalList = sorted(finalSet) print(finalList)
Python
zaydzuhri_stack_edu_python
string 4. Using composition: Use below details and write a program to print the Laptop details along with its processor specification 1. Create two classes Laptop and Processor. 2. Create "display" method in the Laptop class class Processor begin function __init__ self core generation begin set core = core set generati...
""" 4. Using composition: Use below details and write a program to print the Laptop details along with its processor specification 1. Create two classes Laptop and Processor. 2. Create "display" method in the Laptop class """ class Processor: def __init__(self,core,generation): self.core = c...
Python
zaydzuhri_stack_edu_python
function get_remote_file url begin comment Disable the proxies by not trusting the env set session = call Session set trust_env = false comment Make the request call disable_warnings try begin set r = get session url verify=false end except RequestException as e begin comment catastrophic error. bail. print e exit 1 en...
def get_remote_file(url): # Disable the proxies by not trusting the env session = requests.Session() session.trust_env = False # Make the request requests.packages.urllib3.disable_warnings() try: r = session.get(url, verify=False) except requests.exceptions.RequestException as e: ...
Python
nomic_cornstack_python_v1
function __init__ self state_size action_size params device seed=0 begin set state_size = state_size set action_size = action_size set params = params set seed = seed set device = device set noise = call Sampler max_sigma min_sigma end_episode comment Q-Network set critic_local = call DeterministicCriticNet state_size ...
def __init__(self, state_size, action_size, params, device, seed=0): self.state_size = state_size self.action_size = action_size self.params = params self.seed = seed self.device = device self.noise = Sampler(params.max_sigma, params.min_sigma, params.end_episode...
Python
nomic_cornstack_python_v1
function resource_type self begin return get pulumi self string resource_type end function
def resource_type(self) -> str: return pulumi.get(self, "resource_type")
Python
nomic_cornstack_python_v1
import pickle import itertools import pandas as pd import numpy as np from sklearn import metrics from sklearn.metrics import f1_score from sklearn.model_selection import StratifiedKFold , cross_val_score from sklearn.metrics import confusion_matrix from matplotlib import pyplot as plt function plot_confusion_matrix cm...
import pickle import itertools import pandas as pd import numpy as np from sklearn import metrics from sklearn.metrics import f1_score from sklearn.model_selection import StratifiedKFold, cross_val_score from sklearn.metrics import confusion_matrix from matplotlib import pyplot as plt def plot_confusion_matrix(cm, cl...
Python
zaydzuhri_stack_edu_python
function sample_name self sample_name begin set _sample_name = sample_name end function
def sample_name(self, sample_name): self._sample_name = sample_name
Python
nomic_cornstack_python_v1
comment _*_coding:utf-8 _*_ string 人脸攻击判断(rgb活体检测) from seetaface.api import * string 使用到的函数: Predict:对单帧做判断 PredictVideo:多视频做判断(连续多帧统计结果) ResetVideo:重置,用于切换检测视频时需要调用 要加载的功能 : 活体检测功能:LIVENESS 该功能依赖 : 人脸检测:FACE_DETECT 5点关键点识别:LANDMARKER5 set init_mask = LIVENESS ? FACE_DETECT ? LANDMARKER5 set seetaFace = call SeetaFace...
#_*_coding:utf-8 _*_ """ 人脸攻击判断(rgb活体检测) """ from seetaface.api import * """ 使用到的函数: Predict:对单帧做判断 PredictVideo:多视频做判断(连续多帧统计结果) ResetVideo:重置,用于切换检测视频时需要调用 要加载的功能 : 活体检测功能:LIVENESS 该功能依赖 : 人脸检测:FACE_DETECT 5点关键点识别:LANDMARKER5 """ init_mask = LIVENESS|FACE_DETECT|LANDMARKER5 seetaFace = Seeta...
Python
zaydzuhri_stack_edu_python
comment !/usr/bin/env python3 comment -*- encoding:utf-8 -*- string @license: (C) Copyright 2013-2017, Node Supply Chain Manager Corporation Limited. @software: PyCharm @file: PythonTools_Download.py @author: ziv @time: 2019/12/20 @version: v1.0.0 @desc: 视频文件下载 import m3u8 import datetime import requests comment https:...
#!/usr/bin/env python3 # -*- encoding:utf-8 -*- """ @license: (C) Copyright 2013-2017, Node Supply Chain Manager Corporation Limited. @software: PyCharm @file: PythonTools_Download.py @author: ziv @time: 2019/12/20 @version: v1.0.0 @desc: 视频文件下载 """ import m3u8 import datetime import requests ...
Python
zaydzuhri_stack_edu_python
function next self begin set date = call date comment Sets the commission for each element on this tick/bar. for tuple i d in enumerate datas begin call setcommission commission=spreadDiv2 at d at 0 name=_name percabs=true comment Uncomment to keep track of the spreads write spread format string {}, {}, {} date _name s...
def next(self): date = self.datetime.date() # Sets the commission for each element on this tick/bar. for i, d in enumerate(self.datas): self.broker.setcommission(commission=self.spreadDiv2[d][0], name=d._name, percabs=True) # Uncomment to keep track of the spreads ...
Python
nomic_cornstack_python_v1
function __init__ self rect z begin comment Set location of UI Element. Defaulted to location 0, 0, and width 60 and height 30 if rect is none begin set tuple x y = tuple 0 0 set tuple w h = tuple 60 30 set _rect = call Rect tuple x y tuple w h end else begin set _rect = call Rect rect end set _z = z set _visible = tru...
def __init__(self, rect, z): # Set location of UI Element. Defaulted to location 0, 0, and width 60 and height 30 if rect is None: (x, y) = (0, 0) (w, h) = (60, 30) self._rect = pygame.Rect((x, y), (w, h)) else: self._rect = pygame.Rect(rect) ...
Python
nomic_cornstack_python_v1
comment -*- coding:utf-8 -*- comment 找到递推关系式,fn = Σ_{i = 1}^{n-1} fi + 1 comment 所以fn = 2 * fn-1 class Solution begin function jumpFloorII self number begin comment write code here if number < 1 begin return 0 end set results = list append results 1 if number < 2 begin return results at number - 1 end for i in range 2...
# -*- coding:utf-8 -*- # 找到递推关系式,fn = Σ_{i = 1}^{n-1} fi + 1 # 所以fn = 2 * fn-1 class Solution: def jumpFloorII(self, number): # write code here if number < 1: return 0 results = [] results.append(1) if number < 2: return results[number - 1] fo...
Python
zaydzuhri_stack_edu_python
function make_pod_spec begin set md = call metadata set cfg = call config if get cfg string enable-sidecar begin with open string reactive/spec_template_ha.yaml as spec_file begin set pod_spec_template = read spec_file end end else begin with open string reactive/spec_template.yaml as spec_file begin set pod_spec_templ...
def make_pod_spec(): md = metadata() cfg = config() if cfg.get("enable-sidecar"): with open("reactive/spec_template_ha.yaml") as spec_file: pod_spec_template = spec_file.read() else: with open("reactive/spec_template.yaml") as spec_file: pod_spec_template = spec_...
Python
nomic_cornstack_python_v1
function rolling_zscore self Y X lookback begin comment Calculate moving parameters comment 1.beta: set rolling_beta = call rolling_regression Y X window=lookback comment 2.spread: set rolling_spread = Y - rolling_beta * X comment 3.moving average set rolling_avg = mean call rolling window=lookback center=false set nam...
def rolling_zscore(self, Y, X, lookback): # Calculate moving parameters # 1.beta: rolling_beta = self.rolling_regression(Y, X, window=lookback) # 2.spread: rolling_spread = Y - rolling_beta * X # 3.moving average rolling_avg = rolling_spread.rolling(window=lookback, center=False).mean() ...
Python
nomic_cornstack_python_v1
import math comment Step 1: Create an empty list called "filtered_list" set filtered_list = list comment Step 2: Iterate through each number in the original list set original_list = list 3 5 7 9 11 for number in original_list begin comment Step 3: Check if the current number is divisible by any number in the range fro...
import math # Step 1: Create an empty list called "filtered_list" filtered_list = [] # Step 2: Iterate through each number in the original list original_list = [3, 5, 7, 9, 11] for number in original_list: # Step 3: Check if the current number is divisible by any number in the range from 2 to the square root of th...
Python
jtatman_500k
function lines self Width=1 Color=string k begin string read the Excel, then draw the wulf net and Plot points, job done~ clear axes comment self.axes.set_xlim(-90, 450) call set_ylim 0 90 set titles = list string NWSE set titles = list string N string 330 string 300 string W string 240 string 210 string S string 150 s...
def lines(self, Width=1, Color='k'): ''' read the Excel, then draw the wulf net and Plot points, job done~ ''' self.axes.clear() # self.axes.set_xlim(-90, 450) self.axes.set_ylim(0, 90) titles = list('NWSE') titles = ['N', '330', '300', 'W', '240', '210...
Python
jtatman_500k
function test_device_page self app begin call click sleep default_timeout assert call is_displayed assert call is_displayed assert call is_displayed assert call is_displayed end function
def test_device_page(self, app): app.find_element_by_xpath('//a[.=" Camera 0 "]').click() time.sleep(default_timeout) assert app.find_element_by_id('config').is_displayed() assert app.find_element_by_id('start').is_displayed() assert app.find_element_by_id('stop').is_displayed() ...
Python
nomic_cornstack_python_v1
function init_gl_stuff_old begin comment use our zbuffer call glEnable GL_DEPTH_TEST comment setup the camera call glMatrixMode GL_PROJECTION call glLoadIdentity comment setup lens call gluPerspective 45.0 640 / 480.0 0.1 100.0 comment move back call glTranslatef 0.0 0.0 - 3.0 comment orbit higher call glRotatef 25 1 0...
def init_gl_stuff_old(): GL.glEnable(GL.GL_DEPTH_TEST) # use our zbuffer # setup the camera GL.glMatrixMode(GL.GL_PROJECTION) GL.glLoadIdentity() GLU.gluPerspective(45.0, 640 / 480.0, 0.1, 100.0) # setup lens GL.glTranslatef(0.0, 0.0, -3.0) # move back GL.glRotatef(25, 1, 0, 0) # orbit ...
Python
nomic_cornstack_python_v1
import datetime from bark import db from flask import jsonify from bark.users.models import User from bark.persons.models import Person from sqlalchemy.ext.associationproxy import association_proxy set group_owners_associations = call Table string group_owners_associations call Column string group_id Integer call Forei...
import datetime from bark import db from flask import jsonify from bark.users.models import User from bark.persons.models import Person from sqlalchemy.ext.associationproxy import association_proxy group_owners_associations = db.Table('group_owners_associations', db.Column('group_id', db.Integer, db.ForeignKey('g...
Python
zaydzuhri_stack_edu_python
function get_config begin set _gis = gis if not config begin comment Ask set_config to put the appropriate config in response. if gis_config_id begin call set_config gis_config_id end else begin call set_config end end return config end function
def get_config(): _gis = current.response.s3.gis if not _gis.config: # Ask set_config to put the appropriate config in response. if current.session.s3.gis_config_id: GIS.set_config(current.session.s3.gis_config_id) else: GIS.set_confi...
Python
nomic_cornstack_python_v1
from __future__ import division from math import sqrt , ceil , floor import re set pattern = compile string [^a-zA-Z0-9] function encode message begin set message = sub pattern string lower message set size = integer ceil square root length message if size == 0 begin return string end set message = call ljust size ^ ...
from __future__ import division from math import sqrt, ceil, floor import re pattern = re.compile('[^a-zA-Z0-9]') def encode(message): message = re.sub(pattern, '', message.lower()) size = int(ceil(sqrt(len(message)))) if size == 0: return '' message = message.ljust(size ** 2) encoded = ''...
Python
zaydzuhri_stack_edu_python
async function shutdown_event begin close ZEROCONF end function
async def shutdown_event(): ZEROCONF.close()
Python
nomic_cornstack_python_v1
function _translate__l3vpn_ntw_vpn_services_vpn_service_underlay_transport input_yang_obj translated_yang_obj=none begin if call _changed begin set type = type end return translated_yang_obj end function
def _translate__l3vpn_ntw_vpn_services_vpn_service_underlay_transport(input_yang_obj, translated_yang_obj=None): if input_yang_obj.type._changed(): input_yang_obj.type = input_yang_obj.type return translated_yang_obj
Python
nomic_cornstack_python_v1
function submit_quiz quiz_id begin set quiz = call load_quiz quiz_id if quiz is none begin call flash string The quiz you were looking for could not be found. return call not_found end comment Read the answers that the user gave from the form. set answer_set = call read_from_form current_user quiz form comment Save the...
def submit_quiz(quiz_id): quiz = load_quiz(quiz_id) if quiz is None: flash("The quiz you were looking for could not be found.") return not_found() # Read the answers that the user gave from the form. answer_set = AnswerSet.read_from_form(current_user, quiz, request.form) # Save the...
Python
nomic_cornstack_python_v1
import pygame from helpers import message , has_intersect_borders , generate_food , has_intersect_food , snake_intersects_block , snake_intersects_itself , snake_intersects_brick , generate_brick comment CONSTANTS set WINDOW_HEIGHT = 500 set WINDOW_WIDTH = 800 set BLUE = tuple 0 0 255 set RED = tuple 255 0 0 set WHITE ...
import pygame from helpers import message, has_intersect_borders, generate_food, has_intersect_food, snake_intersects_block, \ snake_intersects_itself, snake_intersects_brick, generate_brick # CONSTANTS WINDOW_HEIGHT = 500 WINDOW_WIDTH = 800 BLUE = (0, 0, 255) RED = (255, 0, 0) WHITE = (255, 255, 255) BLACK = (0,...
Python
zaydzuhri_stack_edu_python
import os set textFilePath = string books_list.txt function readFile begin set filesize = get size path textFilePath set books = list if filesize != 0 begin with open textFilePath string r as f begin while true begin set line = strip read line f string " if not line begin break end append books split line string , end...
import os textFilePath = "books_list.txt" def readFile(): filesize = os.path.getsize(textFilePath) books = [] if(filesize!=0): with open(textFilePath, 'r') as f: while True: line = f.readline().strip('"') if not line: break ...
Python
zaydzuhri_stack_edu_python
comment -*- coding: utf-8 -*- from PyQt4.QtCore import * from PyQt4.QtGui import * import sys string Qt提供了很多关于获取窗体位置及显示区域大小的函数,本实例利用一个简单的对话框显 示窗体的各种位置信息,包括窗体的所在点位置,长,宽信息等。本实例的目的是分析各个 有关位置信息的函数之间的区别,如 x(),y(),pos(),rect(),size(),geometry()等,以及在不同的 情况下应使用哪个函数来获取位置信息 x(),y(),frameGeometry(),pos(),geometry(),width(),height...
# -*- coding: utf-8 -*- from PyQt4.QtCore import * from PyQt4.QtGui import * import sys """ Qt提供了很多关于获取窗体位置及显示区域大小的函数,本实例利用一个简单的对话框显 示窗体的各种位置信息,包括窗体的所在点位置,长,宽信息等。本实例的目的是分析各个 有关位置信息的函数之间的区别,如 x(),y(),pos(),rect(),size(),geometry()等,以及在不同的 情况下应使用哪个函数来获取位置信息 x(),y(),frameGeometry(),pos(),geometry(),width(),height(),rect...
Python
zaydzuhri_stack_edu_python
for num in range 10 begin append numbers num end comment last_num = numbers.pop() comment print(numbers) comment print(last_num) pass comment # first_num = numbers.pop(0) comment # comment # print(numbers) comment # print(first_num) comment # one action -> 9 actions comment some_num = numbers.pop(5) print numbers comme...
for num in range(10): numbers.append(num) # # last_num = numbers.pop() # # print(numbers) # print(last_num) pass # # # first_num = numbers.pop(0) # # # # print(numbers) # # print(first_num) # # one action -> 9 actions # # some_num = numbers.pop(5) # print(numbers) # print(some_num) pass print(5 in numbers) print...
Python
zaydzuhri_stack_edu_python
function next_round score begin comment If score is 0 we want to return false otherwise this will incorrectly comment return True if score == 0 begin return false end if score > integer need_higher_than_this or score == integer need_higher_than_this begin return true end end function
def next_round(score): # If score is 0 we want to return false otherwise this will incorrectly # return True if score == 0: return False if score > int(need_higher_than_this) or score == int(need_higher_than_this): return True
Python
nomic_cornstack_python_v1
function SignBuffer self in_buffer begin string Sign a buffer via temp files. Our signing tool can't sign a buffer, so we work around it using temporary files. Args: in_buffer: data to sign Returns: signed data call AssertType in_buffer bytes with named temporary file as temp_in begin write temp_in in_buffer seek temp_...
def SignBuffer(self, in_buffer): """Sign a buffer via temp files. Our signing tool can't sign a buffer, so we work around it using temporary files. Args: in_buffer: data to sign Returns: signed data """ precondition.AssertType(in_buffer, bytes) with tempfile.NamedTemporary...
Python
jtatman_500k
function tag_and_push_docker_image docker_client image tag begin assert call tag tag set response = call push tag print response set response = loads split right strip response string at - 1 if string error in response begin raise exception format string Unable to push image to {} {} tag get get response string errorDe...
def tag_and_push_docker_image(docker_client, image, tag): assert image.tag(tag) response = docker_client.images.push(tag) print(response) response = json.loads(response.rstrip().split('\n')[-1]) if 'error' in response: raise Exception('Unable to push image to {}\n {}'.format( ta...
Python
nomic_cornstack_python_v1
function get_span spans row column begin string Gets the span containing the [row, column] pair Parameters ---------- spans : list of lists of lists A list containing spans, which are lists of [row, column] pairs that define where a span is inside a table. Returns ------- span : list of lists A span containing the [row...
def get_span(spans, row, column): """ Gets the span containing the [row, column] pair Parameters ---------- spans : list of lists of lists A list containing spans, which are lists of [row, column] pairs that define where a span is inside a table. Returns ------- span : ...
Python
jtatman_500k
comment PREDICTION MODULES import trainingmodules import itertools from sklearn import svm from sklearn.model_selection import cross_val_score from sklearn.model_selection import cross_val_predict from sklearn.metrics import confusion_matrix from sklearn.metrics import f1_score from sklearn.externals import joblib from...
#PREDICTION MODULES import trainingmodules import itertools from sklearn import svm from sklearn.model_selection import cross_val_score from sklearn.model_selection import cross_val_predict from sklearn.metrics import confusion_matrix from sklearn.metrics import f1_score from sklearn.externals import joblib from sklea...
Python
zaydzuhri_stack_edu_python
function _calculate_register_results register_qubits gate_result begin set results = dict for tuple name qubit_tuple in items register_qubits begin set slicer = tuple generator expression qubit_map at q for q in qubit_tuple set samples = gather K call samples true slicer axis=- 1 set results at name = call GateResult ...
def _calculate_register_results(register_qubits, gate_result): results = {} for name, qubit_tuple in register_qubits.items(): slicer = tuple(gate_result.qubit_map[q] for q in qubit_tuple) samples = K.gather(gate_result.samples(True), slicer, axis=-1) results[name] = G...
Python
nomic_cornstack_python_v1
function init_model exe args program begin if checkpoint begin call load_persistables exe checkpoint main_program=program info string Finish initing model from %s % checkpoint end if pretrained_model begin string # yapf: disable # This is a dict of fc layers in all the classification models. final_fc_name = [ "fc8_weig...
def init_model(exe, args, program): if args.checkpoint: fluid.io.load_persistables(exe, args.checkpoint, main_program=program) logger.info("Finish initing model from %s" % (args.checkpoint)) if args.pretrained_model: """ # yapf: disable # This is a dict of fc layers in ...
Python
nomic_cornstack_python_v1
function least_common_multiple number1 number2 begin return number1 * number2 // call gcd number1 number2 end function
def least_common_multiple(number1, number2): return number1 * number2 // math.gcd(number1, number2)
Python
nomic_cornstack_python_v1
function apply self begin raise NotImplementedError end function
def apply(self): raise NotImplementedError
Python
nomic_cornstack_python_v1
function created_at self begin return _created end function
def created_at(self): return self._created
Python
nomic_cornstack_python_v1
function replaceWidget old_widget new_widget begin set plotwidget_placeholder_layout = call layout call replaceWidget old_widget new_widget call setObjectName call objectName call hide show comment Goodbye, old widget reference! set __dict__ at call objectName = new_widget end function
def replaceWidget(old_widget: QWidget, new_widget: QWidget): plotwidget_placeholder_layout = old_widget.parent().layout() plotwidget_placeholder_layout.replaceWidget(old_widget, new_widget) new_widget.setObjectName(old_widget.objectName()) old_widget.hide() new_widget.show() old_widget.parentWid...
Python
nomic_cornstack_python_v1
function countoccur i test begin if i == 19 begin return 1 end set count = 0 while true begin set j = find test word at i if j != - 1 begin set count = count + call countoccur i + 1 test at slice j + 1 : : % 10000 set test = test at slice j + 1 : : continue end break end return count end function if __name__ == stri...
def countoccur(i, test): if i == 19: return 1 count = 0 while True: j = test.find(word[i]) if j != -1: count += countoccur(i + 1, test[j + 1:]) % 10000 test = test[j + 1:] continue break return count if __name__ == '__main__': n = ...
Python
zaydzuhri_stack_edu_python
string 45 Jump Game II Given an array of non-negative integers, you are initially positioned at the first index of the array. Each element in the array represents your maximum jump length at that position. Your goal is to reach the last index in the minimum number of jumps. For example: Given array A = [2,3,1,1,4] The ...
""" 45 Jump Game II Given an array of non-negative integers, you are initially positioned at the first index of the array. Each element in the array represents your maximum jump length at that position. Your goal is to reach the last index in the minimum number of jumps. For example: Given array A = [2,3,...
Python
zaydzuhri_stack_edu_python
import matplotlib.pyplot as plt function plot_av_coop_level coop_levels title=string Average cooperation level over time. filename=string av_coop_level.png show=false begin set averages = list for i in range length coop_levels at 0 begin set values = list comprehension sublist at i for sublist in coop_levels append av...
import matplotlib.pyplot as plt def plot_av_coop_level(coop_levels, title="Average cooperation level over time.", filename="av_coop_level.png", show=False): averages = [] for i in range(len(coop_levels[0])): values = [sublist[i] for sublist in coop_levels] averages.append(sum(values) / len(val...
Python
zaydzuhri_stack_edu_python
function build self begin return true end function
def build(self): return True
Python
nomic_cornstack_python_v1
from bs4 import BeautifulSoup import json import requests import lxml.html import time set target_url = string want get URL set dict_str = string set next_url = string set comment_data = list set session = call Session set headers = dict string user-agent string Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/5...
from bs4 import BeautifulSoup import json import requests import lxml.html import time target_url = "want get URL" dict_str = "" next_url = "" comment_data = [] session = requests.Session() headers = {'user-agent': 'Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/69.0.3497.100 Sa...
Python
zaydzuhri_stack_edu_python
function crop_and_rotate im center ps angle tile=false begin if not type ps == int begin raise call TypeError string INPUT ps must be a scalar end if tile begin set offset = call asarray shape at slice : 2 : set center = list offset at 0 + center at 0 offset at 1 + center at 0 set im = call tile_image im end comment r...
def crop_and_rotate(im, center, ps, angle, tile = False): if not type(ps) == int: raise TypeError('INPUT ps must be a scalar') if tile: offset = np.asarray(im.shape[:2]) center = [offset[0] + center[0], offset[1] + center[0]] im = tile_image(im) tmp = ((math.ceil(ps * 2**.5)...
Python
nomic_cornstack_python_v1
function single_mutation_tuple_intSetRep random candidate args begin set bounder = bounder set mutRate = set default args string mutation_rate 0.1 if random > mutRate begin return candidate end set mutant = copy copy candidate set r = random comment choose if the mutation is done in the first or second int set. set ind...
def single_mutation_tuple_intSetRep(random, candidate, args): bounder = args["_ec"].bounder mutRate = args.setdefault("mutation_rate", 0.1) if random.random() > mutRate: return candidate mutant = copy.copy(candidate) r = random.random() indexTuple = 0 if r<0.5 else 1 # choose if the mut...
Python
nomic_cornstack_python_v1
function setBoundingBox self *args begin return call GraphicalObject_setBoundingBox self *args end function
def setBoundingBox(self, *args): return _libsbml.GraphicalObject_setBoundingBox(self, *args)
Python
nomic_cornstack_python_v1
class Employee begin comment self instance variable function getdata self begin comment private variable set __Emp_no = 101 comment private variable set __Emp_name = string Meena Pandey comment private variable set __Salary = 67000 end function function display self begin print string Emp no : __Emp_no print string Emp...
class Employee: def getdata(self): #self instance variable self.__Emp_no=101 #private variable self.__Emp_name="Meena Pandey" #private variable self.__Salary=67000 #private variable def display(self): print("Emp no :",self.__Emp_no) print("Emp Name : ",self.__Emp_...
Python
zaydzuhri_stack_edu_python