code
stringlengths
10
2.58M
original_code
stringlengths
3
3.18M
original_language
stringclasses
1 value
source
stringclasses
7 values
comment import all modules import pandas as pd import seaborn as sns import matplotlib.pyplot as plt comment Create a distplot call distplot df at string Award_Amount kde=false bins=20 comment Display the plot show comment Create a distplot of the Award Amount call distplot df at string Award_Amount hist=false rug=true...
# import all modules import pandas as pd import seaborn as sns import matplotlib.pyplot as plt # Create a distplot sns.distplot(df['Award_Amount'], kde=False, bins=20) # Display the plot plt.show() # Create a distplot of the Award Amount sns.distplot(df['Award_Amount'], hist=Fa...
Python
zaydzuhri_stack_edu_python
function getscans filename scans=string sources=string intent=string bdfdir=default_bdfdir begin comment if no scans defined, set by mode context if scans begin set scans = list comprehension integer i for i in split scans string , end else if sources begin set meta = tuple call read_scans filename bdfdir=bdfdir cal...
def getscans(filename, scans='', sources='', intent='', bdfdir=default_bdfdir): # if no scans defined, set by mode context if scans: scans = [int(i) for i in scans.split(',')] elif sources: meta = (ps.read_scans(filename, bdfdir=bdfdir), ps.read_sources(filename, bdfdir=bdfdir)) # ...
Python
nomic_cornstack_python_v1
import random function reservoir_sample arr k begin set reservoir = list for i in range k begin append reservoir arr at i end for i in range k length arr begin set sample = random integer 1 i + 1 if sample <= k begin set reservoir at sample - 1 = arr at i end end return reservoir end function set test = list 40 48 26 ...
import random def reservoir_sample(arr, k): reservoir = [] for i in range(k): reservoir.append(arr[i]) for i in range(k, len(arr)): sample = random.randint(1, i+1) if sample <= k: reservoir[sample-1] = arr[i] return reservoir test = [40, 48, 26, 44, 15, 20, 40, 33, 42, 34, 1, 14, 24, 47, 27, ...
Python
zaydzuhri_stack_edu_python
function pad_binary_signal x pad_len=10 begin set n = length x set one_idx = array range n at x == 1 if length one_idx == 0 begin return x end set y = zeros n for idx in one_idx begin set start = max idx - pad_len 0 set end = min idx + pad_len + 1 n set y at slice start : end : = 1.0 end return y end function
def pad_binary_signal(x, pad_len=10): n = len(x) one_idx = np.arange(n)[x == 1] if len(one_idx) == 0: return x y = np.zeros(n) for idx in one_idx: start = max(idx - pad_len, 0) end = min(idx + pad_len + 1, n) y[start:end] = 1.0 return y
Python
nomic_cornstack_python_v1
if instalacao == string R begin if kwh <= 500 begin set preco = kwh * 0.4 end else begin set preco = kwh * 0.65 end print string O valor do consumo de { kwh } no tipo de instalação { instalacao } é: R$ { preco } ! end else if instalacao == string I begin if kwh <= 1000 begin set preco = kwh * 0.55 end else begin set pr...
if instalacao == "R": if kwh <= 500: preco = kwh * 0.40 else: preco = kwh * 0.65 print(f"O valor do consumo de {kwh} no tipo de instalação {instalacao} é: R${preco} !") elif instalacao == "I": if kwh <= 1000: preco = kwh * 0.55 else: preco = kwh * 0.60 print(f"O ...
Python
zaydzuhri_stack_edu_python
from typing import Sequence , Optional from part_marker_velocity_reward import PartMarkerVelocityReward from scene.part import Part class ReleasedPartMarkerVelocityReward extends PartMarkerVelocityReward begin string A concrete implementation of PartVelocityReward that takes all parts in the scene (placed parts, curren...
from typing import Sequence, Optional from .part_marker_velocity_reward import PartMarkerVelocityReward from scene.part import Part class ReleasedPartMarkerVelocityReward(PartMarkerVelocityReward): """ A concrete implementation of PartVelocityReward that takes all parts in the scene (placed parts, current p...
Python
zaydzuhri_stack_edu_python
class Tree begin function __init__ self data=none left=none right=none begin set _data = data set _left = left set _right = right end function function preorder self begin if not _data begin print string data _data end if not _left begin call preorder end if not _right begin call preorder end end function function inor...
class Tree: def __init__(self, data=None, left=None, right=None): self._data = data self._left = left self._right = right def preorder(self): if (not self._data): print("data", self._data) if (not self._left): self._left.preorder() if (no...
Python
zaydzuhri_stack_edu_python
function call *names begin set frame = call _getframe 1 set f_locals at string __names__ = list names end function
def call(*names): frame = sys._getframe(1) frame.f_locals['__names__'] = list(names)
Python
nomic_cornstack_python_v1
function init_route_manager self begin set route = list set route_mode = call get_param string ~mode string dynamic if route_mode not in route_modes begin call logerr string Route mode '%s' unknown, exiting route manager. "dynamic" will be used route_mode set route_mode = string dynamic end set poses = call get_param ...
def init_route_manager(self): self.route = [] self.route_mode = rospy.get_param('~mode', "dynamic") if self.route_mode not in NavigationAbTest.route_modes: rospy.logerr("Route mode '%s' unknown, exiting route manager. \"dynamic\" will be used", self.route_mode) self.rout...
Python
nomic_cornstack_python_v1
function del_max self begin set maxVal = call find_max if maxVal is not none begin set items at 1 = items at size set items at size = none set size = size - 1 call perc_down 1 end end function
def del_max(self): maxVal = self.find_max() if maxVal is not None: self.items[1] = self.items[self.size] self.items[self.size] = None self.size -= 1 self.perc_down(1)
Python
nomic_cornstack_python_v1
string 编写一个高效的算法来判断 m x n 矩阵中,是否存在一个目标值。该矩阵具有如下特性: 每行中的整数从左到右按升序排列。 每行的第一个整数大于前一行的最后一个整数。 来源:力扣(LeetCode) 链接:https://leetcode-cn.com/problems/search-a-2d-matrix 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。 输入:matrix = [[1,3,5,7],[10,11,16,20],[23,30,34,60]], target = 3 输出:true class Solution extends object begin function searchM...
''' 编写一个高效的算法来判断 m x n 矩阵中,是否存在一个目标值。该矩阵具有如下特性: 每行中的整数从左到右按升序排列。 每行的第一个整数大于前一行的最后一个整数。 来源:力扣(LeetCode) 链接:https://leetcode-cn.com/problems/search-a-2d-matrix 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。 输入:matrix = [[1,3,5,7],[10,11,16,20],[23,30,34,60]], target = 3 输出:true ''' class Solution(object): def searchMa...
Python
zaydzuhri_stack_edu_python
function link_type self begin return _link_type end function
def link_type(self) -> str: return self._link_type
Python
nomic_cornstack_python_v1
function getcampaign name begin return campaigns at name end function
def getcampaign(name: str) -> ba.Campaign: return _ba.app.campaigns[name]
Python
nomic_cornstack_python_v1
while i * i <= N begin if N % i == 0 begin set a = min a length string N // i end set i = i + 1 end print a
while i*i <= N: if N % i == 0: a = min(a, len(str(N//i))) i += 1 print(a)
Python
zaydzuhri_stack_edu_python
from tkinter import * from tkinter.font import Font from simple_pid import PID class TkApp extends object begin function __init__ self period=1000 kp=1.0 ki=0.0 kd=0.0 init=0.0 begin set master = call Tk set _master = call Tk call geometry string 1600x800 call option_add string *Font string Helvetica 36 set _period = p...
from tkinter import * from tkinter.font import Font from simple_pid import PID class TkApp(object): def __init__(self, period=1000, kp=1.0, ki=0.0, kd=0.0, init=0.0): master = self._master = Tk() master.geometry("1600x800") master.option_add("*Font", "Helvetica 3...
Python
zaydzuhri_stack_edu_python
from tkinter import * set root = call Tk call geometry string 500x300 set fr_up = call Frame root set btn_1 = call Button fr_up text=string ok_1 width=5 height=2 bg=string blue fg=string black font=string arial 14 set btn_2 = call Button fr_up text=string ok_2 width=5 height=2 bg=string yellow fg=string black font=stri...
from tkinter import * root = Tk() root.geometry('500x300') fr_up = Frame(root) btn_1 = Button(fr_up, text = 'ok_1', width = 5, height = 2, bg = 'blue', fg = 'black', font = 'arial 14') btn_2 = Button(fr_up, text = 'ok_2', width = 5, height = 2, bg = 'yellow', fg = 'black', font = 'arial 16') fr_up.pack(side = 'top', fi...
Python
zaydzuhri_stack_edu_python
function reverse_sentence sentence begin set reversed_sentence = string set word = string for char in sentence begin if char == string begin set reversed_sentence = word + char + reversed_sentence set word = string end else begin set word = word + char end end set reversed_sentence = word + string + reversed_sente...
def reverse_sentence(sentence): reversed_sentence = '' word = '' for char in sentence: if char == ' ': reversed_sentence = word + char + reversed_sentence word = '' else: word += char reversed_sentence = word + ' ' + reversed_sentence return revers...
Python
greatdarklord_python_dataset
function make_great magicians begin set great_magicians = list while magicians begin set magician = pop magicians + string the great append great_magicians magician end return great_magicians end function
def make_great(magicians): great_magicians = [] while magicians: magician = magicians.pop() + " the great" great_magicians.append(magician) return great_magicians
Python
nomic_cornstack_python_v1
comment Modify your code from Activity 8 such that the banner character comment can be any character, but defaults to the asterik character if comment no banner characted argument is specified comment Additional practice: comment Consider the following code: function print_message name banner_character=string * begin s...
# Modify your code from Activity 8 such that the banner character # can be any character, but defaults to the asterik character if # no banner characted argument is specified # Additional practice: # Consider the following code: def print_message(name: str, banner_character: str='*'): num_stars = len(name) + 7 ...
Python
zaydzuhri_stack_edu_python
comment Print Formatting print string this is a string set s = string string
# Print Formatting print('this is a string') s = 'string'
Python
zaydzuhri_stack_edu_python
string Create a blueprint with endpoints for logins from configured identity providers. The identity providers include, for example, Google, Shibboleth, or another fence instance. See the other files in this directory for the definitions of the endpoints for each provider. from authlib.common.urls import add_params_to_...
""" Create a blueprint with endpoints for logins from configured identity providers. The identity providers include, for example, Google, Shibboleth, or another fence instance. See the other files in this directory for the definitions of the endpoints for each provider. """ from authlib.common.urls import add_params_...
Python
jtatman_500k
function import_csv_file file_path file_delimiter import_from begin import pandas as pd if upper import_from == string PA:USER_FILE begin print string Importing file from the user space call connect set out_file = call File file_path call pullFile file_path out_file end if upper import_from == string PA:GLOBAL_FILE beg...
def import_csv_file(file_path, file_delimiter, import_from): import pandas as pd if import_from.upper() == "PA:USER_FILE": print("Importing file from the user space") userspaceapi.connect() out_file = gateway.jvm.java.io.File(file_path) userspaceapi.pullFile(file_path, out_file)...
Python
nomic_cornstack_python_v1
function sub a b begin return a - b end function
def sub(a,b): return a-b
Python
nomic_cornstack_python_v1
function list_all_files self directory begin for tuple root dirs files in walk directory begin for filename in files begin set filepath = join path root filename yield filepath end end end function
def list_all_files(self, directory): for root, dirs, files in os.walk(directory): for filename in files: filepath = os.path.join(root, filename) yield filepath
Python
nomic_cornstack_python_v1
set evens_list = list comprehension num for num in list if num % 2 == 0
evens_list = [num for num in list if num % 2 == 0]
Python
flytech_python_25k
function query_mongo_article doi begin set query_cat = list find BioReco_raw dict string doi string { doi } set size = length query_cat print string There are { size } articles in { doi } category return query_cat end function
def query_mongo_article(doi): query_cat = list(db.BioReco_raw.find({'doi': f'{doi}'})) size = len(query_cat) print(f'There are {size} articles in {doi} category') return query_cat
Python
nomic_cornstack_python_v1
comment !/usr/bin/env python comment encoding: utf-8 string @author: Wayne @contact: wangye.hope@gmail.com @software: PyCharm @file: Number of Days Between Two Dates @time: 2020/2/26 17:31 class Solution begin function daysBetweenDates self date1 date2 begin function date s begin set tuple y m d = map int split s strin...
#!/usr/bin/env python # encoding: utf-8 """ @author: Wayne @contact: wangye.hope@gmail.com @software: PyCharm @file: Number of Days Between Two Dates @time: 2020/2/26 17:31 """ class Solution: def daysBetweenDates(self, date1: str, date2: str) -> int: def date(s: str) -> int: y, m, d = map(in...
Python
zaydzuhri_stack_edu_python
function groupby_with_null data *args **kwargs begin string Groupby on columns with NaN/None/Null values Pandas currently does have proper support for groupby on columns with null values. The nulls are discarded and so not grouped on. set by = get kwargs string by args at 0 set altered_columns = dict if not is instanc...
def groupby_with_null(data, *args, **kwargs): """ Groupby on columns with NaN/None/Null values Pandas currently does have proper support for groupby on columns with null values. The nulls are discarded and so not grouped on. """ by = kwargs.get('by', args[0]) altered_columns = {} i...
Python
jtatman_500k
function get_collection_by_name session name begin return first filter name == name end function
def get_collection_by_name(session, name): return session.query(Collection).filter(Collection.name == name).first()
Python
nomic_cornstack_python_v1
class MyBeautifulGril begin string 我的漂亮女神 set __instance = none set __name = none function __new__ cls name begin if not __instance begin set __instance = call __new__ cls end return __instance end function function __init__ self name begin if not __name begin set __name = name print string 遇见 { name } , 我一见钟情! end els...
class MyBeautifulGril: """我的漂亮女神""" __instance = None __name = None def __new__(cls, name): if not cls.__instance: cls.__instance = super().__new__(cls) return cls.__instance def __init__(self, name): if not self.__name: self.__name = name ...
Python
zaydzuhri_stack_edu_python
comment Tests for libxlsxwriter. comment Copyright 2014-2019, John McNamara, jmcnamara@cpan.org import base_test_class class TestCompareXLSXFiles extends XLSXBaseTest begin string Test file created with libxlsxwriter against a file created by Excel. function test_chart_up_down_bars01 self begin call run_exe_test string...
############################################################################### # # Tests for libxlsxwriter. # # Copyright 2014-2019, John McNamara, jmcnamara@cpan.org # import base_test_class class TestCompareXLSXFiles(base_test_class.XLSXBaseTest): """ Test file created with libxlsxwriter against a file cre...
Python
jtatman_500k
string Specify region: python /work2/dechavezv/scripts/SlidingWindowHet_v3.py chr12.vcf.gz 100000 10000 chr12 792227 2707784 Do whole chromosome: python /work2/dechavezv/scripts/SlidingWindowHet_v3.py chr12.vcf.gz 100000 10000 chr12 import sys import pysam import os import gzip import numpy set filename = argv at 1 set...
''' Specify region: python /work2/dechavezv/scripts/SlidingWindowHet_v3.py chr12.vcf.gz 100000 10000 chr12 792227 2707784 Do whole chromosome: python /work2/dechavezv/scripts/SlidingWindowHet_v3.py chr12.vcf.gz 100000 10000 chr12 ''' import sys import pysam import os import gzip import numpy filename = sys.argv[...
Python
zaydzuhri_stack_edu_python
function load_ipython_extension ipython begin call register_magics PProfileMagics end function
def load_ipython_extension(ipython): ipython.register_magics(PProfileMagics)
Python
nomic_cornstack_python_v1
function filter_it self _filter begin with open path as _file begin for line in _file begin set tokens = call _tokenize line if tokens begin set _ip = call group string ip if match _ip begin yield line end end end end end function
def filter_it(self, _filter): with open(self.path) as _file: for line in _file: tokens = self._tokenize(line) if tokens: _ip = tokens.group('ip') if _filter.match(_ip): yield line
Python
nomic_cornstack_python_v1
function register begin if method == string GET begin return call render_template string register.html end else begin set name = get form string name set last_name = get form string last_name set birthday = string parse time get form string birthday string %Y-%m-%d set username = get form string username set password =...
def register(): if request.method == "GET": return render_template('register.html') else: name = request.form.get('name') last_name = request.form.get('last_name') birthday = datetime.strptime(request.form.get('birthday'), "%Y-%m-%d") username = request.form.get('username...
Python
nomic_cornstack_python_v1
comment !/usr/bin/python3 comment -*- coding: utf-8 -*- comment @Time : 2020/5/29 10:21 comment @Author : WH Python学的好,牢饭吃的饱。 comment @FileName: time_test.py comment @Email : oukouwh@163.com comment @Software: PyCharm import time function get_week year month day begin string 获取星期数 :param year: 年 :param month: 月 :param ...
#!/usr/bin/python3 # -*- coding: utf-8 -*- # @Time : 2020/5/29 10:21 # @Author : WH Python学的好,牢饭吃的饱。 # @FileName: time_test.py # @Email : oukouwh@163.com # @Software: PyCharm import time def get_week(year, month, day): ''' 获取星期数 :param year: 年 :param month: 月 :param day: 日 :return: '''...
Python
zaydzuhri_stack_edu_python
function _get_ave_rating target ratings user_sets averages begin if target not in averages begin set attri = user_sets at target set sum_ratings = sum generator expression ratings at tuple target a for a in attri set n_ratings = length attri set averages at target = tuple sum_ratings n_ratings end return averages at ta...
def _get_ave_rating(target, ratings, user_sets, averages): if target not in averages: attri = user_sets[target] sum_ratings = sum(ratings[(target, a)] for a in attri) n_ratings = len(attri) averages[target] = (sum_ratings, n_ratings) return averages[target][0] / averages[target][...
Python
nomic_cornstack_python_v1
function CompareDirToDir DirPath1 DirPath2 begin try begin debug string Compare the contents of two directory with hashes. set hashList1 = dict for filesPath in call GetTheFilesPathOfDirectory DirPath1 begin set hashList1 at filesPath = call md5sum filesPath end set hashList2 = dict for filesPath in call GetTheFilesP...
def CompareDirToDir(DirPath1, DirPath2): try: logs.logger.debug("Compare the contents of two directory with hashes.") hashList1 = {} for filesPath in GetTheFilesPathOfDirectory(DirPath1): hashList1[filesPath] = hash.md5sum(filesPath) hashList2 = {} for filesPath ...
Python
nomic_cornstack_python_v1
import sys from sys import exit from math import gcd , factorial , ceil , floor , sqrt from bisect import bisect_left , bisect_right from copy import deepcopy from heapq import heapify , heappop , heappush from itertools import permutations , combinations , product , accumulate from collections import defaultdict , deq...
import sys from sys import exit from math import gcd, factorial, ceil, floor, sqrt from bisect import bisect_left, bisect_right from copy import deepcopy from heapq import heapify, heappop, heappush from itertools import permutations, combinations, product, accumulate from collections import defaultdict, deque sys.setr...
Python
zaydzuhri_stack_edu_python
function _slice self start end begin string Used internally to get a slice, without error checking. if end == start begin return call __class__ end set offset = _offset set tuple startbyte newoffset = divide mod start + offset 8 set endbyte = end + offset - 1 // 8 set bs = call __class__ call _setbytes_unsafe call getb...
def _slice(self, start, end): """Used internally to get a slice, without error checking.""" if end == start: return self.__class__() offset = self._offset startbyte, newoffset = divmod(start + offset, 8) endbyte = (end + offset - 1) // 8 bs = self.__class__() ...
Python
jtatman_500k
from datetime import datetime , timedelta set GIGASECOND = time delta seconds=1000000000.0 function add_gigasecond date begin return date + GIGASECOND end function
from datetime import datetime, timedelta GIGASECOND = timedelta(seconds=1e9) def add_gigasecond(date: datetime) -> datetime: return date + GIGASECOND
Python
zaydzuhri_stack_edu_python
function _convert x begin set easting = x set northing = y set tuple zone_number zone_letter = split replace x at 1 string , string ; string ; 1 return call to_latlon easting northing integer zone_number zone_letter end function
def _convert(x): easting = x[0].x northing = x[0].y zone_number, zone_letter = x[1].replace(',',';').split(';',1) return convert.to_latlon(easting, northing, int(zone_number), zon...
Python
nomic_cornstack_python_v1
comment !/usr/bin/env python3 string builds a neural network with the Keras librarys import tensorflow.keras as keras function save_model network filename begin string Save a model Args: network: model to save filename: the path of the file that the model should be saved to Returns: None save filename return none end f...
#!/usr/bin/env python3 """builds a neural network with the Keras librarys""" import tensorflow.keras as keras def save_model(network, filename): """Save a model Args: network: model to save filename: the path of the file that the model should be saved to Returns: None """ ...
Python
zaydzuhri_stack_edu_python
import csv import itertools import pandas as pd import numpy as np import nltk from nltk import word_tokenize from nltk.tokenize import RegexpTokenizer from nltk.corpus import stopwords from sklearn.feature_extraction.text import TfidfVectorizer from sklearn.decomposition import TruncatedSVD from sklearn.metrics import...
import csv import itertools import pandas as pd import numpy as np import nltk from nltk import word_tokenize from nltk.tokenize import RegexpTokenizer from nltk.corpus import stopwords from sklearn.feature_extraction.text import TfidfVectorizer from sklearn.decomposition import TruncatedSVD from sklearn.metrics import...
Python
zaydzuhri_stack_edu_python
function get_figure title_name plot_configuration begin set fig = figure title fig=fig title_name=title_name call label_axes fig=fig xlabel=xlabel ylabel=ylabel grid fig=fig is_grid=grid return fig end function
def get_figure(title_name, plot_configuration: PlotConfiguration): fig = plt.figure() title(fig=fig, title_name=title_name) label_axes( fig=fig, xlabel=plot_configuration.xlabel, ylabel=plot_configuration.ylabel ) grid(fig=fig, is_grid=plot_configuration.grid) return fig
Python
nomic_cornstack_python_v1
function cikart x y begin return x - y end function
def cikart(x, y): return x - y
Python
nomic_cornstack_python_v1
string Module containing methods for plotting. import logging import numpy as np import operator as op from math import isnan import brewer2mpl as cb import matplotlib.pyplot as plt comment User modules from import constants function plot_auc fpr tpr auc begin figure plot fpr tpr label=string ROC curve (area = %0.2f),...
"""Module containing methods for plotting.""" import logging import numpy as np import operator as op from math import isnan import brewer2mpl as cb import matplotlib.pyplot as plt # User modules from . import constants def plot_auc(fpr, tpr, auc): plt.figure() plt.plot(fpr, tpr, label='ROC c...
Python
zaydzuhri_stack_edu_python
comment !/usr/bin/env python import sys import re import vtk from vtk import vtkScalarBarActor , vtkTextProperty import Tkinter from vtk.tk.vtkTkRenderWindowInteractor import vtkTkRenderWindowInteractor set continuousType = string HSV set discreateType = string HSV set continuousSize = 0 set discreateSize = 0 set conti...
#!/usr/bin/env python import sys import re import vtk from vtk import vtkScalarBarActor, vtkTextProperty import Tkinter from vtk.tk.vtkTkRenderWindowInteractor import vtkTkRenderWindowInteractor continuousType = "HSV" discreateType = "HSV" continuousSize = 0 discreateSize = 0 continuousData = [] discreteData = [] d...
Python
zaydzuhri_stack_edu_python
function info self begin set maxts = 0 for f in list directory APPINSTALLDIR begin if f at 0 == string . or not ends with f string .desktop begin continue end try begin set ts = call getmtime join path APPINSTALLDIR f if ts > maxts begin set maxts = ts end end comment ignore file not found #752195 (potential race) exce...
def info(self): maxts = 0 for f in os.listdir(APPINSTALLDIR): if f[0] == '.' or not f.endswith(".desktop"): continue try: ts = os.path.getmtime(os.path.join(APPINSTALLDIR, f)) if ts > maxts: maxts = ts except OSError: # ignore file not ...
Python
nomic_cornstack_python_v1
function say_hello begin return string Hello! end function set greeting = call say_hello print greeting function confuse begin print string bears return 42 end function call confuse
def say_hello(): return "Hello!" greeting = say_hello() print(greeting) def confuse(): print ("bears") return 42 confuse()
Python
zaydzuhri_stack_edu_python
function visualise road_map begin set canvas_scale = 3 set canvas_margin = 30 set canvas_height = 180 * canvas_scale + canvas_margin set canvas_width = 360 * canvas_scale + canvas_margin set limits = call distances_and_limits road_map at slice 1 : : set tuple min_lat max_lat = tuple limits at 0 limits at 1 set tuple ...
def visualise(road_map): canvas_scale = 3 canvas_margin = 30 canvas_height = (180 * canvas_scale) + canvas_margin canvas_width = (360 * canvas_scale) + canvas_margin limits = distances_and_limits(road_map)[1:] min_lat, max_lat = limits[0], limits[1] min_long, max_long = limits[2], limit...
Python
nomic_cornstack_python_v1
function get_post id check_author=true begin set post = call fetchone if post is none begin call abort 404 format string Post id {0} doesn't exist. id end if check_author and post at string author_id != user at string id begin call abort 403 end return post end function
def get_post(id, check_author=True): post = get_db().execute( 'SELECT p.id, title, body, created, author_id, username' ' FROM post p JOIN user u ON p.author_id = u.id' ' WHERE p.id = ?', (id,) ).fetchone() if post is None: abort(404, "Post id {0} doesn't exist.".form...
Python
nomic_cornstack_python_v1
for i in range 0 long begin if ordinal save at i <= 90 and ordinal save at i >= 65 begin set save at i = string _ + character ordinal save at i + 32 end end set t = string set s = join t save print s
for i in range(0,long): if(ord(save[i])<=90 and ord(save[i])>=65): save[i]='_'+chr(ord(save[i])+32) t="" s=t.join(save) print(s)
Python
zaydzuhri_stack_edu_python
function filter_users_by_transaction_date self request begin set users = filter transactions__date=data at string date set serializer = call UserSerializer users many=true return call Response data end function
def filter_users_by_transaction_date(self, request): users = User.objects.filter(transactions__date=request.data["date"]) serializer = UserSerializer(users, many=True) return Response(serializer.data)
Python
nomic_cornstack_python_v1
import random set dict = dict set l = dict set S = 11 set m = 3 set n = 5 set x = 1 set y = 0 set aOne = random integer 1 99 set aTwo = random integer 1 99 set p = random integer 40 99 class protocol3 begin function __init__ self dict l S m n x aOne aTwo p y begin set dict = dict set l = l set S = S set m = m set n =...
import random dict = {} l = {} S = 11 m = 3 n = 5 x = 1 y = 0 aOne = (random.randint(1, 99)) aTwo = (random.randint(1, 99)) p = (random.randint(40, 99)) class protocol3(): def __init__(self,dict,l,S,m,n,x,aOne,aTwo,p,y): self.dict = dict self.l = l self.S = S self.m = m ...
Python
zaydzuhri_stack_edu_python
comment def string_length(user1,user2): comment i=0 comment while i<len(user1): comment j=0 comment count_1=0 comment while j<len(user2): comment j=j+1 comment i=i+1 comment if i>j: comment return(i,user1,"length is big") comment elif i==j: comment print(user1) comment return(user2) comment else: comment return(j,user2...
# def string_length(user1,user2): # i=0 # while i<len(user1): # j=0 # count_1=0 # while j<len(user2): # j=j+1 # i=i+1 # if i>j: # return(i,user1,"length is big") # elif i==j: # print(user1) # return(user2) # else: # return(j,user2,"length is long") # u1=input("enter string1: ") # ...
Python
zaydzuhri_stack_edu_python
import numpy as np import pandas as pd from sklearn import preprocessing from sklearn.preprocessing import Imputer from itertools import combinations function binary_features data begin set col_names = list for col in list set columns - set list string TARGET begin set le = call LabelEncoder set le = fit le data at co...
import numpy as np import pandas as pd from sklearn import preprocessing from sklearn.preprocessing import Imputer from itertools import combinations def binary_features(data): col_names = [] for col in list(set(data.columns) - set(['TARGET'])): le = preprocessing.LabelEncoder() le = le.fit(data[col]) ...
Python
zaydzuhri_stack_edu_python
function _forward_mode self *args begin comment Evaluate inner function self.f set X : ndarray set dX : ndarray set tuple X dX = call _forward_mode *args comment The function value set val = call func X comment The derivative set diff = call deriv X * dX return tuple val diff end function
def _forward_mode(self, *args): # Evaluate inner function self.f X: np.ndarray dX: np.ndarray X, dX = self.f._forward_mode(*args) # The function value val = self.func(X) # The derivative diff = self.deriv(X) * dX return (val, diff)
Python
nomic_cornstack_python_v1
function get_frame frame begin return call from_bytes frame byteorder=string big end function
def get_frame(frame): return int.from_bytes(frame, byteorder='big')
Python
nomic_cornstack_python_v1
function enforce self begin return get pulumi self string enforce end function
def enforce(self) -> pulumi.Output[Optional[bool]]: return pulumi.get(self, "enforce")
Python
nomic_cornstack_python_v1
function setup_cross begin if not exists path cross_prefix begin call docmd string mkdir %s % cross_prefix end set epath = environ at string PATH call set_evar string PATH string %s/bin:%s % tuple cross_prefix epath end function
def setup_cross(): if not os.path.exists(cross_prefix): docmd("mkdir %s" % cross_prefix) epath = os.environ["PATH"] set_evar("PATH", "%s/bin:%s" % (cross_prefix, epath))
Python
nomic_cornstack_python_v1
comment vektörel toplam function my_Vector_Addition v w begin set my_result = list for i in range length v begin append my_result 0 end for i in range length v begin set my_result at i = v at i + w at i end return my_result end function comment vektörel çıkarma function my_Vector_Substraction v w begin set size = leng...
def my_Vector_Addition(v,w):#vektörel toplam my_result=[] for i in range (len(v)): my_result.append(0) for i in range(len(v)): my_result[i]=v[i]+w[i] return my_result def my_Vector_Substraction(v,w):#vektörel çıkarma size=len(v) my_result=[] for i in range (size): my_result.append(0) fo...
Python
zaydzuhri_stack_edu_python
function minMax numbers begin set max_num = numbers at 0 set min_num = numbers at 0 for num in numbers begin if num > max_num begin set max_num = num end else if num < min_num begin set min_num = num end end return tuple min_num max_num end function
def minMax(numbers): max_num = numbers[0] min_num = numbers[0] for num in numbers: if num > max_num: max_num = num elif num < min_num: min_num = num return (min_num, max_num)
Python
flytech_python_25k
function test_stress_not_in_two_files generate_no_stress_one_file begin set fname = generate_no_stress_one_file with raises Exception begin call process_files list fname fname end end function
def test_stress_not_in_two_files(generate_no_stress_one_file): fname = generate_no_stress_one_file with pytest.raises(Exception): process_files([fname, fname])
Python
nomic_cornstack_python_v1
from typing import get_args from exceptions.api_exceptions import InternalServerError comment TODO: This severity_risk is just assumed based on similar models. comment Returning the risk_score and the severity of the risk_score function hyperemesis_gravidarum_risk risk_score begin set base_risk = 2 set percent = min 10...
from typing import get_args from ...exceptions.api_exceptions import InternalServerError # TODO: This severity_risk is just assumed based on similar models. # Returning the risk_score and the severity of the risk_score def hyperemesis_gravidarum_risk(risk_score: int) -> dict: base_risk = 2 percent = min(100, (...
Python
zaydzuhri_stack_edu_python
import librosa import soundfile import os , glob , pickle import numpy as np from sklearn.model_selection import train_test_split from sklearn.neural_network import MLPClassifier from sklearn.metrics import accuracy_score from pydub import AudioSegment from tqdm.notebook import tqdm_notebook import matplotlib.pyplot as...
import librosa import soundfile import os, glob, pickle import numpy as np from sklearn.model_selection import train_test_split from sklearn.neural_network import MLPClassifier from sklearn.metrics import accuracy_score from pydub import AudioSegment from tqdm.notebook import tqdm_notebook import matplotlib.pyplot as p...
Python
zaydzuhri_stack_edu_python
import datetime from domain.book import Book from domain.client import Client from domain.rental import Rental function testInitBooks repo begin add repo call Book 0 string Harry Potter and the Philosopher's Stone string first book of HP series string J.K. Rowling add repo call Book 1 string Harry Potter and the Chambe...
import datetime from domain.book import Book from domain.client import Client from domain.rental import Rental def testInitBooks(repo): repo.add(Book(0,"Harry Potter and the Philosopher's Stone ", "first book of HP series", "J.K. Rowling")) repo.add(Book(1,"Harry Potter and the Chamber of Secrets ", "...
Python
zaydzuhri_stack_edu_python
string Generate sales report showing total melons each salesperson sold. comment Creates an empty array for salespeople set salespeople = list comment Creates an empty array for melons sold set melons_sold = list comment Opens our sales report file set f = open string sales-report.txt comment Iterates through each li...
"""Generate sales report showing total melons each salesperson sold.""" salespeople = [] # Creates an empty array for salespeople melons_sold = [] # Creates an empty array for melons sold f = open('sales-report.txt') # Opens our sales report file for line in f: # Iterates through each line in the file line = lin...
Python
zaydzuhri_stack_edu_python
function add num1 num2 begin return num1 + num2 end function function sub num1 num2 begin return num1 - num2 end function function mult num1 num2 begin return num1 * num2 end function function div num1 num2 begin return num1 / num2 end function
def add(num1,num2): return num1+num2 def sub(num1,num2): return num1-num2 def mult(num1,num2): return num1*num2 def div(num1,num2): return num1/num2
Python
zaydzuhri_stack_edu_python
function fl_set_browser_topline ptr_flobject linenum begin set _fl_set_browser_topline = call cfuncproto call load_so_libforms string fl_set_browser_topline none list call POINTER FL_OBJECT c_int string void fl_set_browser_topline(FL_OBJECT * ob, int line) call check_if_flinitialized call verify_flobjectptr_type ptr_fl...
def fl_set_browser_topline(ptr_flobject, linenum): _fl_set_browser_topline = library.cfuncproto( library.load_so_libforms(), "fl_set_browser_topline", None, [cty.POINTER(xfdata.FL_OBJECT), cty.c_int], """void fl_set_browser_topline(FL_OBJECT * ob, int line)""") library.check_if_flinitial...
Python
nomic_cornstack_python_v1
from src.models.Partie import Partie from src.models.Coup import Coup from src import db , engine import cx_Oracle class Gameplay begin decorator staticmethod comment la fonction de creation d'une nouvelle partie, elle appelle la fonction create_partie du Model Partie function newgame user_id level_id begin return call...
from src.models.Partie import Partie from src.models.Coup import Coup from src import db,engine import cx_Oracle class Gameplay: # la fonction de creation d'une nouvelle partie, elle appelle la fonction create_partie du Model Partie @staticmethod def newgame(user_id,level_id): return Partie.create_...
Python
zaydzuhri_stack_edu_python
function node results node multiindex=false keep_none_type=false begin function replace_none col_list reverse=false begin set replacement = if expression reverse then tuple none NONE_REPLACEMENT_STR else tuple NONE_REPLACEMENT_STR none set changed_col_list = list comprehension tuple tuple if expression n1 is replacemen...
def node(results, node, multiindex=False, keep_none_type=False): def replace_none(col_list, reverse=False): replacement = ( (None, NONE_REPLACEMENT_STR) if reverse else (NONE_REPLACEMENT_STR, None) ) changed_col_list = [ ( ( ...
Python
nomic_cornstack_python_v1
function summary self begin if not taf_translations begin update self end return list comprehension call taf trans for trans in forecast end function
def summary(self): if not self.taf_translations: self.update() return [summary.taf(trans) for trans in self.taf_translations.forecast]
Python
nomic_cornstack_python_v1
function parse_args begin set parser = call ArgumentParser description=string Let's train some neural nets! call add_argument string --load-checkpoint default=none help=string Path to model checkpoint file (should end with the extension .h5). Checkpoints are automatically saved when you train your model. If you want to...
def parse_args(): parser = argparse.ArgumentParser( description="Let's train some neural nets!" ) parser.add_argument( '--load-checkpoint', default=None, help='''Path to model checkpoint file (should end with the extension .h5). Checkpoints are automatically saved wh...
Python
nomic_cornstack_python_v1
class Name begin function __init__ self fname=string Alok lname=string Choudhary begin set __fname = fname set __lname = lname end function decorator property function fname self begin return __fname end function decorator setter function fname self f_name begin set __fname = f_name end function decorator property func...
class Name: def __init__(self,fname='Alok', lname='Choudhary'): self.__fname=fname self.__lname=lname @property def fname(self): return self.__fname @fname.setter def fname(self,f_name): self.__fname=f_name @property def lname(self): return self.__lnam...
Python
zaydzuhri_stack_edu_python
from sqlalchemy import Column , Integer , String , Text , ForeignKey from database import Base , session class Item extends Base begin set __tablename__ = string items set id = call Column Integer primary_key=true index=true set title = call Column call String 100 nullable=false set description = call Column Text nulla...
from sqlalchemy import Column, Integer, String, Text, ForeignKey from .database import Base, session class Item(Base): __tablename__ = 'items' id = Column(Integer,primary_key=True,index=True) title = Column(String(100),nullable=False) description = Column(Text,nullable=True) user_id = Column(Inte...
Python
zaydzuhri_stack_edu_python
from datetime import datetime , timedelta from transitions.extensions.asyncio import AsyncMachine import asyncio class Notificator begin set states = list string new string checking_exchange string price_scheduling string expired string done function __init__ self name expired_time begin set my_name = name set target_t...
from datetime import datetime, timedelta from transitions.extensions.asyncio import AsyncMachine import asyncio class Notificator: states = ['new', 'checking_exchange', 'price_scheduling', 'expired', 'done'] def __init__(self, name: str, expired_time: datetime): self.my_name = name self.targe...
Python
zaydzuhri_stack_edu_python
function list_directories dir begin return list comprehension name for name in list directory dir if is directory path join path dir name end function
def list_directories(dir): return [name for name in os.listdir(dir) if os.path.isdir(os.path.join(dir, name))]
Python
nomic_cornstack_python_v1
function tearDown self begin close session end function comment db.drop_all()
def tearDown(self): db.session.close() # db.drop_all()
Python
nomic_cornstack_python_v1
function create_simulation *classes begin class Simulation extends *classes begin pass end class return Simulation end function
def create_simulation(*classes): class Simulation(*classes): pass return Simulation
Python
nomic_cornstack_python_v1
function start_publishers self begin for publisher in _publishers begin start publisher end end function
def start_publishers(self): for publisher in self._publishers: publisher.start()
Python
nomic_cornstack_python_v1
comment -*- coding: utf-8 -*- string Created on Sat Nov 11 13:32:55 2017 @author: ZY comment question 2.3.2 function memory n begin function abc ff begin nonlocal n set n = call ff n print n return abc end function return abc end function
# -*- coding: utf-8 -*- """ Created on Sat Nov 11 13:32:55 2017 @author: ZY """ #question 2.3.2 def memory(n): def abc(ff): nonlocal n n=ff(n) print(n) return abc return abc
Python
zaydzuhri_stack_edu_python
function sayToClient self message client begin write console tuple string admin.say message string player cid end function
def sayToClient(self, message, client): self.console.write(('admin.say', message, 'player', client.cid))
Python
nomic_cornstack_python_v1
comment !/usr/bin/env python comment coding: utf-8 comment In[ ]: comment This Python 3 environment comes with many helpful analytics libraries installed comment It is defined by the kaggle/python docker image: https://github.com/kaggle/docker-python comment For example, here's several helpful packages to load in comme...
#!/usr/bin/env python # coding: utf-8 # In[ ]: # This Python 3 environment comes with many helpful analytics libraries installed # It is defined by the kaggle/python docker image: https://github.com/kaggle/docker-python # For example, here's several helpful packages to load in import numpy as np # linear algebra i...
Python
zaydzuhri_stack_edu_python
function cem x y begin return x + y end function function ferq x y begin return x - y end function function hasil x y begin return x * y end function function nisbet x y begin return x / y end function print string Emelin novunu daxil edin : 1. Toplama 2. CIXMA 3. VURMA 4. BOLME while true begin set secim = input strin...
def cem(x, y): return x + y def ferq(x, y): return x - y def hasil(x, y): return x * y def nisbet(x, y): return x / y print("Emelin novunu daxil edin :\n 1. Toplama\n 2. CIXMA\n 3. VURMA\n 4. BOLME") while True: secim = input("Sechiminiz :") if secim in('1'...
Python
zaydzuhri_stack_edu_python
function localidad self begin return _localidad end function
def localidad(self): return self._localidad
Python
nomic_cornstack_python_v1
function show_fields self block=none begin string Retrieve and return the mapping for the given metadata block. Arguments: block (str): The top-level field to fetch the mapping for (for example, ``"mdf"``), or the special values ``None`` for everything or ``"top"`` for just the top-level fields. **Default:** ``None``. ...
def show_fields(self, block=None): """Retrieve and return the mapping for the given metadata block. Arguments: block (str): The top-level field to fetch the mapping for (for example, ``"mdf"``), or the special values ``None`` for everything or ``"top"`` for just the ...
Python
jtatman_500k
function midpoint_of_points pnts begin set num = length pnts set x = sum generator expression x for pnt in pnts / num set y = sum generator expression y for pnt in pnts / num set z = sum generator expression z for pnt in pnts / num return call Point x y z end function
def midpoint_of_points(pnts: Iterable[Point]) -> Point: num = len(pnts) x = sum(pnt.x for pnt in pnts)/num y = sum(pnt.y for pnt in pnts)/num z = sum(pnt.z for pnt in pnts)/num return Point(x, y, z)
Python
nomic_cornstack_python_v1
from mymodule import stats_word as a import requests from pyquery import PyQuery from wxpy import * comment 初始化机器人,扫码登陆 set bot = call Bot comment 搜索好友,但没有指定好友的名称 comment 搜索名称含有 "游否" 的男性深圳好友 comment 找寻名称为豆彭的好友,后面的[0]是什么意思? set my_friend = search string 豆彭 at 0 decorator call register chats=my_friend msg_types=string SH...
from mymodule import stats_word as a import requests from pyquery import PyQuery from wxpy import * # 初始化机器人,扫码登陆 bot = Bot() # 搜索好友,但没有指定好友的名称 # 搜索名称含有 "游否" 的男性深圳好友 my_friend = bot.friends().search('豆彭')[0] #找寻名称为豆彭的好友,后面的[0]是什么意思? #微信机器人启动了,现在要完成对好友的自动监听,一旦发送类型为sharing 的消息,获取这个消息的url并使用项目一中的代码进行分析并 #返回 @bot.regis...
Python
zaydzuhri_stack_edu_python
function send_result_signal self i token_group=none begin if file_type == SQUID begin set text = list i + 1 token_group at 0 token_group at 1 token_group at 2 split token_group at 3 string / at - 1 token_group at 4 token_group at 7 token_group at 8 token_group at 9 token_group at 5 split token_group at 6 string ? at 0 ...
def send_result_signal(self, i, token_group=None): if self.file_type == settings.SQUID: text = [i + 1, token_group[0], token_group[1], token_group[2], token_group[3].split("/")[-1], token_group[4], token_group[7], token_group[8], token_grou...
Python
nomic_cornstack_python_v1
function test_description_is_valid_html self begin set p = join op directory name op path string DESCRIPTION.en_us.html set msg = string DESCRIPTION.en_us.html is not real html file assert equal call from_file p mime=true string text/html msg end function
def test_description_is_valid_html(self): p = op.join(op.dirname(self.operator.path), 'DESCRIPTION.en_us.html') msg = 'DESCRIPTION.en_us.html is not real html file' self.assertEqual(magic.from_file(p, mime=True), 'text/html', msg)
Python
nomic_cornstack_python_v1
comment you can write to stdout for debugging purposes, e.g. comment print "this is a debug message" function solution A begin sort A reverse=true return max A at 0 * A at 1 * A at 2 A at 0 * A at - 1 * A at - 2 end function
# you can write to stdout for debugging purposes, e.g. # print "this is a debug message" def solution(A): A.sort(reverse=True) return max(A[0] * A[1] * A[2], A[0] * A[-1] * A[-2])
Python
zaydzuhri_stack_edu_python
comment How to declare boolean comment **> can, has, is <** set can_walk = true set can_run = true set has_money = false set is_dog = true print type name print type age print type weight print type can_walk print type can_run
#How to declare boolean # **> can, has, is <** can_walk = True can_run = True has_money = False is_dog = True print(type(name)) print(type(age)) print(type(weight)) print(type(can_walk)) print(type(can_run))
Python
zaydzuhri_stack_edu_python
function softmax2 h begin comment Find the max value from h. set ndims = ndims if ndims != 3 begin raise call ValueError format string Expecting ndims = 3, actual={} ndims end set tuple _ height width = call as_list return reshape tf softmax reshape tf h list - 1 width * height list - 1 height width end function
def softmax2(h): # Find the max value from h. ndims = h.get_shape().ndims if ndims != 3: raise ValueError('Expecting ndims = 3, actual={}'.format(ndims)) _, height, width = h.get_shape().as_list() return tf.reshape( tf.nn.softmax(tf.reshape(h, [-1, width * height])), [-1, height, width])
Python
nomic_cornstack_python_v1
function update_network self context net_id network begin debug call _ string NeutronRestProxyV2.update_network() called call _warn_on_state_status network at string network set session = session with call begin subtransactions=true begin set new_net = call update_network context net_id network call _process_l3_update ...
def update_network(self, context, net_id, network): LOG.debug(_("NeutronRestProxyV2.update_network() called")) self._warn_on_state_status(network['network']) session = context.session with session.begin(subtransactions=True): new_net = super(NeutronRestProxyV2, self).update...
Python
nomic_cornstack_python_v1
for i in range 10 begin print a set tuple a b = tuple b a + b end
for i in range(10): print(a) a, b = b, a + b
Python
jtatman_500k
string Tests for Markov Autoregression models Author: Chad Fulton License: BSD-3 import warnings import os import numpy as np from numpy.testing import assert_equal , assert_allclose import pandas as pd import pytest from statsmodels.tools import add_constant from statsmodels.tsa.regime_switching import markov_autoregr...
""" Tests for Markov Autoregression models Author: Chad Fulton License: BSD-3 """ import warnings import os import numpy as np from numpy.testing import assert_equal, assert_allclose import pandas as pd import pytest from statsmodels.tools import add_constant from statsmodels.tsa.regime_switching import markov_auto...
Python
jtatman_500k
function test_unload install_mockery mock_fetch mock_archive mock_packages working_env begin call install string mpileaks set mpileaks_spec = call concretized comment Set so unload has something to do set environ at string FOOBAR = string mpileaks set environ at spack_loaded_hashes_var = string %s:%s % tuple call dag_h...
def test_unload(install_mockery, mock_fetch, mock_archive, mock_packages, working_env): install("mpileaks") mpileaks_spec = spack.spec.Spec("mpileaks").concretized() # Set so unload has something to do os.environ["FOOBAR"] = "mpileaks" os.environ[uenv.spack_loaded_hashes_var] = "%s:%s" % (mpileaks_...
Python
nomic_cornstack_python_v1
function __ne__ self other begin return not self == other end function
def __ne__(self, other): return not self == other
Python
nomic_cornstack_python_v1
comment !/usr/bin/env python comment -*- coding: utf-8 -*- import RPi.GPIO as GPIO import time comment Ignore warnings for now call setwarnings false call setmode BOARD comment setup every channel we want to use as an input or output setup GPIO 11 OUT comment gpio pin 7 as input with pull up resistor setup GPIO 13 IN p...
#!/usr/bin/env python # -*- coding: utf-8 -*- import RPi.GPIO as GPIO import time GPIO.setwarnings(False) # Ignore warnings for now GPIO.setmode(GPIO.BOARD) # setup every channel we want to use as an input or output GPIO.setup(11, GPIO.OUT) GPIO.setup(13, GPIO.IN, pull_up_down=GPIO.PUD_UP) # gpio pin 7 as input with ...
Python
zaydzuhri_stack_edu_python