code stringlengths 10 2.58M | original_code stringlengths 3 3.18M | original_language stringclasses 1
value | source stringclasses 7
values |
|---|---|---|---|
async function approve self ctx query_id mode=string idol
begin
if mode == string group
begin
comment get the query
set group = await call fetchrow string SELECT groupname, debutdate, disbanddate, description, twitter, youtube, melon, instagram, vlive, spotify, fancafe, facebook, tiktok, fandom, company, website, thumb... | async def approve(self, ctx, query_id: int, mode="idol"):
if mode == "group":
# get the query
group = await ex.conn.fetchrow("""SELECT groupname, debutdate, disbanddate, description, twitter, youtube,
melon, instagram, vlive, spotify, fancafe, facebook, tiktok, fandom, compa... | Python | nomic_cornstack_python_v1 |
function create_grid
begin
return list list string . string . string . list string . string . string . list string . string . string .
end function | def create_grid():
return [['.', '.', '.'], ['.', '.', '.'], ['.', '.', '.']] | Python | nomic_cornstack_python_v1 |
function from_batch self batch_name include=string identity text_key=list apply_edits=true additions=string variables
begin
function _apply_edits_rules ds name b_meta
begin
if call is_array name and get b_meta name
begin
set _meta at string masks at name = b_meta at name
try
begin
set _meta at string lib at string val... | def from_batch(self, batch_name, include='identity', text_key=[],
apply_edits=True, additions='variables'):
def _apply_edits_rules(ds, name, b_meta):
if ds.is_array(name) and b_meta.get(name):
ds._meta['masks'][name] = b_meta[name]
try:
... | Python | nomic_cornstack_python_v1 |
function _get_home_folder_contents self
begin
set tuple subfolders files = call _get_subfolders_and_files_separately home_folder
set subfolders = sorted subfolders key=lambda item -> item at string title
set files = sorted files key=lambda item -> item at string title
return tuple subfolders files
end function | def _get_home_folder_contents(self):
subfolders, files = self._get_subfolders_and_files_separately(self.home_folder)
subfolders = sorted(subfolders, key = lambda item: item['title'])
files = sorted(files, key = lambda item: item['title'])
return subfolders, files | Python | nomic_cornstack_python_v1 |
function rp1_to_s1 v
begin
set tuple x y = tuple v at 0 v at 1
return call row_stack list 2 * x * y / x * x + y * y x * x - y * y / x * x + y * y
end function | def rp1_to_s1(v):
x, y = v[0], v[1]
return np.row_stack([
2*x*y / (x*x + y*y),
(x*x - y*y) / (x*x + y*y)
]) | Python | nomic_cornstack_python_v1 |
function print_status_info self current_room
begin
print string In room { current_room at string room_id } . Current cooldown: { cooldown } Inventory: { if expression items_ then join string , list comprehension item at string name at slice : - 9 : for item in items_ else string None } Players in room: { if expressio... | def print_status_info(self, current_room: dict) -> None:
print(f'\nIn room {current_room["room_id"]}. \nCurrent cooldown: {self.cooldown}'
f'\nInventory: {", ".join([item["name"][:-9] for item in self.items_]) if self.items_ else "None"} '
f'\nPlayers in room: {", ".join(current_room... | Python | nomic_cornstack_python_v1 |
function compute_cross_topic_learning experiments max_votes iterations experiment_data **kw
begin
set frames = list
for cfg in experiments
begin
if nx_graph
begin
info string Sampling from NetworkX graph.
set graphs_by_topic_id = topic_id_to_nx_graph
end
else
begin
info string Sampling from regular graph.
set graphs_b... | def compute_cross_topic_learning(experiments: Sequence[ExperimentConfig],
max_votes: int,
iterations: int,
experiment_data: ExperimentData,
**kw):
frames = []
for cfg in experiment... | Python | nomic_cornstack_python_v1 |
function __str__ self
begin
return format self
end function | def __str__(self):
return self.format() | Python | nomic_cornstack_python_v1 |
function on_save self event
begin
set img = images at current_image
call get_image img
end function | def on_save(self, event):
img = self.panel.images[self.panel.current_image]
self.panel.get_image(img) | Python | nomic_cornstack_python_v1 |
import argparse
import json
import io
from face_detector.trainers.face_trainer_eigen import EigenFaceTrainer
from face_detector.trainers.face_trainer_fisher import FisherFaceTrainer
from face_detector.recognizers.face_recognizer_eigen import EigenFacesRecognizer
from face_detector.recognizers.face_recognizer_fisher imp... | import argparse
import json
import io
from face_detector.trainers.face_trainer_eigen import EigenFaceTrainer
from face_detector.trainers.face_trainer_fisher import FisherFaceTrainer
from face_detector.recognizers.face_recognizer_eigen import EigenFacesRecognizer
from face_detector.recognizers.face_recognizer_fisher imp... | Python | zaydzuhri_stack_edu_python |
function __init__ self num pauli_terms
begin
call __init__ num
set _pauli_terms = deep copy pauli_terms
end function | def __init__(self, num: int, pauli_terms: str):
super().__init__(num)
self._pauli_terms = deepcopy(pauli_terms) | Python | nomic_cornstack_python_v1 |
from client_sender import ClientSender
from constant import QueryType
import time
import test
import sys
import math
import random
import string
comment you should put the IPs of replicas in the hosts
set hosts = list string 155.98.39.45 string 155.98.39.55 string 155.98.39.46
set sender = call ClientSender hosts
set r... | from client_sender import ClientSender
from constant import QueryType
import time
import test
import sys
import math
import random
import string
# you should put the IPs of replicas in the hosts
hosts = ['155.98.39.45', '155.98.39.55', '155.98.39.46']
sender = ClientSender(hosts)
replica_num = 3
def replica_selecti... | Python | zaydzuhri_stack_edu_python |
comment from dailycodingproblem.com
comment Daily Challenge #69
comment Given a list of integers, return the largest product that can be made by multiplying any three integers.
comment For example, if the list is [-10, -10, 5, 2], we should return 500, since that's -10 * -10 * 5. | # from dailycodingproblem.com
#
# Daily Challenge #69
# Given a list of integers, return the largest product that can be made by multiplying any three integers.
#
# For example, if the list is [-10, -10, 5, 2], we should return 500, since that's -10 * -10 * 5.
| Python | zaydzuhri_stack_edu_python |
comment Обход дерева каталогов, отбор файлов с расширением .txt
comment и копирование этих файлов в новую папку
import os
import sys
import glob
import shutil
function copy_files from_dir_path to_dir_path ext
begin
set mask = from_dir_path + string /**/* + ext
set files = glob glob mask recursive=true
for file in files... | # Обход дерева каталогов, отбор файлов с расширением .txt
# и копирование этих файлов в новую папку
import os
import sys
import glob
import shutil
def copy_files(
from_dir_path: str,
to_dir_path: str,
ext: str
):
mask = from_dir_path + "/**/*" + ext
files = glob.glob(mask, recursive=T... | Python | zaydzuhri_stack_edu_python |
function test_user_change_page self
begin
set url = reverse string admin:qualiCar_API_userprofile_change args=list id
set response = get client url
assert equal status_code 200
end function | def test_user_change_page (self):
url = reverse ('admin:qualiCar_API_userprofile_change', args = [self.user.id])
response = self.client.get (url)
self.assertEqual (response.status_code, 200) | Python | nomic_cornstack_python_v1 |
function plot_spectrum self
begin
set tuple fig ax = call subplots figsize=tuple 6 6
set photons = values
set combine = photons at slice 0 : : 2 + photons at slice 1 : : 2
set elow = values at slice 0 : : 2
set ehigh = values at slice 0 : : 2
plot ehigh combine ls=string steps lw=2
comment vertical line for first b... | def plot_spectrum(self):
fig, ax = plt.subplots(figsize=(6,6))
photons = self.df.photons.values
combine = photons[0::2]+photons[1::2]
elow = self.df.emin.values[0::2]
ehigh = self.df.emax.values[0::2]
ax.plot(ehigh, combine, ls='steps', lw=2)
ax.plot([elow[0],elow... | Python | nomic_cornstack_python_v1 |
comment В Англии валютой являются фунты стерлингов £ и пенсы p, и в обращении есть восемь монет:
comment 1p, 2p, 5p, 10p, 20p, 50p, £1 (100p) и £2 (200p).
comment £2 возможно составить следующим образом:
comment 1×£1 + 1×50p + 2×20p + 1×5p + 1×2p + 3×1p
comment Сколькими разными способами можно составить £2, используя ... | # В Англии валютой являются фунты стерлингов £ и пенсы p, и в обращении есть восемь монет:
#
# 1p, 2p, 5p, 10p, 20p, 50p, £1 (100p) и £2 (200p).
# £2 возможно составить следующим образом:
#
# 1×£1 + 1×50p + 2×20p + 1×5p + 1×2p + 3×1p
# Сколькими разными способами можно составить £2, используя любое количество монет?
#
... | Python | zaydzuhri_stack_edu_python |
import sys
function SetRow board row val
begin
for x in range 256
begin
set board at row at x = val
end
return board
end function
function SetCol board col val
begin
for x in range 256
begin
set board at x at col = val
end
return board
end function
function QueryRow board row
begin
set sum = 0
for x in range 256
begin
... | import sys
def SetRow(board, row, val):
for x in range(256):
board[row][x] = val
return board
def SetCol(board, col, val):
for x in range(256):
board[x][col] = val
return board
def QueryRow(board, row):
sum = 0
for x in range(256):
sum = sum + board[row][x] | Python | zaydzuhri_stack_edu_python |
function indices cls hierarchical_dict indices
begin
set new_dict = dict
set all_keys = call get_all_keys hierarchical_dict
for key in all_keys
begin
set value = get cls hierarchical_dict key
if is instance value ndarray or is instance value Tensor
begin
set new_value = value at indices
end
else
if is instance value S... | def indices(cls, hierarchical_dict: dict, indices: List[int]) -> dict:
new_dict = {}
all_keys = cls.get_all_keys(hierarchical_dict)
for key in all_keys:
value = cls.get(hierarchical_dict, key)
if isinstance(value, numpy.ndarray) or isinstance(value, torch.Tensor):
... | Python | nomic_cornstack_python_v1 |
function find_max nums
begin
set temp = none
if is instance nums list
begin
for num in nums
begin
if temp is none
begin
set temp = num
end
else
if num > temp
begin
set temp = num
end
end
return temp
end
else
begin
print string Please enter a list
return none
end
end function
print call find_max list_comp
print call fin... | def find_max(nums):
temp = None
if isinstance(nums, list):
for num in nums:
if temp is None:
temp = num
elif num>temp:
temp = num
return temp
else:
print("Please enter a list")
return None
print(find_max(list_comp))
pri... | Python | zaydzuhri_stack_edu_python |
function get_ai_models self _id typeof
begin
set api_url = string http:// + credentials at string server at string host + string / + credentials at string hiascdi at string endpoint + string /entities/ + _id + string ?type= + typeof + string &attrs=models
set response = get requests api_url headers=headers auth=auth
re... | def get_ai_models(self, _id, typeof):
api_url = "http://" + self.helpers.credentials["server"]["host"] + "/" + \
self.helpers.credentials["hiascdi"]["endpoint"] + \
"/entities/" + _id + "?type=" + typeof + "&attrs=models"
response = requests.get(api_url, headers... | Python | nomic_cornstack_python_v1 |
function _parse_query self source
begin
string Parse one of the rules as either objectfilter or dottysql. Example: _parse_query("5 + 5") # Returns Sum(Literal(5), Literal(5)) Arguments: source: A rule in either objectfilter or dottysql syntax. Returns: The AST to represent the rule.
if search source
begin
set syntax_ =... | def _parse_query(self, source):
"""Parse one of the rules as either objectfilter or dottysql.
Example:
_parse_query("5 + 5")
# Returns Sum(Literal(5), Literal(5))
Arguments:
source: A rule in either objectfilter or dottysql syntax.
Returns:
... | Python | jtatman_500k |
function itkApproximateSignedDistanceMapImageFilterID3ID3_cast *args
begin
return call itkApproximateSignedDistanceMapImageFilterID3ID3_cast *args
end function | def itkApproximateSignedDistanceMapImageFilterID3ID3_cast(*args):
return _itkApproximateSignedDistanceMapImageFilterPython.itkApproximateSignedDistanceMapImageFilterID3ID3_cast(*args) | Python | nomic_cornstack_python_v1 |
comment -*- coding: utf-8 -*-
string 01/19/2018 Description: extract and plot met and orad wdms if there are negative values in them Input(s): .wdm Output(s): .txt and .png files @author: aseck@icprb.org Things To improve: create figures folders if they do not exist and use arrays for the met and prad variables
comment... | # -*- coding: utf-8 -*-
"""
01/19/2018
Description: extract and plot met and orad wdms if there are negative values
in them
Input(s): .wdm
Output(s): .txt and .png files
@author: aseck@icprb.org
Things To improve: create figures folders if
they do not exist and use arrays
for the met and prad variables
"""
#----... | Python | zaydzuhri_stack_edu_python |
function train_from_data esp_service experiment_params training_data_file batch_size=1 epochs=1000 verbose=1
begin
set network_params = experiment_params at string network
set output_layers = network_params at string outputs
set output_names = list comprehension output_layer at string name for output_layer in output_la... | def train_from_data(esp_service, experiment_params, training_data_file, batch_size=1, epochs=1000, verbose=1):
network_params = experiment_params['network']
output_layers = network_params['outputs']
output_names = [output_layer['name'] for output_layer in output_layers]
# Create a model... | Python | nomic_cornstack_python_v1 |
class tax
begin
function __int__ self name gross_income dependents
begin
set name = name
set dependents = dependents
set gross_income = gross_income
end function
function tcalc self
begin
set total = gross_income - 10000 - 2000 * dependents
set intax = total * 0.2
return intax
end function
end class | class tax:
def __int__(self, name, gross_income, dependents):
self.name = name
self.dependents = dependents
self.gross_income = gross_income
def tcalc(self):
total = self.gross_income - 10000 - 2000 * self.dependents
intax = total * 0.2
return... | Python | zaydzuhri_stack_edu_python |
function sq_dist2 self sq1 sq2
begin
set rct1 = list nodes at sq1 at string x nodes at sq1 at string y nodes at sq1 at string width nodes at sq1 at string height
set rct2 = list nodes at sq2 at string x nodes at sq2 at string y nodes at sq2 at string width nodes at sq2 at string height
comment rct2 = [1,5,2,3]
comment ... | def sq_dist2(self, sq1, sq2):
rct1 = [self.g.nodes[sq1]['x'], self.g.nodes[sq1]['y'], self.g.nodes[sq1]['width'], self.g.nodes[sq1]['height']]
rct2 = [self.g.nodes[sq2]['x'], self.g.nodes[sq2]['y'], self.g.nodes[sq2]['width'], self.g.nodes[sq2]['height']]
# rct2 = [1,5,2,3]
# rct1 = [4,... | Python | nomic_cornstack_python_v1 |
function test_Line
begin
set name = string test_Line
add model name
set coords = list tuple 0.0 0.0 tuple 0.0 2.5 tuple SR2 SR2
set mesh_size = list 0.1 0.1 0.01
set coords = list comprehension array c for c in coords
set pts = list comprehension call Point c m_s for tuple c m_s in zip coords mesh_size
set lines = list... | def test_Line():
name = "test_Line"
gmsh.model.add(name)
coords = [(0.0, 0.0), (0.0, 2.5), (SR2, SR2)]
mesh_size = [0.1, 0.1, 0.01]
coords = [np.array(c) for c in coords]
pts = [geo.Point(c, m_s) for c, m_s in zip(coords, mesh_size)]
lines = [geo.Line(pts[0], pts[1]), geo.Line(pts[0], pts[... | Python | nomic_cornstack_python_v1 |
comment 298. Binary Tree Longest Consecutive Sequence
comment Given a binary tree, find the length of the longest consecutive sequence path.
comment The path refers to any sequence of nodes from some starting node to any node in the
comment tree along the parent-child connections. The longest consecutive path need to b... | # 298. Binary Tree Longest Consecutive Sequence
#
# Given a binary tree, find the length of the longest consecutive sequence path.
#
# The path refers to any sequence of nodes from some starting node to any node in the
# tree along the parent-child connections. The longest consecutive path need to be from
# parent to c... | Python | zaydzuhri_stack_edu_python |
function levelup self levelsAwarded victim=0 reason=string
begin
comment Return false if we can't level up
if levelup
begin
return false
end
comment Calculate the new level
set newLevel = level + integer levelsAwarded
comment TODO: Winner check would be good for the callback method of eventlib
comment See if we have a ... | def levelup(self, levelsAwarded, victim=0, reason=''):
# Return false if we can't level up
if self.preventlevel.levelup:
return False
# Calculate the new level
newLevel = self.level + int(levelsAwarded)
# TODO: Winner check would be good for the callback met... | Python | nomic_cornstack_python_v1 |
comment coding: utf-8
import os
import re
import requests
from collections import OrderedDict
from csv import DictReader
from conversions import ft2m
set ROOT_DIR = directory name path directory name path directory name path absolute path path __file__
set AIRPORTS_FILE = join path ROOT_DIR string data string airports.... | # coding: utf-8
import os
import re
import requests
from collections import OrderedDict
from csv import DictReader
from .conversions import ft2m
ROOT_DIR = os.path.dirname(os.path.dirname(os.path.dirname(
os.path.abspath(__file__))))
AIRPORTS_FILE = os.path.join(ROOT_DIR, 'data', 'airports.csv')
RUNWAYS_FILE = o... | Python | zaydzuhri_stack_edu_python |
function test_number_transitions self
begin
set transition_function = call NondeterministicTransitionFunction
assert equal call get_number_transitions 0
set s_from = call State 0
set s_to = call State 1
set s_to_bis = call State 2
set symb_by = call Symbol string a
set symb_by2 = call Symbol string b
call add_transitio... | def test_number_transitions(self):
transition_function = NondeterministicTransitionFunction()
self.assertEqual(transition_function.get_number_transitions(), 0)
s_from = State(0)
s_to = State(1)
s_to_bis = State(2)
symb_by = Symbol("a")
symb_by2 = Symbol("b")
... | Python | nomic_cornstack_python_v1 |
function bucket_type self
begin
comment type: (...) -> BucketType
return get self string bucket_type
end function | def bucket_type(self):
# type: (...) -> BucketType
return self.get('bucket_type') | Python | nomic_cornstack_python_v1 |
function GetElementName self
begin
set callResult = call _Call string GetElementName
if callResult is none
begin
return none
end
return callResult
end function | def GetElementName(self):
callResult = self._Call("GetElementName", )
if callResult is None:
return None
return callResult | Python | nomic_cornstack_python_v1 |
function image_upload_url recipe_id
begin
return reverse string recipe:recipe-upload-image args=list recipe_id
end function | def image_upload_url(recipe_id):
return reverse('recipe:recipe-upload-image', args=[recipe_id]) | Python | nomic_cornstack_python_v1 |
async function survival self
begin
set path = format string /players/{}/survival_mastery id
set resp = await get requests path=path
return call Survival resp
end function | async def survival(self):
path = "/players/{}/survival_mastery".format(self.id)
resp = await self.client.requests.get(path=path)
return Survival(resp) | Python | nomic_cornstack_python_v1 |
comment !/usr/bin/python3
string TEST TEST TEST essah sssah saah... Fine it's working
from console import HBNBCommand
from unittest.mock import patch
import os , sys
from io import StringIO
from unittest import TestCase
class TestConsole extends TestCase
begin
string test for console
function tst self
begin
string unit... | #!/usr/bin/python3
"""TEST TEST TEST essah sssah saah...
Fine it's working"""
from console import HBNBCommand
from unittest.mock import patch
import os, sys
from io import StringIO
from unittest import TestCase
class TestConsole(TestCase):
"""test for console"""
def tst(self):
"""unitest"""
pa... | Python | zaydzuhri_stack_edu_python |
function distance strand_a strand_b
begin
string Interesting solution using zip(): http://exercism.io/submissions/74655d216b42445c86bb98cf818d23ee
if length strand_a != length strand_b
begin
raise call ValueError string Inputs are not same distance
end
set distance = 0
for tuple i v in enumerate strand_a
begin
if stran... | def distance(strand_a, strand_b):
"""
Interesting solution using zip(): http://exercism.io/submissions/74655d216b42445c86bb98cf818d23ee
"""
if len(strand_a) != len(strand_b):
raise ValueError('Inputs are not same distance')
distance = 0
for i, v in enumerate(strand_a):
if strand... | Python | zaydzuhri_stack_edu_python |
import numpy as np
import pandas as pd
import os
from pandas2arff import pandas2arff
from sklearn.preprocessing import StandardScaler
from scipy.io import arff
from scipy import optimize
from sklearn.neural_network import MLPRegressor
from sklearn.model_selection import GridSearchCV
from sklearn.pipeline import Pipelin... | import numpy as np
import pandas as pd
import os
from pandas2arff import pandas2arff
from sklearn.preprocessing import StandardScaler
from scipy.io import arff
from scipy import optimize
from sklearn.neural_network import MLPRegressor
from sklearn.model_selection import GridSearchCV
from sklearn.pipeline import Pipelin... | Python | zaydzuhri_stack_edu_python |
function getTamX self
begin
return tamX
end function | def getTamX(self):
return self.tamX | Python | nomic_cornstack_python_v1 |
string Open the file romeo.txt and read it line by line. For each line, split the line into a list of words using the split() method. The program should build a list of words. For each word on each line check to see if the word is already in the list and if not append it to the list. When the program completes, sort an... | """ Open the file romeo.txt and read it line by line. For each line, split the line into a list of words using the split() method. The program should build a
list of words. For each word on each line check to see if the word is already in the list and if not append it to the list.
When the program completes, sort and... | Python | zaydzuhri_stack_edu_python |
function player_pos self
begin
return _player_pos
end function | def player_pos(self):
return self._player_pos | Python | nomic_cornstack_python_v1 |
async function create_bot_command_cache self
begin
set custom_commands = dict
for tuple server_id command_name message in await call fetch_custom_commands
begin
comment bare yield
await sleep 0
set cache_info = get custom_commands server_id
if cache_info
begin
set cache_info at command_name = message
end
else
begin
se... | async def create_bot_command_cache(self):
self.ex.cache.custom_commands = {}
for server_id, command_name, message in await self.ex.sql.s_customcommands.fetch_custom_commands():
await asyncio.sleep(0) # bare yield
cache_info = self.ex.cache.custom_commands.get(server_id)
... | Python | nomic_cornstack_python_v1 |
comment -*- coding:UTF-8 -*-
comment 这个程序用来爬去b站视频中播放量过10w的av号
from pymongo import MongoClient
import Math
import files
import time
import requests
comment 数据库的连接
set client = call MongoClient string localhost 27017
set db = bilibili
comment collection
set bilibili_video = video
set VIDEO_NOT_EXIST = - 1
set REQUEST_ERR... | # -*- coding:UTF-8 -*-
# 这个程序用来爬去b站视频中播放量过10w的av号
from pymongo import MongoClient
import Math
import files
import time
import requests
# 数据库的连接
client = MongoClient('localhost', 27017)
db = client.bilibili
bilibili_video = db.video # collection
VIDEO_NOT_EXIST = -1
REQUEST_ERROR = -999
def get_video_views(vide... | Python | zaydzuhri_stack_edu_python |
function frequency self
begin
return get pulumi self string frequency
end function | def frequency(self) -> str:
return pulumi.get(self, "frequency") | Python | nomic_cornstack_python_v1 |
import pandas as pd
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import LabelEncoder
from sklearn.linear_model import SGDClassifier
set columns = list string class string cap-shape string cap-surface string cap-color string bruises string odor string gill-attachment string gill-spacin... | import pandas as pd
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import LabelEncoder
from sklearn.linear_model import SGDClassifier
columns = [
'class', 'cap-shape', 'cap-surface', 'cap-color', 'bruises', 'odor', 'gill-attachment', 'gill-spacing', 'gill-size', 'gill-color', 'stalk... | Python | zaydzuhri_stack_edu_python |
comment Python Program for Radix Sort
comment 1) Do the following for each digit i where i varies from the least significant digit to the most significant digit.
comment Sort input array using counting sort (or any stable sort) according to the i\’th digit.
function countingSort arr exp1
begin
set n = length arr
set ou... | # Python Program for Radix Sort
# 1) Do the following for each digit i where i varies from the least significant digit to the most significant digit.
# Sort input array using counting sort (or any stable sort) according to the i\’th digit.
def countingSort(arr, exp1):
n = len(arr)
output = [0] * (n... | Python | zaydzuhri_stack_edu_python |
comment Starter code for Homework 4
comment %%
comment Import the modules we will use
import os
import numpy as np
import pandas as pd
import earthpy as et
import matplotlib.pyplot as plt
comment %%
comment ** MODIFY **
comment Set the file name and path to where you have stored the data
set filename = string streamflo... | # Starter code for Homework 4
# %%
# Import the modules we will use
import os
import numpy as np
import pandas as pd
import earthpy as et
import matplotlib.pyplot as plt
# %%
# ** MODIFY **
# Set the file name and path to where you have stored the data
filename = 'streamflow_week5.txt'
datapath = 'C:/Users/xy_22/Docu... | Python | zaydzuhri_stack_edu_python |
function read_float data
begin
set s_type = string =%s % call get_type string float
return call unpack s_type read data 4 at 0
end function | def read_float(data):
s_type = "=%s" % get_type("float")
return struct.unpack(s_type, data.read(4))[0] | Python | nomic_cornstack_python_v1 |
while true
begin
try
begin
set user = input string Введите радиус окружности?
if user == string Прекрати
begin
break
end
comment radius of circle
set r = decimal user
set p = 3.14
set area = r * r * p
set perimeter = r * 2 * p
print string Площадь окружности area
print string Периметр perimeter
end
except any
begin
pri... | while True:
try:
user=input ("Введите радиус окружности? ")
if user=='Прекрати': break
r=float (user) #radius of circle
p=3.14
area=r*r*p
perimeter=r*2*p
print ("Площадь окружности", area)
print ("Периметр", perimeter)
except:
print ('Радиу... | Python | zaydzuhri_stack_edu_python |
function check_in_line self output expected_entries pattern=compile string \s
begin
set output_strip = list comprehension sub string line for line in call splitlines
for elem in expected_entries
begin
assert any generator expression sub string elem in line for line in output_strip msg format string Not found: {} in: ... | def check_in_line(self, output, expected_entries,
pattern=re.compile(r"\s")):
output_strip = [pattern.sub("", line) for line in output.splitlines()]
for elem in expected_entries:
assert any(
pattern.sub("", elem) in line for line in output_strip), \
... | Python | nomic_cornstack_python_v1 |
import imageio
import numpy as np
from matplotlib import lines as line
from matplotlib import pyplot as plt
from scipy.integrate import odeint
from matplotlib.lines import Line2D
set im = call imread string potential.png
set k = zeros tuple 100 100
set black = list 0 0 0
set blue = list 11 210 239
set red = list 255 0 ... | import imageio
import numpy as np
from matplotlib import lines as line
from matplotlib import pyplot as plt
from scipy.integrate import odeint
from matplotlib.lines import Line2D
im = imageio.imread('potential.png')
k=np.zeros((100,100))
black=[0,0,0]
blue=[11,210,239]
red=[255,0,0]
green=[11,148,1]
i=0
j=0
for y in i... | Python | zaydzuhri_stack_edu_python |
import torch.nn as nn
class DQN extends Module
begin
function __init__ self input_dim output_dim hidden_dim
begin
string DQN Network Args: input_dim (int): `state` dimension. `state` is 2-D tensor of shape (n, input_dim) output_dim (int): Number of actions. Q_value is 2-D tensor of shape (n, output_dim) hidden_dim (int... | import torch.nn as nn
class DQN(nn.Module):
def __init__(self, input_dim: int, output_dim: int, hidden_dim: int) -> None:
"""DQN Network
Args:
input_dim (int): `state` dimension.
`state` is 2-D tensor of shape (n, input_dim)
output_dim (int): Number of acti... | Python | zaydzuhri_stack_edu_python |
comment !/usr/bin/env python
comment Name surname: Melih Safa Celik
comment Student ID: 010180519
comment Probability and Statistics Midterm 31.01.2021
comment Question 1
import numpy as np
import matplotlib.pyplot as plt
from scipy.stats import norm
set array = array list 0 1 0 1 8 0 5 1 9 0 1 0 1 8 0 5 1 9 0 1 0 1 8 ... | #!/usr/bin/env python
# Name surname: Melih Safa Celik
# Student ID: 010180519
# Probability and Statistics Midterm 31.01.2021
# Question 1
import numpy as np
import matplotlib.pyplot as plt
from scipy.stats import norm
array = np.array([0,1,0,1,8,0,5,1,9,0,1,0,1,8,0,5,1,9,0,1,0,1,8,0,5,1,9,0,1,0,1,8,0,5,1,9,0,1,0,1,8... | Python | zaydzuhri_stack_edu_python |
function playNote note length=250
begin
set found = call getNote upper note
if found == false
begin
return false
end
else
begin
call Beep found length
end
end function | def playNote(note, length=250):
found = getNote(note.upper())
if found == False:
return False
else:
winsound.Beep(found, length) | Python | nomic_cornstack_python_v1 |
async function _loop self ctx
begin
if not is_playing
begin
return await call send string Nothing being played at the moment.
end
comment Inverse boolean value to loop and unloop.
set loop = not loop
await call add_reaction string ✅
end function | async def _loop(self, ctx: commands.Context):
if not ctx.voice_state.is_playing:
return await ctx.send('Nothing being played at the moment.')
# Inverse boolean value to loop and unloop.
ctx.voice_state.loop = not ctx.voice_state.loop
await ctx.message.add_reaction('✅') | Python | nomic_cornstack_python_v1 |
from google.cloud import storage
import os
import json
function upload_TFrecord_gcs filepath client bucket
begin
string function to upload TFrecord filepath to gcs bucket intended to be used for TFrecord files, but can be used for any filetype args: filepath: str, path of file to be uploaded client: gcs google.storage.... | from google.cloud import storage
import os
import json
def upload_TFrecord_gcs(filepath, client, bucket):
'''
function to upload TFrecord filepath to gcs bucket
intended to be used for TFrecord files, but can be used for any filetype
args:
filepath: str, path of file to be uploaded
... | Python | zaydzuhri_stack_edu_python |
import os
import numpy as np
from skimage.io import imread
from skimage.transform import rescale , resize , downscale_local_mean
import matplotlib.pyplot as plt
function preprocess datapath
begin
comment This part reads the images
set classes = list string b string c string l string h
set imagelist = list comprehension... | import os
import numpy as np
from skimage.io import imread
from skimage.transform import rescale, resize, downscale_local_mean
import matplotlib.pyplot as plt
def preprocess(datapath):
# This part reads the images
classes = ['b', 'c', 'l', 'h']
imagelist = [fn for fn in os.listdir(datapath)]
N = len(i... | Python | zaydzuhri_stack_edu_python |
string Created on 02-Mar-2019 @author: arvindkumar
set thisdict = dict string brand string Ford ; string model string Mustang ; string year 1964
for tuple x y in items thisdict
begin
print x y
end | '''
Created on 02-Mar-2019
@author: arvindkumar
'''
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
for x,y in thisdict.items():
print(x , y) | Python | zaydzuhri_stack_edu_python |
comment Config code ####################################
comment provides number of functions to manipulate run time environment
import sys
comment Used when writing the mapper code
from sqlalchemy import Column , ForeignKey , Integer , String
comment We will use in the configuration and class code
from sqlalchemy.ext.... | #########Config code ####################################
#provides number of functions to manipulate run time environment
import sys
#Used when writing the mapper code
from sqlalchemy import Column, ForeignKey, Integer, String
#We will use in the configuration and class code
from sqlalchemy.ext.declarative... | Python | zaydzuhri_stack_edu_python |
function x_fd_health_probe self
begin
return get pulumi self string x_fd_health_probe
end function | def x_fd_health_probe(self) -> Optional[str]:
return pulumi.get(self, "x_fd_health_probe") | Python | nomic_cornstack_python_v1 |
function get_checkpoint self
begin
set tuple response checkpoint_commands = call _pre_get_checkpoint conn=conn
set checkpoint_results = call send_commands commands=checkpoint_commands
try
begin
set checkpoint : str = result
end
except IndexError
begin
set checkpoint = string
end
return call _post_get_config response=r... | def get_checkpoint(self) -> ScrapliCfgResponse:
response, checkpoint_commands = self._pre_get_checkpoint(conn=self.conn)
checkpoint_results = self.conn.send_commands(commands=checkpoint_commands)
try:
checkpoint: str = checkpoint_results[2].result
except IndexError:
... | Python | nomic_cornstack_python_v1 |
set num = input
set numm = list num
print *sorted(num) sep=string | num= input()
numm=list(num)
print (*sorted(num),sep="")
| Python | zaydzuhri_stack_edu_python |
comment public parameter:
comment a
comment modulus = 2 ** 256
comment private key:
comment s
comment public key:
comment (a * s) % modulus # truncates and returns least significant bits
comment key agreement:
comment x(a * s) % modulus == s(a * x) % modulus
from crypto.utilities import random_integer
set SECURITY_LEVE... | # public parameter:
# a
# modulus = 2 ** 256
# private key:
# s
# public key:
# (a * s) % modulus # truncates and returns least significant bits
# key agreement:
# x(a * s) % modulus == s(a * x) % modulus
from crypto.utilities import random_integer
SECURITY_LEVEL = 32
A = random_integer(SECURITY_LEVEL)
whi... | Python | zaydzuhri_stack_edu_python |
import os , re
from collections import Counter
from time import sleep
import requests
set corpus_words = counter
set regex = compile string [^a-z]
set wordcount_regex = compile string \b([0-9,one]*) Shortz Era entr
function add word
begin
if length word <= 15
begin
set corpus_words at word = corpus_words at word + 1
en... | import os, re
from collections import Counter
from time import sleep
import requests
corpus_words = Counter()
regex = re.compile('[^a-z]')
wordcount_regex = re.compile('\\b([0-9,one]*) Shortz Era entr')
def add(word):
if len(word) <= 15:
corpus_words[word] += 1
def process(fpath):
w = x = y = z = ""... | Python | zaydzuhri_stack_edu_python |
function part_category self obj
begin
return call get_rule_set obj string part_category
end function | def part_category(self, obj):
return self.get_rule_set(obj, 'part_category') | Python | nomic_cornstack_python_v1 |
from datetime import date , timedelta
from datetime import datetime
from statistics import pvariance , mean
from pymongo import MongoClient
from textblob import TextBlob
from model.exchange_corpus import get_words_of_corpus
from model.exchange_value_name import ExchangeValueName
from model.reddit_submission import get_... | from datetime import date, timedelta
from datetime import datetime
from statistics import pvariance, mean
from pymongo import MongoClient
from textblob import TextBlob
from model.exchange_corpus import get_words_of_corpus
from model.exchange_value_name import ExchangeValueName
from model.reddit_submission import get_... | Python | zaydzuhri_stack_edu_python |
function find_list_difference list1 list2
begin
set diff = list
set list2_set = set list2
for item in list1
begin
if item not in list2_set
begin
append diff item
end
end
return diff
end function | def find_list_difference(list1, list2):
diff = []
list2_set = set(list2)
for item in list1:
if item not in list2_set:
diff.append(item)
return diff
| Python | flytech_python_25k |
import pygame
import game_functions as gf
from settings import Settings
from ship import Ship
from pygame.sprite import Group
from game_stats import GameStats
from button import Button
from scoreboard import Scoreboard
function run_game
begin
comment Initialize game and create a screen object
call init
set display = di... | import pygame
import game_functions as gf
from settings import Settings
from ship import Ship
from pygame.sprite import Group
from game_stats import GameStats
from button import Button
from scoreboard import Scoreboard
def run_game():
# Initialize game and create a screen object
pygame.init()
display = py... | Python | zaydzuhri_stack_edu_python |
comment readutf8.py - read an utf-8 file into a Python Unicode string
import sys , codecs | #
# readutf8.py - read an utf-8 file into a Python Unicode string
#
import sys, codecs
| Python | zaydzuhri_stack_edu_python |
function count self
begin
return call _get string count
end function | def count(self):
return self._get('count') | Python | nomic_cornstack_python_v1 |
import matplotlib.pyplot as plt
import csv
function graph fileName titleName
begin
set times = list
set temperatures = list
with open fileName string r as csvFile
begin
set plots = reader csvFile delimiter=string ,
set count = 0
for row in plots
begin
if count != 0 and row at slice 0 : 1 : != string
begin
append ti... | import matplotlib.pyplot as plt
import csv
def graph(fileName, titleName):
times = []
temperatures = []
with open(fileName, 'r') as csvFile:
plots = csv.reader(csvFile, delimiter = ',')
count = 0
for row in plots:
if count != 0 and row[0:1] != '\n':
... | Python | zaydzuhri_stack_edu_python |
function nanfill a f_a *args **kwargs
begin
string Fill masked areas with np.nan Wrapper for functions that can't handle ma (e.g. scipy.ndimage) This will force filters to ignore nan, but causes adjacent pixels to be set to nan as well: http://projects.scipy.org/scipy/ticket/1155
set a = call checkma a
set ndv = fill_v... | def nanfill(a, f_a, *args, **kwargs):
"""Fill masked areas with np.nan
Wrapper for functions that can't handle ma (e.g. scipy.ndimage)
This will force filters to ignore nan, but causes adjacent pixels to be set to nan as well: http://projects.scipy.org/scipy/ticket/1155
"""
a = checkma(a)
... | Python | jtatman_500k |
import tables
import utilities
from sys import exit
from plots import GlobalPieChart , IndividualChart
comment 1. make a database with tables for players, games, and association table between the two COMPLETE
comment 2. need functions to add players, and add games with associated information COMPLETE
comment 3. need fu... | import tables
import utilities
from sys import exit
from plots import GlobalPieChart, IndividualChart
# 1. make a database with tables for players, games, and association table between the two COMPLETE
# 2. need functions to add players, and add games with associated information COMPLETE
# 3. need functino to d... | Python | zaydzuhri_stack_edu_python |
function _get_node response *ancestors
begin
string Traverse tree to node
set document = response
for ancestor in ancestors
begin
if ancestor not in document
begin
return dict
end
else
begin
set document = document at ancestor
end
end
return document
end function | def _get_node(response, *ancestors):
""" Traverse tree to node """
document = response
for ancestor in ancestors:
if ancestor not in document:
return {}
else:
document = document[ancestor]
return document | Python | jtatman_500k |
comment distance from the sun on 25. september 2009:
set dist_from_sun = 16637000000.0
comment speed traveling from the sun in mph
set speed_from_sun = 38241
set days_since_str = input string Number of days after 9/25/09:
set days_since_float = decimal days_since_str
set hours_since = days_since_float * 24
comment calc... | #distance from the sun on 25. september 2009:
dist_from_sun = 16637e6
#speed traveling from the sun in mph
speed_from_sun = 38241
days_since_str = input("Number of days after 9/25/09: ")
days_since_float = float(days_since_str)
hours_since = days_since_float*24
#calculate the distance in different units
distance_mile... | Python | zaydzuhri_stack_edu_python |
function send_grandfather_email self user certificates mock_run=false
begin
set courses_list = list
for cert in certificates
begin
set course = call get_course_by_id course_id
set course_url = format string https://{}{} SITE_NAME reverse string course_root kwargs=dict string course_id course_id
set course_title = disp... | def send_grandfather_email(self, user, certificates, mock_run=False):
courses_list = []
for cert in certificates:
course = get_course_by_id(cert.course_id)
course_url = 'https://{}{}'.format(
settings.SITE_NAME,
reverse('course_root', kwargs=... | Python | nomic_cornstack_python_v1 |
import numpy
import Slope_aspect
import dist
import time
import rpy
import pickle
import pylab
from scipy import ndimage
function VegetationClassify Elev_arr River_arr
begin
call library string rpart
comment Read the dictionary from the pickle file
set pkl_file = open string decision_tree.pkl string rb
call set_default... | import numpy
import Slope_aspect
import dist
import time
import rpy
import pickle
import pylab
from scipy import ndimage
def VegetationClassify(Elev_arr, River_arr):
rpy.r.library("rpart")
# Read the dictionary from the pickle file
pkl_file = open('decision_tree.pkl','rb')
rpy.set_default_mode(rpy.NO_CONVERS... | Python | zaydzuhri_stack_edu_python |
if op == 1
begin
print format string {} em BINÁRIO é igual a {}. num binary num at slice 2 : :
end
else
if op == 2
begin
print format string {} em OCTAL é igual a {}. num octal num at slice 2 : :
end
else
if op == 3
begin
print format string {} em HEXADECIMAL é igual a {}. num hexadecimal num at slice 2 : :
end
else... | if op == 1:
print('{} em BINÁRIO é igual a {}.'.format(num, bin(num)[2:]))
elif op == 2:
print('{} em OCTAL é igual a {}.'.format(num, oct(num)[2:]))
elif op == 3:
print('{} em HEXADECIMAL é igual a {}.'.format(num, hex(num)[2:]))
else:
print('Opção inválida, tente novamente.') | Python | zaydzuhri_stack_edu_python |
function run_test_is_parallel
begin
comment This runs OUR tests.
call run_test_is_parallel
comment -------------------------------------------------------------------------
comment One ADDITIONAL test (or set of tests).
comment -------------------------------------------------------------------------
comment slope is 1... | def run_test_is_parallel():
m1t.run_test_is_parallel() # This runs OUR tests.
# -------------------------------------------------------------------------
# One ADDITIONAL test (or set of tests).
# -------------------------------------------------------------------------
line1 = Line(Point(15, 30), ... | Python | nomic_cornstack_python_v1 |
class Person
begin
function __init__ self
begin
set _name = string
set _year = 0
end function
function addName self name
begin
set _name = name
end function
function addYear self year
begin
set _year = year
end function
function __repr__ self
begin
return _name + string was born in: + string _year
end function
end cla... | class Person:
def __init__(self):
self._name = ""
self._year = 0
def addName(self, name):
self._name = name
def addYear(self, year):
self._year = year
def __repr__(self):
return (self._name + " was born in: " + str(self._year))
class Student(Person):
... | Python | zaydzuhri_stack_edu_python |
for i in range length daysix_list
begin
set daysix_list at i = integer daysix_list at i
end
comment FIRST STAR
function redistribute bank_list
begin
set max_value = max bank_list
set max_position = index bank_list max_value
set new_bank = list
for item in bank_list
begin
append new_bank item
end
set new_bank at max_po... | for i in range(len(daysix_list)):
daysix_list[i] = int(daysix_list[i])
# FIRST STAR
def redistribute(bank_list):
max_value = max(bank_list)
max_position = bank_list.index(max_value)
new_bank = []
for item in bank_list:
new_bank.append(item)
new_bank[max_position] = 0
if max_position == len(new_bank) - 1:... | Python | zaydzuhri_stack_edu_python |
function get_size self
begin
return length pairs
end function | def get_size(self):
return len(pairs) | Python | nomic_cornstack_python_v1 |
comment coding=utf8
import argparse , os , json
function searchTags dataDict words
begin
set songs = dict
for tuple k v in call iteritems
begin
if k == string song_id_to_name
begin
continue
end
for tuple k2 v2 in call iteritems
begin
if k2 != string song_id and k2 != string info_tags and k2 != string info_tokens
begin... | # coding=utf8
import argparse, os, json
def searchTags(dataDict,words):
songs = {}
for k,v in dataDict.iteritems():
if k == 'song_id_to_name':
continue
for k2,v2 in v.iteritems():
if k2 != 'song_id' and k2 != 'info_tags' and k2 != 'info_tokens':
for w in v2["labels"... | Python | zaydzuhri_stack_edu_python |
function animate_profiles self n=10 loop=1 dt=0.2
begin
set ax = call gca
set time_points = length time
set time_mask = call slice none none time_points // n
set data = emissivity at tuple time_mask slice : :
call cla
set tuple line = plot rho data at tuple 0 slice : :
call set_xlabel string $\rho_\psi$
call set_y... | def animate_profiles(self, n=10, loop=1, dt=0.2):
ax = plt.gca()
time_points = len(self.time)
time_mask = slice(None, None, time_points // n)
data = self.emissivity[time_mask,:]
ax.cla()
line, = ax.plot(self.rho, data[0,:])
ax.set_xlabel(r'$\rho_\psi$')
... | Python | nomic_cornstack_python_v1 |
function post self url data=none json=none **kwargs
begin
set kwargs at string data = data
set kwargs at string json = json
set tuple url kwargs = call __intercept_request string post url kwargs
return call request string post url keyword kwargs
end function | def post(self, url, data=None, json=None, **kwargs):
kwargs["data"] = data
kwargs["json"] = json
url, kwargs = self.__intercept_request("post", url, kwargs)
return self.request("post", url, **kwargs) | Python | nomic_cornstack_python_v1 |
function max_output_buffer self *args **kwargs
begin
return call atsc_ds_to_softds_sptr_max_output_buffer self *args keyword kwargs
end function | def max_output_buffer(self, *args, **kwargs):
return _atsc_swig.atsc_ds_to_softds_sptr_max_output_buffer(self, *args, **kwargs) | Python | nomic_cornstack_python_v1 |
string Uses Mechanize library to get a website's source code
import mechanize
function viewPage url
begin
set browser = call Browser
set page = open url
set source_code = read page
end function | '''
Uses Mechanize library to get a website's source code
'''
import mechanize
def viewPage(url):
browser = mechanize.Browser()
page = browser.open(url)
source_code = page.read() | Python | zaydzuhri_stack_edu_python |
import pandas as pd
function part_1 line
begin
set up = count line string (
set down = count line string )
print string Final floor is: { up - down }
end function
function part_2 line
begin
set current_level = 0
set move_dict = dict string ( 1 ; string ) - 1
for tuple step move in enumerate line
begin
set current_level... | import pandas as pd
def part_1(line: str) -> None:
up = line.count("(")
down = line.count(")")
print(f"Final floor is: {up - down}")
def part_2(line: str) -> None:
current_level = 0
move_dict = {"(": 1, ")": -1}
for step, move in enumerate(line):
current_level += move_dict[move]
... | Python | zaydzuhri_stack_edu_python |
comment Module 1
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
import sklearn as sk
comment Module 2 Numpy
import numpy as np
set a = list 2 3 4
set a1 = array a
set b = list 4 3 2
set b1 = array b | # Module 1
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
import sklearn as sk
#Module 2 Numpy
import numpy as np
a = [2,3,4]
a1 = np.array(a)
b = [4,3,2]
b1 = np.array(b) | Python | zaydzuhri_stack_edu_python |
function wave self energy
begin
comment Set up function q(x) in the equation
set ql = 2 * energy - V_array
for i in range nx
begin
set qr at nx - i - 1 = ql at i
end
comment Find the matching point at the right turning point
set im = integer nx / 2
for i in range nx - 1
begin
if ql at i * ql at i + 1 < 0 and ql at i > ... | def wave(self, energy):
# Set up function q(x) in the equation
self.ql = 2*(energy-self.V_array)
for i in range(self.nx):
self.qr[self.nx-i-1] = self.ql[i]
# Find the matching point at the right turning point
im = int(self.nx/2)
for i in range(self.n... | Python | nomic_cornstack_python_v1 |
import json
import requests
set apikeys = string location/2306179/
set url = string https://www.metaweather.com/api/ + apikeys
set response = get requests url
comment print(type(response.text))
with open string weather.json string w as f
begin
write f text
end
with open string weather.json string r as g
begin
set show ... | import json
import requests
apikeys='location/2306179/'
url='https://www.metaweather.com/api/'+ apikeys
response=requests.get(url)
# print(type(response.text))
with open ('weather.json', 'w') as f:
f.write(response.text)
with open ('weather.json', 'r') as g:
show = json.load(g)
# print(type(show))
... | Python | zaydzuhri_stack_edu_python |
from sys import *
comment ---------------Symboltable code--------------------
function symtab f
begin
set line = list
set sym = list
set define = list
set undefine = list
set size = list
set value = list
set stype = list
set label = list
set addl = list
set undefine_label = list string jmp string je string jl ... | from sys import *
#---------------Symboltable code--------------------
def symtab(f):
line=[]
sym=[]
define=[]
undefine=[]
size=[]
value=[]
stype=[]
label=[]
addl=[]
undefine_label=['jmp','je','jl','jg','jge','jle']
fn=open(f,"r")
l1=fn.readline()
sl=l1.split()
ln... | Python | zaydzuhri_stack_edu_python |
import phys
from graphics import *
comment управление
set FIRST_PLAYER_CONTROL = tuple K_w K_a K_s K_d K_q K_e
set SECOND_PLAYER_CONTROL = tuple K_i K_j K_k K_l K_u K_o
comment игровые константы
comment отвечает за крайнюю по модулю координату нахождения актеров на поле
set ACTOR_BORDER_CORD = 1
set PLAYER_SPEED = 0.00... | import phys
from graphics import *
# управление
FIRST_PLAYER_CONTROL = (K_w, K_a, K_s, K_d, K_q, K_e)
SECOND_PLAYER_CONTROL = (K_i, K_j, K_k, K_l, K_u, K_o)
# игровые константы
ACTOR_BORDER_CORD = 1 # отвечает за крайнюю по модулю координату нахождения актеров на поле
PLAYER_SPEED = .0001
PLAYER_TURN_SPEED = phys.pi... | Python | zaydzuhri_stack_edu_python |
function _read_tf_example self record feature_preprocessor
begin
set keys_to_features = dict
set keys_to_features at _text_feature = call FixedLenFeature list string
for tuple label dtype in items _labels
begin
set keys_to_features at label = call FixedLenFeature list dtype
end
set parsed = call parse_single_example... | def _read_tf_example(self,
record: tf.Tensor,
feature_preprocessor: Callable[[str], List[str]]
) -> types.FeatureAndLabelTensors:
keys_to_features = {}
keys_to_features[self._text_feature] = tf.FixedLenFeature([], tf.string)
for label, dty... | Python | nomic_cornstack_python_v1 |
function align self string length=70 pad=30
begin
set s = string
set strings = list
comment check if "\n" are present in the string. If so, decompose the string.
set string_split_line = split string string
if length string_split_line > 1
begin
for i in range 0 length string_split_line
begin
if i != 0
begin
set string... | def align(self, string, length=70, pad=30):
s = ''
strings = []
# check if "\n" are present in the string. If so, decompose the string.
string_split_line = string.split('\n')
if len(string_split_line) > 1:
for i in range(0,len(string_split_line)):
if ... | Python | nomic_cornstack_python_v1 |
string Authors: Marco Willgren, 502606 Jarno Vuorenmaa, 503618 Exercise 3: Applications of data analysis The Water_data.csv file is a multi-parameter dataset consisting of 268 samples obtained from 67 mixtures of Cadmium, Lead, and tap water. Three features (attributes) where measured for each samples (Mod1, Mod2, Mod3... | '''
Authors: Marco Willgren, 502606
Jarno Vuorenmaa, 503618
Exercise 3: Applications of data analysis
The Water_data.csv file is a multi-parameter dataset consisting of 268 samples obtained from 67 mixtures of Cadmium, Lead, and tap water.
Three features (attributes) where measured for each samples (Mod1,... | Python | zaydzuhri_stack_edu_python |
function mutate mask_old
begin
set mask = copy mask_old
for i in range length mask
begin
if random integer 0 2 == 0
begin
set mask at i = not mask at i
end
end
while sum mask < min_features
begin
set mask at random integer length mask = true
end
return mask
end function | def mutate(mask_old):
mask= mask_old.copy()
for i in range(len(mask)):
if np.random.randint(0, 2) == 0:
mask[i]= not mask[i]
while np.sum(mask) < min_features:
mask[np.random.randint(len(mask))]= True
... | Python | nomic_cornstack_python_v1 |
comment -*- coding: utf-8 -*-
from collections import defaultdict
from ginterval import GInterval
from gparser import Parser
class GTFParser extends Parser
begin
decorator staticmethod
function _process_features features
begin
string Create one GInterval instance from multi gtf feature records. Notes: The features has ... | # -*- coding: utf-8 -*-
from collections import defaultdict
from ginterval import GInterval
from gparser import Parser
class GTFParser(Parser):
@staticmethod
def _process_features(features):
"""
Create one GInterval instance from multi gtf feature
records.
Notes:
... | Python | zaydzuhri_stack_edu_python |
import phonenumbers
from phonenumbers import geocoder
from phonenumbers import carrier
function phone_number
begin
set number = string +84905125206
set vi_number = parse phonenumbers number
print call description_for_number vi_number string en
set service_number = parse phonenumbers number
print call name_for_number se... | import phonenumbers
from phonenumbers import geocoder
from phonenumbers import carrier
def phone_number():
number = "+84905125206"
vi_number = phonenumbers.parse(number)
print(geocoder.description_for_number(vi_number, "en"))
service_number = phonenumbers.parse(number)
print(carrier.name_for_numbe... | Python | zaydzuhri_stack_edu_python |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.