code
stringlengths
10
2.58M
original_code
stringlengths
3
3.18M
original_language
stringclasses
1 value
source
stringclasses
7 values
function elemCheckOrCreate_bdroot_content root fo po aeObjFlags=none hasPlanes=false hasNodes=false hasSignals=false aeBgColor=none aeFirstNodeIdx=none aeBounds=none aeShortCount=none aeClumpNum=none begin if aeObjFlags is not none begin set root_objFlags = call elemFindOrCreate root string objFlags fo po pos=0 call el...
def elemCheckOrCreate_bdroot_content(root, fo, po, aeObjFlags=None, hasPlanes=False, \ hasNodes=False, hasSignals=False, aeBgColor=None, aeFirstNodeIdx=None, aeBounds=None, aeShortCount=None, aeClumpNum=None): if aeObjFlags is not None: root_objFlags = elemFindOrCreate(root, "objFlags",...
Python
nomic_cornstack_python_v1
function write_incar self atoms directory=string ./ **kwargs begin comment jrk 1/23/2015 I added this flag because this function has comment two places where magmoms get written. There is some comment complication when restarting that often leads to magmom comment getting written twice. this flag prevents that issue. s...
def write_incar(self, atoms, directory='./', **kwargs): # jrk 1/23/2015 I added this flag because this function has # two places where magmoms get written. There is some # complication when restarting that often leads to magmom # getting written twice. this flag prevents that issue. ...
Python
nomic_cornstack_python_v1
function show_score self begin comment Draw score call blit score_image score_rect comment Draw high score call blit high_score_image high_score_rect comment Draw lives call draw screen end function
def show_score(self): # Draw score self.screen.blit(self.score_image, self.score_rect) # Draw high score self.screen.blit(self.high_score_image, self.high_score_rect) # Draw lives self.lives.draw(self.screen)
Python
nomic_cornstack_python_v1
function initialize_cursor begin if STAND_TYPE == string TEST begin set conn = call connect string sqlite_python.db set cursor = call cursor end else begin set DATABASE_URL = environ at string DATABASE_URL set conn = call connect DATABASE_URL sslmode=string require set cursor = call cursor end return tuple cursor conn ...
def initialize_cursor(): if STAND_TYPE == 'TEST': conn = sqlite3.connect('sqlite_python.db') cursor = conn.cursor() else: DATABASE_URL = os.environ['DATABASE_URL'] conn = psycopg2.connect(DATABASE_URL, sslmode='require') cursor = conn.cursor() ...
Python
nomic_cornstack_python_v1
function merge_sort arr begin if length arr <= 1 begin return arr end set mid = length arr // 2 set left = arr at slice : mid : set right = arr at slice mid : : set left = call merge_sort left set right = call merge_sort right return merge left right end function function merge left right begin set merged = list s...
def merge_sort(arr): if len(arr) <= 1: return arr mid = len(arr) // 2 left = arr[:mid] right = arr[mid:] left = merge_sort(left) right = merge_sort(right) return merge(left, right) def merge(left, right): merged = [] i = 0 j = 0 while i < len(left) and j < len(ri...
Python
greatdarklord_python_dataset
function _write_visited self visited begin with open join path url_dir search_dir_name string visited.json string w as visited_file begin dump dict string visited_urls list visited visited_file encoding=string utf-8 end end function
def _write_visited(self, visited): with open(path.join(self.url_dir, self.search_dir_name, 'visited.json'), 'w') as visited_file: json.dump( { 'visited_urls': list(visited) }, visited_file, encoding = 'utf-8' )
Python
nomic_cornstack_python_v1
function compartmental t y a b gamm begin set beta_ = b * call entire a=a t=t return list - beta_ * y at 0 * y at 1 beta_ * y at 0 * y at 1 - gamm * y at 1 gamm * y at 1 end function
def compartmental(t,y,a,b,gamm): beta_ = b*entire(a=a,t=t) return [ -beta_*y[0]*y[1], beta_*y[0]*y[1] - gamm*y[1], gamm*y[1] ]
Python
nomic_cornstack_python_v1
comment -*-coding:utf-8 -*- comment Author: w61 comment Date: 2020.10.27 string Description: The function of this module is to transform the data set in VOC format to COCO format. When instantiating class VocToCoco, you need to specify val_num, test_num, voc_xml_path, voc_img_path. import os import random import shutil...
# -*-coding:utf-8 -*- # Author: w61 # Date: 2020.10.27 ''' Description: The function of this module is to transform the data set in VOC format to COCO format. When instantiating class VocToCoco, you need to specify val_num, test_num, voc_xml_path, voc_img_path. ''' import os import random import shutil import sy...
Python
zaydzuhri_stack_edu_python
function vertices_from_edge self edge begin assert is instance edge Edge return map Vertex call vertices_from_edge call topods_shape end function
def vertices_from_edge(self, edge): assert isinstance(edge, Edge) return map(Vertex, self._top_exp.vertices_from_edge(edge.topods_shape()))
Python
nomic_cornstack_python_v1
function _view_form_in_state uid fis begin set storage = storage set form_name = form set form_cfg = forms at form_name set tuple meta tmpl form_cls tmpl_vars = call get_form_by_name form_name APP set kwargs = dictionary template_render_kw or dict update kwargs call build_links meta uid storage if method == string GET ...
def _view_form_in_state(uid, fis): storage = hobj.storage form_name = fis.form form_cfg = hobj.forms[form_name] meta, tmpl, form_cls, tmpl_vars = hobj.get_form_by_name(form_name, APP) kwargs = dict(form_cfg.template_render_kw or {}) kwargs.update(common.build_links(me...
Python
nomic_cornstack_python_v1
function encrypt_string input begin set h = call new string sha512_256 update h encode str input return string hex digest h end function
def encrypt_string(input: str): h = hashlib.new('sha512_256') h.update(str.encode(input)) return str(h.hexdigest())
Python
nomic_cornstack_python_v1
comment !/usr/bin/python string Generate Parentheses Given n pairs of parentheses, write a function to generate all combinations of well-formed parentheses. For example, given n = 3, a solution set is: "((()))", "(()())", "(())()", "()(())", "()()()" class Solution begin comment @param an integer comment @return a list...
#!/usr/bin/python """ Generate Parentheses Given n pairs of parentheses, write a function to generate all combinations of well-formed parentheses. For example, given n = 3, a solution set is: "((()))", "(()())", "(())()", "()(())", "()()()" """ class Solution: # @param an integer # @return a list of stri...
Python
zaydzuhri_stack_edu_python
function _write self begin comment convert build definition list into toml table set build_definitions_table = call table for build_definition in _build_definitions begin set build_definition_as_table = call _build_definition_to_toml_table build_definition add build_definitions_table uuid build_definition_as_table end ...
def _write(self): # convert build definition list into toml table build_definitions_table = tomlkit.table() for build_definition in self._build_definitions: build_definition_as_table = _build_definition_to_toml_table(build_definition) build_definitions_table.add(build_def...
Python
nomic_cornstack_python_v1
function __getitem__ self item begin return get _state at string data item none end function
def __getitem__(self, item): return self._state["data"].get(item, None)
Python
nomic_cornstack_python_v1
function list_all begin set device_type_info = call list_type DEVICE_TYPE return call from_simctl_info device_type_info end function
def list_all() -> List["DeviceType"]: device_type_info = SimulatorControlBase.list_type(SimulatorControlType.DEVICE_TYPE) return DeviceType.from_simctl_info(device_type_info)
Python
nomic_cornstack_python_v1
import math function volume_da_pizza z a begin set z = pi * z ^ 2 return z * a end function
import math def volume_da_pizza(z, a): z = math.pi * (z ** 2) return z * a
Python
zaydzuhri_stack_edu_python
function getGithubData repo_link begin set reg_format = true set m = search string (www\.)?github.(com|org)\/[\S]+?\/[\w.-]+ repo_link if not m begin set reg_format = false set m = search string [\w-]+\.github.(com|org|io)?(\/[\w-]+)* repo_link end if not m begin return dict end set filtered_repo_link = call group 0 s...
def getGithubData(repo_link): reg_format = True m = re.search('(www\.)?github.(com|org)\/[\S]+?\/[\w.-]+', repo_link) if not m: reg_format = False m = re.search('[\w-]+\.github.(com|org|io)?(\/[\w-]+)*', repo_link) if not m: return {} filtered_repo_link = m.group(0) repo = '' if reg_format: repo = fi...
Python
nomic_cornstack_python_v1
comment https://leetcode.com/problems/most-frequent-subtree-sum/ comment Given the root of a tree, you are asked to find the most frequent subtree sum. The subtree sum of a node is defined comment as the sum of all the node values formed by the subtree rooted at that node (including the node itself). So what is comment...
# https://leetcode.com/problems/most-frequent-subtree-sum/ # Given the root of a tree, you are asked to find the most frequent subtree sum. The subtree sum of a node is defined # as the sum of all the node values formed by the subtree rooted at that node (including the node itself). So what is # the most frequent subtr...
Python
zaydzuhri_stack_edu_python
function test_rolling_nodes_restart self cluster_type nodes node_type begin set node_count = length call get_nodes node_type if call is_ms_provider_cluster and node_type == WORKER_MACHINE begin set ocp_nodes = call generate_nodes_for_provider_worker_node_tests end else begin set ocp_nodes = call get_nodes node_type=nod...
def test_rolling_nodes_restart(self, cluster_type, nodes, node_type): node_count = len(get_nodes(node_type)) if is_ms_provider_cluster() and node_type == constants.WORKER_MACHINE: ocp_nodes = generate_nodes_for_provider_worker_node_tests() else: ocp_nodes = get_nodes(node...
Python
nomic_cornstack_python_v1
import cv2 as cv from tensorflow import keras import numpy as np set model = call load_model string densenet121_detection_model.h5 set haar_cascade = call CascadeClassifier string haarcascade_frontalface_default.xml set label_dict = dict 0 string Without Mask ; 1 string With Mask set color_dict = dict 0 tuple 0 0 255 ;...
import cv2 as cv from tensorflow import keras import numpy as np model = keras.models.load_model("densenet121_detection_model.h5") haar_cascade = cv.CascadeClassifier("haarcascade_frontalface_default.xml") label_dict = {0: "Without Mask", 1: "With Mask"} color_dict = {0: (0, 0, 255), 1: (0, 255, 0)} vide...
Python
zaydzuhri_stack_edu_python
comment Using Matplotlib Axes comment Seaborn uses matplotlib as the underlying library for creating plots. comment Most of the time, you can use the Seaborn API to modify your visualizations but sometimes comment it is helpful to use matplotlib's functions to customize your plots. comment The most important object in ...
# Using Matplotlib Axes # Seaborn uses matplotlib as the underlying library for creating plots. # Most of the time, you can use the Seaborn API to modify your visualizations but sometimes # it is helpful to use matplotlib's functions to customize your plots. # The most important object in this case is matplotlib's axe...
Python
zaydzuhri_stack_edu_python
import os from tkinter import * import pandas as pd import tkinter.scrolledtext as scrolledtext comment cwd = os.getenv("HOME") set root = call Tk call geometry string 800x500 title root string Application set files_in_dir = list function getpath begin global entry2 set string = get entry2 set files_in_dir = string t...
import os from tkinter import * import pandas as pd import tkinter.scrolledtext as scrolledtext #cwd = os.getenv("HOME") root = Tk() root.geometry('800x500') root.title('Application') files_in_dir=[] def getpath(): global entry2 string = entry2.get() files_in_dir="" try: os.remove("text.txt...
Python
zaydzuhri_stack_edu_python
function setInvalid self begin Ellipsis end function
def setInvalid(self) -> None: ...
Python
nomic_cornstack_python_v1
function set_rate self density begin assert is instance density ndarray_type comment assert np.all(self.rate_const >= 0.0) set rate = rate_const * call prod density at __rcnt_index ^ __rcnt_expnt axis=1 end function
def set_rate(self, *, density): assert isinstance(density, ndarray_type) # assert np.all(self.rate_const >= 0.0) self.rate = self.rate_const * np.prod( density[self.__rcnt_index] ** self.__rcnt_expnt, axis=1)
Python
nomic_cornstack_python_v1
comment Solutions by Farid Zarbaliyev (@sehrbaz) - www.zfarid.com comment Warmup-1 > sleep_in function sleep_in weekday vacation begin return vacation or not weekday end function comment Warmup-1 > monkey_trouble function monkey_trouble a_smile b_smile begin return a_smile == b_smile end function comment Warmup-1 > sum...
#Solutions by Farid Zarbaliyev (@sehrbaz) - www.zfarid.com #Warmup-1 > sleep_in #### def sleep_in(weekday, vacation): return vacation or not weekday #Warmup-1 > monkey_trouble #### def monkey_trouble(a_smile, b_smile): return a_smile == b_smile #Warmup-1 > sum_double #### def sum_double(a, b): if a == b: re...
Python
zaydzuhri_stack_edu_python
from tkinter import Tk , Toplevel , Menu , Frame , LabelFrame , Label , Button from functions import * class OverButton extends Button begin string Класс определяет кнопки, изменяющие свой цвет и цвет текста при событиях function __init__ self window **kwargs begin call __init__ self window keyword kwargs call bind str...
from tkinter import Tk, Toplevel, Menu, Frame, LabelFrame, Label, Button from functions import * class OverButton(Button): '''Класс определяет кнопки, изменяющие свой цвет и цвет текста при событиях''' def __init__(self, window, **kwargs): Button.__init__(self, window, **kwargs) self.bind('<En...
Python
zaydzuhri_stack_edu_python
comment !/usr/bin/env python3 import sqlite3 import datetime comment currRpm = int, currPmw = double function recordNewValues currRpm currPmw begin if not is instance currRpm float begin if not is instance currRpm int begin return end end if not is instance currPmw float begin if not is instance currPmw int begin retur...
#!/usr/bin/env python3 import sqlite3 import datetime #currRpm = int, currPmw = double def recordNewValues(currRpm, currPmw): if(not(isinstance(currRpm, float))): if(not(isinstance(currRpm, int))): return if(not(isinstance(currPmw, float))): if(not(isinst...
Python
zaydzuhri_stack_edu_python
function assertIs self obj1 obj2 msg=none begin if obj1 is not obj2 begin if msg is none begin set msg = string %s is not %s % tuple obj1 obj2 end call fail msg end end function
def assertIs(self, obj1, obj2, msg=None): if obj1 is not obj2: if msg is None: msg = "%s is not %s" % (obj1, obj2) self.fail(msg)
Python
nomic_cornstack_python_v1
comment coding=utf-8 from data_cleaner import DataCleaner from os import path , makedirs import json import warnings from time import time set script_path = directory name path __file__ function load_rules_for_dataset dataset logger begin set dataset_rules_path = join path script_path string rules string %s.json % data...
# coding=utf-8 from data_cleaner import DataCleaner from os import path, makedirs import json import warnings from time import time script_path = path.dirname(__file__) def load_rules_for_dataset(dataset, logger): dataset_rules_path = path.join(script_path, 'rules', '%s.json' % dataset) if not path.exists(da...
Python
zaydzuhri_stack_edu_python
function _TestSharedAttrsWork self process_count thread_count begin set command_inst = call command_class true set arg_length_sum = 19 set args = list string foo list string bar string baz list list string x string y list string abcd call _RunApply _IncrementByLength args process_count thread_count command_inst=comma...
def _TestSharedAttrsWork(self, process_count, thread_count): command_inst = self.command_class(True) command_inst.arg_length_sum = 19 args = ['foo', ['bar', 'baz'], [], ['x', 'y'], [], 'abcd'] self._RunApply(_IncrementByLength, args, process_count, thread_count, command_inst=comm...
Python
nomic_cornstack_python_v1
comment x = 5 comment if x < 10: comment print ('Smaller') comment if x >= 10: comment print ('Bigger') comment else: comment print ('else was used') comment if x < 5: comment print ('x<5') comment elif x < 10: comment print ('x<10') comment elif x < 20: comment print ('x<20') comment else: comment print ('something el...
#x = 5 #if x < 10: # print ('Smaller') #if x >= 10: # print ('Bigger') #else: # print ('else was used') #if x < 5: # print ('x<5') #elif x < 10: # print ('x<10') #elif x < 20: # print ('x<20') #else: # print ('something else') #astr = 'vega' #try: # istr = int(astr) #except: # istr = -1 #...
Python
zaydzuhri_stack_edu_python
function remove_non_alphabetic string begin set new_string = string for char in string begin if is alpha char begin set new_string = new_string + char end end return new_string end function comment prints Thisisstring print call remove_non_alphabetic string
def remove_non_alphabetic(string): new_string = "" for char in string: if char.isalpha(): new_string += char return new_string print(remove_non_alphabetic(string)) # prints Thisisstring
Python
jtatman_500k
function archive_file tmpdir_factory request begin set archive_file_stub = join path datadir string Foo set extension = param set tmpdir = call mktemp string compression copy shutil archive_file_stub + string . + extension string tmpdir return join path string tmpdir string Foo.%s % extension end function
def archive_file(tmpdir_factory, request): archive_file_stub = os.path.join(datadir, "Foo") extension = request.param tmpdir = tmpdir_factory.mktemp("compression") shutil.copy(archive_file_stub + "." + extension, str(tmpdir)) return os.path.join(str(tmpdir), "Foo.%s" % extension)
Python
nomic_cornstack_python_v1
import xml.etree.ElementTree import abc import pcapp as p import bus as b import module as mod class Config begin function __init__ self name begin set __modules = dict set pcap = call Pcap set bus = call Bus set e = get root parse ElementTree name set __modules at ERROR = call Module pcap bus ERROR list list for m i...
import xml.etree.ElementTree import abc import pcapp as p import bus as b import module as mod class Config: def __init__(self, name): self.__modules = {} self.pcap = p.Pcap() self.bus = b.Bus() e = xml.etree.ElementTree.parse(name).getroot() self.__modules[mod.Module.ERRO...
Python
zaydzuhri_stack_edu_python
function evolved_transformer_base_tpu begin set hparams = call add_evolved_transformer_hparams call transformer_tpu set learning_rate_constant = 1 / learning_rate_warmup_steps ^ 0.5 set learning_rate_schedule = string constant*single_cycle_cos_decay return hparams end function
def evolved_transformer_base_tpu(): hparams = add_evolved_transformer_hparams(transformer.transformer_tpu()) hparams.learning_rate_constant = 1 / hparams.learning_rate_warmup_steps ** 0.5 hparams.learning_rate_schedule = ( "constant*single_cycle_cos_decay") return hparams
Python
nomic_cornstack_python_v1
comment https://drive.google.com/file/d/10eSYB9dvpj_GvrVqU3IuPHaO4I9cmyJb/view?usp=sharing comment Bài 42 - Dinh Quy Pham set n = integer input string Nhập N : set tong = 0 set lst = list for x in range n begin set tong = tong + x if tong < n begin append lst x set a = max lst end end print a
# https://drive.google.com/file/d/10eSYB9dvpj_GvrVqU3IuPHaO4I9cmyJb/view?usp=sharing # Bài 42 - Dinh Quy Pham n = int(input("Nhập N : ")) tong = 0 lst = list() for x in range(n): tong += x if tong < n: lst.append(x) a = max(lst) print(a)
Python
zaydzuhri_stack_edu_python
function estimators_ self begin return estimators_ end function
def estimators_(self): return self.detector_.estimators_
Python
nomic_cornstack_python_v1
comment coding=UTF-8 import urllib2 class Dhttpdownloader extends object begin function download self url begin if url is none begin return none end end function end class
#coding=UTF-8 import urllib2 class Dhttpdownloader(object): def download(self,url): if url is None: return None
Python
zaydzuhri_stack_edu_python
function SetDistanceValueMinMax self min max begin return call itkScalarImageToRunLengthFeaturesFilterIF3_SetDistanceValueMinMax self min max end function
def SetDistanceValueMinMax(self, min: 'double', max: 'double') -> "void": return _itkScalarImageToRunLengthFeaturesFilterPython.itkScalarImageToRunLengthFeaturesFilterIF3_SetDistanceValueMinMax(self, min, max)
Python
nomic_cornstack_python_v1
function test_static_typing begin from ipyrest import ipyrest , extendedtab , responseviews set files = list comprehension __file__ for m in tuple ipyrest extendedtab responseviews set scan = call type_scan files flags=list string ignore-missing-imports assert length list scan == 0 end function
def test_static_typing(): from ipyrest import ipyrest, extendedtab, responseviews files = [m.__file__ for m in (ipyrest, extendedtab, responseviews)] scan = type_scan(files, flags=['ignore-missing-imports']) assert len(list(scan)) == 0
Python
nomic_cornstack_python_v1
function getMidPoint self begin return call Point normalVector + normalVector / 2.0 end function
def getMidPoint(self): return p.Point((self.start.normalVector + self.end.normalVector)/2.0)
Python
nomic_cornstack_python_v1
import os import numpy as np from PIL import Image class ImgRead begin function __init__ self file_dir padding=string ONE begin set cache = list string 3DPeS string CAVIAR4REID string CUHK string GRID string i-LID string MIT string PRID string SARC3D string TownCentre string VIPeR set file_dir = file_dir set padding = ...
import os import numpy as np from PIL import Image class ImgRead: def __init__(self, file_dir, padding='ONE'): self.cache = ['3DPeS', 'CAVIAR4REID', 'CUHK', 'GRID', 'i-LID', 'MIT', 'PRID', 'SARC3D', 'TownCentre', 'VIPeR'] self.file_dir = file_dir self.padding = padding s...
Python
zaydzuhri_stack_edu_python
function waitall self timeout=none begin with _running_lock begin if not _running begin return true end comment if a Reply still runs, we let run_and_release comment signal us -- note that we are still holding the comment _running_lock to avoid race conditions set my_waitall_event = event append _waitall_events my_wait...
def waitall(self, timeout=None): with self._running_lock: if not self._running: return True # if a Reply still runs, we let run_and_release # signal us -- note that we are still holding the # _running_lock to avoid race conditions my_wa...
Python
nomic_cornstack_python_v1
function encadenar_reglas self begin for regla in _reglas_activas begin if regla not in _reglas_inactivas begin set activada = call ejecutar_regla regla encadenamiento_hacia_adelante if activada begin append _reglas_inactivas regla call encadenar_reglas end else begin continue end end end end function
def encadenar_reglas(self): for regla in self._reglas_activas: if regla not in self._reglas_inactivas: activada = self.ejecutar_regla( regla, TipoDeEncadenamiento.encadenamiento_hacia_adelante) if activada: sel...
Python
nomic_cornstack_python_v1
comment -*- coding: utf-8 -*- string Created on Mon Jan 23 14:14:54 2017 @author: swati.arora comment RMSE after 10 fold cross validation: 3.888 import numpy as np import pandas as pd import matplotlib.pyplot as plt from sklearn import linear_model as lm from sklearn import cross_validation set housing = read csv strin...
# -*- coding: utf-8 -*- """ Created on Mon Jan 23 14:14:54 2017 @author: swati.arora """ # RMSE after 10 fold cross validation: 3.888 import numpy as np import pandas as pd import matplotlib.pyplot as plt from sklearn import linear_model as lm from sklearn import cross_validation housing = pd.read_csv("housing_da...
Python
zaydzuhri_stack_edu_python
from create_dataframe import create_df from send_to_s3 import send function create_and_write file_name object_to_parquet send_to_s3=false s3_bucket=none s3_path=none compression=string gzip location=string /tmp begin comment Can be: ['GZIP', 'UNCOMPRESSED'] set file_path : str = string { location } / { file_name } .par...
from create_dataframe import create_df from send_to_s3 import send def create_and_write(file_name, object_to_parquet: dict, send_to_s3: bool = False, s3_bucket: str = None, s3_path: str = None, compression="gzip",...
Python
zaydzuhri_stack_edu_python
import os import json set val = load json open string annotations/captions_val2014.json string r set train = load json open string annotations/captions_train2014.json string r print keys val print val at string info print length val at string images print length val at string annotations print val at string images at 0...
import os import json val = json.load(open('annotations/captions_val2014.json', 'r')) train = json.load(open('annotations/captions_train2014.json', 'r')) print (val.keys()) print (val['info']) print (len(val['images'])) print (len(val['annotations'])) print (val['images'][0]) print (val['annotations'][0]) ...
Python
zaydzuhri_stack_edu_python
function profiler self begin class Task extends object begin string Private class to nicely wrap up the profile data function __init__ self block addr begin set block = block set addr = addr set name = none end function function tidy self sym begin set name = name set CPU_FRAC = value end function function __repr__ sel...
def profiler(self): class Task(object): "Private class to nicely wrap up the profile data" def __init__(self, block, addr): self.block = block self.addr = addr self.name = None def tidy(self, sym): ...
Python
nomic_cornstack_python_v1
from util import memoize , run_search_function import math from time import time function basic_evaluate board begin string The original focused-evaluate function from the lab. The original is kept because the lab expects the code in the lab to be modified. if call is_game_over begin comment If the game has been won, w...
from util import memoize, run_search_function import math from time import time def basic_evaluate(board): """ The original focused-evaluate function from the lab. The original is kept because the lab expects the code in the lab to be modified. """ if board.is_game_over(): # If the game has...
Python
zaydzuhri_stack_edu_python
class Library begin function __init__ self listOfBooks authorName begin set listOfBooks = listOfBooks set authorName = authorName set lend_books = dict for book in listOfBooks begin set lend_books at book = none end end function function displayBooks self begin for tuple index book in enumerate listOfBooks begin print...
class Library: def __init__(self, listOfBooks, authorName): self.listOfBooks = listOfBooks self.authorName = authorName self.lend_books = {} for book in self.listOfBooks: self.lend_books[book] = None def displayBooks(self): for index, book in enu...
Python
zaydzuhri_stack_edu_python
for number in numbers begin append double number * 2 end print double print string - * 40 append double generator expression number * 2 for number in numbers print string this is the comparison way:: double print string - * 40 set numbers = list 1 2 3 4 5 6 7 8 9 set square = list for number in numbers begin if number...
for number in numbers: double.append(number*2) print(double) print('-'*40) double.append(number*2 for number in numbers) print('this is the comparison way::',double) print('-'*40) numbers=[1,2,3,4,5,6,7,8,9] square=[] for number in numbers: if (number**2)%2==0: square.append(number*...
Python
zaydzuhri_stack_edu_python
string comment class MyRangeIterator:# 迭代器 comment def __init__(self,data_end): comment self.data_end = data_end comment self.index = -1 comment def __next__(self): comment # 数据如果到了最大值,则停止迭代. comment if self.index > self.data_end - 2: comment raise StopIteration() comment self.index += 1 comment return self.index comm...
""" """ # class MyRangeIterator:# 迭代器 # def __init__(self,data_end): # self.data_end = data_end # self.index = -1 # # def __next__(self): # # 数据如果到了最大值,则停止迭代. # if self.index > self.data_end - 2: # raise StopIteration() # self.index += 1 # return se...
Python
zaydzuhri_stack_edu_python
function add_reaction_Keq_var_to_problem self reaction lower_bound=none upper_bound=none **kwargs begin set kwargs = call _check_kwargs dict string Keq Keq ; string steady_state_flux steady_state_flux ; string decimal_precision false ; string bound_type string deviation kwargs set steady_state_flux = pop kwargs string ...
def add_reaction_Keq_var_to_problem( self, reaction, lower_bound=None, upper_bound=None, **kwargs ): kwargs = _check_kwargs( { "Keq": reaction.Keq, "steady_state_flux": reaction.steady_state_flux, "decimal_precision": False, ...
Python
nomic_cornstack_python_v1
function test_process_result_vcdc self begin with patch string exams.pearson.download.VCDCReader.read return_value=success_results begin assert call process_vcdc_file string /tmp/file.ext == tuple true list end for profile in success_profiles begin call refresh_from_db assert status == PROFILE_SUCCESS end end function
def test_process_result_vcdc(self): with patch('exams.pearson.download.VCDCReader.read', return_value=self.success_results): assert self.processor.process_vcdc_file("/tmp/file.ext") == (True, []) for profile in self.success_profiles: profile.refresh_from_db() assert...
Python
nomic_cornstack_python_v1
function all_gather_return_max_long value begin if call is_distributed_training_run begin set world_size = call get_world_size set tuple input orig_device = call convert_to_distributed_tensor call LongTensor list value set output = list for _ in range world_size begin set tuple output_tensor _ = call convert_to_distri...
def all_gather_return_max_long(value): if is_distributed_training_run(): world_size = torch.distributed.get_world_size() input, orig_device = convert_to_distributed_tensor(torch.LongTensor([value])) output = [] for _ in range(world_size): output_tensor, _ = convert_to_di...
Python
nomic_cornstack_python_v1
function pop_ans self n_cards begin set cards = answer_cards at slice used_answers : used_answers + n_cards : set used_answers = used_answers + n_cards return cards end function
def pop_ans(self, n_cards): cards = self.answer_cards[self.used_answers : self.used_answers + n_cards] self.used_answers += n_cards return cards
Python
nomic_cornstack_python_v1
for i in range 0 n begin append a list for j in range 0 n begin append a at i list false end end comment 2차원 배열 완성 n과 m과 마찬가지로 visited속성을 가진다 comment 함수 선언
for i in range(0,n): a.append([]) for j in range(0,n): a[i].append([False]) # 2차원 배열 완성 n과 m과 마찬가지로 visited속성을 가진다 # 함수 선언
Python
zaydzuhri_stack_edu_python
import matplotlib.pyplot as plt import pandas as pd comment import the dataset set dataset = read csv string ../data/Mall_Customers.csv comment choose points set X = values comment choose the number of cluster (elbow method) from sklearn.cluster import KMeans set wcss = list for i in range 1 11 begin set kmeans = k me...
import matplotlib.pyplot as plt import pandas as pd # import the dataset dataset = pd.read_csv('../data/Mall_Customers.csv') # choose points X = dataset.iloc[:, [3, 4]].values # choose the number of cluster (elbow method) from sklearn.cluster import KMeans wcss = [] for i in range(1, 11): kmeans = KMeans(n_clu...
Python
zaydzuhri_stack_edu_python
function test_cases begin for i in range 100000 999999 begin if call partial_palindrome string i 2 6 and call partial_palindrome string i + 1 1 6 and call partial_palindrome string i + 2 1 5 and call partial_palindrome string i + 3 0 6 begin print i end end end function
def test_cases(): for i in range(100000,999999): if (partial_palindrome(str(i), 2, 6) and partial_palindrome(str(i + 1), 1, 6) and partial_palindrome(str(i + 2), 1, 5) and partial_palindrome(str(i + 3), 0, 6)): print(i)
Python
nomic_cornstack_python_v1
import json import os import random import sys from subprocess import Popen , PIPE from urllib.parse import urlencode from OpenSSL import SSL from twisted.web.server import Site , NOT_DONE_YET from twisted.web.resource import Resource from twisted.web.static import File from twisted.web.test.test_webclient import Paylo...
import json import os import random import sys from subprocess import Popen, PIPE from urllib.parse import urlencode from OpenSSL import SSL from twisted.web.server import Site, NOT_DONE_YET from twisted.web.resource import Resource from twisted.web.static import File from twisted.web.test.test_webclient import Payloa...
Python
iamtarun_python_18k_alpaca
function _handle_info self *args **kwargs begin string Handles info messages and executed corresponding code if string version in kwargs begin comment set api version number and exit set api_version = kwargs at string version print string Initialized API with version %s % api_version return end try begin set info_code ...
def _handle_info(self, *args, **kwargs): """ Handles info messages and executed corresponding code """ if 'version' in kwargs: # set api version number and exit self.api_version = kwargs['version'] print("Initialized API with version %s" % self.api_ver...
Python
jtatman_500k
import math import matplotlib.pyplot as plt import numpy as np from math import pi from math import sin from math import cos function calculate n period=8 bits=none begin if bits is none begin set bits = list 0 1 1 0 0 0 1 0 end set aValue = 0.0 set bValue = 0.0 comment return aValue, bValue for tuple index bit in enum...
import math import matplotlib.pyplot as plt import numpy as np from math import pi from math import sin from math import cos def calculate(n, period=8, bits=None): if bits is None: bits = [0, 1, 1, 0, 0, 0, 1, 0] aValue = 0.0 bValue = 0.0 # return aValue, bValue for index, bit in enumerate...
Python
zaydzuhri_stack_edu_python
function test_create_consumer_rep self begin set ad_rep_email = string test_consumer_ad_rep@example.com set ad_rep = call create username=ad_rep_email email=ad_rep_email firestorm_id=10 url=string consumer_ad_rep set email = string test_ad_rep_associate@example.com set post_data = dict string email email ; string consu...
def test_create_consumer_rep(self): ad_rep_email = 'test_consumer_ad_rep@example.com' ad_rep = AdRep.objects.create(username=ad_rep_email, email=ad_rep_email, firestorm_id=10, url='consumer_ad_rep') email = 'test_ad_rep_associate@example.com' post_data = {'email': email, 'con...
Python
nomic_cornstack_python_v1
comment https://www.hackerrank.com/challenges/30-arrays/problem set n = integer input set arr = list map int split right strip input reverse arr print arr for x in range length arr begin print arr at x end=string end
#https://www.hackerrank.com/challenges/30-arrays/problem n = int(input()) arr = list(map(int, input().rstrip().split())) arr.reverse() print(arr) for x in range(len(arr)): print(arr[x], end = " ")
Python
zaydzuhri_stack_edu_python
string indi game engine Lighting Use directional lamp sample import igeCore as core from igeCore import devtool from igeCore import apputil from igeCore.apputil import graphicsHelper import igeVmath as vmath import os call convertAssets string . string . TARGET_PLATFORM_PC 0.1 call window true 480 640 set figure = figu...
""" indi game engine Lighting Use directional lamp sample """ import igeCore as core from igeCore import devtool from igeCore import apputil from igeCore.apputil import graphicsHelper import igeVmath as vmath import os devtool.convertAssets('.', '.', core.TARGET_PLATFORM_PC,0.1) core.window(Tr...
Python
zaydzuhri_stack_edu_python
function test_empty_budget self begin set seq = call budget 3.0 assert equal length seq 0 set x = call constant 6 set seq = call components x assert equal length seq 0 set x = call constant 6 + 4j set seq = call components x assert equal length seq 0 set x = call constant 6 set seq = call components x assert equal leng...
def test_empty_budget(self): seq = rp.budget(3.0) self.assertEqual(len(seq),0) x = constant(6) seq = rp.components(x) self.assertEqual(len(seq),0) x = constant(6+4j) seq = rp.components(x) self.assertEqual(len(seq),0) x = constant(6)...
Python
nomic_cornstack_python_v1
import gym import random import numpy as np import tensorflow as tf from tensorflow.keras.models import Model from tensorflow.keras.layers import Input , Dense from tensorflow.keras.optimizers import RMSprop function Q_Net input_size hidden1_size hidden2_size output_size begin set X_input = input input_size set X = cal...
import gym import random import numpy as np import tensorflow as tf from tensorflow.keras.models import Model from tensorflow.keras.layers import Input, Dense from tensorflow.keras.optimizers import RMSprop def Q_Net(input_size, hidden1_size, hidden2_size, output_size): X_input = Input(input_size) X = Dense(hidden1...
Python
zaydzuhri_stack_edu_python
string Async functions for downloading hublogs from S3 comment import datetime from datetime import datetime import sys import time from hublogs.s3 import getMatchingS3Keys comment 02d4d881-02ff-4848-acfa-b5c053a7d96d/20200608T085743/4f94dc04-a107-4d9b-8cb2-0c334f6eb9b1.zip comment in the hub-debug-log bucket files are...
"""Async functions for downloading hublogs from S3""" # import datetime from datetime import datetime import sys import time from hublogs.s3 import getMatchingS3Keys # 02d4d881-02ff-4848-acfa-b5c053a7d96d/20200608T085743/4f94dc04-a107-4d9b-8cb2-0c334f6eb9b1.zip # in the hub-debug-log bucket files are ordered as abov...
Python
zaydzuhri_stack_edu_python
function init_data_display self begin set frame = call GuiSimpleFrame name=string Target Locations call setAlignment qAlignCenter call addWidget frame 2 0 1 3 comment Static Labels set scaled = call QLabel string Scaled (X, Y) set normalized = call QLabel string Normalized set tested = call QLabel string Tested call se...
def init_data_display(self): frame = GuiSimpleFrame(name='Target Locations') frame.grid.setAlignment(qAlignCenter) self.grid.addWidget(frame, 2, 0, 1, 3) # Static Labels scaled = qg.QLabel('Scaled (X, Y)') normalized = qg.QLabel('Normalized') tested = qg.QLabel('T...
Python
nomic_cornstack_python_v1
import pygame from board import init_game comment Declaring variables comment declaring dimensions and colors set tuple width height = tuple 600 600 set black = tuple 0 0 0 set white = tuple 255 255 255 set red = tuple 94 25 20 set blue = tuple 13 213 252 comment creating screen call init set screen = call set_mode lis...
import pygame from board import init_game #Declaring variables #declaring dimensions and colors width, height = 600, 600 black = (0, 0, 0) white = (255, 255, 255) red = (94,25,20) blue =(13, 213, 252) #creating screen pygame.init() screen = pygame.display.set_mode([width,height]) pygame.display.set_caption("Chess") #...
Python
zaydzuhri_stack_edu_python
function hash_file path progress_callback chunk_size=1024 file_size=none algo=string sha256 begin string Hash a file and return the hash, providing progress callbacks :param path: The file to hash :param progress_callback: The callback to call with progress between 0 and 1. May not ever be precisely 1.0. :param chunk_s...
def hash_file(path: str, progress_callback: Callable[[float], None], chunk_size: int = 1024, file_size: int = None, algo: str = 'sha256') -> bytes: """ Hash a file and return the hash, providing progress callbacks :param path: The file to hash :pa...
Python
jtatman_500k
function byte addr begin return call readtype uchar addr end function
def byte(addr: int) -> int: return readtype(pwndbg.gdblib.typeinfo.uchar, addr)
Python
nomic_cornstack_python_v1
import glob import json import os import re import textwrap import pandas as pd comment ## Text colour utilities string print("My text") will print My text in blue on a background of green. The escape sequence is [ followed by ;-separated numbers, followed by m. To end the color, you use . The numbers ar...
import glob import json import os import re import textwrap import pandas as pd # ## Text colour utilities """ print("\033[34;42mMy text\033[m") will print My text in blue on a background of green. The escape sequence is \033[ followed by ;-separated numbers, followed by m. To end the color, you use \033[m. The nu...
Python
zaydzuhri_stack_edu_python
import os from dotenv import load_dotenv from jira import JIRA function sanitize_issue_key issue_key begin return string " + issue_key + string " end function comment Simple object to write down a single issue, being able to write it out to graphviz. class GraphIssue begin function __init__ self issue jira_url begin se...
import os from dotenv import load_dotenv from jira import JIRA def sanitize_issue_key(issue_key): return "\"" + issue_key + "\"" # Simple object to write down a single issue, being able to write it out to graphviz. class GraphIssue: def __init__(self, issue, jira_url): self.issue_key = issue.key ...
Python
zaydzuhri_stack_edu_python
function get_lp self enduse sector technology shape begin comment Get key from lookup dict set position_in_dict = dict_tuple_keys at tuple enduse sector technology comment Get correct object set load_profile_obj = load_profiles at position_in_dict return get attribute load_profile_obj shape end function
def get_lp(self, enduse, sector, technology, shape): # Get key from lookup dict position_in_dict = self.dict_tuple_keys[(enduse, sector, technology)] # Get correct object load_profile_obj = self.load_profiles[position_in_dict] return getattr(load_profile_obj, shape)
Python
nomic_cornstack_python_v1
function generate_body adverts begin set table = string <table> set table = table + string <tr> set table = table + string <th>Category</th> set table = table + string <th>Price</th> set table = table + string <th>Address</th> set table = table + string <th>Distance</th> set table = table + string <th>Link</th> set tab...
def generate_body(adverts: List[scraper.Advert]) -> str: table = "<table>" table += "<tr>" table += "<th>Category</th>" table += "<th>Price</th>" table += "<th>Address</th>" table += "<th>Distance</th>" table += "<th>Link</th>" table += "</tr>" for advert in adverts: link = "...
Python
nomic_cornstack_python_v1
function to_dict self begin string Convert a structure into a Python dictionary. set fsa = dictionary for key in _integer_members begin set fsa at key = get attribute self key end set ra = list comprehension RegisterArea at index for index in call xrange 0 SIZE_OF_80387_REGISTERS set ra = tuple ra set fsa at string Reg...
def to_dict(self): 'Convert a structure into a Python dictionary.' fsa = dict() for key in self._integer_members: fsa[key] = getattr(self, key) ra = [ self.RegisterArea[index] for index in compat.xrange(0, SIZE_OF_80387_REGISTERS) ] ra = tuple(ra) fsa['Registe...
Python
jtatman_500k
import argparse from itertools import permutations set parser = call ArgumentParser description=string AoC day 9 call add_argument string file help=string The file that should be sourced call add_argument string -p string --phase help=string The part of the exercise that we are at type=int default=1 call add_argument s...
import argparse from itertools import permutations parser = argparse.ArgumentParser(description="AoC day 9") parser.add_argument("file", help="The file that should be sourced") parser.add_argument("-p", "--phase", help="The part of the exercise that we are at", type=int, default=1) parser.add_argument("-t", "--target",...
Python
zaydzuhri_stack_edu_python
string Count set bits in an integer Write an efficient program to count number of 1s in binary representation of an integer. function count_bit n begin set count = 0 while n begin set count = count + n ? 1 set n = n ? 1 end return count end function string At Bit level, how will you find if a number is a power of 2 or ...
""" Count set bits in an integer Write an efficient program to count number of 1s in binary representation of an integer. """ def count_bit(n): count = 0 while n: count += (n & 1) n >>= 1 return count """ At Bit level, how will you find if a number is a power of 2 or not. http://geekexplains.blogspot.com/200...
Python
zaydzuhri_stack_edu_python
class Solution begin function summaryRanges self nums begin string :type nums: List[int] :rtype: List[str] if not nums begin return list end set tuple prevNum possibleEndNum = tuple nums at 0 none set rangeList = list string prevNum for tuple i num in enumerate nums at slice 1 : : begin if num == prevNum + 1 begin if...
class Solution: def summaryRanges(self, nums): """ :type nums: List[int] :rtype: List[str] """ if not nums: return [] prevNum, possibleEndNum = nums[0], None rangeList = [str(prevNum)] for i, num in enumerate(nums[1:]): ...
Python
zaydzuhri_stack_edu_python
comment Gemma Buckle comment 10/10/2014 comment Mr/Ms [name] set first_name = input string Please enter your first name: set last_name = input string Please enter your last name: set gender = input string Please enter your gender(m/f): if gender == string m begin print format string Mr {0} {1}. first_name last_name end...
#Gemma Buckle #10/10/2014 #Mr/Ms [name] first_name=input("Please enter your first name: ") last_name=input("Please enter your last name: ") gender=input("Please enter your gender(m/f): ") if gender=="m": print("Mr {0} {1}.".format(first_name, last_name)) elif gender=="f": print("Ms {0} {1}.".format(f...
Python
zaydzuhri_stack_edu_python
function rot_str self string begin for i in string begin call rot *self.dir_map[i] end end function
def rot_str(self, string): for i in string: self.rot(*self.dir_map[i])
Python
nomic_cornstack_python_v1
comment !/usr/bin/env python string GA Data Science Q2 2016 Code walk-through 4: Linear regression using StatsModels * Design matrix * Linear regression * Diagnostics * Transformations import os import numpy as np import pandas as pd import seaborn as sns import statsmodels.api as sm import statsmodels.formula.api as s...
#!/usr/bin/env python ''' GA Data Science Q2 2016 Code walk-through 4: Linear regression using StatsModels * Design matrix * Linear regression * Diagnostics * Transformations ''' import os import numpy as np import pandas as pd import seaborn as sns import statsmodels.api as sm import statsmodels.formula.api as s...
Python
zaydzuhri_stack_edu_python
comment !/usr/bin/env python string simple plot that demonstrates the syntax for many basic plotting functions import numpy as np import matplotlib.pyplot as plt comment create data set theta = linear space 0 2 * pi 1000 set r1 = theta * 1 set r2 = theta * 2 comment create figure set figure = figure comment add axes to...
#!/usr/bin/env python ''' simple plot that demonstrates the syntax for many basic plotting functions ''' import numpy as np import matplotlib.pyplot as plt # create data theta = np.linspace(0, 2*np.pi,1000) r1 = theta * 1 r2 = theta * 2 # create figure figure = plt.figure() # add axes to figure axes = figure.add_su...
Python
zaydzuhri_stack_edu_python
function get_exiting_nodes self node begin set exit_edge_pattern = compile format string edge_{0}_(?P<end_node>\w+)_(?P<iterator>\w+) node set exit_nodes = list for tuple index edge in enumerate edges begin set exit_match = match exit_edge_pattern edge if exit_match begin set exit_node = call groupdict at string end_n...
def get_exiting_nodes(self,node): exit_edge_pattern=re.compile('edge_{0}_(?P<end_node>\w+)_(?P<iterator>\w+)'.format(node)) exit_nodes=[] for index,edge in enumerate(self.edges): exit_match=re.match(exit_edge_pattern,edge) if exit_match: exit_node=exit_mat...
Python
nomic_cornstack_python_v1
comment this is my code for prime set tuple n k = map int split input for i in range n + 1 k begin for j in range 2 i begin if i % j == 0 begin break end set y = j end if y == i - 1 begin set s = s + string i + string end end print strip s
#this is my code for prime n,k=map(int,input().split()) for i in range(n+1,k): for j in range(2,i): if i%j==0: break y=j if y==i-1: s=s+str(i)+" " print(s.strip())
Python
zaydzuhri_stack_edu_python
function test_service_api_predict_single_raw_no_classification service_app begin set response = post string /predict data=dumps data at slice : 1 : content_type=string application/json assert headers at string Content-Type == string application/json assert status_code == 200 assert loads data == dict string message st...
def test_service_api_predict_single_raw_no_classification(service_app): response = service_app.post('/predict', data=json.dumps(data[:1]), content_type='application/json') assert response.headers['Content-Type'] == 'application/json' assert res...
Python
nomic_cornstack_python_v1
import datetime string import os def check_ping(): hostname = "vk.com" response = os.system("ping -c 4 " + hostname) # and then check the response... #string = response[84:] return response function timer begin set now = now set ege = list string география/информатика string математика база string математика профиль st...
import datetime """import os def check_ping(): hostname = "vk.com" response = os.system("ping -c 4 " + hostname) # and then check the response... #string = response[84:] return response """ def timer(): now = datetime.datetime.now() ege = ["география/информатика","математика база","ма...
Python
zaydzuhri_stack_edu_python
function batch iterable size begin set iterator = iterate iterable while true begin set res = list for _ in range size begin try begin append res next iterator end except StopIteration begin break end end if not res begin return end yield res end end function
def batch(iterable, size): iterator = iter(iterable) while True: res = [] for _ in range(size): try: res.append(next(iterator)) except StopIteration: break if not res: return yield res
Python
nomic_cornstack_python_v1
function test_extract_patches self begin set sample_idx = 0 set patch_size = tuple 16 16 with call File hdf5_path string r as f_h5_data begin set h5 = call HDF5File f_h5_data set patches = call get_image_patches sample_idx false COORDS patch_size=patch_size for patch in patches begin assert equal tuple patch_size at 0 ...
def test_extract_patches(self): sample_idx = 0 patch_size = (16, 16) with h5py.File(self.hdf5_path, "r") as f_h5_data: h5 = HDF5File(f_h5_data) patches = h5.get_image_patches(sample_idx, False, Station.COORDS, patch_size=patch_size) for patch in patches: ...
Python
nomic_cornstack_python_v1
function balance token address begin try begin set args = list CLI string balance token address set result = run args capture_output=true check=true print result return split decode stdout string utf-8 at 0 end except CalledProcessError as e begin print output end end function
def balance(token, address): try: args = [CLI, "balance", token, address] result = subprocess.run(args, capture_output=True, check=True) print(result) return result.stdout.decode("utf-8").split()[0] except subprocess.CalledProcessError as e: print(e.output)
Python
nomic_cornstack_python_v1
if group > 8 begin print string Well... you're just going to have to wait then! end else begin print string Right this way. end
if group > 8: print("Well... you're just going to have to wait then!") else: print("Right this way.")
Python
zaydzuhri_stack_edu_python
function relative_strength self symbol begin set result = call date_range symbol columns=list string close set up_close = list set down_close = list set prevres = 0 for res in result begin if res at 0 > prevres begin append up_close res at 0 end else if res at 0 < prevres begin append down_close res at 0 end set prev...
def relative_strength(self, symbol): result = self.rpc.date_range(symbol,columns=['close']) up_close = [] down_close = [] prevres = 0 for res in result: if res[0] > prevres: up_close.append(res[0]) elif res[0] < prevres: dow...
Python
nomic_cornstack_python_v1
string Max digit sum and min digit sum for n numbers set n = integer input set sum = 0 set max = - 1 set min = 1000 set m = integer input set aux = m for j in range 1 n begin while aux != 0 begin set digit = aux % 10 set sum = sum + digit set aux = aux // 10 end if sum > max begin set max = sum set a = m end else if su...
""" Max digit sum and min digit sum for n numbers """ n = int(input()) sum = 0 max = -1 min = 1000 m = int(input()) aux = m for j in range(1, n): while(aux != 0): digit = aux % 10 sum = sum + digit aux = aux // 10 if(sum > max): max = sum a = m else: ...
Python
zaydzuhri_stack_edu_python
comment ! usr/bin/python comment This is for optimizing the k of a single harmonic oscilator import scipy.optimize as op import numpy as np from scipy import pi comment oscilator mass global mas set mas = 1 comment Target oscilator constant global k_targ set k_targ = array list 1.9 comment Oscilator temperature and bet...
#! usr/bin/python # This is for optimizing the k of a single harmonic oscilator import scipy.optimize as op import numpy as np from scipy import pi # oscilator mass global mas mas = 1 # Target oscilator constant global k_targ k_targ = np.array([1.9]) # Oscilator temperature and beta global beta temp = 0.001 # we s...
Python
zaydzuhri_stack_edu_python
import session9 from session9 import * import datetime import pytest from io import StringIO import sys import time import inspect import os import re from decimal import Decimal set README_CONTENT_CHECK_FOR = list string namedtuple string tuple string dictionary string compare string time string faster string slower s...
import session9 from session9 import * import datetime import pytest from io import StringIO import sys import time import inspect import os import re from decimal import Decimal README_CONTENT_CHECK_FOR = [ "namedtuple", 'tuple', "dictionary", "compare", 'time', "faster", "slower", 'f...
Python
zaydzuhri_stack_edu_python
string 什么是函数:一系列Python语句的组合,可以在程序中运行一次或者多次, 一般是完成具体的独立的功能 为什么要使用函数: 代码的复用最大化以及最小化冗余代码,整体代码结构清晰,问题局部化 函数定义: def 函数名(): 函数体[一系列的python语句,表示独立的功能] 函数的调用: 本质上就是去执行函数定义里面的代码块,在调用函数之前 必须先定义 comment print('小张的身高是%f'%1.73) comment print('小张的体重是%f'%160) comment print('小张的爱好是%s'%'唱歌') comment print('小张的身高是%s'%'计算机信息管理') comment ...
''' 什么是函数:一系列Python语句的组合,可以在程序中运行一次或者多次, 一般是完成具体的独立的功能 为什么要使用函数: 代码的复用最大化以及最小化冗余代码,整体代码结构清晰,问题局部化 函数定义: def 函数名(): 函数体[一系列的python语句,表示独立的功能] 函数的调用: 本质上就是去执行函数定义里面的代码块,在调用函数之前 必须先定义 ''' # print('小张的身高是%f'%1.73) # print('小张的体重是%f'%160) # print('小张的爱好是%s'%'唱歌') # print('小张的身高是%s'%'计算机信息管理') # 处理其他的逻辑信息 # 多次去...
Python
zaydzuhri_stack_edu_python
import httplib import logging import Queue import socket import time import threading import dopngtile import shpextract set upq = queue set host = string localhost set port = 8080 set host = string gepy.appspot.com set port = 80 set thread_pool_size = 3 set thread_pool = list function start_thread_pool begin for i in...
import httplib import logging import Queue import socket import time import threading import dopngtile import shpextract upq = Queue.Queue() host = 'localhost' port = 8080 host = 'gepy.appspot.com' port = 80 thread_pool_size = 3 thread_pool = [] def start_thread_pool(): for i in range(thread_pool_size): t = th...
Python
zaydzuhri_stack_edu_python
import tkinter as tk set root = call Tk call geometry string 240x240 title root string GUI Sample set button = call Button root text=string Hello, World call pack call mainloop
import tkinter as tk root = tk.Tk() root.geometry('240x240') root.title('GUI Sample') button = tk.Button(root,text='Hello, World') button.pack() root.mainloop()
Python
zaydzuhri_stack_edu_python
function serialize_numpy self buff numpy begin try begin set _x = self write buff call pack seq secs nsecs set _x = frame_id set length = length _x if python3 or type _x == unicode begin set _x = encode _x string utf-8 set length = length _x end write buff call pack string <I%ss % length length _x set _x = self write b...
def serialize_numpy(self, buff, numpy): try: _x = self buff.write(_get_struct_3I().pack(_x.header.seq, _x.header.stamp.secs, _x.header.stamp.nsecs)) _x = self.header.frame_id length = len(_x) if python3 or type(_x) == unicode: _x = _x.encode('utf-8') length = len(_x) ...
Python
nomic_cornstack_python_v1