code
stringlengths
10
2.58M
original_code
stringlengths
3
3.18M
original_language
stringclasses
1 value
source
stringclasses
7 values
function test_destineo_10 self begin call journey _from=string stop_area:NAN:SA:RSNB to=string stop_area:NAN:SA:CCDI datetime=string 20141028T115000 first_section_mode=list string walking string car last_section_mode=list string walking min_nb_journeys=3 datetime_represents=string arrival wheelchair=true end function
def test_destineo_10(self): self.journey(_from='stop_area:NAN:SA:RSNB', to='stop_area:NAN:SA:CCDI', datetime='20141028T115000', first_section_mode=['walking', 'car'], last_section_mode=['walking'], min_nb_journeys=3, datetime_re...
Python
nomic_cornstack_python_v1
function game_person begin set person = random choice data return person end function
def game_person(): person = random.choice(data) return person
Python
nomic_cornstack_python_v1
tuple absolute all any call ascii binary boolean bytearray call calls character directory divide mod enumerate eval filter decimal format call frozenset hexadecimal integer is instance length list map max min octal open ordinal power print range reversed round set call slice sorted string sum tuple type zip
abs(), all(), any(), ascii(), bin(), bool(), bytearray(), calls(), chr(), dir(), divmod(), enumerate(), eval(), filter(), float(), format(), frozenset(), hex(), int(), isinstance(), len(), list(), map(), max(), min(), oct(), open(), ord(), pow(), print(), range(), reversed(), round(), set(), slice(), sorted(), str(), s...
Python
flytech_python_25k
function pressed_open_button self begin if call cget string text == string Open begin comment Open the selected device set address = integer get device_variable if call open_device address begin set device_open = true set open_address = address call enable_controls call config text=string Close comment Periodically rea...
def pressed_open_button(self): if self.open_button.cget('text') == "Open": # Open the selected device address = int(self.device_variable.get()) if self.open_device(address): self.device_open = True self.open_address = address s...
Python
nomic_cornstack_python_v1
comment This script contains the process for the training and evaluation of the artificial neural network model. comment Import the modules. import matplotlib.pyplot as plt import numpy as np import pandas as pd from sklearn.model_selection import train_test_split from sklearn.preprocessing import MinMaxScaler from eli...
# This script contains the process for the training and evaluation of the artificial neural network model. # Import the modules. import matplotlib.pyplot as plt import numpy as np import pandas as pd from sklearn.model_selection import train_test_split from sklearn.preprocessing import MinMaxScaler from eli5.sklearn ...
Python
zaydzuhri_stack_edu_python
function find_data_files self package src_dir begin string Return filenames for package's data files in 'src_dir' set patterns = call _get_platform_patterns package_data package src_dir set globs_expanded = map glob patterns comment flatten the expanded globs into an iterable of matches set globs_matches = call from_it...
def find_data_files(self, package, src_dir): """Return filenames for package's data files in 'src_dir'""" patterns = self._get_platform_patterns( self.package_data, package, src_dir, ) globs_expanded = map(glob, patterns) # flatten the expanded...
Python
jtatman_500k
comment Library for communicating with eSmart 3 MPPT charger comment skagmo.com, 2018 from typing import List , Optional , Callable import struct , time , serial , socket , requests comment from collections import namedtuple comment States set STATE_START = 0 set STATE_DATA = 1 set REQUEST_MSG0 = b'\xaa\x01\x01\x01\x00...
# Library for communicating with eSmart 3 MPPT charger # skagmo.com, 2018 from typing import List, Optional, Callable import struct, time, serial, socket, requests #from collections import namedtuple # States STATE_START = 0 STATE_DATA = 1 REQUEST_MSG0 = b"\xaa\x01\x01\x01\x00\x03\x00\x00\x1e\x32" LOAD_OFF = b"\xaa...
Python
zaydzuhri_stack_edu_python
from tkinter import * comment ttk is a module (which contains combobox) inside ttk module comment modules inside a module do not get imported unless explicitly imported comment classes and functions are imported with * from tkinter import ttk import sqlite3 function add_student begin set r = get e_roll set n = get e_na...
from tkinter import * #ttk is a module (which contains combobox) inside ttk module #modules inside a module do not get imported unless explicitly imported #classes and functions are imported with * from tkinter import ttk import sqlite3 def add_student(): r = e_roll.get() n = e_name.get() e = e_email.get()...
Python
zaydzuhri_stack_edu_python
import datetime set ROLLOUT_FILENAME = string Traj_Controller_Rollout class TrajectoryDrivingController begin function __init__ self ego traj_builder traj_label timestep=0.1 write=false **kwargs begin set traj_builder = traj_builder set initialisation_params = dict string ego ego ; string traj_builder traj_builder ; st...
import datetime ROLLOUT_FILENAME = "Traj_Controller_Rollout" class TrajectoryDrivingController(): def __init__(self,ego,traj_builder,traj_label,timestep=.1,write=False,**kwargs): self.traj_builder = traj_builder self.initialisation_params = {"ego":ego,"traj_builder":traj_builder,"traj_label":traj...
Python
zaydzuhri_stack_edu_python
function __hash__ self begin raise call TypeError string Transitions are mutable, and thus not hashable. end function
def __hash__(self): raise TypeError("Transitions are mutable, and thus not hashable.")
Python
nomic_cornstack_python_v1
comment Copyright (c) 2012 The Khronos Group Inc. comment Permission is hereby granted, free of charge, to any person obtaining a copy of this software and /or associated documentation files (the "Materials "), to deal in the Materials without restriction, including without limitation the rights to use, copy, modify, m...
# Copyright (c) 2012 The Khronos Group Inc. # Permission is hereby granted, free of charge, to any person obtaining a copy of this software and /or associated documentation files (the "Materials "), to deal in the Materials without restriction, including without limitation the rights to use, copy, modify, merge, publis...
Python
zaydzuhri_stack_edu_python
function set_overrides self *dicts begin set _overrides_configs = list comprehension if expression is instance d ConfigTree then d else call from_dict d for d in dicts call reload end function
def set_overrides(self, *dicts): self._overrides_configs = [ d if isinstance(d, ConfigTree) else ConfigFactory.from_dict(d) for d in dicts ] self.reload()
Python
nomic_cornstack_python_v1
comment -*- coding: utf-8 -*- string Created on Tue Apr 7 09:39:39 2020 @author: Zhuo import numpy as np import pandas as pd import warnings comment 忽略warning信息 filter warnings string ignore set df = call DataFrame columns=list string 身高 string 体重 string 肺活量 set df at string 身高 = list 162 165 168 163 170 174 176 178 17...
# -*- coding: utf-8 -*- """ Created on Tue Apr 7 09:39:39 2020 @author: Zhuo """ import numpy as np import pandas as pd import warnings warnings.filterwarnings('ignore') #忽略warning信息 df = pd.DataFrame(columns=['身高','体重','肺活量']) df['身高'] = [162,165,168,163,170,174,176,178,173,180,182,185] df['体重'] = [600,45.2,50.2...
Python
zaydzuhri_stack_edu_python
function getMinimumCost k costs begin sort costs reverse=true set coef = 1 set person = k set total = 0 for cost in costs begin set total = total + cost * coef set person = person - 1 if person == 0 begin set person = k set coef = coef + 1 end end return total end function set tuple flowers person = list map int split ...
def getMinimumCost(k, costs): costs.sort(reverse=True) coef = 1 person = k total = 0 for cost in costs: total += cost * coef person-=1 if person == 0: person = k coef += 1 return total flowers, person = list(map(int, input().split())) costs = list(m...
Python
zaydzuhri_stack_edu_python
function show_rentals product_id begin with call TrackEntryExit string show_rentals begin set mongo = call MongoDBConnection with mongo begin set database = FlorentinDB set rentals = sort find database at string rental dict string product_id product_id string customer_id set rental_list = list comprehension rental at s...
def show_rentals(product_id): with TrackEntryExit("show_rentals"): mongo = MongoDBConnection() with mongo: database = mongo.connection.FlorentinDB rentals = database["rental"].find({"product_id": product_id})\ .sort("customer_id") rental_list = [r...
Python
nomic_cornstack_python_v1
import numpy as np class GroundedNeural begin function __init__ self nodes begin set nodes = nodes set b = call generateMaskBiases set w = call generateMaskWeights end function function generateMaskBiases self begin set b = zeros tuple nodes nodes * nodes for i in range nodes begin set blocks = list range i nodes * nod...
import numpy as np class GroundedNeural: def __init__(self, nodes): self.nodes = nodes self.b = self.generateMaskBiases() self.w = self.generateMaskWeights() def generateMaskBiases(self): b = np.zeros((self.nodes, self.nodes*self.nodes)) for i in range(self.nodes):...
Python
zaydzuhri_stack_edu_python
function check self results begin if DEPENDS_ON is not none begin if result at string status in tuple PASS FAILURE begin return true end else begin set result at string status = SKIPPED set msg = string Step '%s' is skipped, since depends on step '%s' is skipped or finished with an error. % tuple name name set stdout_f...
def check(self, results): if self.DEPENDS_ON is not None: if results[self.DEPENDS_ON].result["status"] in ( Status.PASS, Status.FAILURE): return True else: self.result["status"] = Status.SKIPPED msg = ("Step '%s' is skip...
Python
nomic_cornstack_python_v1
function waa_adjust_baseline rsl baseline wet waa_max delta_t tau begin if type rsl == Series begin set rsl = values end if type baseline == Series begin set baseline = values end if type wet == Series begin set wet = values end set rsl = as type rsl float64 set baseline = as type baseline float64 set wet = as type wet...
def waa_adjust_baseline(rsl, baseline, wet, waa_max, delta_t, tau): if type(rsl) == pd.Series: rsl = rsl.values if type(baseline) == pd.Series: baseline = baseline.values if type(wet) == pd.Series: wet = wet.values rsl = rsl.astype(np.float64) baseline = baseline.a...
Python
nomic_cornstack_python_v1
function distance_miles self distance_miles begin set _distance_miles = distance_miles end function
def distance_miles(self, distance_miles): self._distance_miles = distance_miles
Python
nomic_cornstack_python_v1
function display_grid grid begin comment show_grid = grid.copy() if grid is none or grid is false begin return none end set all_rows = string ABCDEFGHI set all_cols = string 123456789 set width = max list 3 max list comprehension length grid at pos for pos in grid + 1 set width = 3 set display = string set row_counter...
def display_grid(grid): # show_grid = grid.copy() if grid is None or grid is False: return None all_rows = 'ABCDEFGHI' all_cols = '123456789' width = max([3, max([len(grid[pos]) for pos in grid]) + 1]) width = 3 display = '' row_counter = 0 col_counter = 0 for row in all_...
Python
nomic_cornstack_python_v1
function deriv_double self y t begin set g = g set tuple L1 L2 = tuple L1 L2 set tuple M1 M2 = tuple M1 M2 set tuple F1 F2 = tuple F1 F2 set tuple theta1 z1 theta2 z2 = y comment inverse matrix set tuple A1 B1 = tuple M1 + M2 * L1 M2 * L2 * cos theta1 - theta2 set C1 = - M2 * L2 * z2 ^ 2 * sin theta1 - theta2 - M1 + M2...
def deriv_double(self, y, t): g = self.g L1, L2 = self.L1, self.L2 M1, M2 = self.M1, self.M2 F1, F2 = self.F1, self.F2 theta1, z1, theta2, z2 = y # inverse matrix A1, B1 = (M1+M2)*L1, M2*L2*np.cos(theta1-theta2) C1 = -M2*L2*z2**2*np.sin(theta1-theta2) - (M1+M2)*g*np.sin(theta1) - F1*L1...
Python
nomic_cornstack_python_v1
function save_html self filename=none overwrite=false begin string Save self-contained html to a file. Parameters ---------- filename : str The filename to save to if filename is none begin raise call ValueError string Please provide a filename, e.g. viz.save_html(filename="viz.html"). end import os set base = _html se...
def save_html(self, filename=None, overwrite=False): """ Save self-contained html to a file. Parameters ---------- filename : str The filename to save to """ if filename is None: raise ValueError('Please provide a filename, e.g. viz.save_...
Python
jtatman_500k
string BankAccountCalculator Program Info Elisha Victor CSC 119 - 005 Bank Account Calculator 08/29/2018 Calculating 3 years of having 1000$ with 5 percent interest per year. Version: Uno comment definition of the main program function main begin comment Data to solve problem set bankAccountBalance = 1000.0 set bankAcc...
""" BankAccountCalculator Program Info Elisha Victor CSC 119 - 005 Bank Account Calculator 08/29/2018 Calculating 3 years of having 1000$ with 5 percent interest per year. Version: Uno """ def main(): # definition of the main program # Data to solve problem bankAccoun...
Python
zaydzuhri_stack_edu_python
comment Implement rule 90 function cellular_automata series begin set series = list series for _ in range 25 begin print join string list comprehension if expression x == string 1 then string x else string for x in series set series = list comprehension if expression i < length series - 1 and boolean integer series a...
# Implement rule 90 def cellular_automata(series): series = list(series) for _ in range(25): print(''.join(['x' if x == '1' else ' ' for x in series])) series = ['1' if i < len(series) - 1 and bool(int(series[i-1])) ^ bool(int(series[i+1])) == 1 else '0' for i in range(len(series))] if __name_...
Python
zaydzuhri_stack_edu_python
function formatSentence variableList finalSeparator=string and begin comment Thanks to StackOverflow user Shashank: https://stackoverflow.com/a/30084397 comment Creates a variable for the number of objects being formatted set n = length variableList if n > 1 begin comment shut up return replace format string {}, * n - ...
def formatSentence(variableList, finalSeparator="and"): # Thanks to StackOverflow user Shashank: https://stackoverflow.com/a/30084397 n = len(variableList) # Creates a variable for the number of objects being formatted if n > 1: return ('{}, '*(n-2) + '{} Q*Q*Q {}').format(*variableList).replace("Q...
Python
nomic_cornstack_python_v1
function get_user_commands self uid begin set uc_data = call list_user_commands uid set user_commands = list for uc in uc_data begin append user_commands call ZenossUserCommand api_url api_headers ssl_verify uc parent=call _check_uid uid end return user_commands end function
def get_user_commands(self, uid): uc_data = self.list_user_commands(uid) user_commands = [] for uc in uc_data: user_commands.append( ZenossUserCommand( self.api_url, self.api_headers, self.ssl_verify, ...
Python
nomic_cornstack_python_v1
comment -*- coding: utf-8 -*- string Created on Fri Dec 12 16:16:08 2014 @author: u0091609 Batch averaging tool for fMRI data. For registration purposes. import nibabel as nib import Tkinter , tkFileDialog set root = call Tk import glob import numpy as np import os while true begin set rootdir = call askdirectory initi...
# -*- coding: utf-8 -*- """ Created on Fri Dec 12 16:16:08 2014 @author: u0091609 Batch averaging tool for fMRI data. For registration purposes. """ import nibabel as nib import Tkinter, tkFileDialog root = Tkinter.Tk() import glob import numpy as np import os while True: rootdir = tkFileDialog.askdirectory(init...
Python
zaydzuhri_stack_edu_python
function fit_model X y begin comment Create cross-validation sets from the training data set cv_sets = call ShuffleSplit shape at 0 n_iter=10 test_size=0.2 random_state=0 comment TODO: Create a decision tree regressor object set regressor = call DecisionTreeRegressor comment TODO: Create a dictionary for the parameter ...
def fit_model(X, y): # Create cross-validation sets from the training data cv_sets = ShuffleSplit(X.shape[0], n_iter = 10, test_size = 0.20, random_state = 0) # TODO: Create a decision tree regressor object regressor = DecisionTreeRegressor() # TODO: Create a dictionary for the parameter 'max...
Python
nomic_cornstack_python_v1
from selenium import webdriver from selenium.webdriver.common.action_chains import ActionChains import time set driver = call Chrome call implicitly_wait 10 get driver string http://www.baidu.com comment 鼠标悬停至‘设置’链接 set link = call find_element_by_link_text string 设置 call perform comment 打开搜索设置 call click comment 保存设置 ...
from selenium import webdriver from selenium.webdriver.common.action_chains import ActionChains import time driver = webdriver.Chrome() driver.implicitly_wait(10) driver.get('http://www.baidu.com') #鼠标悬停至‘设置’链接 link = driver.find_element_by_link_text('设置') ActionChains(driver).move_to_element(link).perform() #打开搜索设置 dr...
Python
zaydzuhri_stack_edu_python
function CommitNewLKGM self begin set lv = LooseVersion if not _lkgm and not call lv _lkgm < call lv _old_lkgm begin raise call LKGMNotFound string No valid LKGM found. Did you run FindNewLKGM? end set commit_msg = _COMMIT_MSG % dictionary version=_lkgm try begin comment Add the new versioned file. call WriteFile join ...
def CommitNewLKGM(self): lv = distutils.version.LooseVersion if not self._lkgm and not lv(self._lkgm) < lv(self._old_lkgm): raise LKGMNotFound('No valid LKGM found. Did you run FindNewLKGM?') commit_msg = self._COMMIT_MSG % dict(version=self._lkgm) try: # Add the new versioned file. o...
Python
nomic_cornstack_python_v1
function test_delete_namespaced_network_policy self begin pass end function
def test_delete_namespaced_network_policy(self): pass
Python
nomic_cornstack_python_v1
import requests import json class YaUploader begin function __init__ self begin set token_VK = input string Введите токен приложения VK: set token = input string Введите токен Полигона Яндекс.Диска: set user_ID = input string Введите ID пользователя VK: set yandex_folder = input string Введите имя яндекс-папки: set cou...
import requests import json class YaUploader: def __init__(self): self.token_VK = input('Введите токен приложения VK: ') self.token = input('Введите токен Полигона Яндекс.Диска: ') self.user_ID = input('Введите ID пользователя VK: ') self.yandex_folder = input('Введите имя яндекс-п...
Python
zaydzuhri_stack_edu_python
function test_post_status_success self begin set data = dict string longitude 20 ; string latitude 10 ; string title string new ; string description string cool_checkpoint ; string source_url string my_url ; string position_number 3 call login username=string test.test@gmail.com password=string userpass set response = ...
def test_post_status_success(self): data = { "longitude": 20, "latitude": 10, "title": "new", "description": "cool_checkpoint", "source_url": "my_url", "position_number": 3} self.client.login(username='test.test@gmail.com', password...
Python
nomic_cornstack_python_v1
function load filename begin set tuple file_root file_ext = call splitext filename if lower file_ext != INTR_EXTENSION begin raise call ValueError string Extension %s not supported for CameraIntrinsics. Must be stored with extension %s % tuple file_ext INTR_EXTENSION end set f = open filename string r set ci = load jso...
def load(filename): file_root, file_ext = os.path.splitext(filename) if file_ext.lower() != INTR_EXTENSION: raise ValueError('Extension %s not supported for CameraIntrinsics. Must be stored with extension %s' %(file_ext, INTR_EXTENSION)) f = open(filename, 'r') ci = json.loa...
Python
nomic_cornstack_python_v1
function cmdCancel_Clicked self begin close self pass end function
def cmdCancel_Clicked(self): self.close() pass
Python
nomic_cornstack_python_v1
function world2cam world_coords essential_identity begin set cam_coords = essential_identity @ world_coords return cam_coords end function comment TODO: Verify the logic
def world2cam(world_coords: torch.Tensor, essential_identity: torch.Tensor) -> torch.Tensor: cam_coords = essential_identity @ world_coords return cam_coords # TODO: Verify the logic
Python
nomic_cornstack_python_v1
function run args begin set resp = call request_pv_delete args if resp is not none begin if stderr begin print stderr end print stdout end end function
def run(args): resp = request_pv_delete(args) if resp is not None: if resp.stderr: print(resp.stderr) print(resp.stdout)
Python
nomic_cornstack_python_v1
function get_dashboard_template_data end_date begin set intervals = list set labels = list comment end_date = date.fromtimestamp(float(end_date)) comment end_date = datetime(end_date.year, end_date.month, end_date.day) set end_date = now + time delta hours=2 print string TEMP current end date: { string format time en...
def get_dashboard_template_data(end_date): intervals = [] labels = [] # end_date = date.fromtimestamp(float(end_date)) # end_date = datetime(end_date.year, end_date.month, end_date.day) end_date = datetime.now() + timedelta(hours=2) print(f"TEMP current end date: {end_date.strftime('%I%p')}") ...
Python
nomic_cornstack_python_v1
string def totalSum(num): sum = 0 for i in range(1,num+1): sum += i return sum def x3(num): if num % 3 == 0: print("{0}는 3의 배수가 맞습니다.".format(num)) else: print("{0}는 3의 배수가 아닙니다.".format(num)) def BigNum(): num = int(input("정수1 입력 : ")) num2 = int(input("정수2 입력 : ")) if num > num2: return num else: return num2 def Abs(...
""" def totalSum(num): sum = 0 for i in range(1,num+1): sum += i return sum def x3(num): if num % 3 == 0: print("{0}는 3의 배수가 맞습니다.".format(num)) else: print("{0}는 3의 배수가 아닙니다.".format(num)) def BigNum(): num = int(input("정수1 입력 : ")) num2 = int(input(...
Python
zaydzuhri_stack_edu_python
function update_favorites begin set check_favorite = first filter favorited_item == session at string athlete_id set route = string /athletes/ { session at string athlete_id } if check_favorite is none begin set new_update = call Favorite id=id favorited_item=session at string athlete_id add session new_update end else...
def update_favorites(): check_favorite = Favorite.query.filter(Favorite.favorited_item==session["athlete_id"]).first() route = f'/athletes/{session["athlete_id"]}' if check_favorite is None: new_update = Favorite(id=current_user.id, favorited_item=session["athlete_id"]) db.session.add(new...
Python
nomic_cornstack_python_v1
import cv2 import numpy as np from PIL import Image import pickle import sqlite3 set faceDetect = call CascadeClassifier string haarcascade_frontalface_default.xml comment Local Binary Pattern Histogram(LBPH) set rec = call LBPHFaceRecognizer_create read rec string recognizer\trainingData.yml set path = string dataSet ...
import cv2 import numpy as np from PIL import Image import pickle import sqlite3 faceDetect = cv2.CascadeClassifier("haarcascade_frontalface_default.xml") rec = cv2.face.LBPHFaceRecognizer_create(); #Local Binary Pattern Histogram(LBPH) rec.read("recognizer\\trainingData.yml") path = 'dataSet' def getPro...
Python
zaydzuhri_stack_edu_python
function alfabeto texto begin set texto = upper texto set letras = list for letra in texto begin if letra == string begin continue end else begin append letras letra end end set letras_filtradas = set letras print letras_filtradas end function call alfabeto string O rato roeu a roupa do rei de Roma
def alfabeto(texto): texto = texto.upper() letras = list() for letra in texto: if letra == ' ': continue else: letras.append(letra) letras_filtradas = set(letras) print(letras_filtradas) alfabeto('O rato roeu a roupa do rei de Roma')
Python
zaydzuhri_stack_edu_python
comment Given an array of integers ,find the sum of three numbers so that the sum is nearest to the given target value. function sum_of_three_no Arr target begin sort Arr set mini_diff = 99999999999 set mini_sum = 9999999999999 set length = length Arr for i in range length - 2 begin set j = i + 1 set k = length - 1 whi...
# Given an array of integers ,find the sum of three numbers so that the sum is nearest to the given target value. def sum_of_three_no(Arr,target): Arr.sort() mini_diff = 99999999999 mini_sum = 9999999999999 length = len(Arr) for i in range(length-2): j = i + 1 k =...
Python
zaydzuhri_stack_edu_python
function allequal iterable begin set first = iterable at 0 set rest = iterable at slice 1 : : for item in rest begin if item == first begin continue end else begin return false end end return true end function
def allequal(iterable): first = iterable[0] rest = iterable[1:] for item in rest: if item == first: continue else: return False return True
Python
nomic_cornstack_python_v1
function test_CrossCorrelator2d begin seed 123 comment test 2D data set Npoints2 = 10 set x2 = linear space - 10 10 Npoints2 set tuple X Y = call meshgrid x2 x2 set Z = random tuple Npoints2 Npoints2 seed 123 set sigma = 0.2 comment purposely have sparsely filled values (with lots of zeros) comment place peaks in rando...
def test_CrossCorrelator2d(): np.random.seed(123) # test 2D data Npoints2 = 10 x2 = np.linspace(-10, 10, Npoints2) X, Y = np.meshgrid(x2, x2) Z = np.random.random((Npoints2, Npoints2)) np.random.seed(123) sigma = 0.2 # purposely have sparsely filled values (with lots of zeros) #...
Python
nomic_cornstack_python_v1
function satisfies_s strings1 strings2 begin comment Add '|' to ensure that we don't erroneously think prefix categories comment match (i.e., _|P|PPL|PPLA2 does not satisfy _|P|PPL|PPLA) return all generator expression starts with s1 + string | s2 + string | for tuple s1 s2 in zip strings1 strings2 end function
def satisfies_s(strings1, strings2): # Add '|' to ensure that we don't erroneously think prefix categories # match (i.e., _|P|PPL|PPLA2 does not satisfy _|P|PPL|PPLA) return all((s1 + '|').startswith(s2 + '|') for (s1, s2) in zip(strings1, strings2))
Python
nomic_cornstack_python_v1
function GetBiddingStrategy self request context begin call set_code UNIMPLEMENTED call set_details string Method not implemented! raise call NotImplementedError string Method not implemented! end function
def GetBiddingStrategy(self, request, context): context.set_code(grpc.StatusCode.UNIMPLEMENTED) context.set_details('Method not implemented!') raise NotImplementedError('Method not implemented!')
Python
nomic_cornstack_python_v1
function fileInfo tif begin print flags print geotiff_metadata for page in pages begin print tags print geotiff_tags print shape print dtype print flags end end function
def fileInfo(tif: TiffFile): print(tif.flags) print(tif.geotiff_metadata) for page in tif.pages: print(page.tags) print(page.geotiff_tags) print(page.shape) print(page.dtype) print(page.flags)
Python
nomic_cornstack_python_v1
comment -*- coding:utf-8 -*- string System Backup Tool @author: Ben Created on 2013-4-13 Copyright (c) 2012-2013 ZCTT.Co.Ltd. All rights reserved. import os import stat import time , shutil function start src_path dst_path isremoved=false begin string backup src_path into dst_path. Compared file create or update time a...
# -*- coding:utf-8 -*- ''' System Backup Tool @author: Ben Created on 2013-4-13 Copyright (c) 2012-2013 ZCTT.Co.Ltd. All rights reserved. ''' import os import stat import time, shutil def start(src_path, dst_path, isremoved=False): ''' backup src_path into dst_path. Compared file create or update time and copy up...
Python
zaydzuhri_stack_edu_python
string collect.py from collections import Counter import matplotlib.pyplot as plt import networkx as nx import sys import time import pickle import string from TwitterAPI import TwitterAPI set consumer_key = string kBvjgHEEyqDEAkwolXXdwzQAc set consumer_secret = string 2YJjfIhdFAm7II5bg5f3Uj18vRCM31N8b9c4sBZYspqFSFiNgD...
""" collect.py """ from collections import Counter import matplotlib.pyplot as plt import networkx as nx import sys import time import pickle import string from TwitterAPI import TwitterAPI consumer_key = 'kBvjgHEEyqDEAkwolXXdwzQAc' consumer_secret = '2YJjfIhdFAm7II5bg5f3Uj18vRCM31N8b9c4sBZYspqFSFiNgD' access_token ...
Python
zaydzuhri_stack_edu_python
import math function is_prime n begin if n <= 1 begin return false end if n <= 3 begin return true end if n % 2 == 0 or n % 3 == 0 begin return false end set i = 5 while i * i <= n begin if n % i == 0 or n % i + 2 == 0 begin return false end set i = i + 6 end return true end function function are_all_primes numbers beg...
import math def is_prime(n): if n <= 1: return False if n <= 3: return True if n % 2 == 0 or n % 3 == 0: return False i = 5 while i * i <= n: if n % i == 0 or n % (i + 2) == 0: return False i += 6 return True def are_all_primes(numbers): ...
Python
jtatman_500k
from __future__ import print_function import os import time import sys import argparse import numpy as np import matplotlib.pyplot as plt from scipy import stats comment takes in array of samples to create empirical cdf, then evaluated the comment empirical cdf at values function ecdf samples values begin set samples =...
from __future__ import print_function import os import time import sys import argparse import numpy as np import matplotlib.pyplot as plt from scipy import stats #takes in array of samples to create empirical cdf, then evaluated the # empirical cdf at values def ecdf(samples, values): samples = np.asarray(samples)...
Python
zaydzuhri_stack_edu_python
function reader queue path begin set fails = 0 comment Connect at 9600 baud set conn = call Serial path timeout=1 comment Set 5Hz update rate write conn b'\xb5b\x06\x08\x06\x00\xc8\x00\x01\x00\x01\x00\xdej' comment Push data on to the queue. while fails < 10 begin comment Check we have a GPS device set line = strip rea...
def reader(queue, path): fails = 0 # Connect at 9600 baud conn = serial.Serial(path, timeout=1) # Set 5Hz update rate conn.write(b'\xb5\x62\x06\x08\x06\x00\xc8\x00\x01\x00\x01\x00\xde\x6a') # Push data on to the queue. while fails < 10: # Check we have a GPS device line = ...
Python
nomic_cornstack_python_v1
from numpy import * import matplotlib.pyplot as plt from mpl_toolkits.mplot3d.axes3d import Axes3D import sys function loadDataSet fr begin comment fr = open(filename) set x1 = list set x2 = list set y = list for line in read lines fr begin set curLine = split strip line string append x1 decimal curLine at 0 append ...
from numpy import * import matplotlib.pyplot as plt from mpl_toolkits.mplot3d.axes3d import Axes3D import sys def loadDataSet(fr): #fr = open(filename) x1 = [] x2 = [] y = [] for line in fr.readlines(): curLine = line.strip().split('\t') x1.append(float(curLine[0])) x2.appen...
Python
zaydzuhri_stack_edu_python
function cleanRegistersNewBorn self registers begin set toDelete = list for tuple i j in permutations keys registrosRecienNacido 2 begin if i < j and call similarNewbornRegister loc at i loc at j begin if length registrosRecienNacido at i == 1 begin append toDelete i end else if length registrosRecienNacido at j == 1 ...
def cleanRegistersNewBorn(self, registers): toDelete = [] for i, j in itertools.permutations(self.registrosRecienNacido.keys(), 2): if i < j and similarNewbornRegister(registers.loc[i], registers.loc[j]): if len(self.registrosRecienNacido[i]) == 1: toDele...
Python
nomic_cornstack_python_v1
class LRUCache extends object begin comment python 2 写法 function __init__ self capacity begin set csize = capacity set cache = dict comment 要被移除的key = priority[0] set priority = list end function comment 同時要標記used? function get self key begin if call has_key key begin append priority key remove priority key end retur...
class LRUCache(object): # python 2 写法 def __init__(self, capacity): self.csize = capacity self.cache = {} self.priority = [] # 要被移除的key = priority[0] def get(self, key): # 同時要標記used? if self.cache.has_key(key): self.priority.append(key) self.priori...
Python
zaydzuhri_stack_edu_python
function add_division tournament begin set division_data = loads data set new_division = call Division name=division_data at string name append divisions new_division add session new_division commit session return call jsonify call to_dict new_division end function
def add_division(tournament): division_data = json.loads(request.data) new_division = Division( name = division_data['name'] ) tournament.divisions.append(new_division) DB.session.add(new_division) DB.session.commit() return jsonify(to_dict(new_division))
Python
nomic_cornstack_python_v1
comment To create pre-built adjectives import random import models import models.geometry import models.events import models.forum comment for testing string This module preloads all of its objects directly into the database or does nothing if the objects already exists in the database. All access to these objects occu...
import random # To create pre-built adjectives import models import models.geometry import models.events import models.forum # for testing """ This module preloads all of its objects directly into the database or does nothing if the objects already exists in the database. All access to these objects occurs through...
Python
zaydzuhri_stack_edu_python
function split_array arr begin comment Sort the input array sort arr comment Find the middle index set middle_index = length arr // 2 comment Split the array into two halves set subarray1 = arr at slice : middle_index : set subarray2 = arr at slice middle_index : : return tuple subarray1 subarray2 end function comm...
def split_array(arr): # Sort the input array arr.sort() # Find the middle index middle_index = len(arr) // 2 # Split the array into two halves subarray1 = arr[:middle_index] subarray2 = arr[middle_index:] return subarray1, subarray2 # Test the function arr = [6, 5, 4, 3, 2, 1] result...
Python
jtatman_500k
function test_no_agent_lastname self begin set data = valid_payload set data at string agent_lastname = string set response1 = post reverse string clients data=dumps data content_type=string application/json assert equal status_code HTTP_400_BAD_REQUEST del data at string agent_lastname set response = post reverse str...
def test_no_agent_lastname(self): data = self.valid_payload data['agent_lastname'] = "" response1 = self.client.post( reverse('clients'), data=json.dumps(data), content_type='application/json' ) self.assertEqual(response1.status_code, status.HT...
Python
nomic_cornstack_python_v1
function updateList widget spaces minimum=0 begin clear widget if length spaces <= minimum begin call hide return end list comprehension call addItem call QListWidgetItem item for item in spaces call setFixedHeight call sizeHintForRow 0 * count widget + 2 * call frameWidth show end function
def updateList(widget, spaces, minimum=0): widget.clear() if len(spaces) <= minimum: widget.hide() return [widget.addItem(QtWidgets.QListWidgetItem(item)) for item in spaces] widget.setFixedHeight(widget.sizeHintForRow(0) * widget.count() + 2 * widget.frameWidth...
Python
nomic_cornstack_python_v1
from generate_samples import * from learn_activities import * import csv comment Example of generating sample data. set n_samples = 25 set n_individuals = 50 set activities = list string sports string traveling string media string eating string line set grid_size = list 100 100 set noise = 0.1 set labeled = true set fe...
from generate_samples import * from learn_activities import * import csv # Example of generating sample data. n_samples = 25 n_individuals = 50 activities = ['sports', 'traveling', 'media', 'eating', 'line'] grid_size = [100,100] noise = 0.1 labeled = True features = ['x_pos_high', 'x_pos_low', ...
Python
zaydzuhri_stack_edu_python
import os import numpy as np import pandas as pd import keras from keras.applications.vgg16 import VGG16 from keras.preprocessing import image from keras.applications.vgg16 import preprocess_input from keras.models import Model from keras.layers import Dense , GlobalAveragePooling2D from keras.utils import plot_model i...
import os import numpy as np import pandas as pd import keras from keras.applications.vgg16 import VGG16 from keras.preprocessing import image from keras.applications.vgg16 import preprocess_input from keras.models import Model from keras.layers import Dense,GlobalAveragePooling2D from keras.utils import plot_model...
Python
zaydzuhri_stack_edu_python
comment Create your views here. from django.shortcuts import render_to_response from django.template import RequestContext from phrase.models import Phrase function generate request x=3 y=3 begin set x = integer x set y = integer y set quotesQS = all if count quotesQS < x * y begin return call render_to_response string...
# Create your views here. from django.shortcuts import render_to_response from django.template import RequestContext from phrase.models import Phrase def generate(request, x=3, y=3): x = int(x) y = int(y) quotesQS = Phrase.objects.all() if quotesQS.count() < x * y: return render_to_response( ...
Python
zaydzuhri_stack_edu_python
function test_model_observe_wait task begin set model = call ExecutionEditorModel root=task assert pools == list string test set child = children at 0 set wait = dict string activated true ; string wait list string test2 assert string test2 in pools set wait = dict string activated false ; string wait list string test2...
def test_model_observe_wait(task): model = ExecutionEditorModel(root=task) assert model.pools == ['test'] child = task.children[1].children[0] child.wait = {'activated': True, 'wait': ['test2']} assert 'test2' in model.pools child.wait = {'activated': False, 'wait': ['test2']} assert 'tes...
Python
nomic_cornstack_python_v1
import numpy import sympy function f x begin return x * cos x end function if __name__ == string __main__ begin set x = 1.8 set h = list 0.1 0.01 0.001 0.0001 for i in range length h begin set res = f dist x + h at i - f dist x / f dist h at i print res end end
import numpy import sympy def f( x ): return x * numpy.cos(x) if __name__ == "__main__": x = 1.8 h = [0.1, 0.01, 0.001, 0.0001] for i in range(len(h)): res = (f(x + h[i]) - f(x)) / f(h[i]) print(res)
Python
zaydzuhri_stack_edu_python
comment print(type(vi)) comment print(type(a)) comment print(type(t))
#print(type(vi)) #print(type(a)) #print(type(t))
Python
zaydzuhri_stack_edu_python
for x in string begin if x not in check begin append check x end else begin remove check x end end set found = length check <= 1 if not found begin print string NO end else begin print string YES end
for x in string: if x not in check: check.append(x) else: check.remove(x) found = (len(check)<=1) if not found: print("NO") else: print("YES")
Python
zaydzuhri_stack_edu_python
import math , sys , random import numpy as np from collections import defaultdict from copy import copy from constructive_heuristics import nearest_neighbour_algorithm function hill_climbing_best_fitting graph initial_solution=none begin function init_random_tour tour_length begin set tour = range tour_length shuffle r...
import math, sys, random import numpy as np from collections import defaultdict from copy import copy from constructive_heuristics import nearest_neighbour_algorithm def hill_climbing_best_fitting(graph, initial_solution = None): def init_random_tour(tour_length): tour = range(tour_length) random.shuffle(tour)...
Python
zaydzuhri_stack_edu_python
comment real signature unknown; restored from __doc__ function mapSelectionFromSource self QItemSelection begin return QItemSelection end function
def mapSelectionFromSource(self, QItemSelection): # real signature unknown; restored from __doc__ return QItemSelection
Python
nomic_cornstack_python_v1
function encode_pssms pssms_list window_size begin set half_window = window_size // 2 set arrays_list = list set groups = list for tuple pssm_idx pssm in enumerate pssms_list begin set seq_len = length pssm set training_array = zeros tuple seq_len window_size 20 set scaled_pssm = pssm / 100 set padded_pssm = vertical...
def encode_pssms(pssms_list, window_size): half_window = window_size // 2 arrays_list = [] groups = [] for pssm_idx, pssm in enumerate(pssms_list): seq_len = len(pssm) training_array = np.zeros((seq_len, window_size, 20)) scaled_pssm = pssm / 100 padded_pssm = np.vstack...
Python
nomic_cornstack_python_v1
function test_mutate_after_removal begin set board = call create call dedent string 0|0 0 - 1|1 1 max_pips=2 clear extra_dominoes for _ in range 10 begin set mutated = call mutate random assert call Domino 2 2 not in dominoes end end function
def test_mutate_after_removal(): board = Board.create(dedent("""\ 0|0 0 - 1|1 1"""), max_pips=2) board.extra_dominoes.clear() for _ in range(10): mutated = board.mutate(random) assert Domino(2, 2) not in mutated.dominoes
Python
nomic_cornstack_python_v1
function split self delimiter maxsplit=none begin set split_expr = call ViewExpression dict string $split list self delimiter if maxsplit is none begin return split_expr end if maxsplit <= 0 begin return call ViewExpression list self end comment pylint: disable=invalid-unary-operand-type set maxsplit_expr = call if_els...
def split(self, delimiter, maxsplit=None): split_expr = ViewExpression({"$split": [self, delimiter]}) if maxsplit is None: return split_expr if maxsplit <= 0: return ViewExpression([self]) # pylint: disable=invalid-unary-operand-type maxsplit_expr = (sp...
Python
nomic_cornstack_python_v1
function __init__ self sensor_id access_token websession begin set _sensor_id = sensor_id set websession = websession set _access_token = access_token set _authHeader = dict string Authorization string { _access_token } set _devices = dict set _last_updated = call utcnow - time delta hours=2 set _timeout = 10 set _url...
def __init__(self, sensor_id, access_token, websession): self._sensor_id = sensor_id self.websession = websession self._access_token = access_token self._authHeader = {"Authorization": f"{self._access_token}"} self._devices = {} self._last_updated = datetime.datetime.utc...
Python
nomic_cornstack_python_v1
function verify_document_number self document_number begin if not document_number begin set config at string verify_documentno = string end else begin set config at string verify_documentno = document_number end end function
def verify_document_number(self, document_number): if not document_number: self.config['verify_documentno'] = "" else: self.config['verify_documentno'] = document_number
Python
nomic_cornstack_python_v1
function recieve self begin set new = call recv 1 set new = split string new set nodeId = new at 3 set data = new at 7 end function
def recieve(self): self.new = self.bus.recv(1) self.new = str(self.new).split() self.nodeId = self.new[3] self.data = self.new[7]
Python
nomic_cornstack_python_v1
comment Copyright (c) Microsoft. All rights reserved. comment Licensed under the MIT license. See LICENSE file in the project root for comment full license information. import time import os import sys import asyncio import json from six.moves import input import threading from azure.iot.device.aio import IoTHubModuleC...
# Copyright (c) Microsoft. All rights reserved. # Licensed under the MIT license. See LICENSE file in the project root for # full license information. import time import os import sys import asyncio import json from six.moves import input import threading from azure.iot.device.aio import IoTHubModuleClient ...
Python
zaydzuhri_stack_edu_python
function _default_interface self route_output=none begin string :param route_output: For mocking actual output if not route_output begin set tuple out __ __ = call exec_cmd string /sbin/ip route set lines = call splitlines end else begin set lines = split route_output string end for line in lines begin set line = split...
def _default_interface(self, route_output=None): """ :param route_output: For mocking actual output """ if not route_output: out, __, __ = exec_cmd('/sbin/ip route') lines = out.splitlines() else: lines = route_output.split("\n") for l...
Python
jtatman_500k
function _remove_duplicate_rules_inside_answer_groups cls answer_groups state_name begin set rules_to_remove_with_diff_dest_node = list set rules_to_remove_with_try_again_dest_node = list set seen_rules_with_try_again_dest_node = list set seen_rules_with_diff_dest_node = list for answer_group in answer_groups begin...
def _remove_duplicate_rules_inside_answer_groups( cls, answer_groups: List[state_domain.AnswerGroupDict], state_name: str ) -> None: rules_to_remove_with_diff_dest_node = [] rules_to_remove_with_try_again_dest_node = [] seen_rules_with_try_again_dest_node = [] ...
Python
nomic_cornstack_python_v1
for i in range 12 begin set line = list for j in range 12 begin append line decimal input end append matrix line end for i in range 12 begin for j in range 12 begin if i + j >= 12 and j - i >= 1 and j > 6 begin set resultado = resultado + matrix at i at j end end end if operation == string S begin print format string ...
for i in range(12): line = [] for j in range(12): line.append(float(input())) matrix.append(line) for i in range(12): for j in range(12): if(i + j >= 12 and j - i >= 1) and j > 6: resultado += matrix[i][j] if operation == "S": print("{:.1f}".format(resultado)) else: ...
Python
zaydzuhri_stack_edu_python
function cylinder downCirc=- 120 upCirc=- 70 radius=15 resolution=20 begin set t = linear space 0 2 * pi resolution set cylinderPos = list for num in t begin set x = - cos num * radius set y = sin num * radius append cylinderPos list x y downCirc 0 0 0 string mov end for num in t begin set x = - cos num * radius set y...
def cylinder(downCirc = -120, upCirc = -70,radius = 15, resolution = 20): t = np.linspace(0, 2*m.pi, resolution) cylinderPos = [] for num in t: x = -m.cos(num)*radius y = m.sin(num)*radius cylinderPos.append([x, y, downCirc, 0, 0, 0, 'mov']) for num in t: ...
Python
nomic_cornstack_python_v1
function _array_of_arrays list_of_arrays begin set out = call empty length list_of_arrays dtype=object set out at slice : : = list_of_arrays return out end function
def _array_of_arrays(list_of_arrays): out = np.empty(len(list_of_arrays), dtype=object) out[:] = list_of_arrays return out
Python
nomic_cornstack_python_v1
function apply self state begin set job = call get_job job_id call stalled timestamp end function
def apply(self, state): job = state.jobs.get_job(self.job_id) job.stalled(self.timestamp)
Python
nomic_cornstack_python_v1
function repeater_make *args **kwargs begin return call repeater_make *args keyword kwargs end function
def repeater_make(*args, **kwargs): return _my_lte_swig.repeater_make(*args, **kwargs)
Python
nomic_cornstack_python_v1
function __init__ self begin set items = list end function
def __init__(self): self.items = []
Python
nomic_cornstack_python_v1
function remDupSortReverseList Transaction_list2 begin comment print 'Inside remDupSortReverseList \n ',Transaction_list2 comment Removing Duplicates from the list set b = map list set map tuple Transaction_list2 end function
def remDupSortReverseList(Transaction_list2): #print 'Inside remDupSortReverseList \n ',Transaction_list2 b = map(list, set(map(tuple, Transaction_list2))) #Removing Duplicates from the list
Python
nomic_cornstack_python_v1
async function get_train_stations self latitude longitude valid_stations=none begin set params = dict string location format string {},{} latitude longitude ; string key api_key ; string type string train_station ; string radius 1600 info string Getting train stations near (%f, %f) latitude longitude async_with call Cl...
async def get_train_stations(self, latitude: float, longitude: float, valid_stations=None) -> list: params = { 'location': '{},{}'.format(latitude, longitude), 'key': self.api_key, 'type': "train_station", "radius": 1600 } ...
Python
nomic_cornstack_python_v1
comment 3. 성적 관리 프로그램 comment 을 작성하고자 한다. comment 한 학생의 점수는 4과목으로 구성된다(Bigdata, Python, Flask, DB). comment 한 반의 전체 학생수는 5명이다. comment 학생 리스트를 참고하여 다음과 같이 키보드에서 입력할 수 있다. comment 학생명 입력, 학생명의 점수 입력(4과목 공백으로 구분) comment 데이터 구조: [{홍길동:{과목명:점수}] set scoreList = list set subject = list string Bigdata string Python string ...
# 3. 성적 관리 프로그램 # 을 작성하고자 한다. # 한 학생의 점수는 4과목으로 구성된다(Bigdata, Python, Flask, DB). # 한 반의 전체 학생수는 5명이다. # 학생 리스트를 참고하여 다음과 같이 키보드에서 입력할 수 있다. # 학생명 입력, 학생명의 점수 입력(4과목 공백으로 구분) # 데이터 구조: [{홍길동:{과목명:점수}] scoreList = [] subject = ['Bigdata', 'Python', 'Flask', 'DB'] while True: func = input(f'\t성적 입력(a) or 확인(s) or 검...
Python
zaydzuhri_stack_edu_python
import sys import theano import numpy import theano.tensor as T class VSpaceLayer extends object begin string A layer which has a vector of numerical indices on its input and the corresponding matrix rows on the output. This is to be used as a minibatch. The matrix are the embeddings. decorator classmethod function fro...
import sys import theano import numpy import theano.tensor as T class VSpaceLayer(object): """A layer which has a vector of numerical indices on its input and the corresponding matrix rows on the output. This is to be used as a minibatch. The matrix are the embeddings.""" @classmethod def from_ma...
Python
zaydzuhri_stack_edu_python
function create_tensor self in_layers=none set_tensors=true **kwargs begin if in_layers is none begin set in_layers = in_layers end set in_layers = call convert_to_layers in_layers call build set atom_number = out_tensor set atom_features = call embedding_lookup embedding_list atom_number if set_tensors begin set varia...
def create_tensor(self, in_layers=None, set_tensors=True, **kwargs): if in_layers is None: in_layers = self.in_layers in_layers = convert_to_layers(in_layers) self.build() atom_number = in_layers[0].out_tensor atom_features = tf.nn.embedding_lookup(self.embedding_list, atom_number) if set...
Python
nomic_cornstack_python_v1
function _copy_retention_policy self retention_policy begin set keys = list comprehension retention_property for backup_type in LongTermBackupType set new_retention_policy = dictionary comprehension key : retention_policy at key for key in keys set new_retention_policy at WEEK_OF_YEAR = retention_policy at WEEK_OF_YEAR...
def _copy_retention_policy(self, retention_policy): keys = [backup_type.retention_property for backup_type in BackupRetentionPolicyHelper.LongTermBackupType] new_retention_policy = {key: retention_policy[key] for key in keys} new_retention_policy[BackupRetentionPolicyHelper.WEEK_OF...
Python
nomic_cornstack_python_v1
class Solution begin function repeatedSubstringPattern self s begin set stringLen = length s if stringLen == 1 begin return false end print stringLen for i in range 1 ceil stringLen / 2 + 1 begin if stringLen % i == 0 begin set ssSet = set set startIndex = 0 set endIndex = i set canRepeat = true while endIndex != strin...
class Solution: def repeatedSubstringPattern(self, s: str) -> bool: stringLen = len(s) if stringLen == 1: return False print(stringLen) for i in range(1, math.ceil(stringLen/2)+1): if( stringLen%i == 0 ): ssSet = set() ...
Python
zaydzuhri_stack_edu_python
comment pythonを使って、画面に文字を出力するプログラムです comment ダブルクオーテーションの中身(今はI am vigilante.)を変えることで、画面に出力する文字を変更することができます。 print string I am vigilante.
#pythonを使って、画面に文字を出力するプログラムです #ダブルクオーテーションの中身(今はI am vigilante.)を変えることで、画面に出力する文字を変更することができます。 print("I am vigilante.")
Python
zaydzuhri_stack_edu_python
function __init__ self problem volfrac filter gui maxeval=2000 ftol=0.0001 begin call __init__ problem volfrac filter gui maxeval ftol set init_obj = none set vtot = nelx * nely * volfrac end function
def __init__(self, problem, volfrac, filter, gui, maxeval=2000, ftol=1e-4): super().__init__(problem, volfrac, filter, gui, maxeval, ftol) self.init_obj = None self.vtot = problem.nelx * problem.nely * volfrac
Python
nomic_cornstack_python_v1
for tuple name year in celebs begin if year < 1980 begin print name end end
for name,year in celebs : if year < 1980 : print(name)
Python
zaydzuhri_stack_edu_python
function modify_settings self data begin return call _put string detail data=data end function
def modify_settings(self, data: Dict[str, Any]) -> APIResponse: return self._put("detail", data=data)
Python
nomic_cornstack_python_v1
function train workDir classifier=string DBN ldaDim=- 1 begin print string Loading embeddings set file_name = format string {}/labels.csv workDir set labels = call as_matrix at tuple slice : : 1 set labels = map call itemgetter 1 map split map dirname labels comment Gets the image directory set file_name = format st...
def train(workDir, classifier='DBN',ldaDim=-1): print('Loading embeddings') file_name = '{}/labels.csv'.format(workDir) labels = pd.read_csv(file_name, header=None).as_matrix()[:,1] labels = map(itemgetter(1), map(os.path.split, map(os.path.dirname, labels)))#Gets th...
Python
nomic_cornstack_python_v1
function longest_common_substring string1 string2 begin set x = length string1 set y = length string2 set table = list comprehension list 0 * y + 1 for _ in range x + 1 set tuple longest x_longest = tuple 0 0 for i in range x begin for j in range y begin if string1 at i == string2 at j begin set c = table at i at j + 1...
def longest_common_substring(string1, string2): x = len(string1) y = len(string2) table = [[0]*(y+1) for _ in range(x+1)] longest, x_longest = 0, 0 for i in range(x): for j in range(y): if string1[i] == string2[j]: c = table[i][j] + 1 table[i+1][j+...
Python
jtatman_500k
function play_video self video_id begin set new_video = call get_video video_id if new_video is none begin print string Cannot play video: Video does not exist return end if flagged at 0 begin print format string Cannot play video: Video is currently flagged (reason: {0}) flagged at 1 return end if _play_vid_tag is not...
def play_video(self, video_id): new_video = self._video_library.get_video(video_id) if new_video is None: print("Cannot play video: Video does not exist") return if new_video.flagged[0]: print("Cannot play video: Video is currently flagged (reason: {0})".form...
Python
nomic_cornstack_python_v1
function get_genome_id_to_amounts list_of_drawn_genome_id genome_amounts begin assert is instance list_of_drawn_genome_id list assert is instance genome_amounts list set genome_id_to_amounts = dict for tuple index genome_id in enumerate list_of_drawn_genome_id begin set genome_id_to_amounts at genome_id = genome_amoun...
def get_genome_id_to_amounts(list_of_drawn_genome_id, genome_amounts): assert isinstance(list_of_drawn_genome_id, list) assert isinstance(genome_amounts, list) genome_id_to_amounts = {} for index, genome_id in enumerate(list_of_drawn_genome_id): genome_id_to_amounts[genome_id] = genome_amounts[index] retur...
Python
nomic_cornstack_python_v1