code stringlengths 10 2.58M | original_code stringlengths 3 3.18M | original_language stringclasses 1
value | source stringclasses 7
values |
|---|---|---|---|
import pandas as pd
import numpy as np
from matplotlib import pyplot as plt
from sklearn import preprocessing
from sklearn.model_selection import train_test_split
from sklearn.neighbors import KNeighborsClassifier
set all_data = read csv string profiles.csv
set rate_mapping = dict string not at all 0 ; string rarely 1 ... | import pandas as pd
import numpy as np
from matplotlib import pyplot as plt
from sklearn import preprocessing
from sklearn.model_selection import train_test_split
from sklearn.neighbors import KNeighborsClassifier
all_data = pd.read_csv("profiles.csv")
rate_mapping = {"not at all": 0, "rarely": 1, "socially"... | Python | zaydzuhri_stack_edu_python |
from event import Event
from flow import Flow
from flowReno import FlowReno
from host import Host
from router import Router
import network_map as nwm
import constants
import BellmanFord
function EventHandler cur_event
begin
string Based on the current event's event type, the event handler will perform different functio... | from event import Event
from flow import Flow
from flowReno import FlowReno
from host import Host
from router import Router
import network_map as nwm
import constants
import BellmanFord
def EventHandler(cur_event):
'''
Based on the current event's event type, the event handler will perform
different fun... | Python | zaydzuhri_stack_edu_python |
comment pylint: disable=too-many-statements
function get_df_payload self query_obj=none **kwargs
begin
if not query_obj
begin
set query_obj = call query_obj
end
set cache_key = if expression query_obj then call cache_key query_obj keyword kwargs else none
set cache_value = none
info string Cache key: %s cache_key
set i... | def get_df_payload( # pylint: disable=too-many-statements
self, query_obj: Optional[QueryObjectDict] = None, **kwargs: Any
) -> Dict[str, Any]:
if not query_obj:
query_obj = self.query_obj()
cache_key = self.cache_key(query_obj, **kwargs) if query_obj else None
cache_val... | Python | nomic_cornstack_python_v1 |
class Program
begin
function __init__ self memory input
begin
set memory = memory
set input = input
set output = list
set pc = 0
set halted = false
set awaitingInput = false
end function
function op self
begin
return memory at pc % 10 ^ 2
end function
function op_mode self p
begin
return memory at pc // 10 ^ p + 1 % 1... | class Program:
def __init__(self, memory, input):
self.memory = memory
self.input = input
self.output = []
self.pc = 0
self.halted = False
self.awaitingInput = False
def op(self):
return self.memory[self.pc] % 10**2
def op_mode(self, p):
retu... | Python | zaydzuhri_stack_edu_python |
function get_member_list self
begin
string Return list of (direct) collection member names (UTF-8 byte strings). See DAVResource.get_member_list()
set members = list
set conn = call _init_connection
try
begin
set tuple tableName primKey = call _split_path path
if tableName is none
begin
set retlist = call _list_tables... | def get_member_list(self):
"""Return list of (direct) collection member names (UTF-8 byte strings).
See DAVResource.get_member_list()
"""
members = []
conn = self.provider._init_connection()
try:
tableName, primKey = self.provider._split_path(self.path)
... | Python | jtatman_500k |
function paddingValidation string blockSize
begin
set lastChar = string at - 1
set lastCharNum = ordinal lastChar
if lastCharNum > blockSize
begin
return string
end
set i = lastCharNum - 1
while i >= 0
begin
if string at - lastCharNum - i != lastChar
begin
raise exception string Not PKCS#7 padding!
end
set i = i - 1
en... | def paddingValidation(string, blockSize):
lastChar = string[-1]
lastCharNum = ord(lastChar)
if lastCharNum > blockSize:
return string
i = lastCharNum-1
while i >= 0:
if string[-(lastCharNum-i)] != lastChar:
raise Exception("Not PKCS#7 padding!")
i -= 1
return string[:len(string)-lastCharNum]
| Python | zaydzuhri_stack_edu_python |
from socket import *
set serverPort = 12000
set serverSocket = call socket AF_INET SOCK_DGRAM
call bind tuple string serverPort | from socket import *
serverPort = 12000
serverSocket = socket(AF_INET, SOCK_DGRAM)
serverSocket.bind(('', serverPort))
| Python | zaydzuhri_stack_edu_python |
import re
from konlpy.tag import Mecab
string [한국어 단어의 품사는 9개] -> 명사, 대명사, 수사, 동사, 형용사, 관형사, 부사, 감탄사, 조사 [띄어쓰기의 원칙] 1. 조사를 제외한 나머지 8개 품사는 모두 띄어쓴다 2. 한 글자짜리 관형사/부사를 붙여쓰지 않는다. 3. 조사는 몇 개가 되든 붙여쓴다. [함수에 적용한 것들] 1. 조사는 모두 붙여쓸거임('^J') 2. 테스트 결과 어미('^E')도 모두 붙여써야함 3. 의존명사('NNB', 'NNBC')는 띄어써야함 4. 긍정지정사('VCP'), 부정지정사('VNP')는 ... | import re
from konlpy.tag import Mecab
"""
[한국어 단어의 품사는 9개]
-> 명사, 대명사, 수사, 동사, 형용사, 관형사, 부사, 감탄사, 조사
[띄어쓰기의 원칙]
1. 조사를 제외한 나머지 8개 품사는 모두 띄어쓴다
2. 한 글자짜리 관형사/부사를 붙여쓰지 않는다.
3. 조사는 몇 개가 되든 붙여쓴다.
[함수에 적용한 것들]
1. 조사는 모두 붙여쓸거임('^J')
2. 테스트 결과 어미('^E')도 모두 붙여써야함
3. 의존명사('NNB', 'NNBC')는 띄어써야함
4. 긍정지정사('VCP'), 부정지정사('VNP... | Python | zaydzuhri_stack_edu_python |
function set_orientation self horizontal
begin
set width = width
set height = height
if horizontal
begin
set width = max width height
set height = min width height
end
else
begin
set width = min width height
set height = max width height
end
set horizontal = horizontal
end function | def set_orientation(self, horizontal):
width = self.width
height = self.height
if horizontal:
self.width = max(width, height)
self.height = min(width, height)
else:
self.width = min(width, height)
self.height = max(width, height)
... | Python | nomic_cornstack_python_v1 |
import numpy as np
from network import RBFN
from mnist_loader import load_data_wrapper
import matplotlib.pyplot as plt
import sys
import time
comment live printing on terminal
class Unbuffered extends object
begin
function __init__ self stream
begin
set stream = stream
end function
function write self data
begin
write ... | import numpy as np
from network import RBFN
from mnist_loader import load_data_wrapper
import matplotlib.pyplot as plt
import sys
import time
#live printing on terminal
class Unbuffered(object):
def __init__(self, stream):
self.stream = stream
def write(self, data):
self.stream.write(da... | Python | zaydzuhri_stack_edu_python |
import argparse
from csv import DictWriter
from datetime import datetime , timedelta
import os
import requests
from tqdm import tqdm
set API_ROOT = string https://nyt-games-prd.appspot.com/svc/crosswords
set PUZZLE_INFO = API_ROOT + string /v2/puzzle/daily-{date}.json
set SOLVE_INFO = API_ROOT + string /v2/game/{game_i... | import argparse
from csv import DictWriter
from datetime import datetime, timedelta
import os
import requests
from tqdm import tqdm
API_ROOT = 'https://nyt-games-prd.appspot.com/svc/crosswords'
PUZZLE_INFO = API_ROOT + '/v2/puzzle/daily-{date}.json'
SOLVE_INFO = API_ROOT + '/v2/game/{game_id}.json'
DATE_FORMAT = '%Y-%... | Python | zaydzuhri_stack_edu_python |
function parse csvfilename
begin
set table = list
with open csvfilename string r as csvfile
begin
set csvreader = reader csvfile skipinitialspace=true
for row in csvreader
begin
append table row
end
end
return table
end function | def parse(csvfilename):
table = []
with open(csvfilename, "r") as csvfile:
csvreader = csv.reader(csvfile,
skipinitialspace=True)
for row in csvreader:
table.append(row)
return table | Python | nomic_cornstack_python_v1 |
function test_create_acl_group_rule_success shared_zone_test_context
begin
set client = ok_vinyldns_client
set acl_rule = dict string accessLevel string Read ; string description string test-acl-group-id ; string groupId ok_group at string id ; string recordMask string www-* ; string recordTypes list string A string AA... | def test_create_acl_group_rule_success(shared_zone_test_context):
client = shared_zone_test_context.ok_vinyldns_client
acl_rule = {
"accessLevel": "Read",
"description": "test-acl-group-id",
"groupId": shared_zone_test_context.ok_group["id"],
"recordMask": "www-*",
"reco... | Python | nomic_cornstack_python_v1 |
function get_es_cluster_addresses marathonUrl es_clusterName es_instances
begin
for x in range 0 100
begin
set response = call get_cluster_info_from_marathon marathonUrl es_clusterName
set length = length response at string tasks
comment Wait until all the N nodes in this cluster are up and running
if length == es_inst... | def get_es_cluster_addresses(marathonUrl, es_clusterName, es_instances):
for x in range(0, 100):
response = get_cluster_info_from_marathon(marathonUrl, es_clusterName)
length = len(response['tasks'])
#Wait until all the N nodes in this cluster are up and running
if (... | Python | nomic_cornstack_python_v1 |
import argparse
import pandas as pd
function parse
begin
set parser = call ArgumentParser
call add_argument string -d type=str default=string census required=true help=string defines dataset name choices=list string census string titanic
call add_argument string -m type=str default=string decisiontree required=true hel... | import argparse
import pandas as pd
def parse():
parser = argparse.ArgumentParser()
parser.add_argument('-d',
type=str,
default='census',
required=True,
help='defines dataset name',
choices=['census', 'titanic'])
parser.add_argument('-m',
type=str,
default='decisiontree',... | Python | zaydzuhri_stack_edu_python |
import googlemaps
import xlsxwriter
import os
comment Ordner erstellen (Linux exclusive)
call system string mkdir xml
comment Googlemaps API Authentifizierung
set apikeyfile = open string apikey.txt string r
set apikey = read apikeyfile
set gmaps = call Client key=apikey
comment Funktion die den Dateinamen entgegennimm... | import googlemaps
import xlsxwriter
import os
# Ordner erstellen (Linux exclusive)
os.system("mkdir xml")
# Googlemaps API Authentifizierung
apikeyfile=open("apikey.txt","r")
apikey=apikeyfile.read()
gmaps=googlemaps.Client(key=apikey)
# Funktion die den Dateinamen entgegennimmt und einen darauf angepassten wg... | Python | zaydzuhri_stack_edu_python |
comment -*- coding: utf-8 -*-
set T = integer input
for index in range T
begin
set N = integer input
set H = list map int split input
set total_water = sum H
set num_bottles = 0
while total_water >= 0
begin
set total_water = total_water - 100
set num_bottles = num_bottles + 1
end
print num_bottles - 1
end | # -*- coding: utf-8 -*-
T = int(input())
for index in range(T):
N = int(input())
H = list(map(int, input().split()))
total_water = sum(H)
num_bottles = 0
while(total_water >=0):
total_water -= 100
num_bottles +=1
print(num_bottles - 1) | Python | zaydzuhri_stack_edu_python |
comment -*- coding: UTF-8 -*-
comment @Date : 2020/3/1
comment @Author : WANG JINGE
comment @Email : wang.j.au@m.titech.ac.jp
comment @Language: python 3.7
string
class Solution
begin
function uniqueTwoSum self nums target
begin
sort nums
set count = 0
set tuple left right = tuple 0 length nums - 1
while left < right
... | # -*- coding: UTF-8 -*-
# @Date : 2020/3/1
# @Author : WANG JINGE
# @Email : wang.j.au@m.titech.ac.jp
# @Language: python 3.7
"""
"""
class Solution:
def uniqueTwoSum(self, nums, target):
nums.sort()
count = 0
left, right = 0, len(nums)-1
while left < right:
sumP... | Python | zaydzuhri_stack_edu_python |
import pandas as pd
import numpy as np
import scipy.io as sio
from datetime import datetime
import math
import statsmodels.api as sm
function sigma_equity
begin
string .MAT: allfirmcodes: all codes in mc_data_all, 3593*1 ndarray mthdates:all month-end dates(2019-02-28) deriving from alldates, 273*1 ndarray sigmae_array... | import pandas as pd
import numpy as np
import scipy.io as sio
from datetime import datetime
import math
import statsmodels.api as sm
def sigma_equity():
'''
.MAT:
allfirmcodes: all codes in mc_data_all, 3593*1 ndarray
mthdates:all month-end dates(2019-02-28) deriving from alldates, 273*1 n... | Python | zaydzuhri_stack_edu_python |
function values self
begin
return get pulumi self string values
end function | def values(self) -> Optional[pulumi.Input[Sequence[pulumi.Input[str]]]]:
return pulumi.get(self, "values") | Python | nomic_cornstack_python_v1 |
async function async_added_to_hass self
begin
await call async_added_to_hass
comment Add listener
call async_track_state_change hass sensor_entity_id _async_sensor_changed
call async_track_state_change hass heater_entity_id _async_switch_changed
if _keep_alive
begin
call async_track_time_interval hass _async_control_he... | async def async_added_to_hass(self):
await super().async_added_to_hass()
# Add listener
async_track_state_change(self.hass, self.sensor_entity_id, self._async_sensor_changed)
async_track_state_change(self.hass, self.heater_entity_id, self._async_switch_changed)
if self._keep_al... | Python | nomic_cornstack_python_v1 |
function project self project
begin
set _project = project
end function | def project(self, project):
self._project = project | Python | nomic_cornstack_python_v1 |
comment Definition for an interval.
comment class Interval(object):
comment def __init__(self, s=0, e=0):
comment self.start = s
comment self.end = e
class Solution extends object
begin
function minMeetingRooms self intervals
begin
string :type intervals: List[Interval] :rtype: int
sort intervals comp_lists
set temp = ... | # Definition for an interval.
# class Interval(object):
# def __init__(self, s=0, e=0):
# self.start = s
# self.end = e
class Solution(object):
def minMeetingRooms(self, intervals):
"""
:type intervals: List[Interval]
:rtype: int
"""
intervals.sort(self.c... | Python | zaydzuhri_stack_edu_python |
function _readString self addr isUnicode=false
begin
try
begin
set result = string
set increment = 1
if isUnicode
begin
set increment = 2
end
set index = 0
while true
begin
set byte = call Byte addr + index
if byte is not 0
begin
set result = result + character byte
set index = index + increment
end
else
begin
break
e... | def _readString(self, addr, isUnicode=False):
try:
result = ''
increment = 1
if isUnicode:
increment = 2
index = 0
while True:
byte = self.ida_proxy.Byte(addr + index)
if byte is not 0:
... | Python | nomic_cornstack_python_v1 |
function parse self response
begin
set table = call xpath string //td[@class="text-left col-symbol"]/parent::tr
if crypto_coin != string
begin
set table = list comprehension row for row in table if lower get call css string td.col-symbol::text == lower crypto_coin
end
for row in table
begin
set coin = call CoinItem na... | def parse(self, response):
table = response.xpath('//td[@class="text-left col-symbol"]/parent::tr')
if self.crypto_coin != "":
table = [row for row in table if row.css("td.col-symbol::text").get().lower() == self.crypto_coin.lower()]
for row in table:
coin = CoinItem(
... | Python | nomic_cornstack_python_v1 |
import numpy as np
print zeros tuple 3 3
comment Code executed. | import numpy as np
print(np.zeros((3, 3)))
# Code executed.
| Python | flytech_python_25k |
function connect
begin
set con = call connect DATABASE
set cur = call cursor
return tuple con cur
end function | def connect():
con = sqlite3.connect(UIFunctions.DATABASE)
cur = con.cursor()
return con, cur | Python | nomic_cornstack_python_v1 |
function fit self corpora
begin
pass
end function | def fit(self, corpora: str):
pass | Python | nomic_cornstack_python_v1 |
function date_to_integer day month year
begin
set inte = 0
set delta_year = integer year - 2000
comment aantal jaren tot we aan het huidige jaar zijn, dit jaar telt nog niet mee om dat nog niet opgevuld is
for i in range 1 delta_year
begin
if call is_schrikkel_year year
begin
set inte = inte + 366
end
else
begin
set in... | def date_to_integer( day, month, year):
inte = 0
delta_year = int(year)- 2000
### aantal jaren tot we aan het huidige jaar zijn, dit jaar telt nog niet mee om dat nog niet opgevuld is
for i in range(1,delta_year):
if is_schrikkel_year(year):
inte += 366
else:
inte... | Python | nomic_cornstack_python_v1 |
import requests as rq
import random
import logging
import asyncio
from binascii import hexlify , unhexlify
from aiohttp import ClientSession
set cs = list *map(lambda s: unhexlify(s.strip()), open('ciphertext'))
set oracle = string http://140.122.185.173:8080/oracle
async function crack iv c
begin
string crack a cipher... | import requests as rq
import random
import logging
import asyncio
from binascii import hexlify, unhexlify
from aiohttp import ClientSession
cs = [
*map(
lambda s: unhexlify(s.strip()),
open('ciphertext'),
),
]
oracle = 'http://140.122.185.173:8080/oracle'
async def crack(iv: bytes, c: bytes):... | Python | zaydzuhri_stack_edu_python |
class Solution extends object
begin
function reverseStr self s k
begin
string :type s: str :type k: int :rtype: str
set o = string
set start = 0
while start < length s
begin
set mid = min start + k length s
set end = min start + 2 * k length s
if start == 0
begin
set o = o + s at slice mid - 1 : : - 1
end
else
begin
... | class Solution(object):
def reverseStr(self, s, k):
"""
:type s: str
:type k: int
:rtype: str
"""
o=''
start=0
while start<len(s):
mid=min(start+k,len(s))
end=min(start+2*k,len(s))
if start==0:
o+=s[m... | Python | zaydzuhri_stack_edu_python |
import keras
from keras import layers
from keras.datasets.mnist import load_data
import numpy as np
from matplotlib import pyplot
from keras import backend as K
set imageDim = 28 * 28
set hiddenDim = 256
comment intermediate_dim2 = 64
set latentDim = 2
function sampling args
begin
set tuple z_mean z_log_sigma = args
se... | import keras
from keras import layers
from keras.datasets.mnist import load_data
import numpy as np
from matplotlib import pyplot
from keras import backend as K
imageDim = 28 * 28
hiddenDim = 256
# intermediate_dim2 = 64
latentDim = 2
def sampling(args):
z_mean, z_log_sigma = args
epsilon = K.random_normal(sh... | Python | zaydzuhri_stack_edu_python |
string Input and output for Learning Output of a Students
import os
from grading_system_calculation import student_lOutput
set clear = lambda -> call system string cls
while true
begin
set user = call student_lOutput decimal input string Enter the result of Quiz 1: decimal input string Enter the result of Quiz 2: deci... | '''
Input and output for Learning Output of a Students
'''
import os
from grading_system_calculation import student_lOutput
clear = lambda: os.system('cls')
while True:
user = student_lOutput(
float(input("Enter the result of Quiz 1: ")),
float(input("Enter the result of Quiz 2: ")),
float... | Python | zaydzuhri_stack_edu_python |
function get_auth_token_ssh account signature appid ip=none vo=string def session
begin
set kwargs = dict string account account ; string signature signature
if not call has_permission issuer=account vo=vo action=string get_auth_token_ssh kwargs=kwargs session=session
begin
raise call AccessDenied string User with prov... | def get_auth_token_ssh(account, signature, appid, ip=None, vo='def', *, session: "Session"):
kwargs = {'account': account, 'signature': signature}
if not permission.has_permission(issuer=account, vo=vo, action='get_auth_token_ssh', kwargs=kwargs, session=session):
raise exception.AccessDenied('User wit... | Python | nomic_cornstack_python_v1 |
function find_median arr
begin
comment Remove duplicates from the array
set unique_arr = list set arr
set n = length unique_arr
comment Sort the array in ascending order
for i in range n
begin
for j in range 0 n - i - 1
begin
if unique_arr at j > unique_arr at j + 1
begin
set tuple unique_arr at j unique_arr at j + 1 =... | def find_median(arr):
# Remove duplicates from the array
unique_arr = list(set(arr))
n = len(unique_arr)
# Sort the array in ascending order
for i in range(n):
for j in range(0, n-i-1):
if unique_arr[j] > unique_arr[j+1]:
unique_arr[j], unique_arr[j+1] = unique_a... | Python | jtatman_500k |
function correlate expected observed
begin
comment following list will hold all sets of time differences computed during the correlation.
comment entry j will hold the set found when observed was compared with expected starting at j.
set timeDifferencesAndErrorsAtIndices = list
comment the observed timings will be a s... | def correlate(expected, observed):
# following list will hold all sets of time differences computed during the correlation.
# entry j will hold the set found when observed was compared with expected starting at j.
timeDifferencesAndErrorsAtIndices = []
# the observed timings will be a subset of the... | Python | nomic_cornstack_python_v1 |
function show_image self image_set=string train index=none interactive_mode=true
begin
if interactive_mode
begin
call ion
end
else
begin
call ioff
end
if image_set == string train
begin
set target = train_dataset
end
else
begin
set target = test_dataset
end
if index is none
begin
set index = random integer 0 length tar... | def show_image(self, image_set='train', index=None, interactive_mode=True):
if interactive_mode:
plt.ion()
else:
plt.ioff()
if image_set == 'train':
target = self.train_dataset
else:
target = self.test_dataset
if index is None:
... | Python | nomic_cornstack_python_v1 |
function reverse self
begin
set x = - x
set y = - y
return self
end function | def reverse(self):
self.x = -self.x
self.y = -self.y
return self | Python | nomic_cornstack_python_v1 |
function calculate location orbits_df
begin
set tuple lat lon = location
set counts = 0
set d = list
set swath_distances = list
for orbit in as type unique orbits_df at string orbit_id int
begin
string Find point at the same latitude which
set the_swath = loc at df at string orbit_id == orbit
set swath_lats = values
... | def calculate(location, orbits_df):
lat, lon = location
counts = 0
d = []
swath_distances = []
for orbit in np.unique(orbits_df["orbit_id"]).astype(int):
"""
Find point at the same latitude which
"""
the_swath = df.loc[df['orbit_id'] == orbit]
swath_lats = the_swath.ground_lat.values
nearest_loc, dista... | Python | nomic_cornstack_python_v1 |
function add_calculation self calculation_dict
begin
update calculations calculation_dict
end function | def add_calculation(self, calculation_dict):
self.calculations.update(calculation_dict) | Python | nomic_cornstack_python_v1 |
function info self text
begin
if not is_quiet_err
begin
call __emit text stderr
end
end function | def info(self, text):
if not self.is_quiet_err:
self.__emit(text, sys.stderr) | Python | nomic_cornstack_python_v1 |
comment shows acoustic features for tracks for the given artist
comment (at top of module)
from __future__ import print_function
from spotipy.oauth2 import SpotifyClientCredentials
import json
import spotipy
import time
import sys
comment authentification
set client_credentials_manager = call SpotifyClientCredentials
s... | # shows acoustic features for tracks for the given artist
from __future__ import print_function # (at top of module)
from spotipy.oauth2 import SpotifyClientCredentials
import json
import spotipy
import time
import sys
# authentification
client_credentials_manager = SpotifyClientCredentials()
sp = spotipy.Spotify(... | Python | zaydzuhri_stack_edu_python |
import pyttsx3
import datetime
import speech_recognition as sr
import wikipedia
import webbrowser
import os
from random import randint
import smtplib
import wikipedia
set engine = call init string sapi5
set voices = call getProperty string voices
call setProperty string voice id
function speak audio
begin
call say audi... | import pyttsx3
import datetime
import speech_recognition as sr
import wikipedia
import webbrowser
import os
from random import randint
import smtplib
import wikipedia
engine = pyttsx3.init('sapi5')
voices = engine.getProperty('voices')
engine.setProperty('voice',voices[0].id)
def speak(audio):
... | Python | zaydzuhri_stack_edu_python |
function create_task self submission
begin
raise call NotImplementedError string Not implemented
end function | def create_task(self, submission):
raise NotImplementedError("Not implemented") | Python | nomic_cornstack_python_v1 |
function test_is_accessible_by_with_public_and_hidden self
begin
set user = call create_user
set repository = call create_repository visible=false
assert true call is_accessible_by user
assert true call is_accessible_by call AnonymousUser
end function | def test_is_accessible_by_with_public_and_hidden(self):
user = self.create_user()
repository = self.create_repository(visible=False)
self.assertTrue(repository.is_accessible_by(user))
self.assertTrue(repository.is_accessible_by(AnonymousUser())) | Python | nomic_cornstack_python_v1 |
function get_parent_folder self
begin
return parents at 0
end function | def get_parent_folder(self):
return self.md_file.parents[0] | Python | nomic_cornstack_python_v1 |
string poisson code solves immersed boundary conditions that is, boundary conditions which need not coincide with the meshing, and can have a certain softness to them instead of iterative method, we may also compute a dense matrix of interaction strengths only requires updates for updated points just solve poisson for ... | """
poisson code
solves immersed boundary conditions
that is, boundary conditions which need not coincide with the meshing,
and can have a certain softness to them
instead of iterative method, we may also compute a dense matrix of interaction strengths
only requires updates for updated points
just solve poisson for ... | Python | zaydzuhri_stack_edu_python |
function applyLoggingOpts log_levels log_files
begin
for tuple l lvl in log_levels
begin
call setLevel lvl
end
for tuple l hdl in log_files
begin
for h in handlers
begin
call removeHandler h
end
call addHandler hdl
end
end function | def applyLoggingOpts(log_levels, log_files):
for l, lvl in log_levels:
l.setLevel(lvl)
for l, hdl in log_files:
for h in l.handlers:
l.removeHandler(h)
l.addHandler(hdl) | Python | nomic_cornstack_python_v1 |
function test__literal__handles_unicode self
begin
set renderer = call Renderer
set string_encoding = string ascii
set engine = call _make_render_engine
set literal = literal
assert equal call literal string foo string foo
end function | def test__literal__handles_unicode(self):
renderer = Renderer()
renderer.string_encoding = 'ascii'
engine = renderer._make_render_engine()
literal = engine.literal
self.assertEqual(literal(u"foo"), "foo") | Python | nomic_cornstack_python_v1 |
function KeyChecker self P d s
begin
comment Method Description
comment If the Keyboard is trying to insert value
if d == string 1
begin
comment If the value enter is a value and the current value is not longer than 4 char.
if not is digit P and length s < 4
begin
return false
end
end
return true
end function | def KeyChecker(self,P,d,s):
# Method Description
#If the Keyboard is trying to insert value
if d == '1':
# If the value enter is a value and the current value is not longer than 4 char.
if not (P.isdigit() and len(s) < 4):
return False
return True | Python | nomic_cornstack_python_v1 |
function is_point_inside_mask border target
begin
set degree = 0
for i in range length border - 1
begin
set a = border at i
set b = border at i + 1
comment calculate distance of vector
set A = call get_cartersian_distance a at 0 a at 1 b at 0 b at 1
set B = call get_cartersian_distance target at 0 target at 1 a at 0 a ... | def is_point_inside_mask(border, target):
degree = 0
for i in range(len(border) - 1):
a = border[i]
b = border[i + 1]
# calculate distance of vector
A = get_cartersian_distance(a[0], a[1], b[0], b[1])
B = get_cartersian_distance(target[0], target[1], a[0], a[1])
... | Python | nomic_cornstack_python_v1 |
string Q61
import itertools
set M = 5
set N = 4
set TABLE = list comprehension i for i in range M * N
function solve
begin
string 解答
set cnt = 0
for i in call combinations TABLE M * N // 2
begin
set BLUE = list i
if 0 in BLUE
begin
set WHITE = list set TABLE - set BLUE
call check BLUE BLUE at 0
if not BLUE
begin
call c... | """Q61
"""
import itertools
M = 5
N = 4
TABLE = [i for i in range(M * N)]
def solve():
"""解答
"""
cnt = 0
for i in itertools.combinations(TABLE, M * N // 2):
BLUE = list(i)
if 0 in BLUE:
WHITE = list(set(TABLE) - set(BLUE))
check(BLUE, BLUE[0])
if no... | Python | zaydzuhri_stack_edu_python |
function testOneHashInBinQuery1Subject2PairOutsideMatch self
begin
set queryLandmark = call Landmark string AlphaHelix string A 100 20
set queryTrigPoint = call TrigPoint string Peaks string P 110
set subjectLandmark = call Landmark string AlphaHelix string A 100 20
set subjectTrigPoint = call TrigPoint string Peaks st... | def testOneHashInBinQuery1Subject2PairOutsideMatch(self):
queryLandmark = Landmark('AlphaHelix', 'A', 100, 20)
queryTrigPoint = TrigPoint('Peaks', 'P', 110)
subjectLandmark = Landmark('AlphaHelix', 'A', 100, 20)
subjectTrigPoint = TrigPoint('Peaks', 'P', 110)
histogram = Histogra... | Python | nomic_cornstack_python_v1 |
function plot_confusion_matrix cm classes save_tag=string normalize=false title=string Confusion matrix cmap=Blues
begin
if normalize
begin
set cm = as type cm string float / sum axis=1 at tuple slice : : newaxis
print string Normalized confusion matrix
end
else
begin
print string Confusion matrix, without normaliz... | def plot_confusion_matrix(cm, classes,
save_tag = '',
normalize=False,
title='Confusion matrix',
cmap=plt.cm.Blues):
if normalize:
cm = cm.astype('float') / cm.sum(axis=1)[:, np.newaxis]
print("No... | Python | nomic_cornstack_python_v1 |
while t
begin
set t = t - 1
set case = case + 1
set n = list
set s = input
set s = list comprehension c for c in s
while length s != 0
begin
if string Z in s
begin
append n 0
for i in string ZERO
begin
remove s i
end
end
if string W in s
begin
append n 2
for i in string TWO
begin
remove s i
end
end
if string X in s
be... | while t:
t -= 1
case += 1
n = []
s = input()
s = [c for c in s]
while len(s) != 0:
if 'Z' in s:
n.append(0)
for i in 'ZERO':
s.remove(i)
if 'W' in s:
n.append(2)
for i in 'TWO':
s.remove(i)
if 'X' in s:
n.append(6)
for i in 'SIX':
s.remove(i)
if 'G' in s:
... | Python | zaydzuhri_stack_edu_python |
function setNodeXDegree self new_deg
begin
set xdeg = new_deg
end function | def setNodeXDegree(self, new_deg):
self.xdeg = new_deg | Python | nomic_cornstack_python_v1 |
function name self
begin
return get pulumi self string name
end function | def name(self) -> pulumi.Output[str]:
return pulumi.get(self, "name") | Python | nomic_cornstack_python_v1 |
function test_fma_invalid_param_str_floatnum_intarray_none_1314 self
begin
comment This version is expected to pass.
call fma floatarrayx floatnumy floatarrayz
comment This is the actual test.
with assert raises TypeError
begin
call fma strx floatnumy intarrayz
end
end function | def test_fma_invalid_param_str_floatnum_intarray_none_1314(self):
# This version is expected to pass.
arrayfunc.fma(self.floatarrayx, self.floatnumy, self.floatarrayz)
# This is the actual test.
with self.assertRaises(TypeError):
arrayfunc.fma(self.strx, self.floatnumy, self.intarrayz) | Python | nomic_cornstack_python_v1 |
import sys
set name = stdin
function FizzBuzz T *args
begin
set i = 0
while i < T + 1
begin
for instances in args
begin
set instance = list range 1 instances + 1
for number in instance
begin
if number % 3 == 0 and number % 5 == 0
begin
print string FizzBuzz
end
else
if number % 3 == 0
begin
print string Fizz
end
else
i... | import sys
name = sys.stdin
def FizzBuzz(T, *args):
i = 0
while i < T + 1:
for instances in args:
instance = list(range(1, instances+1))
for number in instance:
if number % 3 == 0 and number % 5 == 0:
print('FizzBuzz')
elif nu... | Python | zaydzuhri_stack_edu_python |
function plot_segs image_nii seg_niis out_file bbox_nii=none masked=false colors=none compress=string auto **plot_params
begin
string plot segmentation as contours over the image (e.g. anatomical). seg_niis should be a list of files. mask_nii helps determine the cut coordinates. plot_params will be passed on to nilearn... | def plot_segs(image_nii, seg_niis, out_file, bbox_nii=None, masked=False,
colors=None, compress='auto', **plot_params):
""" plot segmentation as contours over the image (e.g. anatomical).
seg_niis should be a list of files. mask_nii helps determine the cut
coordinates. plot_params will be pass... | Python | jtatman_500k |
function s3_upload_base
begin
return string https://testing.s3.amazonaws.com/course-1/
end function | def s3_upload_base():
return "https://testing.s3.amazonaws.com/course-1/" | Python | nomic_cornstack_python_v1 |
function get_id
begin
raise call NotImplementedError
end function | def get_id():
raise NotImplementedError() | Python | nomic_cornstack_python_v1 |
function random_uniform self n_samples=1 max_norm=1
begin
set point = call rand n_samples dimension - 0.5 * max_norm
set point = call intrinsic_to_extrinsic_coords point
assert all call belongs point
assert ndim == 2
return point
end function | def random_uniform(self, n_samples=1, max_norm=1):
point = ((np.random.rand(n_samples, self.dimension) - .5)
* max_norm)
point = self.intrinsic_to_extrinsic_coords(point)
assert np.all(self.belongs(point))
assert point.ndim == 2
return point | Python | nomic_cornstack_python_v1 |
import socket
from datetime import datetime
set HOST = call gethostname
set PORT = 6789
set max_size = 1024
set sock = call socket AF_INET SOCK_STREAM
call bind tuple HOST PORT
print string Starting the server at: now
print string waiting for the incoming connection from client..
call listen 5
set tuple client addr = c... | import socket
from datetime import datetime
HOST=socket.gethostname()
PORT=6789
max_size=1024
sock=socket.socket(socket.AF_INET,socket.SOCK_STREAM)
sock.bind((HOST,PORT))
print('Starting the server at: ',datetime.now())
print('waiting for the incoming connection from client..')
sock.listen(5)
client, ad... | Python | zaydzuhri_stack_edu_python |
comment !/usr/bin/python
from prettytable import PrettyTable
import sys
import os
set fname = argv at 1 | #!/usr/bin/python
from prettytable import PrettyTable
import sys
import os
fname = sys.argv[1]
| Python | zaydzuhri_stack_edu_python |
function chooseAction self gameState
begin
function value state currentAgentIndex currentDepth alpha beta
begin
if currentDepth == depth or call isOver
begin
return evaluate self state
end
if currentAgentIndex == index
begin
set maxValue = call maximumValue state currentAgentIndex currentDepth alpha beta
return maxValu... | def chooseAction(self, gameState):
def value(state, currentAgentIndex, currentDepth, alpha, beta):
if currentDepth == self.depth or state.isOver():
return self.evaluate(state)
if currentAgentIndex == self.index:
maxValue = maximumValue(state, currentAgentIndex, currentDepth, ... | Python | nomic_cornstack_python_v1 |
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import tensorflow as tf
from tensorflow import keras
import time
from sklearn.utils import shuffle
comment =======================Parameters================================
comment load model or create one
set LOAD = false
set MODEL_TO_LOAD_NAME = s... | import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import tensorflow as tf
from tensorflow import keras
import time
from sklearn.utils import shuffle
#=======================Parameters================================
LOAD = False # load model or create one
MODEL_TO_LOAD_NAME = 'modelNew... | Python | zaydzuhri_stack_edu_python |
comment !/usr/bin/python2
import os
import sys
import matplotlib.pyplot as plt
with open string total_dos.dat as f
begin
set lines = read lines f
end
close f
set freq = list
set dos = list
set wdos = list
for i in range 1 length lines
begin
append freq decimal split lines at i at 0
append dos decimal split lines at ... | #!/usr/bin/python2
import os
import sys
import matplotlib.pyplot as plt
with open('total_dos.dat') as f:
lines = f.readlines()
f.close()
freq = []
dos = []
wdos = []
for i in range(1, len(lines)):
freq.append(float(lines[i].split()[0]))
dos.append(float(lines[i].split()[1]))
for i in range(len(dos)):
... | Python | zaydzuhri_stack_edu_python |
function list_installed_depends_by_extra installed_dists project_name
begin
comment type: Dict[Optional[NormalizedName], Set[NormalizedName]]
set res = dict
set base_depends = call list_installed_depends installed_dists project_name
set res at none = base_depends
for extra in extra_requires
begin
set extra_depends = c... | def list_installed_depends_by_extra(
installed_dists: InstalledDistributions,
project_name: NormalizedName,
) -> Dict[Optional[NormalizedName], Set[NormalizedName]]:
res = {} # type: Dict[Optional[NormalizedName], Set[NormalizedName]]
base_depends = list_installed_depends(installed_dists, project_name)... | Python | nomic_cornstack_python_v1 |
import pandas as pd
from sklearn.linear_model import LogisticRegression
from sklearn.preprocessing import LabelEncoder
from sklearn.cross_validation import train_test_split
from sklearn.metrics import confusion_matrix
set data = read csv string adults.txt sep=string ,
for label in list string race string occupation
beg... | import pandas as pd
from sklearn.linear_model import LogisticRegression
from sklearn.preprocessing import LabelEncoder
from sklearn.cross_validation import train_test_split
from sklearn.metrics import confusion_matrix
data = pd.read_csv('adults.txt', sep=',')
for label in ['race', 'occupation']:
data[label] = Label... | Python | zaydzuhri_stack_edu_python |
import socket
set PORT = 4000
set HOST = string
set s = call socket AF_INET SOCK_STREAM | import socket
PORT = 4000
HOST = ''
s = socket.socket(AF_INET, socket.SOCK_STREAM) | Python | zaydzuhri_stack_edu_python |
function get_form self
begin
if has attribute self string form
begin
return form
end
if method == string get
begin
return call get_unbound_form
end
return call get_bound_form
end function | def get_form(self):
if hasattr(self, 'form'):
return self.form
if self.method == 'get':
return self.get_unbound_form()
return self.get_bound_form() | Python | nomic_cornstack_python_v1 |
function runInference exp sequences enableFeedback=true
begin
string Run inference on this set of sequences and compute error
end function | def runInference(exp, sequences, enableFeedback=True):
"""
Run inference on this set of sequences and compute error
""" | Python | jtatman_500k |
function check_strings arr
begin
for string in arr
begin
set digit_count = 0
set lowercase_count = 0
set special_char_count = 0
for char in string
begin
if is digit char
begin
set digit_count = digit_count + 1
end
else
if is lower char
begin
set lowercase_count = lowercase_count + 1
end
else
if not is alphanumeric char... | def check_strings(arr):
for string in arr:
digit_count = 0
lowercase_count = 0
special_char_count = 0
for char in string:
if char.isdigit():
digit_count += 1
elif char.islower():
lowercase_count += 1
elif no... | Python | jtatman_500k |
import requests
from bs4 import BeautifulSoup
comment website Url
set URL = string https://www.empireonline.com/movies/features/best-movies-2/
set response = get requests URL
set website_html = text
set soup = call BeautifulSoup website_html string html.parser
comment get all movie data from website
set all_movies = fi... | import requests
from bs4 import BeautifulSoup
#website Url
URL = "https://www.empireonline.com/movies/features/best-movies-2/"
response = requests.get(URL)
website_html = response.text
soup = BeautifulSoup(website_html, "html.parser")
#get all movie data from website
all_movies = soup.find_all(name='div',class_='jsx-... | Python | zaydzuhri_stack_edu_python |
function new_game cls user num_card_types
begin
if num_card_types not in range 2 14
begin
raise call ValueError string Number of card types must be between 2 and 13
end
set board = range 0 num_card_types * 4
shuffle random board
set game = call Game user=user num_card_types=num_card_types board=string board matched_car... | def new_game(cls, user, num_card_types):
if num_card_types not in range(2, 14):
raise ValueError('Number of card types must be between 2 and 13')
board = range(0, num_card_types) * 4
random.shuffle(board)
game = Game(user=user,
num_card_types=num_card_type... | Python | nomic_cornstack_python_v1 |
function actionNextJob_triggered self
begin
set cj = current_job
if cj + 1 < length job_names
begin
call open_job cj + 1
end
else
begin
print string Last job open
return
end
end function | def actionNextJob_triggered(self):
cj = self.current_job
if cj + 1 < len(self.job_names):
self.open_job(cj + 1)
else:
print('Last job open')
return | Python | nomic_cornstack_python_v1 |
function check_netbackup_processes self recursion=false
begin
set server_name = name
try
begin
set nb_processes = call getoutput string ssh root@ { server_name } eval /usr/openv/netbackup/bin/bpps -a
info string Got processes from { server_name }
end
except Exception as e
begin
error string from: check_netbackup_proces... | def check_netbackup_processes(self, recursion=False) -> [list, None]:
server_name = self.name
try:
nb_processes = subprocess.getoutput(f"ssh root@{server_name} eval /usr/openv/netbackup/bin/bpps -a")
logging.info(f"Got processes from {server_name}")
except Exception as e:
logging.error(f"from: check_net... | Python | nomic_cornstack_python_v1 |
function _fgn_autocovariance hurst n
begin
set ns_2h = array range n + 1 ^ 2 * hurst
return insert np ns_2h at slice : - 2 : - 2 * ns_2h at slice 1 : - 1 : + ns_2h at slice 2 : : / 2 0 1
end function | def _fgn_autocovariance(hurst, n):
ns_2h = np.arange(n + 1) ** (2 * hurst)
return np.insert((ns_2h[:-2] - 2 * ns_2h[1:-1] + ns_2h[2:]) / 2, 0, 1) | Python | nomic_cornstack_python_v1 |
function get_relative_path path
begin
set file_directory = directory name path real path path __file__
return join path file_directory path
end function | def get_relative_path(path):
file_directory = os.path.dirname(os.path.realpath(__file__))
return os.path.join(file_directory, path) | Python | nomic_cornstack_python_v1 |
function gdf_to_shapefile gdf shp_fname **kwargs
begin
if not is instance gdf GeoDataFrame
begin
raise call ValueError string expected gdf to be a GeoDataFrame
end
set gdf = copy gdf
set geom_name = name
comment Rename columns for shapefile so they are 10 characters or less
set rename = dict
comment Change data types,... | def gdf_to_shapefile(gdf, shp_fname, **kwargs):
if not isinstance(gdf, geopandas.GeoDataFrame):
raise ValueError("expected gdf to be a GeoDataFrame")
gdf = gdf.copy()
geom_name = gdf.geometry.name
# Rename columns for shapefile so they are 10 characters or less
rename = {}
# Change data... | Python | nomic_cornstack_python_v1 |
function _convertToNewStyle newClass oldInstance
begin
comment if the oldInstance was an ExperimentHandler it wouldn't throw an error related
comment to itself, but to the underlying loops within it. So check if we have that and then
comment do imports on each loop
if __name__ == string ExperimentHandler
begin
set newH... | def _convertToNewStyle(newClass, oldInstance):
#if the oldInstance was an ExperimentHandler it wouldn't throw an error related
#to itself, but to the underlying loops within it. So check if we have that and then
#do imports on each loop
if oldInstance.__class__.__name__=='ExperimentHandler':
... | Python | nomic_cornstack_python_v1 |
comment -*- coding: utf-8 -*-
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import logging
from collections import Counter
from operator import mul
set logger = call getLogger __name__
class Fusion extends object
begin
set name = string base_fusion
function... | # -*- coding: utf-8 -*-
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import logging
from collections import Counter
from operator import mul
logger = logging.getLogger(__name__)
class Fusion(object):
name = 'base_fusion'
def train(self, gps, g... | Python | zaydzuhri_stack_edu_python |
function sendUpStatCountTagCounts node tag
begin
function pushUp node
begin
set t = 0
set ta = 0
for child in children
begin
set tuple tc tac = call pushUp child
set ta = ta + tac
set t = t + tc
end
set tagTranscriptAnnotations = tagTranscriptAnnotations + ta
set tagTranscripts = tagTranscripts + t
return tuple tagTran... | def sendUpStatCountTagCounts(node, tag):
def pushUp(node):
t = 0
ta = 0
for child in node.children:
tc, tac = pushUp(child)
ta += tac
t += tc
node.tagTranscriptAnnotations += ta
node.tagTranscripts += t
return node.tagTranscripts, node.tagTranscriptAnnotations
if ':' in tag... | Python | nomic_cornstack_python_v1 |
from dataclasses import dataclass , field
from operator import itemgetter
from typing import NamedTuple
from resources import query_hotels_by_param
class HotelsParsed extends NamedTuple
begin
string Структура возвращаемых данных после исполнения команды. :param hotels (optional) list[dict]: обработанная информация о на... | from dataclasses import dataclass, field
from operator import itemgetter
from typing import NamedTuple
from resources import query_hotels_by_param
class HotelsParsed(NamedTuple):
"""
Структура возвращаемых данных после исполнения команды.
:param hotels (optional) list[dict]: обработанная информация о на... | Python | zaydzuhri_stack_edu_python |
function subscribe self node=string data=string level=string dataset priority=string low move=string n static=string n custodial=string n group=string AnalysisOps timeStart=string requestOnly=string n noMail=string n comments=string format=string json instance=string prod
begin
set name = string subscribe
if not no... | def subscribe(self, node='', data='', level='dataset', priority='low',
move='n', static='n', custodial='n', group='AnalysisOps',
timeStart='', requestOnly='n', noMail='n', comments='',
format='json', instance='prod'):
name = "subscribe"
if not (node ... | Python | nomic_cornstack_python_v1 |
if b * b - 4 * a * c < 0
begin
print string answer involves imaginary numbers
end
else
begin
set option_1 = - b + b * b - 4 * a * c ^ 1 / 2 / 2 * a
set option_2 = - b - b * b - 4 * a * c ^ 1 / 2 / 2 * a
print string x = + string option_1 + string , + string option_2
end | if ((b*b)-(4*a*c)) < 0:
print('answer involves imaginary numbers')
else:
option_1 = ((-b + (((b*b)-(4*a*c))**(1/2)))/(2*a))
option_2 = ((-b - (((b*b)-(4*a*c))**(1/2)))/(2*a))
print('x = ' + str(option_1) + ' , ' + str(option_2)) | Python | zaydzuhri_stack_edu_python |
comment !/usr/bin/env python3
comment -*- coding: utf-8 -*-
string Created on Wed Mar 28 08:25:57 2018 @author: mikulas
import scipy.optimize as op
import numpy as np
import numpy.linalg as la
import matplotlib as plt
set hartree = 27.21138602
set amuel = 1822.157434
set bohr = 0.529177
function mu amu1 amu2
begin
retu... | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Wed Mar 28 08:25:57 2018
@author: mikulas
"""
import scipy.optimize as op
import numpy as np
import numpy.linalg as la
import matplotlib as plt
hartree= 27.21138602
amuel= 1822.157434
bohr= 0.529177
def mu(amu1, amu2):
return 1.0*amu1*amu2*amuel/(amu1... | Python | zaydzuhri_stack_edu_python |
function relative_complements_on_segment_edges self segments
begin
set self_edges = call get_set_self_segment_edges sort=true
set other_edges = set
for s in segments
begin
set tuple u v = call get_edge_vertices_pair_from_segment segment=s sort=true
add other_edges tuple u v
end
set intersection = intersection self_edge... | def relative_complements_on_segment_edges(self, segments):
self_edges = self.get_set_self_segment_edges(sort=True)
other_edges = set()
for s in segments:
u, v = self.get_edge_vertices_pair_from_segment(segment=s, sort=True)
other_edges.add((u, v))
intersection = s... | Python | nomic_cornstack_python_v1 |
function getCount x y w h
begin
set min = y
if h - y < min
begin
set min = h - y
end
if x < min
begin
set min = x
end
if w - x < min
begin
set min = w - x
end
return min
end function
if __name__ == string __main__
begin
set tuple x y w h = map int split strip input string
print call getCount x y w h
end | def getCount(x, y, w, h):
min = y
if h - y < min:
min = h - y
if x < min:
min = x
if w - x < min:
min = w - x
return min
if __name__=='__main__':
x, y, w, h = map(int, input().strip().split(' '))
print(getCount(x, y, w, h))
| Python | zaydzuhri_stack_edu_python |
set content_string = read open string adressen.csv string r
set content = list comprehension dictionary comprehension split split content_string string at 0 string ; at slice : - 1 : at idx : value for tuple idx value in enumerate content_line for content_line in list comprehension split line string ; at slice : - 1... | content_string = open('adressen.csv', 'r').read()
content = [{content_string.split('\n')[0].split(';')[:-1][idx] : value for idx, value in enumerate(content_line)}
for content_line in [line.split(';')[:-1] for line in content_string.split('\n')][1:]]
print(content) | Python | zaydzuhri_stack_edu_python |
function code
begin
set msg = input string enter the message you want to convey ^_^....
for character in msg
begin
if character in alpha
begin
set posi = find alpha character
set nposi = posi + key % 26
set newcar = alpha at nposi
set newmsg = newmsg + newcar
end
else
begin
set newmsg = newmsg + character
end
end
print... | def code():
msg=input("enter the message you want to convey ^_^.... ")
for character in msg:
if character in alpha:
posi=alpha.find(character)
nposi=(posi+key)%26
newcar=alpha[nposi]
newmsg+=newcar
else:
newmsg+=character
print('your secret message is...',newmsg)
def decode():
msg=input("ent... | Python | zaydzuhri_stack_edu_python |
function parse_args argv=none
begin
set description = call dedent string Panacea - This script does ... (Fill in Later)
set parser = call ArgumentParser description=description formatter_class=RawTextHelpFormatter
call add_argument string -rt string --reduce_twi help=string Reduce Twighlight frames for calibration acti... | def parse_args(argv=None):
description = textwrap.dedent('''Panacea -
This script does ... (Fill in Later)
''')
parser = ap.ArgumentParser(description=description,
formatter_class=ap.RawTextHe... | Python | nomic_cornstack_python_v1 |
comment Function definitions
function addition a b
begin
return a + b
end function
function subtraction a b
begin
return a - b
end function
function multiplication a b
begin
return a * b
end function
function division a b
begin
return a / b
end function
comment Taking input from the User and then converting it from str... | # Function definitions
def addition(a, b):
return a + b
def subtraction(a, b):
return a - b
def multiplication(a, b):
return a * b
def division(a, b):
return a / b
# Taking input from the User and then converting it from string into Integer type
num1 = int(input("Enter First Number: "))
num2 = int(i... | Python | zaydzuhri_stack_edu_python |
import json
set mayfile = string task_2.json
with open mayfile encoding=string utf-8 as read_file
begin
set data = load json read_file
sort data key=lambda user -> user at string shop
print data
end | import json
mayfile = "task_2.json"
with open(mayfile,encoding="utf-8") as read_file:
data = json.load(read_file)
data.sort(key=lambda user: user["shop"])
print (data)
| Python | zaydzuhri_stack_edu_python |
string This code will run the main game using the snake and food classes imported
comment Diego Buenrostro
comment CPSC 386-01
comment 04-27-2021
comment dbuenrostro64@csu.fullerton.edu
comment @dbuenrostro64
comment Snake Game
comment Implementation of classic game of Snake
import os
import sys
import pygame
import py... | """This code will run the main game using the snake and food classes imported """
# Diego Buenrostro
# CPSC 386-01
# 04-27-2021
# dbuenrostro64@csu.fullerton.edu
# @dbuenrostro64
#
# Snake Game
#
# Implementation of classic game of Snake
#
import os
import sys
import pygame
import pygame.freetype
from pygame.locals i... | Python | zaydzuhri_stack_edu_python |
function extract_topics self
begin
set topics = list
if call has_key string topics
begin
for r in results at string topics
begin
comment initialize
set topic = call get_default_entity
set topic at string type at string name = string Category
comment populate and add to list
set topic at string entity at string name = ... | def extract_topics(self):
topics = []
if self.results.has_key('topics'):
for r in self.results['topics']:
# initialize
topic = self.get_default_entity()
topic['type']['name'] = 'Category'
# populate and add to l... | Python | nomic_cornstack_python_v1 |
import os
from pathlib import Path
for f in list directory
begin
comment print(os.path.splitext(f))
if ends with f string pdf
begin
print absolute path path f
end
end | import os
from pathlib import Path
for f in os.listdir():
#print(os.path.splitext(f))
if f.endswith('pdf'):
print(os.path.abspath(f)) | Python | zaydzuhri_stack_edu_python |
if D == 0
begin
set base = 1
end
else
if D == 1
begin
set base = 100
end
else
if D == 2
begin
set base = 10000
end
print base * N | if D == 0:
base = 1
elif D == 1:
base = 100
elif D == 2:
base = 10000
print(base * N)
| Python | zaydzuhri_stack_edu_python |
comment coding:utf-8
import random
import urllib.parse
import urllib.request
from datetime import datetime
from hashlib import md5
comment from wallet.RedisConnector import RedisConnector
from config.myredis import MyRedis
class PhoneNumberVerificator
begin
comment 短信网关配置
function __init__ self
begin
set www_sms_com_AP... | # coding:utf-8
import random
import urllib.parse
import urllib.request
from datetime import datetime
from hashlib import md5
#from wallet.RedisConnector import RedisConnector
from config.myredis import MyRedis
class PhoneNumberVerificator():
# 短信网关配置
def __init__(self):
self.www_sms_com_API = {
... | Python | zaydzuhri_stack_edu_python |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.