code stringlengths 10 2.58M | original_code stringlengths 3 3.18M | original_language stringclasses 1
value | source stringclasses 7
values |
|---|---|---|---|
function get_mask lons2d lats2d shp_path=string polygon_name=none
begin
set ds = open shp_path
string :type : ogr.DataSource
set xx = copy lons2d
set yy = lats2d
comment set longitudes to be from -180 to 180
set xx at xx > 180 = xx at xx > 180 - 360
set mask = zeros shape dtype=int
set tuple nx ny = shape
set pt = cal... | def get_mask(lons2d, lats2d, shp_path="", polygon_name=None):
ds = ogr.Open(shp_path)
"""
:type : ogr.DataSource
"""
xx = lons2d.copy()
yy = lats2d
# set longitudes to be from -180 to 180
xx[xx > 180] -= 360
mask = np.zeros(lons2d.shape, dtype=int)
nx, ny = mask.shape
pt ... | Python | nomic_cornstack_python_v1 |
function read_local_config cfg
begin
string Parses local config file for override values Args: :local_file (str): filename of local config file Returns: dict object of values contained in local config file
try
begin
if exists path cfg
begin
set config = call import_file_object cfg
return config
end
else
begin
warning s... | def read_local_config(cfg):
""" Parses local config file for override values
Args:
:local_file (str): filename of local config file
Returns:
dict object of values contained in local config file
"""
try:
if os.path.exists(cfg):
config = import_file_object(cfg)
... | Python | jtatman_500k |
function get_users_connection self
begin
return users
end function | def get_users_connection(self):
return self.m_connection.users | Python | nomic_cornstack_python_v1 |
function play self
begin
string Sends a "play" command to the player.
set msg = call Message
set type = PLAY
call send_message msg
end function | def play(self):
"""
Sends a "play" command to the player.
"""
msg = cr.Message()
msg.type = cr.PLAY
self.send_message(msg) | Python | jtatman_500k |
comment This files contains your custom actions which can be used to run
comment custom Python code.
comment See this guide on how to implement these action:
comment https://rasa.com/docs/rasa/core/actions/#custom-actions/
comment This is a simple example for a custom action which utters "Hello World!"
import pymongo
f... | # This files contains your custom actions which can be used to run
# custom Python code.
#
# See this guide on how to implement these action:
# https://rasa.com/docs/rasa/core/actions/#custom-actions/
# This is a simple example for a custom action which utters "Hello World!"
import pymongo
from pymongo import MongoCl... | Python | zaydzuhri_stack_edu_python |
from tkinter import *
import math
from tkinter.font import Font as f
function evaluer event
begin
call configure text=string Resulat : + string eval get entree
end function
comment Programme Principale
set fenetre = call Tk
title fenetre string Calculatrice
set entree = call Entry fenetre width=20
call bind string <Ret... | from tkinter import *
import math
from tkinter.font import Font as f
def evaluer(event):
chaine.configure(text="Resulat :"+str(eval(entree.get())))
#Programme Principale
fenetre = Tk()
fenetre.title("Calculatrice")
entree = Entry(fenetre,width=20)
entree.bind("<Return>", evaluer)
entree.config(font =f... | Python | zaydzuhri_stack_edu_python |
import json
import argparse
import numpy as np
import transfer
import networks
import plotting
comment data_frac: fraction of the amount (data) that we want to train the first network on
function run name network amount data_frac val_split first_layers second_layers interm_fraction neuron_count_per_layer
begin
set unti... | import json
import argparse
import numpy as np
import transfer
import networks
import plotting
# data_frac: fraction of the amount (data) that we want to train the first network on
def run(name, network, amount, data_frac, val_split, first_layers, second_layers, interm_fraction, neuron_count_per_layer):
until = a... | Python | zaydzuhri_stack_edu_python |
comment Assume the variable dct references a dictionary. Write an if statement
comment that determines whether the key 'Jim' exists in the dictionary. If so,
comment delete 'Jim' and its associated value
function main
begin
set dct = dict string Jay string Ford ; string Jerry string Chevy ; string Jim string Chrysler
i... | # Assume the variable dct references a dictionary. Write an if statement
# that determines whether the key 'Jim' exists in the dictionary. If so,
# delete 'Jim' and its associated value
def main():
dct = {'Jay':'Ford', 'Jerry': 'Chevy', 'Jim': 'Chrysler'}
if 'Jim' in dct:
popped_item = dct.pop('Jim')
... | Python | zaydzuhri_stack_edu_python |
import networkx as nx
import csv
from sets import Set
import random
import numpy as np
from collections import Counter
import matplotlib.pyplot as plt
from scipy.optimize import curve_fit
comment General Maintenance Functions
function loadResults rfName
begin
set results = list
with open rfName string rb as ifile
begi... | import networkx as nx
import csv
from sets import Set
import random
import numpy as np
from collections import Counter
import matplotlib.pyplot as plt
from scipy.optimize import curve_fit
# General Maintenance Functions
def loadResults(rfName):
results = []
with open(rfName,'rb') as ifile:
f = csv.rea... | Python | zaydzuhri_stack_edu_python |
import nltk
from nltk.tag import StanfordNERTagger
from nltk.tokenize import word_tokenize
from datetime import datetime
function ProcessSentence sentence command_response
begin
set startTime = now
comment text = 'While in France, Christine Lagarde discussed short-term stimulus efforts in a recent interview with the Wa... | import nltk
from nltk.tag import StanfordNERTagger
from nltk.tokenize import word_tokenize
from datetime import datetime
def ProcessSentence(sentence, command_response):
startTime = datetime.now()
##text = 'While in France, Christine Lagarde discussed short-term stimulus efforts in a recent interview ... | Python | zaydzuhri_stack_edu_python |
for i in range 1 7
begin
for a in range 1 1 + i
begin
print string * end=string
end
print
end | for i in range(1,7):
for a in range(1,1+i):
print("*",end='')
print()
| Python | zaydzuhri_stack_edu_python |
from rlbot.utils.structures.game_interface import GameInterface
from rlbot.utils.structures.game_data_struct import GameTickPacket
from rlbot.utils.logging_utils import get_logger
from utils import *
import pyttsx3
import psutil
from queue import Queue
import threading
import random
import time
import math
function hos... | from rlbot.utils.structures.game_interface import GameInterface
from rlbot.utils.structures.game_data_struct import GameTickPacket
from rlbot.utils.logging_utils import get_logger
from utils import *
import pyttsx3
import psutil
from queue import Queue
import threading
import random
import time
import math
def host(_q... | Python | zaydzuhri_stack_edu_python |
from mcpi.minecraft import Minecraft
from mcpi import block
from time import sleep
function init
begin
set mc = call create string 127.0.0.1 4711
set tuple x y z = call getPos
return mc
end function
function gun mc x y z direction mussle_length
begin
print string mussle_length mussle_length
comment WOOD_PLANKS 5 GLASS ... | from mcpi.minecraft import Minecraft
from mcpi import block
from time import sleep
def init():
mc = Minecraft.create("127.0.0.1", 4711)
x, y, z = mc.player.getPos()
return mc
def gun(mc,x,y,z,direction,mussle_length):
print("mussle_length ",mussle_length)
#WOOD_PLANKS 5 GLASS 20 gold 41
m = 2... | Python | zaydzuhri_stack_edu_python |
import numpy as np
import pandas as pd
import statsmodels.api as sm
from statsmodels.tsa.stattools import adfuller , kpss , acf , grangercausalitytests
from statsmodels.graphics.tsaplots import plot_acf , plot_pacf , month_plot , quarter_plot
from scipy import signal
import matplotlib.pyplot as plt
import seaborn as sn... | import numpy as np
import pandas as pd
import statsmodels.api as sm
from statsmodels.tsa.stattools import adfuller, kpss, acf, grangercausalitytests
from statsmodels.graphics.tsaplots import plot_acf, plot_pacf,month_plot,quarter_plot
from scipy import signal
import matplotlib.pyplot as plt
import seaborn as sns... | Python | zaydzuhri_stack_edu_python |
import kanu
while true
begin
print string Select one:
print string 1 -> Solve a linear equation
print string 2 -> Simplify any expression
print string 3 -> Is this number a Perfect Square?
print string 4 -> Get Prime Numbers
print string 5 -> START A NUCLEAR WAR :)
print string 6 -> Factor Integers
set choice = input
i... | import kanu
while True:
print('\n Select one:')
print('\t1 -> Solve a linear equation')
print('\t2 -> Simplify any expression')
print('\t3 -> Is this number a Perfect Square?')
print('\t4 -> Get Prime Numbers')
print('\t5 -> START A NUCLEAR WAR :)')
print('\t6 -> Factor Integers')... | Python | jtatman_500k |
function sort_objects_from_viewworld self viewworld
begin
set opaque_objects = list
set transparent_objects = list
set centers = list
for guid in objects
begin
set obj = objects at guid
if is instance obj BufferObject
begin
if opacity * opacity < 1 and bounding_box_center is not none
begin
append transparent_objects... | def sort_objects_from_viewworld(self, viewworld):
opaque_objects = []
transparent_objects = []
centers = []
for guid in self.objects:
obj = self.objects[guid]
if isinstance(obj, BufferObject):
if obj.opacity * self.opacity < 1 and obj.bounding_box_... | Python | nomic_cornstack_python_v1 |
comment !/usr/bin/env python3
comment -*- coding: utf-8 -*-
string Created on Fri Mar 15 16:08:54 2019 @author: Nicholas Sotiriou - github: @nsotiriou88
comment %% Import functions
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
from mpl_toolkits.mplot3d import Axes3D
from mpl_toolkits.mplot3d.ar... | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Fri Mar 15 16:08:54 2019
@author: Nicholas Sotiriou - github: @nsotiriou88
"""
#%% Import functions
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
from mpl_toolkits.mplot3d import Axes3D
from mpl_toolkits.mplot3d.art3d import Poly3... | Python | zaydzuhri_stack_edu_python |
function urgent_first patient_list patient
begin
comment traverse the queue
for x in range 0 length patient_list
begin
comment if the treatment time of the current patient is longer
if levelOfUrgency <= levelOfUrgency
begin
comment if we have traversed the complete queue
if x == length patient_list - 1
begin
comment ad... | def urgent_first(patient_list, patient):
# traverse the queue
for x in range(0, len(patient_list)):
# if the treatment time of the current patient is longer
if patient.levelOfUrgency <= patient_list[x].levelOfUrgency:
# if we have traversed the complete queue
... | Python | nomic_cornstack_python_v1 |
function testGetAccessDenied self
begin
call runGet none sequencer=sodar_uuid
call response_401
for user in tuple norole unrelated_owner
begin
call runGet user sequencer=sodar_uuid
call response_403
end
end function | def testGetAccessDenied(self):
self.runGet(None, sequencer=self.hiseq2000.sodar_uuid)
self.response_401()
for user in (self.norole, self.unrelated_owner):
self.runGet(user, sequencer=self.hiseq2000.sodar_uuid)
self.response_403() | Python | nomic_cornstack_python_v1 |
string requests and upload
from flask import Flask , request
from ex03_pizzaria import pizzaria
set app = call Flask __name__
string Exemplo de chamada POST curl http://127.0.0.1:5000/trata -d "num1=1&num2=2" url_for('static', filename='style.css')
set template1 = read open string pizza1.html
set template2 = read open ... | """
requests and upload
"""
from flask import Flask, request
from ex03_pizzaria import pizzaria
app = Flask(__name__)
"""
Exemplo de chamada POST
curl http://127.0.0.1:5000/trata -d "num1=1&num2=2"
url_for('static', filename='style.css')
"""
template1 = open("pizza1.html").read()
template2 = open("pizza2.html")... | Python | zaydzuhri_stack_edu_python |
function delobj obj_name byref=false
begin
set ret_string = string
set obj = search obj_name
if not obj
begin
call msg string (Objects to destroy must either be local or specified with a unique #dbref.)
return string
end
set obj_name = name
if not call access caller string control or call access caller string delete
... | def delobj(obj_name, byref=False):
ret_string = ""
obj = caller.search(obj_name)
if not obj:
self.msg(
" (Objects to destroy must either be local or specified with a unique #dbref.)"
)
return ""
obj_name ... | Python | nomic_cornstack_python_v1 |
from PIL import Image , ImageFilter
import numpy as np
from PIL.ImageQt import ImageQt
from PyQt5.QtGui import QPixmap , QImage
from image.Layer import Layers
class BinaryImage
begin
function __init__ self
begin
set original_image = Image
set image = original_image
set image_array = list
set array = list
set width = ... | from PIL import Image, ImageFilter
import numpy as np
from PIL.ImageQt import ImageQt
from PyQt5.QtGui import QPixmap, QImage
from image.Layer import Layers
class BinaryImage:
def __init__(self):
self.original_image = Image
self.image = self.original_image
self.image_array = []
se... | Python | zaydzuhri_stack_edu_python |
string Construct a program with Python for calculating the average of the numbers in a given list
function calculate_average numbers
begin
comment Calculate the sum of the numbers
set total_sum = 0
for n in numbers
begin
set total_sum = total_sum + n
end
comment Calculate the average of the numbers
set average = total_... | """
Construct a program with Python for calculating the average of the numbers in a given list
"""
def calculate_average(numbers):
# Calculate the sum of the numbers
total_sum = 0
for n in numbers:
total_sum += n
# Calculate the average of the numbers
average = total_sum/len(numbers)
... | Python | jtatman_500k |
function insertMeasurement self temp salinity par ph flow
begin
comment Create a connection to the database
set conn = call connect DATA_FILE
set cur = call cursor
comment Create the table if it does not exist
execute cur string CREATE TABLE IF NOT EXISTS measurements (timestamp TEXT NOT NULL, temperature TEXT NOT NULL... | def insertMeasurement(self, temp, salinity, par, ph, flow):
## Create a connection to the database
##
conn = sqlite3.connect(DATA_FILE)
cur = conn.cursor()
## Create the table if it does not exist
##
cur.execute("""CREATE TABLE IF NOT EXISTS measurements
... | Python | nomic_cornstack_python_v1 |
function test_within self
begin
set models_within_world = call within roi_world
set models_within_ne = call within roi_ne
set models_within_smaller_g = call within roi_smaller_g
assert equal length models_within_world 2
assert equal length models_within_ne 1
assert equal length models_within_smaller_g 0
assert equal ty... | def test_within(self):
models_within_world = self.model_provider.within(self.roi_world)
models_within_ne = self.model_provider.within(self.roi_ne)
models_within_smaller_g = self.model_provider.within(
self.roi_smaller_g
)
self.assertEqual(len(models_within_world), 2... | Python | nomic_cornstack_python_v1 |
from manim import *
from itertools import combinations
class Main extends ThreeDScene
begin
function construct self
begin
comment Objects needed for the scene
set title_text = call Text string Euler's formula for polyhedra
set formula = call MathTex string F string - string E string + string V string = 2
set f_expl = c... | from manim import *
from itertools import combinations
class Main(ThreeDScene):
def construct(self):
# Objects needed for the scene
title_text = Text("Euler's formula for polyhedra")
formula = MathTex("F", "-", "E", "+", "V", "= 2")
f_expl = Text("Number of faces").set_color(RED)
... | Python | zaydzuhri_stack_edu_python |
if n % 10 == 1 and n != 11
begin
print n string korova
end
else
if n > 21 or n < 5
begin
if n % 10 == 2 or n % 10 == 3 or n % 10 == 4
begin
print n string korovy
end
else
begin
print n string korov
end
end
else
begin
print n string korov
end | if (n % 10 == 1) and (n != 11):
print(n, 'korova')
elif (n > 21) or (n < 5):
if (n % 10 == 2) or (n % 10 == 3) or (n % 10 == 4):
print(n, 'korovy')
else:
print(n, 'korov')
else:
print(n, 'korov')
| Python | zaydzuhri_stack_edu_python |
comment !/user/bin/env python
comment -*- coding:utf-8 -*-
from selenium import webdriver
from selenium.webdriver.common.action_chains import ActionChains
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.support.ui import WebDriverWait
from selenium.common.exceptions import NoSuchElementException... | #!/user/bin/env python
# -*- coding:utf-8 -*-
from selenium import webdriver
from selenium.webdriver.common.action_chains import ActionChains
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.support.ui import WebDriverWait
from selenium.common.exceptions import NoSuchElementException
import time,... | Python | zaydzuhri_stack_edu_python |
function do_scan_results sk if_index driver_id results
begin
string Retrieve the results of a successful scan (SSIDs and data about them). This function does not require root privileges. It eventually calls a callback that actually decodes data about SSIDs but this function kicks that off. May exit the program (sys.exi... | def do_scan_results(sk, if_index, driver_id, results):
"""Retrieve the results of a successful scan (SSIDs and data about them).
This function does not require root privileges. It eventually calls a callback that actually decodes data about
SSIDs but this function kicks that off.
May exit the program ... | Python | jtatman_500k |
function print_versioned package_releases package
begin
comment sort them via pkg_resources' version sorting
set versioned = default dictionary list
for package_release in package_releases
begin
set version = call get_package_version package_release package
append versioned at version format string {}={} package_releas... | def print_versioned(package_releases, package):
# sort them via pkg_resources' version sorting
versioned = defaultdict(list)
for package_release in package_releases:
version = get_package_version(package_release, package)
versioned[version].append("{}={}".format(
package_release... | Python | nomic_cornstack_python_v1 |
function print_reverse_vowels s i
begin
if i < 0 or i >= length s
begin
return
end
if lower s at i in list string a string e string i string o string u
begin
print s at i
end
call print_reverse_vowels s i - 1
end function
comment Example usage
set s = string Hello World
call print_reverse_vowels s length s - 1 | def print_reverse_vowels(s, i):
if i < 0 or i >= len(s):
return
if s[i].lower() in ['a', 'e', 'i', 'o', 'u']:
print(s[i])
print_reverse_vowels(s, i-1)
# Example usage
s = "Hello World"
print_reverse_vowels(s, len(s)-1)
| Python | jtatman_500k |
function adjust_env_for_platform self env
begin
if name == string windows
begin
call _add_systemroot_to_env_win32 env
end
end function | def adjust_env_for_platform(self, env):
if platform_.name == "windows":
self._add_systemroot_to_env_win32(env) | Python | nomic_cornstack_python_v1 |
function members self key
begin
if is instance key basestring
begin
return _info_by_command at key
end
else
begin
return _info_by_role at keyword
end
end function | def members(self, key):
if isinstance(key, basestring):
return self._info_by_command[key]
else:
return self._info_by_role[key.keyword] | Python | nomic_cornstack_python_v1 |
import argparse
import copy
import numpy as np
import os
from os.path import join
from run_data_sampling import generate_data
from run_train_model import train_model
string This script is used to train a ResNet-18-based UNet segmentation model using active learning. A small dataset is first collected and used to train ... | import argparse
import copy
import numpy as np
import os
from os.path import join
from run_data_sampling import generate_data
from run_train_model import train_model
'''
This script is used to train a ResNet-18-based UNet segmentation model using active learning.
A small dataset is first collected and used to train ... | Python | zaydzuhri_stack_edu_python |
function orion_version_conflict old_config new_config
begin
return call OrionVersionConflict old_config new_config
end function | def orion_version_conflict(old_config, new_config):
return conflicts.OrionVersionConflict(old_config, new_config) | Python | nomic_cornstack_python_v1 |
function Navigate self URL=defaultNamedNotOptArg Flags=defaultNamedOptArg TargetFrameName=defaultNamedOptArg PostData=defaultNamedOptArg Headers=defaultNamedOptArg
begin
return call InvokeTypes 104 LCID 1 tuple 24 0 tuple tuple 8 1 tuple 16396 17 tuple 16396 17 tuple 16396 17 tuple 16396 17 URL Flags TargetFrameName Po... | def Navigate(self, URL=defaultNamedNotOptArg, Flags=defaultNamedOptArg, TargetFrameName=defaultNamedOptArg, PostData=defaultNamedOptArg
, Headers=defaultNamedOptArg):
return self._oleobj_.InvokeTypes(104, LCID, 1, (24, 0), ((8, 1), (16396, 17), (16396, 17), (16396, 17), (16396, 17)),URL
, Flags, TargetFrameName... | Python | nomic_cornstack_python_v1 |
function off_color self
begin
return _off_color
end function | def off_color(self):
return self._off_color | Python | nomic_cornstack_python_v1 |
function _calcOnAxisFactor self aLocation deltaAxis deltasOnSameAxis deltaLocation
begin
string Calculate the on-axis factors.
if deltaAxis == string origin
begin
set f = 0
set v = 0
end
else
begin
set f = aLocation at deltaAxis
set v = deltaLocation at deltaAxis
end
set i = list
set iv = dict
for value in deltasOnSa... | def _calcOnAxisFactor(self, aLocation, deltaAxis, deltasOnSameAxis, deltaLocation):
"""
Calculate the on-axis factors.
"""
if deltaAxis == "origin":
f = 0
v = 0
else:
f = aLocation[deltaAxis]
v = deltaLocation[deltaAxis]
... | Python | jtatman_500k |
import torch
from torch.autograd import Variable
from torchvision import transforms
from torch.utils.data import Dataset , DataLoader
from PIL import Image
from MyDatasetCuda import MyDatasetCuda
import time
from vggModel import VGG16
set root = string G:/liudongbo/dataset/small_pic_test/
set device = device if express... | import torch
from torch.autograd import Variable
from torchvision import transforms
from torch.utils.data import Dataset, DataLoader
from PIL import Image
from MyDatasetCuda import MyDatasetCuda
import time
from vggModel import VGG16
root="G:/liudongbo/dataset/small_pic_test/"
device = torch.device("cu... | Python | zaydzuhri_stack_edu_python |
function vc_output_record samples
begin
string Prepare output record from variant calling to feed into downstream analysis. Prep work handles reformatting so we return generated dictionaries. For any shared keys that are calculated only once for a batch, like variant calls for the batch, we assign to every sample.
set ... | def vc_output_record(samples):
"""Prepare output record from variant calling to feed into downstream analysis.
Prep work handles reformatting so we return generated dictionaries.
For any shared keys that are calculated only once for a batch, like variant calls
for the batch, we assign to every sample.... | Python | jtatman_500k |
function get_sprite_image self lump mirror
begin
if palette is none
begin
return none
end
if mirror
begin
set lump_name = format string {}M name
end
else
begin
set lump_name = name
end
if lump_name in sprite_image_cache
begin
return sprite_image_cache at lump_name
end
set image = call Image call get_data palette mirror... | def get_sprite_image(self, lump, mirror):
if self.palette is None:
return None
if mirror:
lump_name = '{}M'.format(lump.name)
else:
lump_name = lump.name
if lump_name in self.sprite_image_cache:
return self.sprite_image_cache[lump_name]
... | Python | nomic_cornstack_python_v1 |
function removeEdge self vertexIn vertexOut
begin
if vertexOut in dictOut at vertexIn
begin
remove dictOut at vertexIn vertexOut
end
if vertexIn in dictIn at vertexOut
begin
remove dictIn at vertexOut vertexIn
end
if call isEdge vertexIn vertexOut == false
begin
for index in range 0 length listOfEdges
begin
if listOfEd... | def removeEdge(self,vertexIn ,vertexOut):
if vertexOut in self.dictOut[vertexIn]:
self.dictOut[vertexIn].remove(vertexOut)
if vertexIn in self.dictIn[vertexOut]:
self.dictIn[vertexOut].remove(vertexIn)
if self.isEdge(vertexIn,vertexOut)==False:
for index in ... | Python | nomic_cornstack_python_v1 |
function getAntivirusThreats self df=none ts=none cursor=none pageSize=none
begin
set params = dict string df df ; string ts ts ; string cursor cursor ; string pageSize pageSize
return call api_get_request string { NINJA_API_QUERIES_ANTIVIRUS_THREATS } params=params
end function | def getAntivirusThreats(self, df: str = None, ts: str = None, cursor: str = None, pageSize: int = None):
params = {
'df': df,
'ts': ts,
'cursor': cursor,
'pageSize': pageSize
}
return self.api_get_request(f'{self.NINJA_API_QUERIES_ANTIVIRUS_THREATS... | Python | nomic_cornstack_python_v1 |
function make_butter_spso self spso_wn_pass spso_wn_stop spso_order
begin
set nyquist = s_freq / 2
set wn_pass_arr = call asarray spso_wn_pass
set wn_stop_arr = call asarray spso_wn_stop
comment must remake filter for each pt bc of differences in s_freq
if any wn_pass_arr <= 0 or any wn_pass_arr >= 1
begin
set wn_pass_... | def make_butter_spso(self, spso_wn_pass, spso_wn_stop, spso_order):
nyquist = self.s_freq/2
wn_pass_arr = np.asarray(spso_wn_pass)
wn_stop_arr = np.asarray(spso_wn_stop)
# must remake filter for each pt bc of differences in s_freq
if np.any(wn_pass_arr <=0) or np.any(wn_... | Python | nomic_cornstack_python_v1 |
function GetBalloonStyle self
begin
return call InvokeTypes 88 LCID 1 tuple 3 0 tuple
end function | def GetBalloonStyle(self):
return self._oleobj_.InvokeTypes(88, LCID, 1, (3, 0), (),) | Python | nomic_cornstack_python_v1 |
function init_from_masks_dict self masks_dict normalize_dataparallel_keys=false
begin
for tuple name mask in items zeros_mask_dict
begin
if name not in masks_dict
begin
set masks_dict at name = none
end
end
set state = dict string masks_dict masks_dict
load state dict self state normalize_dataparallel_keys
end function | def init_from_masks_dict(self, masks_dict, normalize_dataparallel_keys=False):
for name, mask in self.zeros_mask_dict.items():
if name not in masks_dict:
masks_dict[name] = None
state = {'masks_dict': masks_dict}
self.load_state_dict(state, normalize_dataparallel_keys... | Python | nomic_cornstack_python_v1 |
comment %%
import turtle
set t = call Turtle
call forward 1000
call forward 1000
input string Press any key to exit ...
call forward 90
comment %%
set msg = string Hello World
print msg
comment %% | # %%
import turtle
t = turtle.Turtle()
t.forward(1000)
t.forward(1000)
input("Press any key to exit ...")
t.forward(90)
# %%
msg = "Hello World"
print(msg)
# %%
| Python | zaydzuhri_stack_edu_python |
comment query_delete.py
comment Deletes records from tables within quincy database
comment Records are determined from queries contained in
comment inputted textfile, where filename is inputted as argument from command line
comment Adds the parent directory to the path of this program
import os , sys , inspect
set curr... | # query_delete.py
# Deletes records from tables within quincy database
# Records are determined from queries contained in
# inputted textfile, where filename is inputted as argument from command line
# Adds the parent directory to the path of this program
import os,sys,inspect
currentdir = os.path.dirname(os.path.absp... | Python | zaydzuhri_stack_edu_python |
function make *args **kwargs
begin
return call Block_interleaver_ATSC_make *args keyword kwargs
end function | def make(*args, **kwargs):
return _mack_sdr_rossi_swig.Block_interleaver_ATSC_make(*args, **kwargs) | Python | nomic_cornstack_python_v1 |
import unittest
from root.core.processingthread import ProcessingThread
from time import sleep
class SimpleProcessingThread extends ProcessingThread
begin
function __init__ self
begin
call __init__ self
set called = false
end function
function process_step self
begin
set called = true
end function
end class
class TestP... | import unittest
from root.core.processingthread import ProcessingThread
from time import sleep
class SimpleProcessingThread( ProcessingThread ):
def __init__(self):
ProcessingThread.__init__( self )
self.called = False
def process_step(self):
self.called = True
class TestProc... | Python | zaydzuhri_stack_edu_python |
function OnRender self event
begin
comment if the frame is about to be deleted, don't bother
if not _frame or call IsBeingDeleted
begin
return
end
if not call GetSizer
begin
return
end
if not call IsShownOnScreen
begin
return
end
set mouse = call GetMouseState
set mousePos = call Point call GetX call GetY
set point = c... | def OnRender(self, event):
# if the frame is about to be deleted, don't bother
if not self._frame or self._frame.IsBeingDeleted():
return
if not self._frame.GetSizer():
return
if not self._frame.IsShownOnScreen():
return
mouse = wx.GetMouse... | Python | nomic_cornstack_python_v1 |
function add_routes meteor_app url_path=string /importv2
begin
string Add two routes to the specified instance of :class:`meteorpi_server.MeteorApp` to implement the import API and allow for replication of data to this server. :param meteorpi_server.MeteorApp meteor_app: The :class:`meteorpi_server.MeteorApp` to which ... | def add_routes(meteor_app, url_path='/importv2'):
"""
Add two routes to the specified instance of :class:`meteorpi_server.MeteorApp` to implement the import API and allow
for replication of data to this server.
:param meteorpi_server.MeteorApp meteor_app:
The :class:`meteorpi_server.MeteorApp` ... | Python | jtatman_500k |
string Created on @author: Administrator
function get_data_col_num sheet
begin
set row = call row_values 0
set col = 0
for n in row
begin
if n == string ACTION
begin
set action_col_num = col
set col = col + 1
end
else
if n == string VALUE
begin
set value_col_num = col
set col = col + 1
end
else
begin
set col = col + 1
... | '''
Created on
@author: Administrator
'''
def get_data_col_num(sheet):
row=sheet.row_values(0)
col=0
for n in row:
if(n=="ACTION"):
action_col_num=col
col+=1
elif(n=="VALUE"):
value_col_num=col
col+=1
else:
col+=1
retu... | Python | zaydzuhri_stack_edu_python |
function age_simulants self event
begin
string Updates simulant age on every time step. Parameters ---------- event : An event object emitted by the simulation containing an index representing the simulants affected by the event and timing information.
set population = get population_view index query=string alive == 'a... | def age_simulants(self, event: Event):
"""Updates simulant age on every time step.
Parameters
----------
event :
An event object emitted by the simulation containing an index
representing the simulants affected by the event and timing
information.
... | Python | jtatman_500k |
function needs_quote word
begin
set reserved = set literal string string $ string % string & string ( string ) string [ string ] string { string } string * string | string < string > string @ string ? string !
set state = 0
for current in word
begin
if state == 0 and current in reserved
begin
return true
end
else
if s... | def needs_quote(word):
reserved = {' ', '$', '%', '&', '(', ')', '[', ']', '{', '}', '*', '|',
'<', '>', '@', '?', '!'}
state = 0
for current in word:
if state == 0 and current in reserved:
return True
elif state == 0 and current == '\... | Python | nomic_cornstack_python_v1 |
comment Complete the printLinkedList function below.
comment For your reference:
comment SinglyLinkedListNode:
comment int data
comment SinglyLinkedListNode next
function printLinkedList head
begin
if head
begin
set current = head
while current
begin
print data
set current = next
end
end
end function | # Complete the printLinkedList function below.
# For your reference:
#
# SinglyLinkedListNode:
# int data
# SinglyLinkedListNode next
def printLinkedList(head):
if head:
current = head
while current:
print(current.data)
current = current.next
| Python | zaydzuhri_stack_edu_python |
function items_per_page self items_per_page
begin
set _items_per_page = items_per_page
end function | def items_per_page(self, items_per_page):
self._items_per_page = items_per_page | Python | nomic_cornstack_python_v1 |
function is_recurring self
begin
return recurring
end function | def is_recurring(self):
return self.recurring | Python | nomic_cornstack_python_v1 |
import unittest
from py_calendrical.calendars.bahai import WesternBahaiDate , FutureBahaiDate
class WesternBahaiDateTestCase extends TestCase
begin
function testKnownDates self
begin
set knownDates = dict - 214193 call WesternBahaiDate - 6 6 3 7 12 ; - 61387 call WesternBahaiDate - 5 9 3 14 13 ; 25469 call WesternBahai... | import unittest
from py_calendrical.calendars.bahai import WesternBahaiDate, FutureBahaiDate
class WesternBahaiDateTestCase(unittest.TestCase):
def testKnownDates(self):
knownDates = {
-214193: WesternBahaiDate(-6, 6, 3, 7, 12),
-61387: WesternBahaiDate(-5, 9, 3, 14, 13),
... | Python | zaydzuhri_stack_edu_python |
function loadtrkfile T_filename threshold_short_streamlines=10.0
begin
print string Loading %s % T_filename
set tuple T hdr = read trackvis T_filename as_generator=false
set T = array list comprehension s at 0 for s in T dtype=object
return tuple T hdr
end function | def loadtrkfile(T_filename, threshold_short_streamlines=10.0):
print("Loading %s" % T_filename)
T, hdr = trackvis.read(T_filename, as_generator=False)
T = np.array([s[0] for s in T], dtype=np.object)
return T, hdr | Python | nomic_cornstack_python_v1 |
function Gap self
begin
return call _get_attribute string gap
end function | def Gap(self):
return self._get_attribute('gap') | Python | nomic_cornstack_python_v1 |
function set_goal_impedance self action
begin
if use_delta_impedance
begin
comment clip resulting kp and damping
set goal_kp = call clip impedance_kp at action_mask + action at slice kp_index at 0 : kp_index at 1 : kp_min kp_max
set goal_damping = call clip impedance_damping at action_mask + action at slice damping_in... | def set_goal_impedance(self, action):
if self.use_delta_impedance:
# clip resulting kp and damping
self.goal_kp = np.clip(self.impedance_kp[self.action_mask] + action[self.kp_index[0]:self.kp_index[1]],
self.kp_min, self.kp_max)
self.goal_da... | Python | nomic_cornstack_python_v1 |
comment to read text file
function fileread
begin
comment this open the inventory file in read mode
set file = open string inventory.txt string r
set a = read file
close file
set s = string WELCOME TO OUR SHOP!!
set s = s + string HOW MAY I HELP YOU ??
set s = s + string ************************************
set s = s +... | def fileread():#to read text file
file = open("inventory.txt","r")#this open the inventory file in read mode
a = file.read()
file.close()
s = " WELCOME TO OUR SHOP!! \n"
s = s +" HOW MAY I HELP YOU ?? \n"
s = s = s +"************************************\n"
s = s+"product\tprice... | Python | zaydzuhri_stack_edu_python |
function getSystemModeStatus
begin
set systemModeStatus = first call order_by call desc
return systemModeStatus at 0
end function | def getSystemModeStatus():
systemModeStatus = (
db.session.query(adminSettings.enableOpsMode)
.order_by(adminSettings.id.desc())
.first()
)
return systemModeStatus[0] | Python | nomic_cornstack_python_v1 |
if resto == 1
begin
print string ímpar
end
else
begin
print string par
end | if resto==1:
print("ímpar")
else:
print("par") | Python | zaydzuhri_stack_edu_python |
function bubbleSort input_list
begin
string 函数说明:冒泡排序(升序) Author: www.cuijiahua.com Parameters: input_list - 待排序列表 Returns: sorted_list - 升序排序好的列表
if length input_list == 0
begin
return list
end
set sorted_list = input_list
for i in range length sorted_list - 1
begin
print string 第%d趟排序: % i + 1
for j in range length ... | def bubbleSort(input_list):
'''
函数说明:冒泡排序(升序)
Author:
www.cuijiahua.com
Parameters:
input_list - 待排序列表
Returns:
sorted_list - 升序排序好的列表
'''
if len(input_list) == 0:
return []
sorted_list = input_list
for i in range(len(sorted_list) - 1):
print('... | Python | zaydzuhri_stack_edu_python |
from db import get_db
import random
function draw_mask
begin
set tuple db cursor = call get_db
execute cursor string SELECT id, total, order_max FROM order_set WHERE status=0
set order_round = call fetchone
if order_round is none
begin
return string 没有未执行抽签的预约
end
execute cursor string UPDATE order_set SET status=1 WHE... | from db import get_db
import random
def draw_mask():
db, cursor = get_db()
cursor.execute("SELECT id, total, order_max FROM order_set WHERE status=0")
order_round = cursor.fetchone()
if order_round is None:
return "没有未执行抽签的预约"
cursor.execute("UPDATE order_set SET status=1 WHERE id=%s", or... | Python | zaydzuhri_stack_edu_python |
function group_median x groups axis=0
begin
comment Find set of unique groups
set ugroups = call unique_group groups
comment Convert groups to a numpy array
set groups = call asarray groups
comment Loop through unique groups and normalize
set xmedian = nan * zeros shape
for group in ugroups
begin
set idx = groups == gr... | def group_median(x, groups, axis=0):
# Find set of unique groups
ugroups = unique_group(groups)
# Convert groups to a numpy array
groups = np.asarray(groups)
# Loop through unique groups and normalize
xmedian = np.nan * np.zeros(x.shape)
for group in ugroups:
idx = group... | Python | nomic_cornstack_python_v1 |
function unsubscribechannel
begin
print string *No undo. (Resubscribe later.)
set deleteit = input string Unsubscribe from a channel: are you sure? (y/n)
if deleteit == string y
begin
set channelnum = input string *Unsubscribe from channel number?
set postcontent = call subscribe_channel channelnum
call serverresponse ... | def unsubscribechannel():
print("*No undo. (Resubscribe later.)")
deleteit = input("Unsubscribe from a channel: are you sure? (y/n)")
if deleteit == "y":
channelnum = input("*Unsubscribe from channel number? ")
postcontent = pnutpy.api.subscribe_channel(channelnum)
serverresponse("unsubscribed", postcontent)
... | Python | nomic_cornstack_python_v1 |
string This script do the experiments of questions 13.
import argparse
import numpy as np
import matplotlib.pyplot as plt
set ITERS = 300
function get_data train_path test_path
begin
string Load and split data.
comment load data
set train = call genfromtxt train_path
set test = call genfromtxt test_path
comment split x... | """ This script do the experiments of questions 13. """
import argparse
import numpy as np
import matplotlib.pyplot as plt
ITERS = 300
def get_data(train_path, test_path):
""" Load and split data."""
# load data
train = np.genfromtxt(train_path)
test = np.genfromtxt(test_path)
# split x/y
x... | Python | zaydzuhri_stack_edu_python |
comment -*- coding: utf-8 -*-
string Created on Tue Mar 26 11:41:38 2019 @author: Manmeet Kaur
set a = list
print length a
append a string hello world
print a
insert a 0 2
print a
set a at 0 = 5
print a
set tuple b c = a
print b
print c
append a string how
append a string are
append a string you
append a 28
append a 1... | # -*- coding: utf-8 -*-
"""
Created on Tue Mar 26 11:41:38 2019
@author: Manmeet Kaur
"""
a=[]
print (len(a))
a.append("hello world")
print (a)
a.insert(0,2)
print(a)
a[0]=5
print(a)
b,c=a
print(b)
print(c)
a.append("how")
a.append("are")
a.append("you")
a.append(28)
a.append(14)
print(a)
val=a.... | Python | zaydzuhri_stack_edu_python |
function __init__ self membre
begin
set pouvoirs = list string espionner
call __init__ membre role_name=string Petite Fille pouvoirs=pouvoirs channel_name=list string Petite Fille
end function | def __init__(self, membre):
pouvoirs = ["espionner"]
super(PetiteFille, self).__init__(membre, role_name="Petite Fille", pouvoirs = pouvoirs, channel_name=["Petite Fille"]) | Python | nomic_cornstack_python_v1 |
import asyncio
from discord.ext import commands
import json
print string Pom! initialized.
class Pom extends Cog
begin
function __init__ self bot
begin
set bot = bot
call create_task call save_users
with open string users.json string r as f
begin
set users = load json f
end
end function
async function save_users self
b... | import asyncio
from discord.ext import commands
import json
print("Pom! initialized.")
class Pom(commands.Cog):
def __init__(self, bot):
self.bot = bot
self.bot.loop.create_task(self.save_users())
with open('users.json', 'r') as f:
self.users = json.load(f)
async def sav... | Python | zaydzuhri_stack_edu_python |
import cv2
import os
set face_cascade = call CascadeClassifier string /home/daiver/coding/libs/opencv/data/haarcascades/haarcascade_frontalface_default.xml
set dirName = string data
set listOfImages = list comprehension join path dirName x for x in list directory dirName
for name in listOfImages
begin
set img = call im... | import cv2
import os
face_cascade = cv2.CascadeClassifier('/home/daiver/coding/libs/opencv/data/haarcascades/haarcascade_frontalface_default.xml')
dirName = 'data'
listOfImages = [os.path.join(dirName, x) for x in os.listdir(dirName)]
for name in listOfImages:
img = cv2.imread(name)
faces = face_cascade.dete... | Python | zaydzuhri_stack_edu_python |
string Creates the files needed to run the charecters match recommender algorithm
from typing import List
import pandas as pd
from sklearn.preprocessing import MultiLabelBinarizer
set ap_df = read csv string ../../data/anime_planet/anime_data.csv encoding=string utf-8
set characters_df = read csv string ../../data/anim... | """ Creates the files needed to run the charecters match recommender algorithm """
from typing import List
import pandas as pd
from sklearn.preprocessing import MultiLabelBinarizer
ap_df = pd.read_csv("../../data/anime_planet/anime_data.csv", encoding="utf-8")
characters_df = pd.read_csv("../../data/anime_planet/ch... | Python | zaydzuhri_stack_edu_python |
function class_Pk self z=0.0 k=call logspace - 4.0 2.0 1001 nonlinear=false halofit=string halofit **kwargs
begin
comment Set halofit for non-linear computation
if nonlinear == true
begin
set halofit = halofit
end
else
begin
set halofit = string none
end
comment Setting lengths
set nk = length call atleast_1d k
set nz ... | def class_Pk(self,
z = 0.,
k = np.logspace(-4., 2., 1001),
nonlinear = False,
halofit = 'halofit',
**kwargs):
# Set halofit for non-linear computation
if nonlinear == True: halofit = halofit
else: ... | Python | nomic_cornstack_python_v1 |
comment !/usr/local/bin/python3
import random
import math
import json
import uuid
import copy
import itertools
import difflib
import plac
comment This metaclass will provide every features with the same base logic
class FeatureMeta extends type
begin
function __new__ cls name bases attrs
begin
set method_list = list st... | #!/usr/local/bin/python3
import random
import math
import json
import uuid
import copy
import itertools
import difflib
import plac
# This metaclass will provide every features with the same base logic
class FeatureMeta(type):
def __new__(cls, name, bases, attrs):
method_list = [
"check_for_upd... | Python | zaydzuhri_stack_edu_python |
function test_slepp_get_at_id mocker
begin
patch string serial.Serial.open
patch string serial.Serial.flushInput
set cgs = patch string pysds011.driver.SDS011.cmd_get_sleep
set runner = call CliRunner
set result = call invoke main list string --id string ABCD string sleep
call assert_called_once_with id=b'\xab\xcd'
ass... | def test_slepp_get_at_id(mocker):
mocker.patch('serial.Serial.open')
mocker.patch('serial.Serial.flushInput')
cgs = mocker.patch('pysds011.driver.SDS011.cmd_get_sleep')
runner = CliRunner()
result = runner.invoke(main, ['--id', 'ABCD', 'sleep'])
cgs.assert_called_once_with(id=b'\xab\xcd')
a... | Python | nomic_cornstack_python_v1 |
class Solution extends object
begin
function removeDuplicates self S
begin
set stack = list
for x in S
begin
if stack == list or stack at - 1 != x
begin
append stack x
end
else
begin
pop stack
end
end
return join string stack
end function
end class
if __name__ == string __main__
begin
set solution = call Solution
se... | class Solution(object):
def removeDuplicates(self, S):
stack = []
for x in S:
if stack == [] or stack[-1] != x:
stack.append(x)
else:
stack.pop()
return "".join(stack)
if __name__ == "__main__":
solution = Solution()
S = "abbac... | Python | zaydzuhri_stack_edu_python |
function words self
begin
string Return a list of word tokens. This excludes punctuation characters. If you want to include punctuation characters, access the ``tokens`` property. :returns: A :class:`WordList <WordList>` of word tokens.
return call WordList call word_tokenize raw tokenizer include_punc=false
end functi... | def words(self):
"""Return a list of word tokens. This excludes punctuation characters.
If you want to include punctuation characters, access the ``tokens``
property.
:returns: A :class:`WordList <WordList>` of word tokens.
"""
return WordList(
word_tokenize... | Python | jtatman_500k |
from threading import Lock
set _building_services = set
set _building_services_lock = lock
function new_building_service service_name
begin
comment true: ok
comment false: service already exists
with _building_services_lock
begin
if service_name in _building_services
begin
return false
end
else
begin
add _building_serv... | from threading import Lock
_building_services = set()
_building_services_lock = Lock()
def new_building_service(service_name: str) -> bool:
# true: ok
# false: service already exists
with _building_services_lock:
if service_name in _building_services:
return False
else:
... | Python | zaydzuhri_stack_edu_python |
function wished_size self
begin
return __wished_size
end function | def wished_size(self):
return self.__wished_size | Python | nomic_cornstack_python_v1 |
function get_words wordlist minimum count
begin
comment Create the empty list object for the sublist
set selection = list
comment Launch a loop. This loop will continue all the time the length of the sublist (selection) is less that the number of items we want in that list (count)
while length selection < count
begin
... | def get_words(wordlist, minimum, count):
# Create the empty list object for the sublist
selection = []
# Launch a loop. This loop will continue all the time the length of the sublist (selection) is less that the number of items we want in that list (count)
while len(selection) < count:
# Get a r... | Python | nomic_cornstack_python_v1 |
function __new__ *args **kwargs
begin
Ellipsis
end function | def __new__(*args, **kwargs):
... | Python | nomic_cornstack_python_v1 |
function to_str self
begin
return call pformat call to_dict
end function | def to_str(self):
return pprint.pformat(self.to_dict()) | Python | nomic_cornstack_python_v1 |
function add_file folder filename contents bucket
begin
if call get_key name
begin
set path = format string {0}/{1} name filename
set key = call new_key path
return call set_contents_from_string contents
end
end function | def add_file(folder, filename, contents, bucket):
if bucket.get_key(folder.name):
path = "{0}/{1}".format(folder.name, filename)
key = bucket.new_key(path)
return key.set_contents_from_string(contents) | Python | nomic_cornstack_python_v1 |
import random
import matplotlib.pyplot as plt
import matplotlib as mpl
set Y = list
append Y list comprehension random integer 0 40 for i in range 50
set x = list
append x list comprehension 0.1 * i for i in range 50
set x1 = list
append x1 list comprehension 0.1 * i for i in range 50
remove x1 at 0 0
remove x1 at 0... | import random
import matplotlib.pyplot as plt
import matplotlib as mpl
Y=[]
Y.append([random.randint(0,40) for i in range(50)])
x=[]
x.append([0.1*i for i in range(50)])
x1=[]
x1.append([0.1*i for i in range(50)])
x1[0].remove(0)
x1[0].remove(1)
def scs(Y): #расчёт скользящего среднего
Ys=[]
a=0
... | Python | zaydzuhri_stack_edu_python |
string # amaliy mashg'ulot. 2-masala #butun sonlardan iborat ruyxat berilgan.juftlarini ekranga chiqarish. sonlar = [1, 2, 3, 4, 5, 6, 7, 8] for son in sonlar: if son % 2 ==0: print(sonlar) #3-masala. butun sonlardan iborat ruyxat berilgan. oldin juftlarini keyin toqlarini yangi ruyxatga # o'zlashtirib konsulga chiqari... | """# amaliy mashg'ulot. 2-masala
#butun sonlardan iborat ruyxat berilgan.juftlarini ekranga chiqarish.
sonlar = [1, 2, 3, 4, 5, 6, 7, 8]
for son in sonlar:
if son % 2 ==0:
print(sonlar)
#3-masala. butun sonlardan iborat ruyxat berilgan. oldin juftlarini keyin toqlarini yangi ruyxatga
# o'zlashtirib konsulga... | Python | zaydzuhri_stack_edu_python |
function sumar a b
begin
set c = a + b
return c
end function
print string sumaremos 2 numeros enteros
set x = input string Ingrese el primer numero:
set y = input string Ingrese el segundo numero:
try
begin
set x = integer x
set y = integer y
call sumar x y
print string el resultado de la suma es call sumar x y
end
exc... | def sumar(a,b):
c = a + b
return c
print("sumaremos 2 numeros enteros")
x=input("Ingrese el primer numero: ")
y=input("Ingrese el segundo numero: ")
try :
x = int(x)
y = int(y)
sumar(x,y)
print("el resultado de la suma es", sumar(x,y))
except :
print("no ingreso un numero entero")
| Python | zaydzuhri_stack_edu_python |
function decodeBy key hex
begin
return join string generator expression character bit ? key for bit in call fromhex hex
end function
function total_score key hex
begin
set tuple score decode = tuple 0.0 call decodeBy key hex
for c in decode
begin
if lower c in scores
begin
set score = score + scores at lower c
end
end... | def decodeBy(key, hex):
return ''.join(chr(bit^key) for bit in bytes.fromhex(hex))
def total_score(key, hex):
score, decode = 0.0, decodeBy(key, hex)
for c in decode:
if c.lower() in scores:
score += scores[c.lower()]
return score, decode
def findKey(hex):
return ma... | Python | zaydzuhri_stack_edu_python |
function project_set_cpu_type self target_type=none
begin
set system_block = find self string system_block
call set_module_info dict string cpu dict string cpu_type target_type
end function | def project_set_cpu_type(self, target_type=None):
system_block = self.find('system_block')
system_block.set_module_info({'cpu': {'cpu_type': target_type}}) | Python | nomic_cornstack_python_v1 |
function EvaluateScore X_train X_test y_train y_test parModel scoring=string default pw=false
begin
set model = call SelectModel keyword parModel
fit model X_train y_train
set y_pred = predict model X_test
if scoring == string default
begin
set score = score model X_test y_test
end
else
if scoring == string kt
begin
if... | def EvaluateScore(X_train, X_test, y_train, y_test, parModel, scoring='default', pw=False):
model = SelectModel(**parModel)
model.fit(X_train,y_train)
y_pred = model.predict(X_test)
if scoring == 'default':
score = model.score(X_test,y_test)
elif scoring == 'kt':
if pw is T... | Python | nomic_cornstack_python_v1 |
for i in range length materias - 1 - 1 - 1
begin
set cal = decimal input string ¿Qué nota has sacado en + materias at i + string ?
if cal >= 6
begin
pop materias i
end
end
print string Tienes que repetir + string materias | for i in range(len(materias)-1, -1, -1):
cal = float(input("¿Qué nota has sacado en " + materias[i] + "?"))
if cal >= 6:
materias.pop(i)
print("Tienes que repetir " + str(materias)) | Python | zaydzuhri_stack_edu_python |
function FindMaximumPhase FFT
begin
if FFT <= 0
begin
set maxPhase = absolute FFT
end
else
begin
set maxPhase = 360 - FFT
end
end function | def FindMaximumPhase(FFT):
if FFT <= 0:
maxPhase=abs(FFT)
else:
maxPhase=360-FFT
| Python | nomic_cornstack_python_v1 |
function get_task self task_id
begin
return tasks at task_id
end function | def get_task(self, task_id: int) -> dict:
return self.tasks[task_id] | Python | nomic_cornstack_python_v1 |
import time
import gc
sleep 0.1
set a = list 11 22 33
set b = a
comment c = (a, b)
comment e = c
print call id a
print call id b
comment print(id(c))
comment print(id(e))
if a == b
begin
print string 123
end
if a is b
begin
print string 123
end
set c = 99999
set d = 99999
print call id c
print call id d
if c is d
begin... | import time
import gc
time.sleep(0.1)
a = [11, 22, 33]
b = a
# c = (a, b)
# e = c
print(id(a))
print(id(b))
# print(id(c))
# print(id(e))
if a == b:
print("123")
if a is b:
print("123")
c = 99999
d = 99999
print(id(c))
print(id(d))
if c is d:
print("========")
def login(func):
def temp():
... | Python | zaydzuhri_stack_edu_python |
comment ---------------------------------------------------
comment * ในการทำงานบางอย่างที่ต้องการทำงานซ้ำๆ เราสามารถสร้างเป็น Function ได้
comment * Python มี Build in function มากมาย
comment * ตัวยอย่างของ Build in function
comment ---------------------------------------------------
print string abc
length string abc... | #---------------------------------------------------
#* ในการทำงานบางอย่างที่ต้องการทำงานซ้ำๆ เราสามารถสร้างเป็น Function ได้
#* Python มี Build in function มากมาย
#* ตัวยอย่างของ Build in function
#---------------------------------------------------
print('abc')
len('abc')
#------------------------------------------... | Python | zaydzuhri_stack_edu_python |
comment !/usr/bin/python
comment Copyright (c) 2011 The Native Client Authors. All rights reserved.
comment Use of this source code is governed by a BSD-style license that can be
comment found in the LICENSE file.
import os
import posixpath
import sys
function SimpleTar src dst
begin
string Tar a directory in a simple ... | #!/usr/bin/python
# Copyright (c) 2011 The Native Client Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
import os
import posixpath
import sys
def SimpleTar(src, dst):
"""Tar a directory in a simple format.
Arguments:
src: s... | Python | zaydzuhri_stack_edu_python |
function get_status self
begin
try
begin
call get_instance_group_configs
end
except HttpError as e
begin
set error_reason = call _get_reason
print error_reason
comment if instance is not found, it has a NOTEXISTS status
if string not found in error_reason
begin
return NOTEXISTS
end
else
begin
raise e
end
end
return cal... | def get_status(self):
try:
self.get_instance_group_configs()
except HttpError as e:
error_reason = e._get_reason()
print(error_reason)
# if instance is not found, it has a NOTEXISTS status
if 'not found' in error_reason:
return ... | Python | nomic_cornstack_python_v1 |
function get_hwmon_dir architecture
begin
set hwmons = list directory string /sys/class/hwmon
for hwmon in hwmons
begin
set name_file = open string /sys/class/hwmon/ + hwmon + string /name
set name = strip read name_file
if name == string coretemp or name == string cpu_thermal
begin
comment The name file seems to alway... | def get_hwmon_dir(architecture):
hwmons = listdir("/sys/class/hwmon")
for hwmon in hwmons:
name_file = open("/sys/class/hwmon/" + hwmon + "/name")
name = name_file.read().strip()
if(name == "coretemp" or name == "cpu_thermal"):
# The name file seems to always... | Python | nomic_cornstack_python_v1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.