code stringlengths 10 2.58M | original_code stringlengths 3 3.18M | original_language stringclasses 1
value | source stringclasses 7
values |
|---|---|---|---|
function wait_until_summit_moved_distance self distance
begin
set rate = call Rate 5
while data < distance
begin
sleep
end
call loginfo string Summit has moved disatance= + string data
end function | def wait_until_summit_moved_distance(self, distance):
rate = rospy.Rate(5)
while self._summit_mved_distance.data < distance:
rate.sleep()
rospy.loginfo("Summit has moved disatance="+str(self._summit_mved_distance.data)) | Python | nomic_cornstack_python_v1 |
function white_noise
begin
return random integer - 32767 32767
end function | def white_noise():
return random.randint(-32767, 32767) | Python | nomic_cornstack_python_v1 |
function train_model X_train y_train parameters
begin
set d_train = call Dataset X_train label=y_train
set boosting_type = parameters at string boosting_type
set objective = parameters at string objective
set metric = parameters at string metric
set max_depth = parameters at string max_depth
set learning_rate = paramet... | def train_model(X_train: np.ndarray, y_train: np.ndarray, parameters: Dict) -> lgb:
d_train = lgb.Dataset(X_train, label=y_train)
boosting_type = parameters["boosting_type"]
objective = parameters["objective"]
metric = parameters["metric"]
max_depth = parameters["max_depth"]
learning_r... | Python | nomic_cornstack_python_v1 |
function fit self data historical_data=none
begin
if historical_data is none
begin
set total_data = data
end
else
begin
extend historical_data data
set total_data = historical_data
end
comment No incremental training. Create a model and train from scratch
set model = call Prophet interval_width=scoring_confidence_inter... | def fit(
self, data: TimeSeriesData, historical_data: Optional[TimeSeriesData] = None
) -> None:
if historical_data is None:
total_data = data
else:
historical_data.extend(data)
total_data = historical_data
# No incremental training. Create a mod... | Python | nomic_cornstack_python_v1 |
string input 3
from sys import stdin
import math
function make_dp
begin
set dp = list 0 * 1001
set dp at 1 = 1
set dp at 3 = 5
for i in range 5 100 2
begin
set dp at i = dp at i - 2 + i + i - 2
end
return dp
end function
comment main starts
set x = integer strip read line stdin
if x == 3
begin
print 5
exit
end
set dp =... | '''input
3
'''
from sys import stdin
import math
def make_dp():
dp = [0] * 1001
dp[1] = 1
dp[3] = 5
for i in range(5, 100, 2):
dp[i] = dp[i - 2] + i + i - 2
return dp
# main starts
x = int(stdin.readline().strip())
if x == 3:
print(5)
exit()
dp = make_dp()
for i in range(1, len(dp)):
if x <= dp[i]:
pr... | Python | jtatman_500k |
function split_into_episodes self p n
begin
return list comprehension call sample_episode list n index at 0 at 1 for index in call argwhere p == - 1
end function | def split_into_episodes(self, p, n):
return [self.sample_episode([], n, index[0])[1]
for index in np.argwhere(p == -1)] | Python | nomic_cornstack_python_v1 |
comment !/usr/bin/python
comment -*- coding: utf-8 -*-
string @author bendell02 @desc extract files by time_prefix @date 20200226
import os
import os.path
import shutil
import datetime
import re
from enum import Enum
import random
function has_time_prefix name
begin
comment OK example 20200226_xxxx
comment length
if le... | #!/usr/bin/python
# -*- coding: utf-8 -*-
"""
@author bendell02
@desc extract files by time_prefix
@date 20200226
"""
import os
import os.path
import shutil
import datetime
import re
from enum import Enum
import random
def has_time_prefix(name):
# OK example 20200226_xxxx
# length
if(len(name) <= 9):
... | Python | zaydzuhri_stack_edu_python |
from bs4 import BeautifulSoup
set html_file = open string D://Django//csspractice.html string r
set page = read html_file
print page
set soup = call BeautifulSoup page string html.parser
set paragraph = find all soup string ol
for p in paragraph
begin
print get text p
end | from bs4 import BeautifulSoup
html_file=open("D://Django//csspractice.html","r")
page=html_file.read()
print(page)
soup=BeautifulSoup(page,"html.parser")
paragraph=soup.find_all('ol')
for p in paragraph:
print(p.get_text())
| Python | zaydzuhri_stack_edu_python |
comment -*- coding: utf-8 -*-
string Created on Fri Dec 13 20:41:14 2019 @author: kshamaj
comment -*- coding: utf-8 -*-
string Created on Sun Nov 24 19:00:21 2019 @author: kshamaj
pwd
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
comment data cleaning............
comment l... | # -*- coding: utf-8 -*-
"""
Created on Fri Dec 13 20:41:14 2019
@author: kshamaj
"""
# -*- coding: utf-8 -*-
"""
Created on Sun Nov 24 19:00:21 2019
@author: kshamaj
"""
pwd
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
#data cleaning............... | Python | zaydzuhri_stack_edu_python |
function recreate_user_with_no_access self
begin
call run_user_recreate_with_no_access
end function | def recreate_user_with_no_access(self):
self.test_runner.run_user_recreate_with_no_access() | Python | nomic_cornstack_python_v1 |
function dipole_to_point dipole deg=true
begin
comment Get distances between coordinates.
set tuple dx dy dz = squeeze diff np T
set length = norm list dx dy dz
comment Get angles from complex planes.
comment same as: np.arctan2(dy, dx)
set azimuth = call angle dx + 1j * dy deg=deg
comment (dz, dxy)
set elevation = cal... | def dipole_to_point(dipole, deg=True):
# Get distances between coordinates.
dx, dy, dz = np.diff(dipole.T).squeeze()
length = np.linalg.norm([dx, dy, dz])
# Get angles from complex planes.
azimuth = np.angle(dx + 1j*dy, deg=deg) # same as: np.arctan2(dy, dx)
elevation = np.angle(np.sqrt(dx**2... | Python | nomic_cornstack_python_v1 |
function column_range self
begin
string Returns a [*begin*, *end*) tuple describing the range of columns spanned by this range. If range spans more than one line, returned *end* is the last column of the line.
if call line == call line
begin
return tuple call column call column
end
else
begin
return tuple call column l... | def column_range(self):
"""
Returns a [*begin*, *end*) tuple describing the range of columns spanned
by this range. If range spans more than one line, returned *end* is
the last column of the line.
"""
if self.begin().line() == self.end().line():
return self.b... | Python | jtatman_500k |
import math
while true
begin
set countLoop = integer input
if countLoop == 0
begin
break
end
set matriz = list
for x in range countLoop
begin
append matriz list
for y in range countLoop
begin
append matriz at x 0
end
end
for x in range countLoop
begin
for y in range countLoop
begin
if y == 0
begin
set matriz at x at y... | import math
while True:
countLoop = int(input())
if countLoop == 0:
break
matriz = []
for x in range(countLoop):
matriz.append([])
for y in range(countLoop):
matriz[x].append(0)
for x in range(countLoop):
for y in range(countLoop):
if y == 0:
... | Python | zaydzuhri_stack_edu_python |
function plot all_exps
begin
comment Reduce the experiment logs values across **time**
set frame = call to_data_frame all_exps reduce_fn=reduce_last
comment Take the mean of weighting schemes across **experiments**
set frame = call reduce_mean_keys frame col_keys=tuple string weighting_scheme string layers
comment Rena... | def plot(all_exps):
# Reduce the experiment logs values across **time**
frame = log_processor.to_data_frame(all_exps, reduce_fn=log_processor.reduce_last)
# Take the mean of weighting schemes across **experiments**
frame = log_processor.reduce_mean_keys(frame, col_keys=('weighting_scheme', 'layers'))
... | Python | nomic_cornstack_python_v1 |
function __on_connect __client userdata flags rc
begin
info string Connected to broker
call subscribe __commands_topic qos=2
end function | def __on_connect(__client, userdata, flags, rc):
logger.info("Connected to broker ")
__client.subscribe(
Switch.active_instance.__commands_topic,
qos=2) | Python | nomic_cornstack_python_v1 |
function getch_name timeout=0
begin
set ords = call getch_ords timeout
return get KEYS ords call chars ords
end function | def getch_name(timeout=0):
ords = getch_ords(timeout)
return settings.KEYS.get(ords, conversion.chars(ords)) | Python | nomic_cornstack_python_v1 |
import RPi.GPIO as GPIO
import time
call setmode BCM
call setwarnings false
setup GPIO 26 OUT
print string LED on
call output 26 HIGH
sleep 1
print string LED off
call output 26 LOW | import RPi.GPIO as GPIO
import time
GPIO.setmode(GPIO.BCM)
GPIO.setwarnings(False)
GPIO.setup(26,GPIO.OUT)
print("LED on")
GPIO.output(26,GPIO.HIGH)
time.sleep(1)
print("LED off")
GPIO.output(26,GPIO.LOW)
| Python | zaydzuhri_stack_edu_python |
import pyautogui , random
import time
set tuple w h = size pyautogui
try
begin
set time1 = decimal input string enter time gap in sec:
set time2 = decimal input string enter time gap2 in sec:
end
except any
begin
print string not a valid input
sleep 3
while true
begin
pass
end
end
sleep 1
while true
begin
for i in rang... | import pyautogui,random
import time
w,h = pyautogui.size()
try:
time1=float(input('enter time gap in sec:'))
time2=float(input('enter time gap2 in sec:'))
except:
print('not a valid input')
time.sleep(3)
while True:
pass
time.sleep(1)
while True:
for i in range(random.randint(1,10)):
xaxis_ran... | Python | zaydzuhri_stack_edu_python |
function to_str self
begin
return call pformat call to_dict
end function | def to_str(self):
return pprint.pformat(self.to_dict()) | Python | nomic_cornstack_python_v1 |
function _splpy_convert_tuple attributes
begin
string Create a function that converts tuples to be submitted as dict objects into Python tuples with the value by position. Return function handles tuple,dict,list[tuple|dict|None],None
function _to_tuples tuple_
begin
if is instance tuple_ tuple
begin
return tuple_
end
i... | def _splpy_convert_tuple(attributes):
"""Create a function that converts tuples to
be submitted as dict objects into Python tuples
with the value by position.
Return function handles tuple,dict,list[tuple|dict|None],None
"""
def _to_tuples(tuple_):
if isinstance(tuple_, tuple):
... | Python | jtatman_500k |
from datetime import date
from typing import Optional
from base import Base
class RelatedPersonMovie extends Base
begin
string Model to represent movie in which the person took part.
set id : str
set role : str
end class
class Person extends Base
begin
string Model to represent Person objects.
set id : str
set full_nam... | from datetime import date
from typing import Optional
from .base import Base
class RelatedPersonMovie(Base):
"""Model to represent movie in which the person took part."""
id: str
role: str
class Person(Base):
"""Model to represent Person objects."""
id: str
full_name: str
birth_date: ... | Python | zaydzuhri_stack_edu_python |
function set_lang self lang
begin
set _strings = strings at lang
call _set_texts
end function | def set_lang(self, lang: LangEnum) -> None:
self._strings = strings[lang]
self._set_texts() | Python | nomic_cornstack_python_v1 |
function test_missing_password_raises self
begin
with call object AsanaHook string get_connection return_value=call Connection conn_type=string asana
begin
set hook = call AsanaHook
end
with assert raises ValueError
begin
call get_conn
end
end function | def test_missing_password_raises(self):
with patch.object(AsanaHook, "get_connection", return_value=Connection(conn_type="asana")):
hook = AsanaHook()
with self.assertRaises(ValueError):
hook.get_conn() | Python | nomic_cornstack_python_v1 |
comment __author: bwzhang
comment __date: 2018/6/15
comment 闭包
comment x为外部变量
function outer x
begin
comment x为外部变量
set x = 10
comment 内部函数
function inner
begin
comment x为外部环境变量
print x
end function
comment inner为一个闭包
return inner
end function
comment inner()#inner 为局部变量,全局无法调用
set f = call outer
f dist | #__author: bwzhang
#__date: 2018/6/15
# 闭包
def outer(x): # x为外部变量
x=10 # x为外部变量
def inner(): #内部函数
print(x) #x为外部环境变量
return inner #inner为一个闭包
# inner()#inner 为局部变量,全局无法调用
f = outer()
f()
| Python | zaydzuhri_stack_edu_python |
import random
function number_guess
begin
print string Enter a number below between 1 and 10
set random_number = random integer 1 10
set guess = integer input
while guess != random_number
begin
if guess > random_number
begin
print string { guess } is greater than the answer
set guess = integer input
end
else
if guess <... | import random
def number_guess():
print('Enter a number below between 1 and 10')
random_number = random.randint(1, 10)
guess = int(input())
while guess != random_number:
if guess > random_number:
print(f'{guess} is greater than the answer')
guess = int(input())
... | Python | zaydzuhri_stack_edu_python |
function perform_sensitivity_analysis model net_params sparsities test_func group
begin
if group not in list string element string filter string channel
begin
raise call ValueError format string group parameter contains an illegal value: {} group
end
set sensitivities = ordered dictionary
comment Terminated layer for c... | def perform_sensitivity_analysis(model, net_params, sparsities, test_func, group):
if group not in ['element', 'filter', 'channel']:
raise ValueError("group parameter contains an illegal value: {}".format(group))
sensitivities = OrderedDict()
# Terminated layer for channel pruning
last_layer_na... | Python | nomic_cornstack_python_v1 |
function notification_broadcast actor key **kwargs
begin
set channel_layer = call get_channel_layer
set id_value = pop kwargs string id_value none
set recipient = pop kwargs string recipient none
set payload = dict string type string receive ; string key key ; string actor_name username ; string id_value id_value ; str... | def notification_broadcast(actor, key, **kwargs):
channel_layer = get_channel_layer()
id_value = kwargs.pop("id_value", None)
recipient = kwargs.pop("recipient", None)
payload = {
"type": "receive",
"key": key,
"actor_name": actor.username,
"id_value": id_value,
"... | Python | nomic_cornstack_python_v1 |
function _set_state self v load=false
begin
if has attribute v string _utype
begin
set v = call _utype v
end
try
begin
set t = call YANGDynClass v base=yc_state_openconfig_access_points__access_points_access_point_interfaces_interface_subinterfaces_subinterface_ipv4_addresses_address_state is_container=string container... | def _set_state(self, v, load=False):
if hasattr(v, "_utype"):
v = v._utype(v)
try:
t = YANGDynClass(v,base=yc_state_openconfig_access_points__access_points_access_point_interfaces_interface_subinterfaces_subinterface_ipv4_addresses_address_state, is_container='container', yang_name="state", parent=s... | Python | nomic_cornstack_python_v1 |
async function listloaded ctx
begin
await call send not_implemented
end function | async def listloaded(ctx):
await ctx.send(utils.not_implemented) | Python | nomic_cornstack_python_v1 |
import pygame
from lib.constants import COLOR_ACTIVE , RED , DEFAULT_FONT_SIZE
from lib.logic import is_valid_guess , is_valid_length_in_dictionary
from lib.parser import parse_dictionary
class inputBox
begin
function __init__ self x y width height text=string
begin
set text_bounding_box = call Rect x y width height
se... | import pygame
from lib.constants import COLOR_ACTIVE, RED, DEFAULT_FONT_SIZE
from lib.logic import is_valid_guess, is_valid_length_in_dictionary
from lib.parser import parse_dictionary
class inputBox:
def __init__(self, x: int, y: int, width: int, height: int, text: str = ""):
self.text_bounding_box = py... | Python | zaydzuhri_stack_edu_python |
import numpy as np
import datasets
from skimage import transform
import tensorflow as tf
from queue import Queue
from threading import Thread
class MetaBatchIterator
begin
function __init__ self dataset batch_size=100 classes_per_set=5 samples_per_class=1 query_per_cls=19
begin
set dataset = dataset
set batch_size = ba... | import numpy as np
import datasets
from skimage import transform
import tensorflow as tf
from queue import Queue
from threading import Thread
class MetaBatchIterator:
def __init__(self, dataset, batch_size=100, classes_per_set=5, samples_per_class=1, query_per_cls=19):
self.dataset = dataset
self... | Python | zaydzuhri_stack_edu_python |
comment real signature unknown; restored from __doc__
function setDate self p_int p_int_1 p_int_2
begin
return false
end function | def setDate(self, p_int, p_int_1, p_int_2): # real signature unknown; restored from __doc__
return False | Python | nomic_cornstack_python_v1 |
while true
begin
for b in range 0 c
begin
for a in range 0 b
begin
if a ^ 2 + b ^ 2 == c ^ 2
begin
if a + b + c == 1000
begin
print format string a = {}, b = {}, c = {}, a*b*c = {} a b c a * b * c
end
end
end
end
set c = c + 1
end | while True:
for b in range(0, c):
for a in range(0, b):
if a**2 + b**2 == c**2:
if a + b + c == 1000:
print('a = {}, b = {}, c = {}, a*b*c = {}'.format(a,b,c,a*b*c))
c += 1
| Python | zaydzuhri_stack_edu_python |
function update self game
begin
set cur_game = copy game
set visited = set literal cur_game
while not call is_terminal cur_game and not call is_unrolled_out_leaf cur_game
begin
set cur_game = call best_child cur_game
add visited cur_game
end
comment Once we get to a leaf that we need to rollout, do that. If cur_node
co... | def update(self, game):
cur_game = game.copy()
visited = {cur_game}
while not self.is_terminal(cur_game) and not self.is_unrolled_out_leaf(cur_game):
cur_game = self.best_child(cur_game)
visited.add(cur_game)
# Once we get to a leaf that we need to rollout, do th... | Python | nomic_cornstack_python_v1 |
function predict self test_data
begin
return predict leader test_data
end function | def predict(self, test_data):
return self.leader.predict(test_data) | Python | nomic_cornstack_python_v1 |
comment !/usr/bin/python
comment # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # ## # # # # # # # # # # # # # # # # # # # # # #
comment Author: Jorgen Vagan #
comment joiPlot.py | Joined data plot: A simple generic plot function, which takes multiple file input and #
comment and plots it according to instru... | #!/usr/bin/python
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # ## # # # # # # # # # # # # # # # # # # # # # #
# Author: Jorgen Vagan #
# joiPlot.py | Joined data plot: A simple generic plot function, which takes multipl... | Python | zaydzuhri_stack_edu_python |
function set_layouts self layouts
begin
try
begin
from zcrmsdk.src.com.zoho.crm.api.layouts import Layout
end
except Exception
begin
from layouts import Layout
end
if layouts is not none and not is instance layouts Layout
begin
raise call SDKException DATA_TYPE_ERROR string KEY: layouts EXPECTED TYPE: Layout none none
... | def set_layouts(self, layouts):
try:
from zcrmsdk.src.com.zoho.crm.api.layouts import Layout
except Exception:
from ..layouts import Layout
if layouts is not None and not isinstance(layouts, Layout):
raise SDKException(Constants.DATA_TYPE_ERROR, 'KEY: layouts EXPECTED TYPE: Layout', None, None)
se... | Python | nomic_cornstack_python_v1 |
class Bill
begin
function __init__ self amount
begin
set amount = amount
end function
function __str__ self
begin
return format string A {}$ bill amount
end function
function __repr__ self
begin
return call __str__
end function
function __int__ self
begin
return amount
end function
function __eq__ self other
begin
retu... | class Bill:
def __init__(self, amount):
self.amount = amount
def __str__(self):
return "A {}$ bill".format(self.amount)
def __repr__(self):
return self.__str__()
def __int__(self):
return self.amount
def __eq__(self, other):
return self.amount == other.am... | Python | zaydzuhri_stack_edu_python |
function BMICalculator weight height
begin
set bmi = weight / height ^ 2
return bmi
end function
print call BMICalculator 100 1.75 | def BMICalculator(weight , height):
bmi = weight / (height ** 2)
return bmi
print(BMICalculator(100,1.75))
| Python | zaydzuhri_stack_edu_python |
comment Extra components needed to transition to drawing environment.
from time import sleep
import ctypes
set user32 = user32
comment Prompt user for shape input
set shape2Draw = input string Would you like to draw a square, diamond, or rectangle?
comment wrong choice
if shape2Draw != string square and shape2Draw != s... | #Extra components needed to transition to drawing environment.
from time import sleep
import ctypes
user32 = ctypes.windll.user32
#Prompt user for shape input
shape2Draw=input("Would you like to draw a square, diamond, or rectangle?\n")
#wrong choice
if shape2Draw != "square" and shape2Draw != "rec... | Python | zaydzuhri_stack_edu_python |
import sys
set MAX = maxint
class Solution extends object
begin
function minSubArrayLen self s nums
begin
string :type s: int :type nums: List[int] :rtype: int @algorithm, sliding window O(n) @link https://leetcode.com/problems/minimum-size-subarray-sum/
set sum = 0
set start = 0
set minLen = MAX
for i in call xrange l... | import sys
MAX = sys.maxint
class Solution(object):
def minSubArrayLen(self, s, nums):
"""
:type s: int
:type nums: List[int]
:rtype: int
@algorithm, sliding window O(n)
@link https://leetcode.com/problems/minimum-size-subarray-sum/
"""
sum = 0
... | Python | zaydzuhri_stack_edu_python |
function append self item **data
begin
append _items item
if data
begin
set _data at item = data
end
end function | def append(self, item, **data):
self._items.append(item)
if data:
self._data[item] = data | Python | nomic_cornstack_python_v1 |
string dict 客户端 发起请求,展示结果
from socket import *
from getpass import getpass
import requests
from bs4 import BeautifulSoup
set ADDR = tuple string 127.0.0.1 8000
comment 所有函数都用s
set s = call socket
comment s.connect(ADDR)
comment 二级界面
function login name
begin
while true
begin
print string ================Query==========... | """
dict 客户端
发起请求,展示结果
"""
from socket import *
from getpass import getpass
import requests
from bs4 import BeautifulSoup
ADDR = ('127.0.0.1', 8000)
# 所有函数都用s
s = socket()
# s.connect(ADDR)
# 二级界面
def login(name):
while True:
print("""
================Query=================
1. 查书单 2.... | Python | zaydzuhri_stack_edu_python |
comment IMPORT LABRARIES
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
from sklearn.linear_model import LinearRegression
from sklearn.model_selection import train_test_split
from sklearn.linear_model import Ridge
from sklearn.linear_model import Lasso
from sklearn.metrics import mean_absolute_e... | #IMPORT LABRARIES
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
from sklearn.linear_model import LinearRegression
from sklearn.model_selection import train_test_split
from sklearn.linear_model import Ridge
from sklearn.linear_model import Lasso
from sklearn.metrics import mean_absolut... | Python | zaydzuhri_stack_edu_python |
function app_module_nav context namespace
begin
set context at string nav = call get_module_nav_list namespace call get_url_name context user
return context
end function | def app_module_nav(context, namespace):
context['nav'] = get_module_nav_list(namespace, get_url_name(context), context.request.user)
return context | Python | nomic_cornstack_python_v1 |
async function send self data
begin
debug string Sending data: %s % data
await call send_all encode data
end function | async def send(self, data):
self.logger.debug('Sending data: %s' % data)
await self.socket.send_all(data.encode()) | Python | nomic_cornstack_python_v1 |
function __init__ self transMatrix pi emissionMatrix statesDict=dict emissionsDict=dict
begin
set transMatrix = transMatrix
set pi = pi
set emissionMatrix = emissionMatrix
set statesDict = statesDict
set emissionsDict = emissionsDict
end function | def __init__(self, transMatrix, pi, emissionMatrix, statesDict = {}, emissionsDict = {}):
self.transMatrix = transMatrix
self.pi = pi
self.emissionMatrix = emissionMatrix
self.statesDict = statesDict
self.emissionsDict = emissionsDict | Python | nomic_cornstack_python_v1 |
function delete_all_hosting_devices self context force_delete=false
begin
string Deletes all hosting devices.
for item in call _get_collection_query context HostingDeviceTemplate
begin
call delete_all_hosting_devices_by_template context template=item force_delete=force_delete
end
end function | def delete_all_hosting_devices(self, context, force_delete=False):
"""Deletes all hosting devices."""
for item in self._get_collection_query(
context, hd_models.HostingDeviceTemplate):
self.delete_all_hosting_devices_by_template(
context, template=item, force_... | Python | jtatman_500k |
comment asyncio是Python 3.4版本引入的标准库,直接内置了对异步IO的支持。
comment asyncio的编程模型就是一个消息循环。我们从asyncio模块中直接获取一个EventLoop的引用,
comment 然后把需要执行的协程扔到EventLoop中执行,就实现了异步IO。
import asyncio
import threading
decorator coroutine
comment @asyncio.coroutine把一个generator标记为coroutine类型:协程类型
function hello
begin
print string a ---- %s % call curr... | # asyncio是Python 3.4版本引入的标准库,直接内置了对异步IO的支持。
# asyncio的编程模型就是一个消息循环。我们从asyncio模块中直接获取一个EventLoop的引用,
# 然后把需要执行的协程扔到EventLoop中执行,就实现了异步IO。
import asyncio
import threading
#@asyncio.coroutine把一个generator标记为coroutine类型:协程类型
@asyncio.coroutine
def hello():
print('a ---- %s' % threading.currentThread())
... | Python | zaydzuhri_stack_edu_python |
import random
from player import Player
comment Random claim
comment Random choice
class RandomPlayer extends Player
begin
function __init__ self
begin
call __init__
end function
end class
comment Random claim
comment Honesty level never goes below A (80%)
class HonestPlayer extends Player
begin
function __init__ self
... | import random
from player import Player
# Random claim
# Random choice
class RandomPlayer(Player):
def __init__(self):
super().__init__()
# Random claim
# Honesty level never goes below A (80%)
class HonestPlayer(Player):
def __init__(self):
super().__init__()
def choose(self, clai... | Python | zaydzuhri_stack_edu_python |
function stopActionByTag self tag
begin
set actionManager = call getActionManager
call removeActionByTag tag self
end function | def stopActionByTag(self, tag):
actionManager = self.getDirector().getActionManager()
actionManager.removeActionByTag(tag, self) | Python | nomic_cornstack_python_v1 |
from utils import *
import numpy as np
import pickle
import cv2
from models.FisherModel import MyFisherModel , sklearnLDA
if __name__ == string __main__
begin
comment Getting the data
set tuple X_train y_train = call getData
set tuple X_test y_test = call getData type=string test
set X_train = reshape X_train shape at ... | from utils import *
import numpy as np
import pickle
import cv2
from models.FisherModel import MyFisherModel, sklearnLDA
if __name__ == '__main__':
# Getting the data
X_train, y_train = getData()
X_test, y_test = getData(type='test')
X_train = X_train.reshape(X_train.shape[0], -1)
X_test = X_test.r... | Python | zaydzuhri_stack_edu_python |
set R = integer input
set PI = 3.141592653589793
set eu_area = R * R * PI
set ta_area = 2 * R * R
print string %0.6f % eu_area
print string %0.6f % ta_area | R = int(input())
PI = 3.14159265358979323846264338327950288419
eu_area = R * R * PI
ta_area = 2 * R * R
print('%0.6f' % eu_area)
print('%0.6f' % ta_area) | Python | zaydzuhri_stack_edu_python |
from bs4 import BeautifulSoup
import requests
import numpy as np
import pandas as pd
import datetime
import itertools
import unicodedata
import re
import requests
import time
import lxml
from typing import Iterable
comment NOTE: dates always start from 'week of saturday'
comment GOES all way back to august 17,1963, DOE... | from bs4 import BeautifulSoup
import requests
import numpy as np
import pandas as pd
import datetime
import itertools
import unicodedata
import re
import requests
import time
import lxml
from typing import Iterable
#NOTE: dates always start from 'week of saturday'
#GOES all way back to august 17,1963, DOESNT MATTER if... | Python | zaydzuhri_stack_edu_python |
string 분류 : DFS & BFS 문제 : 촌수계산 (백준 2644) 작성일자 : 2021.04.04
comment 목적 : 두 사람의 촌수 관계 구하기
comment 접근 : 목적지까지 도달하는 최단 경로 (간선의 비용이 1로 동일)
comment 연결된 정점관의 관계를 매트릭스에 표현
comment 방문표시를 하고, 큐를 다 돌았는데도 발견하지 못하면 -1을 출력
from collections import deque
function bfs s
begin
comment 현재 위치를 방문처리
set visit at s = 1
set q = deque list t... | '''
분류 : DFS & BFS
문제 : 촌수계산 (백준 2644)
작성일자 : 2021.04.04
'''
# 목적 : 두 사람의 촌수 관계 구하기
# 접근 : 목적지까지 도달하는 최단 경로 (간선의 비용이 1로 동일)
# 연결된 정점관의 관계를 매트릭스에 표현
# 방문표시를 하고, 큐를 다 돌았는데도 발견하지 못하면 -1을 출력
from collections import deque
def bfs(s) :
# 현재 위치를 방문처리
visit[s] = 1
q = deque([(s,0)])
while q :
... | Python | zaydzuhri_stack_edu_python |
function fibonachi n
begin
set cache = list comprehension - 1 for _ in range n + 1
function iterate n
begin
comment 기저사례 1.
if n < 2
begin
return n
end
comment 기저사례 2.
if cache at n != - 1
begin
return cache at n
end
comment 기저사례 충족 못할 시 값을 실제로 구함
set cache at n = call iterate n - 1 + call iterate n - 2
return cache at... | def fibonachi(n):
cache = [-1 for _ in range(n+1)]
def iterate(n):
# 기저사례 1.
if n < 2:
return n
# 기저사례 2.
if cache[n] != -1:
return cache[n]
# 기저사례 충족 못할 시 값을 실제로 구함
cache[n] = iterate(n-1) + iterate(n-2)
return cache[n]
return iterate... | Python | zaydzuhri_stack_edu_python |
set a = integer input string 客人給了 :
set b = 1000 - a
print string 找零 b string 元
set c = b // 500
set d = b % 500 // 100
set e = b % 100 // 50
set f = b % 50 // 10
set g = b % 10 // 5
set h = b % 5 // 1
print c d e f g h
print string 500元找了 c string 張
print string 100元找了 d string 張
print string 50元找了 e string 張
print st... | a=int(input('客人給了 : '))
b=1000-a
print('找零',b,'元')
c=b//500
d=((b%500)//100)
e=(((b)%100)//50)
f=(((b%50)//10))
g=(((b%10)//5))
h=((b%5)//1)
print(c, d, e, f, g, h)
print('500元找了',c,'張')
print('100元找了',d,'張')
print('50元找了',e,'張')
print('10元找了',f,'張')
print('5元找了',g,'張')
print('1元找了',h,'張')
print(c*500+d*100+e*50+f*10... | Python | zaydzuhri_stack_edu_python |
import argparse
import datetime
import json
import os
import bs4
function get_abstract soup
begin
set abstract_element = find find soup string abstract string p
set abstract_text = if expression abstract_element then text else string **NONE**
comment needs to be smarter
if string Abstract in abstract_text
begin
set abs... | import argparse
import datetime
import json
import os
import bs4
def get_abstract(soup):
abstract_element = soup.find('abstract').find('p')
abstract_text = abstract_element.text if abstract_element else '**NONE**'
# needs to be smarter
if 'Abstract' in abstract_text:
abstract_text = abstrac... | Python | zaydzuhri_stack_edu_python |
comment !/usr/bin/env python3
comment -*- coding: utf-8 -*-
string Created on Wed Feb 13 14:15:50 2019 @author: nicolas
comment Importation de bibliothèque
import cv2
import couleur
import os.path
from skimage.feature import greycomatrix
from skimage.feature.texture import greycoprops
import numpy as np
set pathDataset... | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Wed Feb 13 14:15:50 2019
@author: nicolas
"""
#Importation de bibliothèque
import cv2
import couleur
import os.path
from skimage.feature import greycomatrix
from skimage.feature.texture import greycoprops
import numpy as np
pathDataset = "./dataset"
pathF... | Python | zaydzuhri_stack_edu_python |
comment !/usr/bin/env python3
comment -*- coding: utf-8 -*-
string Created on Sun Mar 3 23:05:33 2019 @author: StephenTivenan
set c = 0
import numpy as np
set y = zeros list 0 4
set N = 1000
for ii in range 1 N
begin
for jj in range ii N
begin
set c = square root ii ^ 2 + jj ^ 2
if ii + jj + c > 1026
begin
break
end
if... | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sun Mar 3 23:05:33 2019
@author: StephenTivenan
"""
c=0
import numpy as np
y=np.zeros( [0,4] )
N=1000
for ii in range(1,N):
for jj in range(ii,N):
c=np.sqrt(ii**2+jj**2)
if ii+jj+c>1026:
break
if c.is_integer() =... | Python | zaydzuhri_stack_edu_python |
function copy_files_subfolders from_dataset merged_folder original_name=string
begin
for child in call iterdir
begin
comment go one layer deeper
if call is_dir
begin
for elem in call iterdir
begin
try
begin
set new_dir = merged_folder / name
make directory new_dir parents=true exist_ok=true
copy shutil string elem merg... | def copy_files_subfolders(from_dataset, merged_folder, original_name=''):
for child in from_dataset.iterdir():
if child.is_dir(): # go one layer deeper
for elem in child.iterdir():
try:
new_dir = merged_folder / child.name
new_dir.mkdir(pa... | Python | nomic_cornstack_python_v1 |
comment !/usr/bin/python3
import sys
from ohbot import ohbot
comment import ohbot
comment import os
import time
import csv
from os.path import expanduser
set home = expand user string ~ + string /
set path_to_csv = format string {}catkin_ws/src/robot_chatbot/chatbot.csv home
comment number arrives from sys.argv[i] it i... | #!/usr/bin/python3
import sys
from ohbot import ohbot
# import ohbot
# import os
import time
import csv
from os.path import expanduser
home = expanduser("~") + "/"
path_to_csv = "{}catkin_ws/src/robot_chatbot/chatbot.csv".format(home)
# number arrives from sys.argv[i] it is a string
def get_csv_text(number):
with op... | Python | zaydzuhri_stack_edu_python |
import pandas as pd
import os , sys
import textwrap
set MAIN_DIR = directory name path directory name path absolute path path __file__
set DATA_DIR = join path MAIN_DIR string data/
append path MAIN_DIR
from config import *
function _extract_positive df minimum_positive_reviewer_score minimum_positive_word_count
begin
... | import pandas as pd
import os, sys
import textwrap
MAIN_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
DATA_DIR = os.path.join(MAIN_DIR, "data/")
sys.path.append(MAIN_DIR)
from config import *
def _extract_positive(df, minimum_positive_reviewer_score, minimum_positive_word_count):
pos_extrac... | Python | zaydzuhri_stack_edu_python |
string Database functionality
from os import path , makedirs
from datetime import datetime
import pandas as pd
import tinydb
from tinydb import TinyDB , Query
class DBNonUniquenessException extends Exception
begin
pass
end class
class DBMissingRootException extends Exception
begin
pass
end class
class DBWriteConflictEx... | '''Database functionality
'''
from os import path, makedirs
from datetime import datetime
import pandas as pd
import tinydb
from tinydb import TinyDB, Query
class DBNonUniquenessException(Exception):
pass
class DBMissingRootException(Exception):
pass
class DBWriteConflictException(Exception):
pass
cla... | Python | zaydzuhri_stack_edu_python |
function buyuktenkucuge liste eleman
begin
if length liste == 0
begin
comment liste boş ise eleman listeye ekleniyor
append liste eleman
return
end
comment listede eleman var ise liste tek tek eleman ile karsilastirilip
comment eleman listede mevcut sayıdan kucuk ise sonraki liste elemanına ilerliyoruz
comment listedek... | def buyuktenkucuge(liste, eleman):
if len(liste) == 0:
# liste boş ise eleman listeye ekleniyor
liste.append(eleman)
return
# listede eleman var ise liste tek tek eleman ile karsilastirilip
# eleman listede mevcut sayıdan kucuk ise sonraki liste elemanına ilerliyoruz
# listedeki ... | Python | nomic_cornstack_python_v1 |
function gb self
begin
return gb
end function | def gb(self):
return self.data.gb | Python | nomic_cornstack_python_v1 |
import pandas as pd
from pm4py.objects.log import log as log_instance
comment from pm4py.objects.conversion.log import factory as log_conv_fact
from pm4py.objects.conversion.log.versions import to_event_stream
function apply log parameters=none
begin
string Return a Pandas dataframe from a given log Parameters --------... | import pandas as pd
from pm4py.objects.log import log as log_instance
#from pm4py.objects.conversion.log import factory as log_conv_fact
from pm4py.objects.conversion.log.versions import to_event_stream
def apply(log, parameters=None):
"""
Return a Pandas dataframe from a given log
Parameters
... | Python | zaydzuhri_stack_edu_python |
function meta boxhome=join path string / string %s/home % environ at string CO_STORAGE_DIR
begin
set form = call FieldStorage
set boxs = call getlist string box
if length boxs != 1
begin
raise call QueryError string Error: exactly one box= parameter should be specified code=400
end
set box = boxs at 0
set dbname = call... | def meta(boxhome=os.path.join('/', '%s/home' % os.environ['CO_STORAGE_DIR'])):
form = cgi.FieldStorage()
boxs = form.getlist('box')
if len(boxs) != 1:
raise QueryError('Error: exactly one box= parameter should be specified', code=400)
box = boxs[0]
dbname = get_database_name(boxhome, box)
... | Python | nomic_cornstack_python_v1 |
function Uploads1
begin
if method == string POST
begin
if string file not in files
begin
call flash string No file part
return call redirect url
end
set file = files at string file
save join path string Wind filename
return call render_template string index.html message=string File Uploaded Successfuly
end
return call ... | def Uploads1():
if request.method=="POST":
if 'file' not in request.files:
flash('No file part')
return redirect(request.url)
file=request.files["file"]
file.save(os.path.join("Wind", file.filename))
return render_template("index.html", message = "File Uploade... | Python | nomic_cornstack_python_v1 |
function get_datastore self datastore_cls dataset_conf
begin
pass
end function | def get_datastore(self, datastore_cls: Type[BaseDatasetLoader], dataset_conf: Dict) -> BaseDatasetLoader:
pass | Python | nomic_cornstack_python_v1 |
function random_uniform_orientation self
begin
set Z = call standard_normal tuple 3 3
set tuple Q _ = call qr Z
assert sum absolute call eye 3 3 - dot Q < 1e-08
assert absolute call det Q - 1.0 < 1e-08
return Q
end function | def random_uniform_orientation(self):
Z = np.random.standard_normal((3, 3))
Q, _ = np.linalg.qr(Z)
assert np.sum(np.abs(np.eye(3, 3) - Q.T.dot(Q))) < 1e-8
assert np.abs(np.linalg.det(Q) - 1.0) < 1e-8
return Q | Python | nomic_cornstack_python_v1 |
comment -*- coding:utf-8 -*-
import requests
from bs4 import BeautifulSoup
from threading import Thread
import time
class Downloader extends object
begin
function __init__ self target
begin
set _url = target
end function
string 获取每一章节的url
function get_url self
begin
set req = get requests url=_url
set bf = call Beautif... | # -*- coding:utf-8 -*-
import requests
from bs4 import BeautifulSoup
from threading import Thread
import time
class Downloader(object):
def __init__(self, target):
self._url = target
"""获取每一章节的url"""
def get_url(self):
req = requests.get(url=self._url)
bf = BeautifulSoup(req.tex... | Python | zaydzuhri_stack_edu_python |
function plot_example_psds example rate
begin
set NFFT = 512
set rem = example at 0
set nrem_stage1 = example at 1
set nrem_stage2 = example at 2
set nrem_stage34 = example at 3
figure
comment YOUR CODE HERE
set tuple Pxx freqs = call psd rem NFFT=NFFT Fs=rate
comment normalize
set Pxx = Pxx / sum Pxx
plot freqs Pxx la... | def plot_example_psds(example, rate):
NFFT = 512
rem = example[0]
nrem_stage1 = example[1]
nrem_stage2 = example[2]
nrem_stage34 = example[3]
plt.figure()
##YOUR CODE HERE
Pxx, freqs = m.psd(rem, NFFT=NFFT, Fs=rate)
Pxx = Pxx / np.sum(Pxx) # normalize
plt.plot(freqs, ... | Python | nomic_cornstack_python_v1 |
import datetime
import time
import requests
import matplotlib.pyplot as plt
function timeit method
begin
function timed *args **kwards
begin
set start_time = time
set result = call method *args keyword kwards
set elapsed_time = time - start_time
print __name__ string took round elapsed_time 2 string s.
return result
en... | import datetime
import time
import requests
import matplotlib.pyplot as plt
def timeit(method):
def timed(*args, **kwards):
start_time = time.time()
result = method(*args, **kwards)
elapsed_time = time.time() - start_time
print(method.__name__, "took", round(elapsed_time, 2), "s.")... | Python | zaydzuhri_stack_edu_python |
from Gamer import Gamer
class User extends Gamer
begin
function __init__ self
begin
call __init__
comment 선택한 코인
set _chip_choice = 0
comment 가진 금액
set _balance = INIT_MONEY
set _money_status = true
set name = string User
end function
function new_game self
begin
comment 선택한 코인
set _chip_choice = 0
comment 가진 금액
set _b... | from Gamer import Gamer
class User(Gamer):
def __init__(self):
super().__init__()
self._chip_choice = 0 # 선택한 코인
self._balance = self.INIT_MONEY # 가진 금액
self._money_status = True
self.name = 'User'
def new_game(self):
self._chip_choice = 0 # 선택한 코인
s... | Python | zaydzuhri_stack_edu_python |
comment arr = map(int, raw_input().strip().split())
set y = read lines fil1
set arr = split strip y at 0
set n = arr at 0
set m = arr at 1
set t = min n m
if m > n
begin
set x = join string list comprehension string GB for i in range t + join string list comprehension string G for i in range m - n
end
else
begin
set ... | #arr = map(int, raw_input().strip().split())
y = fil1.readlines()
arr = y[0].strip().split()
n = arr[0]
m = arr[1]
t = min(n ,m)
if m>n:
x = ''.join(['GB' for i in range(t)]) + ''.join(['G' for i in range(m-n)])
else:
x = ''.join(['BG' for i in range(t) ]) + ''.join(['B' for i in range(n-m)])
fil2.write(x)
| Python | zaydzuhri_stack_edu_python |
function test_disabled self
begin
set enabled = false
assert equal call can_send string test@example.com false
set enabled = true
end function | def test_disabled(self):
self.test_provider.enabled = False
self.assertEqual(self.test_provider.can_send("test@example.com"), False)
self.test_provider.enabled = True | Python | nomic_cornstack_python_v1 |
function __init__ self model validate_args=false name=none
begin
call __init__ model validate_args name or string JointDistributionNamed
end function | def __init__(self, model, validate_args=False, name=None):
super(JointDistributionNamed, self).__init__(
model, validate_args, name or 'JointDistributionNamed') | Python | nomic_cornstack_python_v1 |
from pylab import *
from sim import simulate
from curve import curvature
set l = 10.0
comment Destination
set dests = array call curvature 10
comment initial point
set initial = list 0.0 0.0
comment stud mag without grid
set list x y gx gy corr err = call simulate 0 l initial pi / 2 dests 1.0 1 100 c_mag=0.01 c_align=0 | from pylab import *
from sim import simulate
from curve import curvature
l = 10.0
#Destination
dests = array(curvature(10))
#initial point
initial = [0.0, 0.0]
#stud mag without grid
[x, y, gx, gy, corr, err] = simulate(0, l, initial, pi/2, dests, 1.0,1,100, c_mag = 1e-2,c_align=0) | Python | zaydzuhri_stack_edu_python |
comment What is 7 to the power of 4
7 ^ 4
comment Split this string
comment s = "Hi there Sam!"
comment into a list
set s = string Hi there Sam!
split s
comment Given the variables:
comment planet = "Earth"
comment diameter = 12742
comment Use .format() to print the following string:
comment The diameter of Earth is 12... | ################################################################################
# What is 7 to the power of 4
################################################################################
7**4
################################################################################
# Split this string
#
## s = "Hi there S... | Python | zaydzuhri_stack_edu_python |
for i in range m + 1 n
begin
if i % 2 == 0
begin
print i
end
end | for i in range(m+1,n):
if(i%2==0):
print(i)
| Python | zaydzuhri_stack_edu_python |
function write
begin
call local_css string style.css
call markdown string <h1 style='text-align: center; color: black;font-size: 30px;'>German English Translator</h1> unsafe_allow_html=true
write st string This app translates the given input german text to english. This is based on “Neural Machine Translation by Jointl... | def write():
local_css("style.css")
st.markdown("<h1 style='text-align: center; color: black;font-size: 30px;'>German English Translator</h1>", unsafe_allow_html=True)
st.write(
"""
This app translates the given input german text to english. This is based on “Neural Machine Transl... | Python | nomic_cornstack_python_v1 |
string Write a python code using function, file input and print each line with line number in the terminal. *********************data.txt(File Extenstion)*********************** Python is an interpreted High-level,gentral purpose programming language Created by gudio van Rossum and first releasted in 1991 Its supports ... | """
Write a python code using function, file input and print each line with line number in the terminal.
*********************data.txt(File Extenstion)***********************
Python is an interpreted
High-level,gentral purpose programming language
Created by gudio van Rossum and first releasted in 1991
Its supports ... | Python | zaydzuhri_stack_edu_python |
function f_isOwrd *args
begin
return call f_isOwrd *args
end function | def f_isOwrd(*args):
return _idaapi.f_isOwrd(*args) | Python | nomic_cornstack_python_v1 |
function satisfies self requirement
begin
set requirement = call maybe_requirement requirement
set link_name = lower call safe_name name
if link_name != key
begin
return false
end
return raw_version in requirement
end function | def satisfies(self, requirement):
requirement = maybe_requirement(requirement)
link_name = safe_name(self.name).lower()
if link_name != requirement.key:
return False
return self.raw_version in requirement | Python | nomic_cornstack_python_v1 |
function get_select_endpoints self endpoints=list
begin
if type endpoints is str
begin
set endpoints = list endpoints
end
else
if not endpoints
begin
raise call ValueError string Please provide a valid list of endpoints
end
set result = dict
for symbol in symbolList
begin
set temp = dict
try
begin
set ds = data_set a... | def get_select_endpoints(self, endpoints=[]):
if type(endpoints) is str:
endpoints = [endpoints]
elif not endpoints:
raise ValueError("Please provide a valid list of endpoints")
result = {}
for symbol in self.symbolList:
temp = {}
... | Python | nomic_cornstack_python_v1 |
function get_position self
begin
return _position
end function | def get_position(self):
return self._position | Python | nomic_cornstack_python_v1 |
function score self X y
begin
set y_hat = predict self X
set df = call global_score X y y_hat
set df at string accuracy = score model transpose X y
return df
end function | def score(self, X: np.array, y: np.array) -> dict:
y_hat = self.predict(X)
df = global_score(X, y, y_hat)
df['accuracy'] = self.model.score(X.transpose(), y)
return df | Python | nomic_cornstack_python_v1 |
function precompute_all_features self vision_net train_or_test
begin
comment type str, either "train" or "test"
print string Precomputing features...
import time
set start = time
set feature_saver = call FeatureSaver
set loaded = call load_if_already_have string features _config _reference_descriptor_vec episodes train... | def precompute_all_features(self, vision_net,
train_or_test): # type str, either "train" or "test"
print("Precomputing features...")
import time; start = time.time()
feature_saver = FeatureSaver()
loaded = feature_saver.load_if_already_have("featu... | Python | nomic_cornstack_python_v1 |
function primes n
begin
set P = list
set S = list true * n
set tuple S at 0 S at 1 = tuple false false
for i in call xrange length S
begin
if S at i == true
begin
append P i
for m in call xrange 2 n / i + 1
begin
if m * i < length S
begin
set S at m * i = false
end
end
end
end
return P
end function
set K = call primes... | def primes(n):
P=[]
S=[True]*n
S[0],S[1]= False, False
for i in xrange(len(S)):
if S[i]==True:
P.append(i)
for m in xrange(2,n/i+1):
if m*i<len(S):
S[m*i]=False
return P
K=primes(10000)
def sumdiv(t):
s=t
a=[]
while t%2=... | Python | zaydzuhri_stack_edu_python |
function get_xbins xcolname
begin
set tuple xmin xmax = tuple decimal string inf - decimal string inf
for res in rsts
begin
set xdata = call _base_unit df xcolname
set xmin = min xmin min
set xmax = max xmax max
end
return dict string size xmax - xmin / 1000
end function | def get_xbins(xcolname):
xmin, xmax = (float("inf"), -float("inf"))
for res in self.rsts:
xdata = self._base_unit(res.df, xcolname)
xmin = min(xmin, xdata.min())
xmax = max(xmax, xdata.max())
return {"size" : (xmax - xmin) / 1000} | Python | nomic_cornstack_python_v1 |
for num in lst
begin
if num % 2 == 0
begin
append even_numbers num
end
else
begin
set num = num * 10
end
print num
end
print even_numbers | for num in lst:
if num % 2 == 0:
even_numbers.append(num)
else:
num *= 10
print(num)
print(even_numbers) | Python | jtatman_500k |
comment -*- coding: utf-8 -*-
string Created on Sun Sep 29 19:51:15 2019 @author: Charl
comment %% Import data
import pandas as pd
comment %% Read dataset
set train = read csv string D:/Documents/UFS/5th Year/Honours Project/Data Sources/train_V2.csv
fill missing winPlacePerc 1 inplace=true
loc at is null train at stri... | # -*- coding: utf-8 -*-
"""
Created on Sun Sep 29 19:51:15 2019
@author: Charl
"""
#%% Import data
import pandas as pd
#%% Read dataset
train = pd.read_csv('D:/Documents/UFS/5th Year/Honours Project/Data Sources/train_V2.csv')
train.winPlacePerc.fillna(1,inplace=True)
train.loc[train['winPlacePerc']... | Python | zaydzuhri_stack_edu_python |
function findResonances self nMin nMax maxL eFieldList energyRange=list - 5000000000.0 + 5000000000.0 Bz=0 progressOutput=false
begin
set eFieldList = eFieldList
set Bz = Bz
comment in GHz
set eMin = energyRange at 0 * 1e-09
set eMax = energyRange at 1 * 1e-09
comment find where is the original pair state
set sm1 = cal... | def findResonances(
self,
nMin,
nMax,
maxL,
eFieldList,
energyRange=[-5.0e9, +5.0e9],
Bz=0,
progressOutput=False,
):
self.eFieldList = eFieldList
self.Bz = Bz
eMin = energyRange[0] * 1.0e-9 # in GHz
eMax = energyRange[... | Python | nomic_cornstack_python_v1 |
comment Write a Python code to ask user to enter two values: one for GPA and the other for Number of Lectures. According to the below table, decide whether user will be graduated or not. If not, give an appropriate message as given table.
set gpa = decimal input string Please type your GPA:
set numberOflectures = decim... | #Write a Python code to ask user to enter two values: one for GPA and the other for Number of Lectures. According to the below table, decide whether user will be graduated or not. If not, give an appropriate message as given table.
gpa = float(input("Please type your GPA: "))
numberOflectures = float(input("Please type... | Python | zaydzuhri_stack_edu_python |
function convertDate self date
begin
set date_list = list
for one in date
begin
if find one string / 1 5 != - 1
begin
set new_one = split one string /
set new_one = tuple new_one at 2 new_one at 1 new_one at 0
set new_one = join string - new_one
append date_list new_one
end
end
return date_list
end function | def convertDate(self, date):
date_list = []
for one in date:
if one.find("/", 1, 5) != -1:
new_one = one.split("/")
new_one = new_one[2], new_one[1], new_one[0]
new_one = "-".join(new_one)
date_list.append(new_one)
retu... | Python | nomic_cornstack_python_v1 |
import numpy as np
import matplotlib.pyplot as plt
import GPy.models
seed 123
comment Expensive Function
function fe x
begin
return 6.0 * x - 2.0 ^ 2 * sin 12 * x - 4 + 0.1
end function
comment Cheap Function
function fc x
begin
set A = 0.5
set B = 10
set C = 5
return A * call fe x + B * x - 0.5 - C + 0.2
end function
... | import numpy as np
import matplotlib.pyplot as plt
import GPy.models
np.random.seed(123)
################################################################################
# Expensive Function
def fe(x):
return (6.0 * x - 2.) ** 2 * np.sin(12 * x - 4) + 0.1
# Cheap Function
def fc(x):
A = 0.5
B = 10
C... | Python | zaydzuhri_stack_edu_python |
import os
import sys
import pyttsx3 as spk
import speech_recognition as sr
import search_any as sa
function get_response y
begin
call speak string Which file shall i open for you sir ?
set r = call Recognizer
set mic = call Microphone
with mic as source
begin
call adjust_for_ambient_noise source
set audio = call listen... | import os
import sys
import pyttsx3 as spk
import speech_recognition as sr
import search_any as sa
def get_response(y):
spk.speak("Which file shall i open for you sir ?")
r = sr.Recognizer()
mic = sr.Microphone()
with mic as source:
r.adjust_for_ambient_noise(source)
audio = r.listen(source)
inst = r.recogniz... | Python | zaydzuhri_stack_edu_python |
function sum n m
begin
return tuple n m
end function
set n = integer input
set m = integer input
print n + m | def sum (n,m):
return n,m
n = int(input())
m = int(input())
print(n+m)
| Python | zaydzuhri_stack_edu_python |
function EventStatusEnableRegisterQuery self
begin
return query self string *ESE?
end function | def EventStatusEnableRegisterQuery(self):
return self.query('*ESE?') | Python | nomic_cornstack_python_v1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.