code
stringlengths
10
2.58M
original_code
stringlengths
3
3.18M
original_language
stringclasses
1 value
source
stringclasses
7 values
function receive_video self begin while true begin set tuple data addr = call recvfrom MAX_DATAGRAM_SIZE if call should_video_flow and addr at 0 == call get_send_address at 0 begin set udp_datagram = call udp_datagram_from_msg data insert udp_buffer udp_datagram end end end function
def receive_video(self): while True: data, addr = self.receive_socket.recvfrom(MAX_DATAGRAM_SIZE) if self.call_control.should_video_flow() and addr[0] == self.call_control.get_send_address()[0]: udp_datagram = udp_datagram_from_msg(data) self.udp_buffer.in...
Python
nomic_cornstack_python_v1
comment you can write to stdout for debugging purposes, e.g. comment print("this is a debug message") function solution A begin comment write your code in Python 3.6 comment key point: sort the array set sorted_array = sorted A for index in range length A - 2 begin if sorted_array at index + sorted_array at index + 1 >...
# you can write to stdout for debugging purposes, e.g. # print("this is a debug message") def solution(A): # write your code in Python 3.6 # key point: sort the array sorted_array = sorted(A) for index in range( len(A)-2 ): if sorted_array[index] + sorted_array[index+1] > sorted_arra...
Python
zaydzuhri_stack_edu_python
import TCP import threading import read_files import sys import os import math import analysis set _BUFFER_SIZE = 400 class serverThread extends Thread begin function __init__ self serverSocket begin call __init__ self set serverSocket = serverSocket end function function run self begin set file_name = call receive try...
import TCP import threading import read_files import sys import os import math import analysis _BUFFER_SIZE = 400 class serverThread(threading.Thread): def __init__(self, serverSocket): threading.Thread.__init__(self) self.serverSocket = serverSocket def run(self): file_name = self.se...
Python
zaydzuhri_stack_edu_python
while t <= T begin set seen_digits = set set N = integer call raw_input if N == 0 begin print string Case #%d: INSOMNIA % t set t = t + 1 continue end set cur = N while length seen_digits < 10 begin for d in string cur begin add seen_digits d end set cur = cur + N end set cur = cur - N print string Case #%d: %d % tuple...
while t <= T: seen_digits = set() N = int(raw_input()) if N == 0: print("Case #%d: INSOMNIA" % t) t += 1 continue cur = N while(len(seen_digits) < 10): for d in str(cur): seen_digits.add(d) cur += N cur -= N print("Case #%d: %d" % (t, cur)) t += 1
Python
zaydzuhri_stack_edu_python
comment !/usr/bin/env python import numpy as np from nupic.algorithms.temporal_memory import TemporalMemory from group_by import groupby2 from nupic.bindings.math import SparseMatrixConnections class TM extends TemporalMemory begin function __init__ self **kwargs begin call __init__ keyword kwargs end function end clas...
#!/usr/bin/env python import numpy as np from nupic.algorithms.temporal_memory import TemporalMemory from group_by import groupby2 from nupic.bindings.math import SparseMatrixConnections class TM(TemporalMemory): def __init__(self, **kwargs): super(TM, self).__init__(**kwargs)
Python
zaydzuhri_stack_edu_python
function tearDown self begin call Empty end function
def tearDown(self): self._resolver_context.Empty()
Python
nomic_cornstack_python_v1
import tensorflow as tf import numpy as np import sqlite3 import random import os import glob import sys from multiprocessing import Pool from functools import partial from sklearn.metrics import mean_squared_error from nnmodels import compare set EMBEDDINGS = 100 set VECTORS = string allMeSH_2016_%i.vectors.txt % EMBE...
import tensorflow as tf import numpy as np import sqlite3 import random import os import glob import sys from multiprocessing import Pool from functools import partial from sklearn.metrics import mean_squared_error from nnmodels import compare EMBEDDINGS = 100 VECTORS = 'allMeSH_2016_%i.vectors.txt' % EMBEDDINGS DB ...
Python
zaydzuhri_stack_edu_python
function generate self metrics=none begin set metric_group = metrics at call find_exercise if autogen begin set children = list if sets and weight_expr begin set children = list set reps=reps weight=weight_expr * sets end else if bottom and top and increment begin set w = decimal call WeightExpr bottom metric_group=me...
def generate(self, metrics=None): self.metric_group = metrics[self.find_exercise()] if self.autogen: self.children = [] if self.sets and self.weight_expr: self.children = [Set(reps=self.reps, weight=self.weight_expr)] * self.sets elif self.bottom and s...
Python
nomic_cornstack_python_v1
string Recognize handwritten digits using OpenCV library import cv2 import numpy as np comment Load the model set model = call SVM_load string svm_model.xml comment Read the input image set img = call imread string input.png comment Convert to grayscale and apply Gaussian filtering set img_gray = call cvtColor img COLO...
""" Recognize handwritten digits using OpenCV library """ import cv2 import numpy as np # Load the model model = cv2.ml.SVM_load('svm_model.xml') # Read the input image img = cv2.imread('input.png') # Convert to grayscale and apply Gaussian filtering img_gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) img_gray = cv2.Ga...
Python
jtatman_500k
import matplotlib.pyplot as plt import scipy.cluster.vq as vq import numpy as np set _COLORS = load np join path directory name path __file__ string pca_toy_colors.npy function plot_label_3d x y begin string Show a 3D scatter plot of data. Parameters ---------- x: (n, 3) array-like y: (n,) array-like The labels set y =...
import matplotlib.pyplot as plt import scipy.cluster.vq as vq import numpy as np _COLORS = np.load(path.join(path.dirname(__file__), 'pca_toy_colors.npy')) def plot_label_3d(x, y): """ Show a 3D scatter plot of data. Parameters ---------- x: (n, 3) array-like y: (n,) array-like The ...
Python
zaydzuhri_stack_edu_python
function _build_trex_packet self packet_definition adjust_size=true required_size=64 begin import trex_stl_lib.api as TApi function _value_repr value begin string Check if value contains layers. if is instance value tuple list tuple begin return call type value list map _value_repr value end else if is instance value d...
def _build_trex_packet(self, packet_definition, adjust_size=True, required_size=64): import trex_stl_lib.api as TApi def _value_repr(value): """Check if value contains layers. """ if isinstance(value, (list, tuple)): return type(value)(list(map(_valu...
Python
nomic_cornstack_python_v1
function _get_submodule_has_out_user_under_public_parent self public_module node_out_user begin for module_struct in module_structs begin if onnx_name in onnx_names begin return module_struct end end return none end function
def _get_submodule_has_out_user_under_public_parent(self, public_module: ModuleStruct, node_out_user: NodeStruct): for module_struct in public_module.module_structs: if node_out_user.onnx_name in module_struct.onnx_names: return module_struct return None
Python
nomic_cornstack_python_v1
function test_migrate_all_carni_in_cell_new_location standard_map_peninsula begin set parameters at string mu = 1000 set mock_ek = dict tuple 1 18 2 call _migrate_all_carnivores_in_cell standard_map_peninsula tuple 1 19 mock_ek set parameters at string mu = 0.24 assert carnivore_list == list assert carnivore_list != l...
def test_migrate_all_carni_in_cell_new_location( standard_map_peninsula): animals.Carnivores.parameters["mu"] = 1000 mock_ek = {(1, 18): 2} standard_map_peninsula.raster_model[( 1, 19)]._migrate_all_carnivores_in_cell( standard_map_peninsula, (1, 19), mock_ek) animals.Carnivores....
Python
nomic_cornstack_python_v1
comment from flask_testing import TestCase import unittest from app import create_app , db class BaseTestCase extends TestCase begin string Parent of all test units function setUp self begin string Define test variables and init app set app = call create_app config_name=string testing set client = test_client comment b...
# from flask_testing import TestCase import unittest from app import create_app, db class BaseTestCase(unittest.TestCase): """ Parent of all test units """ def setUp(self): """ Define test variables and init app """ self.app = create_app(config_name="testing") self.client = self.app.t...
Python
zaydzuhri_stack_edu_python
import pandas as pd import io import string import itertools as it import pickle as pk from talib.abstract import MA , EMA , WMA , RSI , CCI , ROC , MOM , WILLR from pyCBT.providers.gdrive.account import get_client from pyCBT.common.path import exist class DriveTables extends object begin comment parent ID of data tabl...
import pandas as pd import io import string import itertools as it import pickle as pk from talib.abstract import MA, EMA, WMA, RSI, CCI, ROC, MOM, WILLR from pyCBT.providers.gdrive.account import get_client from pyCBT.common.path import exist class DriveTables(object): # parent ID of data tables in Google Driv...
Python
zaydzuhri_stack_edu_python
function count_bits x begin set c = 0 while x begin set x = x / 2 set c = c + 1 end return c end function function get_bit x i begin set mask = 1 ? i return integer not not x ? mask end function class Solution extends object begin function rangeBitwiseAnd self m n begin string :type m: int :type n: int :rtype: int set ...
def count_bits(x): c = 0 while x: x /= 2 c += 1 return c def get_bit(x, i): mask = (1 << i) return int(not(not(x & mask))) class Solution(object): def rangeBitwiseAnd(self, m, n): """ :type m: int :type n: int :rtype: int """ flag...
Python
zaydzuhri_stack_edu_python
function run self begin for pipe in inputs begin for row in call rows begin put row end end end function
def run(self): for pipe in self.inputs: for row in pipe.rows(): self.put(row)
Python
nomic_cornstack_python_v1
comment Import required libraries import pandas as pd import numpy as np from datetime import datetime from geneticalgorithm import geneticalgorithm as ga from scipy.optimize import differential_evolution import matplotlib.pyplot as plt import math import os import tkinter as tk from tkinter import messagebox from tkin...
#Import required libraries import pandas as pd import numpy as np from datetime import datetime from geneticalgorithm import geneticalgorithm as ga from scipy.optimize import differential_evolution import matplotlib.pyplot as plt import math import os import tkinter as tk from tkinter import messagebox fro...
Python
zaydzuhri_stack_edu_python
import itertools as it import more_itertools as mi import numpy as np import fileinput , sys from collections import defaultdict comment lol call setrecursionlimit 10 ^ 6 function solve line begin set buf = list for c in line begin if buf and buf at - 1 == call swapcase begin pop buf end else begin append buf c end en...
import itertools as it import more_itertools as mi import numpy as np import fileinput, sys from collections import defaultdict sys.setrecursionlimit(10**6) #lol def solve(line: str): buf = [] for c in line: if buf and buf[-1] == c.swapcase(): buf.pop() else: buf.append(c) return len(buf) de...
Python
zaydzuhri_stack_edu_python
function filter_excluded self nodes begin debug string Excluded nodes: debug excluded set filtered_nodes = list for node in nodes begin comment TODO: Add a filter here. None now as I do not know what filters are needed, if any. append filtered_nodes node end return filtered_nodes end function
def filter_excluded(self, nodes): self.logger.debug('Excluded nodes:') self.logger.debug(self.excluded) filtered_nodes = [] for node in nodes: # TODO: Add a filter here. None now as I do not know what filters are needed, if any. filtered_nodes.append(node) ...
Python
nomic_cornstack_python_v1
comment -*- coding: utf-8 -*- import time from html.parser import HTMLParser import numpy as np import urllib from urllib import request from openpyxl import Workbook set hds = list set literal string Mozilla/5.0 (Windows; U; Windows NT 6.1; en-US; rv:1.9.1.6) Gecko/20091201 Firefox/3.5.6 set literal string Mozilla/5.0...
# -*- coding: utf-8 -*- import time from html.parser import HTMLParser import numpy as np import urllib from urllib import request from openpyxl import Workbook hds=[{'Mozilla/5.0 (Windows; U; Windows NT 6.1; en-US; rv:1.9.1.6) Gecko/20091201 Firefox/3.5.6'},{'Mozilla/5.0 (Windows NT 6.2) AppleWebKit/535.11 (KHTML, lik...
Python
zaydzuhri_stack_edu_python
function swap_columns df column1 column2 inplace=true begin set columns_name = list df comment Change the parameters to index if they are column name if is instance column1 str begin set column1 = index columns_name column1 end if is instance column2 str begin set column2 = index columns_name column2 end comment Swap t...
def swap_columns(df, column1, column2, inplace=True): columns_name = list(df) # Change the parameters to index if they are column name if isinstance(column1, str): column1 = columns_name.index(column1) if isinstance(column2, str): column2 = columns_name.index(column2) # Swap the co...
Python
nomic_cornstack_python_v1
function delete_user user_name begin set iam_user = call delete_user user_name return end function
def delete_user(user_name): iam_user = iam_manager.delete_user(user_name) return
Python
nomic_cornstack_python_v1
function read_chain_annotated_interactome inPath begin set interactome = call read_table inPath sep=string set interactome at string Mapping_chains = apply interactome at string Mapping_chains str_to_tuples return interactome end function
def read_chain_annotated_interactome (inPath): interactome = pd.read_table(inPath, sep='\t') interactome["Mapping_chains"] = interactome["Mapping_chains"].apply( str_to_tuples ) return interactome
Python
nomic_cornstack_python_v1
comment Don't erase the template code, except "Your code here" comments. import torch comment Pi import math string Task 1 function get_rho begin comment (1) Your code here; theta = ... set theta = linear space - pi pi 1000 dtype=float64 assert shape == tuple 1000 comment (2) Your code here; rho = ... set rho = 1 + 0.9...
# Don't erase the template code, except "Your code here" comments. import torch import math # Pi """ Task 1 """ def get_rho(): # (1) Your code here; theta = ... theta = torch.linspace(-math.pi, math.pi, 1000, dtype=torch.float64) assert theta.shape == (1000,) # (2) Your code her...
Python
zaydzuhri_stack_edu_python
comment !/usr/bin/python comment coding=utf-8 comment 文件输入流
#!/usr/bin/python #coding=utf-8 #文件输入流
Python
zaydzuhri_stack_edu_python
import random class Solution extends object begin function __init__ self nums begin string :type nums: List[int] set nums = nums set numsBak = nums at slice : : end function comment print 111, self.nums, self.numsBak function reset self begin string :rtype: List[int] comment print 222, self.nums, self.numsBak return...
import random class Solution(object): def __init__(self, nums): """ :type nums: List[int] """ self.nums = nums self.numsBak = nums[:] ##print 111, self.nums, self.numsBak def reset(self): """ :rtype: List[int] """ ##print ...
Python
zaydzuhri_stack_edu_python
function formatPickupType string begin if string == string N/A begin return 0 end else if string == string D begin return 1 end else if string == string M begin return 2 end else if string == string C begin return 3 end else if string == string R begin return 4 end else begin return 5 end end function
def formatPickupType(string): if string == 'N/A': return 0 elif string == 'D': return 1 elif string == 'M': return 2 elif string == 'C': return 3 elif string == 'R': return 4 else: return 5
Python
nomic_cornstack_python_v1
function lda X y begin string Calculates the projection matrix U to perform LDA on X with labels y. LDA finds the projecting matrix W that allows us to linearly project X to another (sub) space in which the between-class and within-class variances are jointly optimized: the between-class variance is maximized while the...
def lda(X, y): """Calculates the projection matrix U to perform LDA on X with labels y. LDA finds the projecting matrix W that allows us to linearly project X to another (sub) space in which the between-class and within-class variances are jointly optimized: the between-class variance is maximized while the ...
Python
zaydzuhri_stack_edu_python
function visualize_images images figure_size=tuple 7 7 browser_style=string buttons custom_info_callback=none begin comment Make sure that images is a list even with one member if not is instance images Sized begin set images = list images end comment Get the number of images set n_images = length images comment Define...
def visualize_images( images, figure_size=(7, 7), browser_style="buttons", custom_info_callback=None ): # Make sure that images is a list even with one member if not isinstance(images, Sized): images = [images] # Get the number of images n_images = len(images) # Define the styling opti...
Python
nomic_cornstack_python_v1
function StringToDoubleAddress pString begin set parts = split pString string . if length parts is not 4 begin raise call LabJackException 0 string IP address not correctly formatted end try begin set value = integer parts at 0 ? 8 * 3 + integer parts at 1 ? 8 * 2 + integer parts at 2 ? 8 + integer parts at 3 end excep...
def StringToDoubleAddress(pString): parts = pString.split('.') if len(parts) is not 4: raise LabJackException(0, "IP address not correctly formatted") try: value = (int(parts[0]) << 8*3) + (int(parts[1]) << 8*2) + (int(parts[2]) << 8) + int(parts[3]) except ValueError...
Python
nomic_cornstack_python_v1
function print_objects objects begin set longest_name = max list comprehension length name for obj in objects for obj in objects begin print string %s: handle=%s, size=%0.1f, rot_x_p=%d, rot_x_m_sym=%d, rot_y_p=%d, rot_y_m_sym=%d, rot_z_p=%d, rot_z_m_sym=%d, Handles: nondiag=%s, diag=%s % tuple call ljust longest_name ...
def print_objects(objects): longest_name = max([len(obj.name) for obj in objects]) for obj in objects: print("%s: handle=%s, size=%0.1f, " "rot_x_p=%d, rot_x_m_sym=%d, " "rot_y_p=%d, rot_y_m_sym=%d, " "rot_z_p=%d, rot_z_m_sym=%d, " "Handles: nondi...
Python
nomic_cornstack_python_v1
function show_schema_updates self begin for mode in list string source string target begin set deltas = database at string deltas at string new_columns_in_ + mode set working_db = if expression mode == string source then source at string alias else target at string alias set other_db = if expression mode == string sour...
def show_schema_updates(self): for mode in ['source', 'target']: deltas = self.database['deltas']['new_columns_in_' + mode] working_db = self.source['alias'] if mode == 'source' else self.target['alias'] other_db = self.target['alias'] if mode == 'source' else self.source['al...
Python
nomic_cornstack_python_v1
function handle_order begin set order = lower input string > if order != string quit begin if order in available_menu begin append order_list order if order in order_list begin set count = 0 for i in order_list begin if i == order begin set count = count + 1 end end print string ** { count } order of { order } have bee...
def handle_order(): order=input("> ").lower() if order != "quit": if order in available_menu: order_list.append(order) if order in order_list: count=0 for i in order_list: if i==order: count+=1 print(f"** {count} order of {order} have been added to your meal **") handle_order() ...
Python
nomic_cornstack_python_v1
import numpy as np import pandas as pd import matplotlib.pyplot as plt set data = values set tuple N d = shape set X = reshape data at tuple slice : : slice 0 : d - 1 : - 1 d - 1 set y = reshape data at tuple slice : : 2 - 1 1 function sigmoid x begin return 1 / 1 + exp - x end function scatter plt X at tuple sl...
import numpy as np import pandas as pd import matplotlib.pyplot as plt data = pd.read_csv('dataset.csv').values N, d = data.shape X = data[:, 0:d-1].reshape(-1, d-1) y = data[:, 2].reshape(-1, 1) def sigmoid(x): return 1 / (1 + np.exp(-x)) plt.scatter(X[:10,0], X[:10,1], color = 'red', label = 'Cho vay') plt.sca...
Python
zaydzuhri_stack_edu_python
function team_stats self begin return call _aggregate_event_stats string team_id string stat_key end function
def team_stats(self): return self._aggregate_event_stats("team_id", "stat_key")
Python
nomic_cornstack_python_v1
comment https://www.codewars.com/kata/54edbc7200b811e956000556 function count_sheeps arrayOfSheeps begin return count arrayOfSheeps true end function
# https://www.codewars.com/kata/54edbc7200b811e956000556 def count_sheeps(arrayOfSheeps): return arrayOfSheeps.count(True)
Python
zaydzuhri_stack_edu_python
function collect scan_folder copy_folder begin set files = call get_files call Path scan_folder set copy_folder = call Path copy_folder set copy_id = 0 if not call is_dir begin make directory copy_folder end print string { length files } have been found and will be copied. for wavfile in files begin set copy_id = copy_...
def collect(scan_folder, copy_folder): files = get_files(Path(scan_folder)) copy_folder = Path(copy_folder) copy_id = 0 if not copy_folder.is_dir(): copy_folder.mkdir() print(f'{len(files)} have been found and will be copied.') for wavfile in files: copy_id += 1 ...
Python
nomic_cornstack_python_v1
comment Claculates correlation between two graphs. Collects graphs by using collect_graphs() comment from graphs.py comment CHANGELOG ######################## comment v0.1 (alpha): ## comment + Begun alpha development ## comment + Imported 'collect_graphs' from graphs.py to do ## comment just that ## comment + Added a ...
# Claculates correlation between two graphs. Collects graphs by using collect_graphs() # from graphs.py ######################## CHANGELOG ######################## ########################################################### ## v0.1 (alpha): ## ## + Begun alpha development ...
Python
zaydzuhri_stack_edu_python
function cluster_indices x begin set x = absolute x > 1e-20 set indices = list where diff np x at 0 + 1 if x at 0 begin set indices = list 0 + indices end if x at - 1 begin set indices = indices + list length x end set indices = array indices set bounds = call empty tuple shape at 0 // 2 2 dtype=int32 for tuple i tuple...
def cluster_indices(x): x = np.abs(x) > 1e-20 indices = list(np.where(np.diff(x))[0] + 1) if x[0]: indices = [0] + indices if x[-1]: indices = indices + [len(x)] indices = np.array(indices) bounds = np.empty((indices.shape[0] // 2, 2), dtype=np.int32) for (i, (a, b)) in enu...
Python
nomic_cornstack_python_v1
comment See figure 3.2 in [Algorithmic Beauty of Plants](http://algorithmicbotany.org/papers/abop/abop.pdf) comment on page [69](http://algorithmicbotany.org/papers/abop/abop.pdf#page=81). import lsystem.exec set ex = exec call set_axiom string a(1) call add_rule string a(t) string F(1)[&(30)L(0)]/(137.5)a(add(t,1)) st...
# See figure 3.2 in [Algorithmic Beauty of Plants](http://algorithmicbotany.org/papers/abop/abop.pdf) # on page [69](http://algorithmicbotany.org/papers/abop/abop.pdf#page=81). import lsystem.exec ex = lsystem.exec.Exec() ex.set_axiom("a(1)") ex.add_rule("a(t)", "F(1)[&(30)L(0)]/(137.5)a(add(t,1))", "lt(t,7)") ex.add...
Python
zaydzuhri_stack_edu_python
function restore_config self begin call _clear_previous_windows_assigment call _restart_i3_config end function
def restore_config(self): self._clear_previous_windows_assigment() self._restart_i3_config()
Python
nomic_cornstack_python_v1
function shortestpath graph current end visited=list distances=dict predecessors=dict begin comment we've found our end node, now find the path to it, and return if current == end begin set pathShortest = list while end != none begin append pathShortest end set end = get predecessors end none end pass return tuple d...
def shortestpath(graph, current, end, visited=[], distances={}, predecessors={}): # we've found our end node, now find the path to it, and return if current == end: pathShortest = [] while end != None: pathShortest.append(end) end = predecessors.get(end, None) pass return distances[current], pathShortes...
Python
nomic_cornstack_python_v1
function annotate_function_of_rare_variants inputs outputs begin comment use only the filtered input file, leave dropped set filtered = inputs at 0 call get_stats_on_prefiltered_variants input=filtered outputs=outputs at slice 2 : 4 : cleanup=false end function
def annotate_function_of_rare_variants(inputs, outputs): filtered = inputs[0] # use only the filtered input file, leave dropped get_stats_on_prefiltered_variants(input=filtered, outputs=outputs[2:4], cleanup=False)
Python
nomic_cornstack_python_v1
function get_non_blocking_io self path mode=string r buffering=- 1 encoding=none errors=none newline=none closefd=true opener=none begin if path not in _path_to_data begin set queue = queue set t = thread target=_poll_jobs args=tuple queue start t set _path_to_data at path = call PathData queue t end set binary = strin...
def get_non_blocking_io( self, path: str, mode: str = "r", buffering: int = -1, encoding: Optional[str] = None, errors: Optional[str] = None, newline: Optional[str] = None, closefd: bool = True, opener: Optional[Callable] = None, ) -> Union[IO[...
Python
nomic_cornstack_python_v1
comment -*- coding: utf-8 -*- string Created on Wed Jul 11 14:06:37 2018 @author: Administrator import numpy as np import matplotlib.pyplot as plt axis list 0 100 0 1 call ion for i in range 100 begin set y = random scatter plt i y call pause 0.1 end show
# -*- coding: utf-8 -*- """ Created on Wed Jul 11 14:06:37 2018 @author: Administrator """ import numpy as np import matplotlib.pyplot as plt plt.axis([0, 100, 0, 1]) plt.ion() for i in range(100): y = np.random.random() plt.scatter(i, y) plt.pause(0.1) plt.show()
Python
zaydzuhri_stack_edu_python
comment Importing the libraries import numpy as np import pandas as pd comment Import the dataset set dataset = read csv string spam.csv comment Cleaning the texts import re import nltk call download string stopwords from nltk.corpus import stopwords from nltk.stem.porter import PorterStemmer set corpus = list for i i...
# Importing the libraries import numpy as np import pandas as pd # Import the dataset dataset = pd.read_csv ('spam.csv') # Cleaning the texts import re import nltk nltk.download('stopwords') from nltk.corpus import stopwords from nltk.stem.porter import PorterStemmer corpus = [] for i in range(0, dataset.shape[0]): ...
Python
jtatman_500k
import webbrowser comment You can insert your desired link here set link = string https://github.com/michaelcronk function run_website begin try begin open link new=2 autoraise=true print link end except ValueError begin print string That's not a valid link. Please try again. end end function call run_website
import webbrowser link = 'https://github.com/michaelcronk' # You can insert your desired link here def run_website(): try: webbrowser.open(link, new=2, autoraise=True) print(link) except ValueError: print("That's not a valid link. Please try again.") run_website()
Python
zaydzuhri_stack_edu_python
with open string ../data/9.txt as f begin set data = read line f end function is_valid string idx begin set exclamations = 0 while idx > 0 begin set idx = idx - 1 if string at idx == string ! begin set exclamations = exclamations + 1 end else begin break end end comment If even number of exclamations they cancel out, e...
with open("../data/9.txt") as f: data = f.readline() def is_valid(string: str, idx: int): exclamations = 0 while idx > 0: idx -= 1 if string[idx] == "!": exclamations += 1 else: break # If even number of exclamations they cancel out, else invalid. re...
Python
zaydzuhri_stack_edu_python
function select_area ev x y _1 _2 begin global x_init y_init drawing top_left bottom_right orig_img img if ev == EVENT_LBUTTONDOWN begin set drawing = true set x_init = x set y_init = y end else if ev == EVENT_MOUSEMOVE and drawing begin call draw_rect img x_init y_init x y end else if ev == EVENT_LBUTTONUP begin set d...
def select_area(ev, x, y, _1, _2): global x_init, y_init, drawing, top_left, bottom_right, orig_img, img if ev == cv.EVENT_LBUTTONDOWN: drawing = True x_init = x y_init = y elif ev == cv.EVENT_MOUSEMOVE and drawing: draw_rect(img, x_init, y_init, x, y) elif ev == cv.EVEN...
Python
nomic_cornstack_python_v1
function New *args **kargs begin set obj = call __New_orig__ import itkTemplate call New obj *args keyword kargs return obj end function
def New(*args, **kargs): obj = itkMorphologicalWatershedFromMarkersImageFilterIUL3IUL3.__New_orig__() import itkTemplate itkTemplate.New(obj, *args, **kargs) return obj
Python
nomic_cornstack_python_v1
string author:dengwei date:2020-05-06 descript:遍历文件夹,读取Excel文件,将信息汇总到一个Excel文件中 import os import openpyxl from exceloperator import * from loggerhelper import * function get_all_excel_data directory begin string 文件夹目录 set workbook = call Workbook set worksheet = active set title = string total set rows = list comment ...
''' author:dengwei date:2020-05-06 descript:遍历文件夹,读取Excel文件,将信息汇总到一个Excel文件中 ''' import os import openpyxl from exceloperator import * from loggerhelper import * def get_all_excel_data(directory): ''' 文件夹目录 ''' workbook = openpyxl.Workbook() worksheet = workbook.active worksheet.title = "tota...
Python
zaydzuhri_stack_edu_python
comment import numpy as np class Solution begin function subtractProductAndSum self n begin comment intを文字列にしてからをリストに変換⇒各桁をリストに追加 set n_list = list map int list string n set prod = 1 set sum = 0 for i in n_list begin set prod = prod * i set sum = sum + i end return prod - sum end function end class comment return np.pr...
# import numpy as np class Solution: def subtractProductAndSum(self, n: int) -> int: # intを文字列にしてからをリストに変換⇒各桁をリストに追加 n_list = list(map(int,list(str(n)))) prod = 1 sum = 0 for i in n_list: prod *= i sum += i return prod-sum # return np....
Python
zaydzuhri_stack_edu_python
import torch.nn as nn import torch.optim as optim class Optimizer extends object begin function __init__ self params lr lr_decay=1.0 weight_decay=0.0 max_grad_norm=none begin set parameters = params set lr = lr set lr_decay = lr_decay set weight_decay = weight_decay set max_grad_norm = max_grad_norm set optimizer = non...
import torch.nn as nn import torch.optim as optim class Optimizer(object): def __init__(self, params, lr, lr_decay=1.0, weight_decay=0.0, max_grad_norm=None): self.parameters = params self.lr = lr self.lr_...
Python
zaydzuhri_stack_edu_python
function PP_SPF_AVG Dataframe HNAME_List Raceday begin set Feature_DF = loc at tuple slice : : list string HNAME string RARID set Extraction = call Extraction_Database format string Select HNAME, RARID, BEYER_SPEED PP_SPF_AVG from Race_PosteriorDb where RADAT < {Raceday} and HNAME in {HNAME_List} Raceday=Raceday HNA...
def PP_SPF_AVG(Dataframe, HNAME_List, Raceday): Feature_DF = Dataframe.loc[:,['HNAME','RARID']] Extraction = Extraction_Database(""" Select HNAME, RARID, BEYER_SPEED PP_SPF_AVG from Race_PosteriorDb where RADAT < {Raceday} and HNAME in ...
Python
nomic_cornstack_python_v1
import tensorflow as tf import numpy as np from torchvision import transforms import random import torch import cv2 from PIL import ImageEnhance from PIL import Image class RandomCropTarget extends object begin string Crop the image and target randomly in a sample. Args: output_size (tuple or int): Desired output size....
import tensorflow as tf import numpy as np from torchvision import transforms import random import torch import cv2 from PIL import ImageEnhance from PIL import Image class RandomCropTarget(object): """ Crop the image and target randomly in a sample. Args: output_size (tuple or int): Desired output s...
Python
zaydzuhri_stack_edu_python
function debug self **kwargs begin set logger = logger if string level in kwargs begin set level = kwargs at string level call setLevel level end else begin call setLevel INFO end end function
def debug(self, **kwargs): logger = self.logger if 'level' in kwargs: level = kwargs['level'] logger.setLevel(level) else: logger.setLevel(logging.INFO)
Python
nomic_cornstack_python_v1
function _init_words_embedding self glove_vectors=string glove.6B.300d begin set vocab = call Vocab counter words_dict vectors=glove_vectors specials=SPECIAL_TOKENS return tuple stoi itos vectors end function
def _init_words_embedding( self, glove_vectors: Optional[str] = "glove.6B.300d" ) -> Tuple[defaultdict, List[str], torch.Tensor]: vocab = Vocab(Counter(self.words_dict), vectors=glove_vectors, specials=SPECIAL_TOKENS) return vocab.stoi, vocab.itos, vocab.vectors
Python
nomic_cornstack_python_v1
function _finishMany self results request begin set templateURLs = list for tuple succeeded result in results begin if succeeded begin set low = lower result if starts with low string http:// or starts with low string https:// begin set result = string <a href="%s">%s</a> % tuple result result end append templateURLs ...
def _finishMany(self, results, request): templateURLs = [] for (succeeded, result) in results: if succeeded: low = result.lower() if low.startswith('http://') or low.startswith('https://'): result = '<a href="%s">%s</a>' % (result, result) ...
Python
nomic_cornstack_python_v1
if km <= 1.5 begin print string 所需車資為: total end else begin set a = km - 1.5 * 1000 if a <= 250 begin set total = total + 5 print string 所需車資為: total end else if a % 250 == 0 begin set total = total + 5 * a // 250 print string 所需車資為: total end else begin set total = total + 5 * a // 250 + 5 print string 所需車資為: total en...
if (km<=1.5): print("所需車資為:",total) else: a=(km-1.5)*1000 if (a<=250): total=total+5 print("所需車資為:",total) else: if ((a%250)==0): total=total+5*(a//250) print("所需車資為:",total) else: total=total+5*(a//250)+5 print("所需車資為:",t...
Python
zaydzuhri_stack_edu_python
function write_network_info self layers layer_names begin for tuple layer name in zip layers layer_names begin call add_histogram name + string Bias bias epoch call add_histogram name + string Weights weight epoch end flush writer end function
def write_network_info(self, layers: list, layer_names: list): for layer, name in zip(layers, layer_names): self.writer.add_histogram(name + " Bias", layer.bias, self.epoch) self.writer.add_histogram(name + " Weights", layer.weight, self.epoch) self.writer.flush()
Python
nomic_cornstack_python_v1
comment Definition for a binary tree node. comment class TreeNode(object): comment def __init__(self, x): comment self.val = x comment self.left = None comment self.right = None comment Non trivial Iterative solution class Solution extends object begin function preorderTraversal self root begin string :type root: TreeN...
# Definition for a binary tree node. # class TreeNode(object): # def __init__(self, x): # self.val = x # self.left = None # self.right = None # Non trivial Iterative solution class Solution(object): def preorderTraversal(self, root): """ :type root: TreeNode :rty...
Python
zaydzuhri_stack_edu_python
function word_value word begin return if expression word == string then 0 else call word_value word at slice : - 1 : + call letter_index_upper word at - 1 end function
def word_value(word: str) -> int: return (0 if word == '' else word_value(word[:-1]) + alpha.letter_index_upper(word[-1]))
Python
nomic_cornstack_python_v1
function remove_colors string begin set color_list = list string  string  string  string  string  string  string  string  string  string  string  string  string  string  string  string  string  string ...
def remove_colors(string): color_list = ['\x1b[0;30m', '\x1b[0;31m', '\x1b[0;32m', '\x1b[0;33m', '\x1b[0;34m', '\x1b[0;35m', '\x1b[0;36m', '\x1b[0;37m', '\x1b[0;39m', '\x1b[0;40m', '\x1b[0;41m', '\x1b[0;42m', '\x1b[0;43m', '\x1b[0;44m', '\x1b[0;45m', '\x1b[0;46m', '\x1b[0;47m', '\x1b[0;49m', '\x1b[0;90m', '\x1b[0;9...
Python
nomic_cornstack_python_v1
function lookup_class_name name context depth=3 begin string given a table name in the form `schema_name`.`table_name`, find its class in the context. :param name: `schema_name`.`table_name` :param context: dictionary representing the namespace :param depth: search depth into imported modules, helps avoid infinite recu...
def lookup_class_name(name, context, depth=3): """ given a table name in the form `schema_name`.`table_name`, find its class in the context. :param name: `schema_name`.`table_name` :param context: dictionary representing the namespace :param depth: search depth into imported modules, helps avoid inf...
Python
jtatman_500k
from metaflow import FlowSpec , step , retry import json class ReinforcementLearningSimulatorFlow extends FlowSpec begin string Train RL Agents With Different Input States and Reward Functions. Simulate the Same Trained Agent in Simulations of 1. Left Environment with all left data. 2. Right Environment with all Right ...
from metaflow import FlowSpec, step, retry import json class ReinforcementLearningSimulatorFlow(FlowSpec): ''' Train RL Agents With Different Input States and Reward Functions. Simulate the Same Trained Agent in Simulations of 1. Left Environment with all left data. 2. Right Environment...
Python
zaydzuhri_stack_edu_python
import sys comment 직사각형 개수 set n = integer read line stdin comment 너비는 1로 고정 set h = list for i in range n begin comment 직사각형 높이 append h integer read line stdin end sort h
import sys n = int(sys.stdin.readline()) # 직사각형 개수 # 너비는 1로 고정 h = [] for i in range(n): h.append(int(sys.stdin.readline())) # 직사각형 높이 h.sort()
Python
zaydzuhri_stack_edu_python
import re comment pattern for check response as reference_number set reference_number = compile string ^([A-Z0-9]){64} function AssertNotEmptyOrError status result begin string Ожидание что result, возвращаемый вызовом метода, не пустой и не содержит слово Error assert status msg string Status or request: + string stat...
import re reference_number = re.compile("^([A-Z0-9]){64}") # pattern for check response as reference_number def AssertNotEmptyOrError(status, result): """Ожидание что result, возвращаемый вызовом метода, не пустой и не содержит слово Error""" assert status, "Status or request: " + str(status) + "...
Python
zaydzuhri_stack_edu_python
function line_geo_plot two_line_gdf begin set tuple _ ax = call subplots plot ax=ax return call VectorTester ax end function
def line_geo_plot(two_line_gdf): _, ax = plt.subplots() two_line_gdf.plot(ax=ax) return VectorTester(ax)
Python
nomic_cornstack_python_v1
function __expandArgs args forStages=none substitutions=none begin return call from_iterable generator expression call forCommandLine forStages substitutions for arg in args end function
def __expandArgs(args, forStages=None, substitutions=None): return chain.from_iterable(arg.forCommandLine(forStages, substitutions) for arg in args)
Python
nomic_cornstack_python_v1
string The sum of the squares of the first ten natural numbers is, 1^2 + 2^2 + ... + 10^2 = 385 The square of the sum of the first ten natural numbers is, (1 + 2 + ... + 10)^2 = 552 = 3025 Hence the difference between the sum of the squares of the first ten natural numbers and the square of the sum is 3025 - 385 = 2640...
''' The sum of the squares of the first ten natural numbers is, 1^2 + 2^2 + ... + 10^2 = 385 The square of the sum of the first ten natural numbers is, (1 + 2 + ... + 10)^2 = 552 = 3025 Hence the difference between the sum of the squares of the first ten natural numbers and the square of the sum is 3025 - 385 = ...
Python
zaydzuhri_stack_edu_python
function remove_duplicate_peaks self begin set peaks = list comprehension dictionary t for t in set generator expression call frozenset items d for d in peaks end function
def remove_duplicate_peaks(self): self.peaks = [dict(t) for t in set(frozenset(d.items()) for d in self.peaks)]
Python
nomic_cornstack_python_v1
function myFunc begin set num_1 = integer input string Please enter your first number: set num_2 = integer input string Please enter your second number: print num_1 + num_2 end function set is_Running = true while is_Running == true begin try begin call myFunc end except ValueError begin print string I said enter a num...
def myFunc(): num_1 = int(input("Please enter your first number: ")) num_2 = int(input("Please enter your second number: ")) print(num_1+num_2) is_Running = True while is_Running == True: try: myFunc() except ValueError: print('I said enter a number...') choice = input...
Python
zaydzuhri_stack_edu_python
function is_event_service_task jeditaskid begin set eventservice = false set query = dict string jeditaskid jeditaskid set task = list values filter keyword query string eventservice if length task > 0 and string eventservice in task at 0 and task at 0 at string eventservice is not none and task at 0 at string eventser...
def is_event_service_task(jeditaskid): eventservice = False query = {'jeditaskid': jeditaskid} task = list(JediTasks.objects.filter(**query).values('eventservice')) if len(task) > 0 and 'eventservice' in task[0] and task[0]['eventservice'] is not None and task[0]['eventservice'] == 1: eventserv...
Python
nomic_cornstack_python_v1
from random import randint from time import sleep import sys import pyttsx set FMT_STR = string {} {} -------------- function speak engine what begin call say what call runAndWait end function set colors = list string red string yellow string blue string green set directions = list string right string left set body_par...
from random import randint from time import sleep import sys import pyttsx FMT_STR = "{}\n\n{}\n\n--------------\n" def speak(engine, what): engine.say(what) engine.runAndWait() colors = ["red", "yellow", "blue", "green"] directions = ["right", "left"] body_part = ["hand", "foot"] part_colors = [[None, None], [No...
Python
zaydzuhri_stack_edu_python
comment e.g. 8-2 from tkinter import * set widget = call Button text=string Spam padx=10 pady=10 call pack padx=20 pady=20 call config bg=string black fg=string white call config font=tuple string times 25 string italic underline call config bd=8 relief=string raised call config cursor=string target call mainloop
# e.g. 8-2 from tkinter import * widget = Button(text='Spam', padx=10, pady=10) widget.pack(padx=20, pady=20) widget.config(bg='black', fg='white') widget.config(font=('times', 25, 'italic underline')) widget.config(bd=8, relief='raised') widget.config(cursor='target') mainloop()
Python
zaydzuhri_stack_edu_python
import pygame , sys , time call init comment good luck !! comment window settings set width = 900 set height = 600 set win_size = tuple width height comment game_box settings set box_width = 600 set box_height = 600 comment colors code set gris = tuple 179 182 183 set light_salmon = tuple 255 160 122 set gris_feta7 = t...
import pygame, sys, time pygame.init() #good luck !! #window settings width = 900 height= 600 win_size = width,height #game_box settings box_width = 600 box_height=600 #colors code gris = ( 179, 182, 183 ) light_salmon = ( 255, 160, 122) gris_feta7 = (93, 109, 126) blue = (0,0,255) # #colors of surfaces menu_color ...
Python
zaydzuhri_stack_edu_python
function equal_split weights nbin begin set inds = call argsort weights at slice : : - 1 set bins = list comprehension list for b in call xrange nbin set bw = zeros list nbin for i in inds begin set j = argument minimum bw append bins at j i set bw at j = bw at j + weights at i end return bins end function
def equal_split(weights, nbin): inds = np.argsort(weights)[::-1] bins = [[] for b in xrange(nbin)] bw = np.zeros([nbin]) for i in inds: j = np.argmin(bw) bins[j].append(i) bw[j] += weights[i] return bins
Python
nomic_cornstack_python_v1
function GetStatus self begin return response at string status end function
def GetStatus(self): return self.response['status']
Python
nomic_cornstack_python_v1
function instance_id self begin return get pulumi self string instance_id end function
def instance_id(self) -> Optional[pulumi.Input[str]]: return pulumi.get(self, "instance_id")
Python
nomic_cornstack_python_v1
function read_config self key registers_str=string begin comment treat as int or list if registers_str begin set registers = call literal_eval registers_str end else begin set registers = none end if is instance io FakeIO begin set chip = call get_chip key set packets = call get_configuration_packets CONFIG_WRITE_PACKE...
def read_config(self, key, registers_str=''): if registers_str: # treat as int or list registers = ast.literal_eval(registers_str) else: registers = None if isinstance(self.board.io, FakeIO): chip = self.board.get_chip(key) packets = chip.get_conf...
Python
nomic_cornstack_python_v1
function close self begin if _con is not none begin call _commit close _con set _con = none end end function
def close(self): if self._con is not None: self._commit() self._con.close() self._con = None
Python
nomic_cornstack_python_v1
import sys set stdin = open string input.txt string r from collections import deque comment 1개만 남을때까지 항상 K 번째 수(K의 배수)가 제거됨. set tuple N K = map int split input set dq = list range 1 N + 1 set dq = deque dq while dq begin comment 아무 변수 없이 반복 for _ in range K - 1 begin comment 맨 앞에거가 pop set cur = call popleft comment 맨...
import sys sys.stdin=open("input.txt", "r") from collections import deque # 1개만 남을때까지 항상 K 번째 수(K의 배수)가 제거됨. N, K = map(int, input().split()) dq = list(range(1, N+1)) dq = deque(dq) while dq: for _ in range(K-1): #아무 변수 없이 반복 cur = dq.popleft() # 맨 앞에거가 pop dq.append(cur) # 맨 뒤로 붙이기 #이렇게 해서 K번...
Python
zaydzuhri_stack_edu_python
function directiveString self begin return string %s %s %s %s %d %f %f %d ; %s % tuple atomtype1 atomtype2 atomtype3 atomtype4 func _value _value multiplicity comment end function
def directiveString(self): return '%s %s %s %s %d %f %f %d ; %s\n'%(self.atomtype1, self.atomtype2, self.atomtype3, self.atomtype4, self.func, self.phi._value, self.kphi._value, self.multiplicity, self.comment)
Python
nomic_cornstack_python_v1
from crypto_support import * comment find certs with CERT_FIND_SUBJECT_STR_W by dn function find_certs_subject_str CertStore dn begin set founded_certs_list = list set pCertPrev = none comment search for first cert set pCert = call fCertFindCertificateInStore CertStore X509_ASN_ENCODING ? PKCS_7_ASN_ENCODING 0 CERT_FI...
from crypto_support import * # find certs with CERT_FIND_SUBJECT_STR_W by dn def find_certs_subject_str(CertStore, dn): founded_certs_list = [] pCertPrev = None # search for first cert pCert = fCertFindCertificateInStore(CertStore, X509_ASN_ENCODING | PKCS_7_ASN...
Python
zaydzuhri_stack_edu_python
function write self data begin write _out data end function
def write(self, data): self._out.write(data)
Python
nomic_cornstack_python_v1
string Surrogate model based on Kriging. import numpy as np import scipy.linalg as linalg import os.path from hashlib import md5 from scipy.optimize import minimize from openmdao.surrogate_models.surrogate_model import SurrogateModel from openmdao.warnings import issue_warning , CacheWarning set MACHINE_EPSILON = eps c...
"""Surrogate model based on Kriging.""" import numpy as np import scipy.linalg as linalg import os.path from hashlib import md5 from scipy.optimize import minimize from openmdao.surrogate_models.surrogate_model import SurrogateModel from openmdao.warnings import issue_warning, CacheWarning MACHINE_EPSILON = np.finfo(...
Python
zaydzuhri_stack_edu_python
function set_palette_colors self palette begin set palette = split palette string : for i in range 16 begin set color = call color_parse palette at i call set_color color end end function
def set_palette_colors(self, palette): palette = palette.split(':') for i in range(16): color = gtk.gdk.color_parse(palette[i]) self.get_widget('palette_%d' % i).set_color(color)
Python
nomic_cornstack_python_v1
comment Exercise 5 from pathlib import Path import numpy as np import pandas as pd import xarray as xr import matplotlib.pyplot as plt set input_dir = call Path string data set output_dir = call Path string solution comment 1. Go to http://surfobs.climate.copernicus.eu/dataaccess/access_eobs.php#datafiles comment and d...
# Exercise 5 from pathlib import Path import numpy as np import pandas as pd import xarray as xr import matplotlib.pyplot as plt input_dir = Path("data") output_dir = Path("solution") # 1. Go to http://surfobs.climate.copernicus.eu/dataaccess/access_eobs.php#datafiles # and download the 0.25 deg. file for daily m...
Python
zaydzuhri_stack_edu_python
import json with open string Beta/data/magias.json as f begin set magias = load json f end with open string Beta/data/classes.json as g begin set classes = load json g end set me = dict set clase = list while true begin while true begin set m = input string Qual nome da magia que você deseja editar? set continuar = 0...
import json with open('Beta/data/magias.json') as f: magias=json.load(f) with open('Beta/data/classes.json') as g: classes=json.load(g) me={} clase=[] while True: while True: m=input('Qual nome da magia que você deseja editar?\n') continuar=0 if m in magias: break elif m==...
Python
zaydzuhri_stack_edu_python
function _get_float data position dummy0 dummy1 dummy2 begin string Decode a BSON double to python float. set end = position + 8 return tuple call _UNPACK_FLOAT data at slice position : end : at 0 end end function
def _get_float(data, position, dummy0, dummy1, dummy2): """Decode a BSON double to python float.""" end = position + 8 return _UNPACK_FLOAT(data[position:end])[0], end
Python
jtatman_500k
function c L n m begin return sum generator expression call b L i m for i in range n + 1 end function
def c(L,n,m): return sum(b(L,i,m) for i in range(n+1))
Python
nomic_cornstack_python_v1
function ls args begin string List S3 buckets. See also "aws s3 ls". Use "aws s3 ls NAME" to list bucket contents. set table = list for bucket in call filter_collection buckets args begin set LocationConstraint = call get_bucket_location Bucket=name at string LocationConstraint set cloudwatch = cloudwatch set bucket_r...
def ls(args): """ List S3 buckets. See also "aws s3 ls". Use "aws s3 ls NAME" to list bucket contents. """ table = [] for bucket in filter_collection(resources.s3.buckets, args): bucket.LocationConstraint = clients.s3.get_bucket_location(Bucket=bucket.name)["LocationConstraint"] clou...
Python
jtatman_500k
function build_conv_net self begin set conv1 = conv 2d inputs=inputs filters=32 kernel_size=list 8 8 strides=tuple 4 4 padding=string valid kernel_initializer=call xavier_initializer_conv2d name=string conv1 set conv1_out = relu conv1 name=string conv1_out set conv2 = conv 2d inputs=conv1_out filters=64 kernel_size=tup...
def build_conv_net(self): conv1 = tf.layers.conv2d( inputs=self.inputs, filters=32, kernel_size=[8, 8], strides=(4, 4), padding='valid', kernel_initializer=tf.contrib.layers.xavier_initializer_conv2d(), name='conv1' ) ...
Python
nomic_cornstack_python_v1
function run self begin comment loop until the recipe limit is reached or there are no more crawlers left while num_recipes < recipe_limit or length crawlers < 1 begin set crawler = next crawler_iter try begin set num_recipes = num_recipes + call crawl end except AnchorListsEmptyError as e begin info string E is: { e }...
def run(self) -> None: # loop until the recipe limit is reached or there are no more crawlers left while self.num_recipes < self.recipe_limit or len(self.crawlers) < 1: crawler = next(self.crawler_iter) try: self.num_recipes += crawler.crawl() except A...
Python
nomic_cornstack_python_v1
from typing import List , Callable import numpy as np seed 42 set fns = list lambda x -> - call power x 3 lambda x -> log absolute x lambda x -> sin 3 * x lambda x -> exp x lambda x -> x + 4 lambda x -> - x + square root absolute x lambda x -> x function generate functions target_index=0 n_samples=1000 x_normal_loc=0.0...
from typing import List, Callable import numpy as np np.random.seed(42) fns = [ lambda x: -np.power(x, 3), lambda x: np.log(np.abs(x)), lambda x: np.sin(3 * x), lambda x: np.exp(x), lambda x: x + 4, lambda x: -x + np.sqrt(np.abs(x)), lambda x: x ] def generate( functions: List[C...
Python
zaydzuhri_stack_edu_python
function connect self event_name callback begin call connect event_name callback end function
def connect(self, event_name, callback): self.canvas.connect(event_name, callback)
Python
nomic_cornstack_python_v1
function confidence95 self begin set degfreedom = reps at 0 - 1 return call student_t_quantile95 degfreedom * call Si2 n / reps at 0 ^ 0.5 end function
def confidence95(self): degfreedom = self.reps[0] - 1 return student_t_quantile95(degfreedom) * \ (self.Si2(self.n) / self.reps[0]) ** 0.5
Python
nomic_cornstack_python_v1
function all_with_acl cls user=none begin comment If no user, assume the user that made the request. if not user begin set user = current_user end comment pylint: disable=singleton-comparison return filter call or_ user == user call and_ user == none group == none call in_ list comprehension id for group in groups perm...
def all_with_acl(cls, user=None): # If no user, assume the user that made the request. if not user: user = current_user # pylint: disable=singleton-comparison return cls.query.filter( or_( cls.AccessControlEntry.user == user, and_(...
Python
nomic_cornstack_python_v1
function create_superuser self email username password begin set user = call create_user email password=password username=username set is_admin = true save using=_db return user end function
def create_superuser(self, email, username, password): user = self.create_user(email, password=password, username=username ) user.is_admin = True user.save(using=self._db) return user
Python
nomic_cornstack_python_v1