code stringlengths 10 2.58M | original_code stringlengths 3 3.18M | original_language stringclasses 1
value | source stringclasses 7
values |
|---|---|---|---|
string script que permite convertir de un objeto de python a un flujo de bytes
import pickle , time
import numpy as np
set l1 = array list list 1 2 list 0 1
comment convertir la lista a flujo de bytes
set b1 = dumps l1
comment guardar la variable b1 en un archivo binario
set a1 = open string info string wb
write a1 b1
... | """
script que permite convertir de un objeto de python a un flujo de bytes
"""
import pickle,time
import numpy as np
l1=np.array([[1,2],[0,1]])
#convertir la lista a flujo de bytes
b1=pickle.dumps(l1)
#guardar la variable b1 en un archivo binario
a1=open("info","wb")
a1.write(b1)
a1.close()
| Python | zaydzuhri_stack_edu_python |
comment !/usr/bin/env python
comment coding: utf8
set letters = string ABC123456789
set tips = tuple string 宝包请按%s string 宝包你按了%s吗 string 宝包再按一下%s
set good_msg = tuple string 太棒了, 宝包答对了 string 宝包真厉害
set bad_msg = tuple string 只差一点了, 别灰心 string 没有答对, 再试一次吧
from random import choice
from os import environ
from utils impo... | #!/usr/bin/env python
#coding: utf8
letters = 'ABC123456789'
tips = (
'宝包请按%s',
'宝包你按了%s吗',
'宝包再按一下%s',
)
good_msg = (
'太棒了, 宝包答对了',
'宝包真厉害',
)
bad_msg = (
'只差一点了, 别灰心',
'没有答对, 再试一次吧',
)
from random import choice
from os import environ
from utils import getch, say
l = choice(letters)
... | Python | zaydzuhri_stack_edu_python |
comment !/usr/bin/python
comment coding=utf-8
comment Needed modules will be imported
import RPi.GPIO as GPIO
import Adafruit_DHT
import time
from datetime import datetime
comment The break of 2 seconds will be configured here
set sleeptime = 2
comment Sensor should be set to Adafruit_DHT.DHT11,
comment Adafruit_DHT.DH... | #!/usr/bin/python
# coding=utf-8
# Needed modules will be imported
import RPi.GPIO as GPIO
import Adafruit_DHT
import time
from datetime import datetime
# The break of 2 seconds will be configured here
sleeptime = 2
# Sensor should be set to Adafruit_DHT.DHT11,
# Adafruit_DHT.DHT22, or Adafruit_DHT.AM2302.
DHTSen... | Python | zaydzuhri_stack_edu_python |
function test_build_envoy_image_from_source_fail mock_get_source_tree
begin
set nighthawk_source_repo = call SourceRepository identity=SRCID_NIGHTHAWK source_path=string /some_random_not_envoy_directory
set return_value = nighthawk_source_repo
set manager = call _generate_default_source_manager
set builder = call Envoy... | def test_build_envoy_image_from_source_fail(mock_get_source_tree):
nighthawk_source_repo = proto_source.SourceRepository(
identity=proto_source.SourceRepository.SourceIdentity.SRCID_NIGHTHAWK,
source_path='/some_random_not_envoy_directory')
mock_get_source_tree.return_value = nighthawk_source_repo
ma... | Python | nomic_cornstack_python_v1 |
for i in range 199 0 - 2
begin
print i
end | for i in range(199, 0, -2):
print(i)
| Python | jtatman_500k |
function affirmative msg
begin
set ans = call raw_input msg + string (enter 'y' or 'Y' for yes):
if ans in tuple string y string Y
begin
return true
end
else
begin
return false
end
end function | def affirmative(msg):
ans = raw_input(msg + " (enter 'y' or 'Y' for yes): ")
if ans in ('y', 'Y'):
return True
else:
return False | Python | nomic_cornstack_python_v1 |
function get_data self
begin
set all_data = ordered dictionary
set projects = list comprehension call Path proj for proj in glob string call joinpath string * if call is_dir
for project in projects
begin
set files = list
comment Read all csv files and save them as a list in files
for ver in glob string call joinpath s... | def get_data(self):
all_data = OrderedDict()
projects = [Path(proj) for proj in glob(str(self.data_path.joinpath("*"))) if Path(proj).is_dir()]
for project in projects:
files = []
# Read all csv files and save them as a list in files
for ver in ... | Python | nomic_cornstack_python_v1 |
function decode self output_dict
begin
for name in _states
begin
set top_k_predicted_indices = output_dict at string { name } _top_k_predictions at 0
set output_dict at string { name } _top_k_predicted_tokens = list call decode_all top_k_predicted_indices
end
return output_dict
end function | def decode(self, output_dict: Dict[str, torch.Tensor]) -> Dict[str, List[List[str]]]:
for name in self._states:
top_k_predicted_indices = output_dict[f"{name}_top_k_predictions"][0]
output_dict[f"{name}_top_k_predicted_tokens"] = [self.decode_all(top_k_predicted_indices)]
return... | Python | nomic_cornstack_python_v1 |
function increase_global_step_index self
begin
set _global_step_index = _global_step_index + 1
set _local_step_index = _local_step_index + 1
end function | def increase_global_step_index(self):
self._global_step_index += 1
self._local_step_index += 1 | Python | nomic_cornstack_python_v1 |
function _get_recommend self user
begin
return call calculate target_user_id=user user_n=user_n item_n=item_n type=2
end function | def _get_recommend(self, user):
return self.user_cf.calculate(target_user_id=user, user_n=self.user_n,
item_n=self.item_n, type=2) | Python | nomic_cornstack_python_v1 |
comment imports random function
import random
comment imports time function
import time
comment this is iterative version of GCD
comment defined new hcf function
function computeHCF x y
begin
comment checks whether x > y
if x > y
begin
comment if x is greater assigns smaller = y
set smaller = y
end
else
begin
comment i... | import random #imports random function
import time #imports time function
# this is iterative version of GCD
def computeHCF(x,y): #defined new hcf function
if x > y: #checks whether x > y
smaller = y # if... | Python | zaydzuhri_stack_edu_python |
comment !/usr/bin/python
comment -*- coding: utf-8 -*-
string solve
set __author__ = string Zagfai
set __date__ = string 2016-04
set __license__ = string MIT
function reverse line i
begin
for j in range i + 1
begin
if line at j == string +
begin
set line at j = string -
end
else
if line at j == string -
begin
set line ... | #!/usr/bin/python
# -*- coding: utf-8 -*-
""" solve
"""
__author__ = 'Zagfai'
__date__ = '2016-04'
__license__ = 'MIT'
def reverse(line, i):
for j in range(i+1):
if line[j] == '+':
line[j] = '-'
elif line[j] == '-':
line[j] = '+'
return list(reversed(line[:i+1])) + line[... | Python | zaydzuhri_stack_edu_python |
comment Set Operations
comment Description
comment In a school, there are total 20 students numbered from 1 to 20. You’re given three lists named ‘C’, ‘F’, and ‘H’,
comment representing students who play cricket, football, and hockey, respectively. Based on this information,
comment find out and print the following:
co... | # Set Operations
# Description
# In a school, there are total 20 students numbered from 1 to 20. You’re given three lists named ‘C’, ‘F’, and ‘H’,
# representing students who play cricket, football, and hockey, respectively. Based on this information,
# find out and print the following:
# 1. Students who play all the t... | Python | zaydzuhri_stack_edu_python |
string 問題文 yukiさんは一袋 K 粒だけ豆が入った袋を N 袋拾いました. ところで,節分には年齢の数だけの豆を食べる習慣があります. yukiさんの家族は F 人家族で,それぞれの年齢は A1,A2,…,AF 歳です. それぞれが年齢の数だけの豆を食べたら最終的に何粒残るかを求める下さい. ただし,全員が年齢の数だけ豆を食べることができないなら -1 を出力して下さい. 入力 K N F A1 A2⋯AF 1≤K≤1000 1≤N≤1000 1≤F≤100 1≤Ak≤100 出力 残る豆の粒の数を出力するか,-1を出力して下さい.
set tuple k n f = map int split input
set l ... | '''
問題文
yukiさんは一袋 K
粒だけ豆が入った袋を N 袋拾いました.
ところで,節分には年齢の数だけの豆を食べる習慣があります.
yukiさんの家族は F 人家族で,それぞれの年齢は A1,A2,…,AF 歳です.
それぞれが年齢の数だけの豆を食べたら最終的に何粒残るかを求める下さい.
ただし,全員が年齢の数だけ豆を食べることができないなら -1 を出力して下さい.
入力
K
N
F
A1 A2⋯AF
1≤K≤1000
1≤N≤1000
1≤F≤100
1≤Ak≤100
出力
残る豆の粒の数を出力するか,-1を出力して下さい.
'''
k,n,f=map(int,input().split())
l=list(... | Python | zaydzuhri_stack_edu_python |
comment Hash Table (Chaining 방법) 구현
comment 작성자: 이종은
comment oepn addressing과 대비되는 다른 충돌 회피 방법은 chaining.
comment open addressing은 한 slot당 들어갈 수 있는 entry가 하나지만 chaining은 아님.
comment chaining은 하나의 slot에 여러 개의 item 들어갈 수 있다. 각 slot은 연결리스트로 관리하겠음.
comment 3번에 23 넣을 때 pushFront(23)가 O(1)이니 set(23)도 O(1)
comment search(66)와... | ## Hash Table (Chaining 방법) 구현
# 작성자: 이종은
# oepn addressing과 대비되는 다른 충돌 회피 방법은 chaining.
# open addressing은 한 slot당 들어갈 수 있는 entry가 하나지만 chaining은 아님.
# chaining은 하나의 slot에 여러 개의 item 들어갈 수 있다. 각 slot은 연결리스트로 관리하겠음.
# 3번에 23 넣을 때 pushFront(23)가 O(1)이니 set(23)도 O(1)
# search(66)와 remove는 O(충돌 key의 평균 개수(=연결리스트 길이))
# 해... | Python | zaydzuhri_stack_edu_python |
function _create_solr_query self line
begin
string Actual search - easier to test.
set p0 = string
if line
begin
set p0 = strip line
end
set p1 = call _query_string_to_solr_filter line
set p2 = call _object_format_to_solr_filter line
set p3 = call _time_span_to_solr_filter
set result = p0 + p1 + p2 + p3
return strip r... | def _create_solr_query(self, line):
"""Actual search - easier to test. """
p0 = ""
if line:
p0 = line.strip()
p1 = self._query_string_to_solr_filter(line)
p2 = self._object_format_to_solr_filter(line)
p3 = self._time_span_to_solr_filter()
result = p0 +... | Python | jtatman_500k |
string title: 偏函数 time: 2018.04.04 17:00 author: 杨龙(Alex)
string 偏函数: 在python中定义函数时,我们可以使用默认参数,来降低调用函数时的难度,同样的使用偏函数也可以达到这样的效果 需要引入 import functools functools.partical 就是用来创建一个新的函数.不需要我们自行定义函数.直接将结果赋值给一个变量,而这个变量就是一个函数.这个函数的目的是将默认参数给固定住
comment 使用封装
comment def int2(x, base = 2):
comment return int(x, base)
comment print... | '''
title: 偏函数
time: 2018.04.04 17:00
author: 杨龙(Alex)
'''
'''
偏函数:
在python中定义函数时,我们可以使用默认参数,来降低调用函数时的难度,同样的使用偏函数也可以达到这样的效果
需要引入
import functools
functools.partical 就是用来创建一个新的函数.不需要我们自行定义函数.直接将结果赋值给一个变量,而这个变量就是一个函数.这个函数的目的是将默认参数给固定住
'''
# 使用封装
# def int2(x, base = 2):
# return int(x, base)
# print(int2('10001001... | Python | zaydzuhri_stack_edu_python |
comment PROJECT 1 -- DATA ANALYSIS PROFESSIONAL TRACK
comment MAHMOUD ALI HASHEM
import time
import pandas as pd
set CITY_DATA = dict string chicago string chicago.csv ; string new york city string new_york_city.csv ; string washington string washington.csv
function check_input input_str input_type
begin
string check t... | #PROJECT 1 -- DATA ANALYSIS PROFESSIONAL TRACK
#MAHMOUD ALI HASHEM
import time
import pandas as pd
CITY_DATA = {'chicago': 'chicago.csv',
'new york city': 'new_york_city.csv',
'washington': 'washington.csv'}
def check_input(input_str, input_type):
"""
check the validity of user inp... | Python | zaydzuhri_stack_edu_python |
from django import forms
from string import digits
from passenger_view.models import ScheduledFlight , Airport
class AirportForm extends ModelForm
begin
string Form for creating new airports
class Meta
begin
set model = Airport
set fields = list string airport_name string airport_city string airport_country
end class
f... | from django import forms
from string import digits
from passenger_view.models import ScheduledFlight, Airport
class AirportForm(forms.ModelForm):
"""Form for creating new airports"""
class Meta:
model = Airport
fields = [
'airport_name',
'airport_city',
'air... | Python | zaydzuhri_stack_edu_python |
comment !/usr/bin/env python3
import shutil as sh
import psutil as ps
function check_disk_usage disk
begin
set du = disk usage disk
set free = free / toal * 100
return free > 20
end function
function check_cpu_usage
begin
set cp_usage = call cpu_percent 1
end function | #!/usr/bin/env python3
import shutil as sh
import psutil as ps
def check_disk_usage(disk):
du = sh.disk_usage(disk)
free = du.free / du.toal * 100
return free > 20
def check_cpu_usage():
cp_usage = ps.cpu_percent(1) | Python | zaydzuhri_stack_edu_python |
comment Library of fault injection functions called at runtime for common operations in TensorFlow
comment NOTE: These are called by the corresponding functions inserted in the TensorFlow graph at RUNTIME
import tensorflow as tf
import numpy as np
import logging
from fiConfig import *
from fiLog import *
from threading... | # Library of fault injection functions called at runtime for common operations in TensorFlow
# NOTE: These are called by the corresponding functions inserted in the TensorFlow graph at RUNTIME
import tensorflow as tf
import numpy as np
import logging
from fiConfig import *
from fiLog import *
from threading import c... | Python | jtatman_500k |
function can_load self step context
begin
raise call NotImplementedError
end function | def can_load(self, step: 'BaseTransformer', context: 'CX'):
raise NotImplementedError() | Python | nomic_cornstack_python_v1 |
import os
import pandas as pd
set keys = list string Open string High string Low string Close string Volume
function run file_name path=string ../../data is_adjusted=false
begin
if is_adjusted
begin
set file_name = file_name + string _adjusted
end
else
begin
set file_name = file_name + string _unadjusted
end
set full_p... | import os
import pandas as pd
keys = ['Open', 'High', 'Low', 'Close', 'Volume']
def run(file_name, path='../../data', is_adjusted=False):
if is_adjusted:
file_name += '_adjusted'
else:
file_name += '_unadjusted'
full_path = os.path.join(path, file_name) + '.txt'
data = {}
with ... | Python | zaydzuhri_stack_edu_python |
function real_div_compute data_1 data_2 output_z kernel_name=string real_div
begin
set shape_x = call shape_to_list shape
set shape_y = call shape_to_list shape
set tuple shape_x shape_y shape_max = call produce_shapes shape_x shape_y
call check_shape_size shape_max SHAPE_SIZE_LIMIT
set data_x = call broadcast data_1 s... | def real_div_compute(data_1, data_2, output_z, kernel_name="real_div"):
shape_x = te.lang.cce.util.shape_to_list(data_1.shape)
shape_y = te.lang.cce.util.shape_to_list(data_2.shape)
shape_x, shape_y, shape_max = util.produce_shapes(shape_x, shape_y)
util.check_shape_size(shape_max, SHAPE_SIZE_LIMIT)
... | Python | nomic_cornstack_python_v1 |
function get_from_input_state self inputs input_state object_id related_id=none
begin
set address = call address object_id=object_id related_id=related_id
if address not in inputs
begin
raise call ValueError format string {} address {} for {} {} target {} was not sent as an input address address_type address _name_id o... | def get_from_input_state(self, inputs, input_state, object_id, related_id=None):
address = self.address(object_id=object_id, related_id=related_id)
if address not in inputs:
raise ValueError(
"{} address {} for {} {} target {} was not sent as an input address".format(
... | Python | nomic_cornstack_python_v1 |
function environment self
begin
return get pulumi self string environment
end function | def environment(self) -> pulumi.Output[Optional['outputs.FunctionEnvironment']]:
return pulumi.get(self, "environment") | Python | nomic_cornstack_python_v1 |
function base_codes self
begin
set bases = list
if is_gas_giant
begin
append bases string G
end
if is_naval_base
begin
append bases string N
end
if is_scout_base
begin
append bases string S
end
if is_research_base
begin
append bases string R
end
if is_tas
begin
append bases string T
end
if is_consulate
begin
append ba... | def base_codes(self):
bases = []
if self.is_gas_giant:
bases.append("G")
if self.is_naval_base:
bases.append("N")
if self.is_scout_base:
bases.append("S")
if self.is_research_base:
bases.append("R")
if self.is_tas:
... | Python | nomic_cornstack_python_v1 |
function detect_de_node parser
begin
set success = call is_node_exists string test_c string test_n parser
if not success
begin
return true
end
raise call Assert_Error string de node fail
end function | def detect_de_node(parser):
success = HAagent_info.is_node_exists("test_c", "test_n", parser)
if not success:
return True
raise TA_error.Assert_Error("de node fail") | Python | nomic_cornstack_python_v1 |
from time import time
from math import sqrt , floor
from decimal import Decimal
function find_blue_balls all_balls
begin
string Return number of blue balls for a P(bb)= 1/2 probability.
set all_balls_equ = 1 + 2 * all_balls * all_balls - 1
return call Decimal 1 + square root all_balls_equ / 2
end function
if __name__ =... | from time import time
from math import sqrt, floor
from decimal import Decimal
def find_blue_balls(all_balls):
"""Return number of blue balls for a P(bb)= 1/2 probability."""
all_balls_equ = 1 + 2 * all_balls * (all_balls-1)
return Decimal(1 + sqrt(all_balls_equ))/2
if __name__ == '__main__':
curr, upper = ... | Python | zaydzuhri_stack_edu_python |
string 常见的函数变换包括:开方,平方,对数 数据规范化: 1.离差标准化(最小最大标准化)--消除量纲(单位)影响以及编变异大小因素的影响 x1=(x-min)/(max-min) 2.标准差标准化(零-均值标准化)--消除单位影响以及变量自身变异影响 x1=(x-平均数)/标准差 3.小数定标规范化--消除单位影响 x1=x/10^k k=log10(x的绝对值的最大值)
import numpy
import pymysql
import pandas
import matplotlib.pylab
import math
set conn = call connect host=string 127.0.0.1 por... | '''
常见的函数变换包括:开方,平方,对数
数据规范化:
1.离差标准化(最小最大标准化)--消除量纲(单位)影响以及编变异大小因素的影响 x1=(x-min)/(max-min)
2.标准差标准化(零-均值标准化)--消除单位影响以及变量自身变异影响 x1=(x-平均数)/标准差
3.小数定标规范化--消除单位影响 x1=x/10^k k=log10(x的绝对值的最大值)
'''
import numpy
import pymysql
import pandas
import matplotlib.pylab
import math
conn = pymysql.connect(host="127.0.0.1", ... | Python | zaydzuhri_stack_edu_python |
import math
import random
import pygame
import tkinter
import tkinter.font as font
set BOARDSIZE = 600
set BOARDHEIGHT = 24
set BOARDWIDTH = 10
class Cube extends object
begin
function __init__ self color
begin
pass
end function
function move self
begin
pass
end function
function draw self
begin
pass
end function
end c... | import math
import random
import pygame
import tkinter
import tkinter.font as font
BOARDSIZE = 600
BOARDHEIGHT = 24
BOARDWIDTH = 10
class Cube(object):
def __init__(self, color):
pass
def move(self):
pass
def draw(self):
pass
class Piece(object):
def __init__(self):
... | Python | zaydzuhri_stack_edu_python |
function grouping self grouping
begin
set _grouping = grouping
end function | def grouping(self, grouping):
self._grouping = grouping | Python | nomic_cornstack_python_v1 |
function fusion_srm_oa_api_set_blade_power self bay_numb power_cmd
begin
call set_blade_power bay_numb=bay_numb power_cmd=power_cmd
end function | def fusion_srm_oa_api_set_blade_power(self, bay_numb, power_cmd):
self.oa_client.set_blade_power(bay_numb=bay_numb, power_cmd=power_cmd) | Python | nomic_cornstack_python_v1 |
from models import Player , Caster , RoundPairing
from django.http import HttpResponse
from django.shortcuts import render , redirect
from django.db.models import Max
from django.core.urlresolvers import reverse
import random
function _generate_round round_number
begin
string Generate a new round of the given round num... | from .models import Player, Caster, RoundPairing
from django.http import HttpResponse
from django.shortcuts import render, redirect
from django.db.models import Max
from django.core.urlresolvers import reverse
import random
def _generate_round(round_number):
"""
Generate a new round of the given round number.
No ... | Python | zaydzuhri_stack_edu_python |
while true
begin
set row = input string please input a row:
if row == string quit
begin
break
end
set row = integer row
for i in range - row row + 1
begin
if i < 0
begin
set i = - i
end
else
begin
set i = i
end
print string * i + string * * 2 * row - 1 - 2 * i
end
for i in range - row row + 1
begin
if i < 0
begin
set ... | while True:
row=input("please input a row:")
if row=="quit":
break
row=int(row)
for i in range(-row, row+1):
if i < 0:
i = -i
else:
i = i
print(" " * i + "*" * ((2*row-1)- 2 * i))
for i in range(-row, row+1):
if i < 0:
i = ... | Python | zaydzuhri_stack_edu_python |
import os
import sys
import time
import getch
import random
from termcolor import cprint
comment It will store the command, which will be used to change the wallpaper
set cmd = string
comment This is the main function of this project. It carry the main menu and call the other helper functions as needed.
function home_... | import os
import sys
import time
import getch
import random
from termcolor import cprint
cmd = '' # It will store the command, which will be used to change the wallpaper
# This is the main function of this project. It carry the main menu and call the other helper functions as needed.
def home_scr():
global cmd # ... | Python | zaydzuhri_stack_edu_python |
comment !/usr/bin/env python
comment coding: utf-8
comment In[735]:
string 1.Importing Libraries
import pandas as pd
import numpy as np
import pandas as pd
import json
import re
import string
import nltk
import matplotlib.pyplot as plt
from nltk.corpus import stopwords
from nltk.stem import PorterStemmer
from nltk.toke... | #!/usr/bin/env python
# coding: utf-8
# In[735]:
'''
1.Importing Libraries
'''
import pandas as pd
import numpy as np
import pandas as pd
import json
import re
import string
import nltk
import matplotlib.pyplot as plt
from nltk.corpus import stopwords
from nltk.stem import PorterStemmer
from nltk.tokenize import Tw... | Python | zaydzuhri_stack_edu_python |
import pandas as pd
set df = call DataFrame dict string Col1 list 4 2 8 none 6 ; string Col2 list 7 5 none 3 1
set df = drop missing df subset=list string Col1
set df = sort values df by=string Col1 ascending=false
set result_list = call tolist | import pandas as pd
df = pd.DataFrame({'Col1': [4, 2, 8, None, 6], 'Col2': [7, 5, None, 3, 1]})
df = df.dropna(subset=['Col1'])
df = df.sort_values(by='Col1', ascending=False)
result_list = df['Col1'].tolist()
| Python | jtatman_500k |
function check_report_is_at_recognition_of_prior_learning text
begin
set recog_check_regex = match text
set check_flag_recog = recog_check_regex is not none
return check_flag_recog
end function | def check_report_is_at_recognition_of_prior_learning(text) -> bool:
recog_check_regex = re.compile(r"^recognition\sof\sprior\slearning", re.IGNORECASE).match(text)
check_flag_recog = recog_check_regex is not None
return check_flag_recog | Python | nomic_cornstack_python_v1 |
set n = integer input
set z = list comprehension integer i for i in split input
set z2 = list z
sort z2
if length set z2 == 1
begin
print - 1
end
else
begin
print *z2
end | n = int(input())
z = [int(i) for i in input().split()]
z2 = list(z)
z2.sort()
if(len(set(z2)) == 1):
print(-1)
else:
print(*z2) | Python | zaydzuhri_stack_edu_python |
comment coding: utf-8
comment # Logistic Regression in Apache pyspark
comment ## Introduction: | # coding: utf-8
# # Logistic Regression in Apache pyspark
# ## Introduction:
| Python | zaydzuhri_stack_edu_python |
function get_esg_by_region self measure pricing_date=none
begin
return call _get_esg_breakdown MEASURES_BY_REGION measure pricing_date
end function | def get_esg_by_region(self,
measure: ESGMeasure,
pricing_date: dt.date = None) -> pd.DataFrame:
return self._get_esg_breakdown(ESGCard.MEASURES_BY_REGION, measure, pricing_date) | Python | nomic_cornstack_python_v1 |
set celsius = list 20 30 40 50 60
set farenheit = list comprehension 9 / 5 + i + 32 for i in celsius
print farenheit | celsius=[20,30,40,50,60]
farenheit=[9/5+i+32 for i in celsius]
print(farenheit)
| Python | zaydzuhri_stack_edu_python |
class Solution extends object
begin
function longestValidParentheses self s
begin
string :type s: str :rtype: int
set stack = list
set maxLen = 0
for i in range length s
begin
if s at i == string (
begin
append stack i
end
else
if length stack > 0
begin
if s at stack at - 1 == string (
begin
set stack = stack at slice... | class Solution(object):
def longestValidParentheses(self, s):
"""
:type s: str
:rtype: int
"""
stack = []
maxLen = 0
for i in range(len(s)):
if s[i] == '(':
stack.append(i)
else:
if len(stack) > 0:
... | Python | zaydzuhri_stack_edu_python |
class Vendor
begin
function __init__ self inventory=none
begin
if inventory == none
begin
set inventory = list
end
else
begin
set inventory = inventory
end
end function
function add self item
begin
if item not in inventory
begin
append inventory item
end
return item
end function
function remove self item
begin
if item... | class Vendor:
def __init__(self, inventory = None):
if inventory == None:
self.inventory = []
else:
self.inventory = inventory
def add(self, item):
if item not in self.inventory:
self.inventory.append(item)
return item
def remove(self, i... | Python | zaydzuhri_stack_edu_python |
for i in range 0 11
begin
print i
end | for i in range(0,11):
print(i) | Python | jtatman_500k |
function multiplication_table n
begin
set table = list
for i in range 1 n + 1
begin
set row = list
for j in range 1 n + 1
begin
append row i * j
end
append table row
end
return table
end function
comment Test the function
set number = 5
set result = call multiplication_table number
for row in result
begin
print row
e... | def multiplication_table(n):
table = []
for i in range(1, n+1):
row = []
for j in range(1, n+1):
row.append(i * j)
table.append(row)
return table
# Test the function
number = 5
result = multiplication_table(number)
for row in result:
print(row)
| Python | jtatman_500k |
import tensorflow as tf
set a = call constant 2
set b = call constant 3 | import tensorflow as tf
a = tf.constant(2)
b = tf.constant(3)
| Python | zaydzuhri_stack_edu_python |
function _set_listen_range self v load=false
begin
string Setter method for listen_range, mapped from YANG variable /rbridge_id/router/router_bgp/address_family/ipv4/ipv4_unicast/af_vrf/listen_range (list) If this variable is read-only (config: false) in the source YANG file, then _set_listen_range is considered as a p... | def _set_listen_range(self, v, load=False):
"""
Setter method for listen_range, mapped from YANG variable /rbridge_id/router/router_bgp/address_family/ipv4/ipv4_unicast/af_vrf/listen_range (list)
If this variable is read-only (config: false) in the
source YANG file, then _set_listen_range is considered ... | Python | jtatman_500k |
import random
import unittest
import tests.util as util
from heaps import HeapQueue
class TestSorting extends TestCase
begin
set _seed = call randrange 10 ^ 4 10 ^ 9
function test_simple_list self
begin
set heap_instance = call HeapQueue
set list_to_test = list tuple 1 1 tuple 2 2 tuple 3 3 tuple 4 4 tuple 5 5
set retr... | import random
import unittest
import tests.util as util
from heaps import HeapQueue
class TestSorting(unittest.TestCase):
_seed = random.randrange(10 ** 4, 10 ** 9)
def test_simple_list(self):
heap_instance = HeapQueue()
list_to_test = [(1, 1), (2, 2), (3, 3), (4, 4), (5, 5)]
retriev... | Python | zaydzuhri_stack_edu_python |
import numpy as np
from numpy import array
function hr_images images
begin
set images_hr = array images
return images_hr
end function
function normalize input_data
begin
return as type input_data float32 - 127.5 / 127.5
end function
function denormalize input_data
begin
set input_data = input_data + 1 * 127.5
return as... | import numpy as np
from numpy import array
def hr_images(images):
images_hr = array(images)
return images_hr
def normalize(input_data):
return (input_data.astype(np.float32) - 127.5) / 127.5
def denormalize(input_data):
input_data = (input_data + 1) * 127.5
return input_data.astype(np.uint8) | Python | zaydzuhri_stack_edu_python |
function make_multiplier factor
begin
function multiply number
begin
return number * factor
end function
return multiply
end function
set mult6 = call make_multiplier 6
set mult7 = call make_multiplier 7
comment prints 42
print call mult6 7
comment prints 42
print call mult7 6 | def make_multiplier(factor):
def multiply(number):
return number * factor
return multiply
mult6 = make_multiplier(6)
mult7 = make_multiplier(7)
print(mult6(7)) # prints 42
print(mult7(6)) # prints 42
| Python | zaydzuhri_stack_edu_python |
function word_counter word_list
begin
set words_list = dict
set word_sorting = list
for line in word_list
begin
set words = split line string
for word in words
begin
append word_sorting word
end
end
for sorted_word in sorted word_sorting
begin
if length sorted_word > 6
begin
set word_amount = integer get words_list l... | def word_counter(word_list):
words_list = {}
word_sorting = []
for line in word_list:
words = line.split(' ')
for word in words:
word_sorting.append(word)
for sorted_word in sorted(word_sorting):
if len(sorted_word) > 6:
word_amount = int(words_list.get(so... | Python | zaydzuhri_stack_edu_python |
comment !/usr/bin/env python
function r8_tiny
begin
comment *****************************************************************************80
comment R8_TINY returns the smallest positive R8.
comment Licensing:
comment This code is distributed under the GNU LGPL license.
comment Modified:
comment 04 June 2013
comment Aut... | #!/usr/bin/env python
def r8_tiny ( ):
#*****************************************************************************80
#
## R8_TINY returns the smallest positive R8.
#
# Licensing:
#
# This code is distributed under the GNU LGPL license.
#
# Modified:
#
# 04 June 2013
#
# Author:
#
# John Burkardt
#
# P... | Python | zaydzuhri_stack_edu_python |
comment !/usr/bin/python
comment encoding: utf-8
import sys
set current = string
set total = 0
for line in stdin
begin
set tuple words freq = split strip line string 2
set freq = integer freq
if words == current
begin
set total = total + freq
end
end | #!/usr/bin/python
#encoding: utf-8
import sys
current = ""
total = 0
for line in sys.stdin:
(words, freq) = line.strip().split("\t",2)
freq = int(freq)
if words == current:
total += freq | Python | zaydzuhri_stack_edu_python |
import os
import errno
import requests
set IMAGE_DIRECTORY_ROOT = string images
set SPACEX_DIRECTORY_NAME = string spacex
set HUBBLE_DIRECTORY_NAME = string hubble
function build_full_image_name img_name img_url
begin
set tuple img_url_without_extension img_extension = call splitext img_url
return string { img_name } {... | import os
import errno
import requests
IMAGE_DIRECTORY_ROOT = 'images'
SPACEX_DIRECTORY_NAME = 'spacex'
HUBBLE_DIRECTORY_NAME = 'hubble'
def build_full_image_name(img_name, img_url):
img_url_without_extension, img_extension = os.path.splitext(img_url)
return f'{img_name}{img_extension}'
def load_image_to_d... | Python | zaydzuhri_stack_edu_python |
import facebook
set token = string CAAKDZBXNh5AkBALpiQ8MYlfrgDCYn9yJWGsWgP9qhmhsCsjkJUScW87kdT5kSgJBNjCtHLzrPSoy7hOmcr5Nz5fN1VyllKwdoRUs7TmZAJ9qDD9asxscZAwnH1dn1qI9UlVRxRdbguxjLeLY929h7kwynOZAs8n7iYv0BqXZA9ZAxjxrn0UHfThDnkeXUiUwatoGSYAGzb0ZBcCJFZAG6T68
set graph = call GraphAPI token
set profile = call get_object strin... | import facebook
token = 'CAAKDZBXNh5AkBALpiQ8MYlfrgDCYn9yJWGsWgP9qhmhsCsjkJUScW87kdT5kSgJBNjCtHLzrPSoy7hOmcr5Nz5fN1VyllKwdoRUs7TmZAJ9qDD9asxscZAwnH1dn1qI9UlVRxRdbguxjLeLY929h7kwynOZAs8n7iYv0BqXZA9ZAxjxrn0UHfThDnkeXUiUwatoGSYAGzb0ZBcCJFZAG6T68'
graph = facebook.GraphAPI(token)
profile = graph.get_object("me")
friends ... | Python | zaydzuhri_stack_edu_python |
string Code for Discrete Fourier Transform using numpy functions
import cv2
import numpy as np
from matplotlib import pyplot as plt
set img = call imread string fft.jpg 0
comment Fourier Transform
set f = call fft2 img
comment Shifting the DC component from top left to center
set fshift = call fftshift f
comment Findin... | """Code for Discrete Fourier Transform using numpy functions
"""
import cv2
import numpy as np
from matplotlib import pyplot as plt
img = cv2.imread('fft.jpg',0)
#Fourier Transform
f = np.fft.fft2(img)
#Shifting the DC component from top left to center
fshift = np.fft.fftshift(f)
#Finding the Magnitude Spectrum... | Python | zaydzuhri_stack_edu_python |
string Huajie Shao@2016/7/23 Function: get assertion Id(num) and get the corresponding tweets
comment -*- coding:utf-8 -*-
import ast
import operator
comment we need to get the num ids of the assertions from the source claims
set Num_id = list
comment cluster_cred_temp.txt
set f_read_ids = open string cluster_cred_tem... | '''
Huajie Shao@2016/7/23
Function: get assertion Id(num) and get the corresponding tweets
'''
# -*- coding:utf-8 -*-
import ast
import operator
## we need to get the num ids of the assertions from the source claims
Num_id = []
f_read_ids = open("cluster_cred_temp.txt",'r') #cluster_cred_temp.txt
for lines in f_rea... | Python | zaydzuhri_stack_edu_python |
class Solution
begin
function uniquePaths self m n memo=dict
begin
comment Note the original function did not have a "memo" parameter. This was
comment added to facilitate necessary memoization in the recursion
comment If we go "out of bounds," no legal moves can be made- return 0
if m == 0 or n == 0
begin
return 0
end... | class Solution:
def uniquePaths(self, m: int, n: int, memo: dict = {}) -> int:
# Note the original function did not have a "memo" parameter. This was
# added to facilitate necessary memoization in the recursion
# If we go "out of bounds," no legal moves can be made- return 0
if m ==... | Python | zaydzuhri_stack_edu_python |
function is_even num
begin
if num % 2 == 0
begin
return true
end
else
begin
return false
end
end function
print call is_even 111
function iterate_through num
begin
for i in range 1 num
begin
if call is_even i
begin
print i string jest parzyste
end
else
begin
print i string jest nieparzyste
end
end
end function
print ca... | def is_even(num):
if num % 2 == 0:
return True
else:
return False
print(is_even(111))
def iterate_through(num):
for i in range(1, num):
if is_even(i):
print(i, 'jest parzyste')
else:
print(i, 'jest nieparzyste')
print(iterate_through(11))
| Python | zaydzuhri_stack_edu_python |
comment CTI-110
comment P3T1 - Areas of Rectangles
comment Steven Jackson
comment 6/26/18
comment Write a program that asks for the length and width of two Rectangles.
print string This program will calculate the area of two rectangles.
print string Calculate the area of the first rectangle.
comment Define the first re... | # CTI-110
# P3T1 - Areas of Rectangles
# Steven Jackson
# 6/26/18
## Write a program that asks for the length and width of two Rectangles.
print("This program will calculate the area of two rectangles.")
print("Calculate the area of the first rectangle.")
# Define the first rectangle and the second recta... | Python | zaydzuhri_stack_edu_python |
from gtts import gTTS
import os
function say_text
begin
set tts = call gTTS text=string I am responding using my voice now lang=string en
save string say.mp3
call system string start say.mp3
end function | from gtts import gTTS
import os
def say_text():
tts = gTTS(text='I am responding using my voice now', lang='en')
tts.save('say.mp3')
os.system('start say.mp3')
| Python | flytech_python_25k |
comment TODO: Check the naming convention.
function x_offset self
begin
string :return: The X offset of the data in the buffer in number of pixels from the image origin to handle areas of interest.
try
begin
if _part
begin
set value = x_offset
end
else
begin
set value = offset_x
end
end
except InvalidParameterException... | def x_offset(self): # TODO: Check the naming convention.
"""
:return: The X offset of the data in the buffer in number of pixels from the image origin to handle areas of interest.
"""
try:
if self._part:
value = self._part.x_offset
else:
... | Python | jtatman_500k |
function weight_to_plate weight
begin
comment Subtract typical bar weight
set weight = weight - 45
set plate45 = 0
set plate35 = 0
set plate25 = 0
set plate10 = 0
set plate5 = 0
set plate2_5 = 0
while weight / 2 * 45
begin
set weight = weight - 2 * 45
set plate45 = plate45 + 1
end
while weight / 2 * 35
begin
set weight... | def weight_to_plate(weight):
weight -= 45 #Subtract typical bar weight
plate45 = 0
plate35 = 0
plate25 = 0
plate10 = 0
plate5 = 0
plate2_5 = 0
while weight/(2*45):
weight -= (2*45)
plate45 += 1
while weight/(2*35):
weight -= (2*35)
plate35 += 1
... | Python | nomic_cornstack_python_v1 |
function feature_expand x degree flags=list true true true
begin
comment Adding column of ones
set tx = c_ at tuple ones length x x
for j in range 2 degree + 1
begin
set tx = c_ at tuple tx x ^ j
end
set tx = c_ at tuple tx square root absolute x
if flags at 0 == true
begin
set tx = c_ at tuple tx log absolute x
end
if... | def feature_expand(x,degree,flags=[True,True,True]):
tx = np.c_[np.ones(len(x)), x] # Adding column of ones
for j in range(2,degree+1):
tx = np.c_[tx, x**j ]
tx = np.c_[tx, np.sqrt(np.abs(x)) ]
if flags[0]==True:
tx=np.c_[tx,np.log(np.abs(x))]
if flag... | Python | nomic_cornstack_python_v1 |
class MyList
begin
function __init__ self count=0 value=0
begin
set data = list
for x in range count
begin
append data value
end
end function
function __repr__ self
begin
return string MyList( + call repr data + string )
end function
function setValueAt self index value
begin
set data at index = value
end function
fun... | class MyList:
def __init__(self,count=0,value=0):
self.data=[]
for x in range(count):
self.data.append(value)
def __repr__(self):
return "MyList("+repr(self.data)+")"
def setValueAt(self,index,value):
self.data[index]=value
def __setitem__(self, index, valu... | Python | zaydzuhri_stack_edu_python |
function register bot update user_data
begin
if first filter chatID == chat_id
begin
if first filter call and_ chatID == chat_id DOB != none
begin
set messageContent = string Already registered!
call sendMessage chat_id=chat_id text=messageContent
return END
end
set student_data = first filter chatID == chat_id
set use... | def register(bot, update, user_data):
if Chat.query.filter(Chat.chatID == update.message.chat_id).first():
if Chat.query.filter(and_(Chat.chatID == update.message.chat_id, Chat.DOB != None)).first():
messageContent = "Already registered!"
bot.sendMessage(chat_id=update.message.chat_i... | Python | nomic_cornstack_python_v1 |
function out_degree_centrality self
begin
try
begin
if not call is_directed
begin
warning string G为无向网络!
end
else
begin
info string 正在计算有向网络的出度中心性 ...
return call order_dict call out_degree_centrality G index=1
end
end
except Exception as e
begin
error format string 计算失败,原因:{0} e
end
end function | def out_degree_centrality(self):
try:
if not self.G.is_directed():
self.logger.warning('G为无向网络!')
else:
self.logger.info('正在计算有向网络的出度中心性 ...')
return self.order_dict(nx.out_degree_centrality(self.G), index=1)
except Exception as e:... | Python | nomic_cornstack_python_v1 |
function main
begin
call vip_main vav_agent version=__version__
end function | def main():
utils.vip_main(vav_agent, version=__version__) | Python | nomic_cornstack_python_v1 |
function freeze_ansible_role_requirements_file filename=string
begin
call update_ansible_role_requirements_file filename branchname=string master milestone_freeze=true
end function | def freeze_ansible_role_requirements_file(filename=""):
update_ansible_role_requirements_file(
filename, branchname="master", milestone_freeze=True
) | Python | nomic_cornstack_python_v1 |
function rewrite_calendars metro_arch gtfs_dir
begin
set calendars : Dict at tuple str List at str = dict
comment Load calendars from gtfs_dir
with open join gtfs_dir string calendar_dates.txt string r encoding=string utf-8 newline=string as f
begin
set tuple calendars local_start local_end = call read_calendars f cal... | def rewrite_calendars(metro_arch: ZipFile, gtfs_dir: str) -> Set[str]:
calendars: Dict[str, List[str]] = {}
# Load calendars from gtfs_dir
with open(join(gtfs_dir, "calendar_dates.txt"), "r", encoding="utf-8", newline="") as f:
calendars, local_start, local_end = read_calendars(f, calendars)
... | Python | nomic_cornstack_python_v1 |
function model_factory X_continuos X_categorical_selection X_categorical_audience X_categorical_browser X_categorical_city X_categorical_device y_data variables_to_be_used variant_df arviz_inference samples
begin
with model as varying_intercept_slope_noncentered
begin
comment with pm.Model(coords=coords) as varying_int... | def model_factory(X_continuos,
X_categorical_selection,
X_categorical_audience,
X_categorical_browser,
X_categorical_city,
X_categorical_device,
y_data,
variables_to_be_used,
... | Python | nomic_cornstack_python_v1 |
comment Intro to Tutorial Challenges
set a = input
set b = input
print index split input a
comment Insertions Sort-pt1
set n = integer input
set arr = list comprehension integer x for x in split input
function insertion_sort arr
begin
set e = arr at length arr - 1
set ar = arr at slice 0 : length arr - 1 :
set l = len... | #Intro to Tutorial Challenges
a = input()
b = input()
print(input().split().index(a))
#Insertions Sort-pt1
n = int(input())
arr = [int(x) for x in input().split()]
def insertion_sort(arr):
e = arr[len(arr) - 1]
ar = arr[0:len(arr) - 1]
l = len(ar)
last = l - 1
parr = []
... | Python | zaydzuhri_stack_edu_python |
function _make_qheader self job_name qout_path qerr_path
begin
string Return a string with the options that are passed to the resource manager.
comment get substitution dict for replacements into the template
set subs_dict = call get_subs_dict
comment Set job_name and the names for the stderr and stdout of the
comment ... | def _make_qheader(self, job_name, qout_path, qerr_path):
"""Return a string with the options that are passed to the resource manager."""
# get substitution dict for replacements into the template
subs_dict = self.get_subs_dict()
# Set job_name and the names for the stderr and stdout of ... | Python | jtatman_500k |
comment Essa é a implementação de um jogo de adivinhação de numeros.
import random
print string Olá, qual o seu nome?
set name = input
set numberMin = 0
set numberMax = 20
set secretNumber = random integer numberMin numberMax
print string Hm... %s, eu estou pensando em um numero entre %s e %s. % tuple name numberMin nu... | # Essa é a implementação de um jogo de adivinhação de numeros.
import random
print('Olá, qual o seu nome?')
name = input()
numberMin = 0
numberMax = 20
secretNumber = random.randint(numberMin, numberMax)
print("Hm... %s, eu estou pensando em um numero entre %s e %s." % (name, numberMin, numberMax))
# Perguntar ... | Python | zaydzuhri_stack_edu_python |
function OpenHand self value=0.0 timeout=none
begin
if simulated
begin
set robot = call GetRobot
set p = SaveParameters
with call CreateRobotStateSaver ActiveDOF ? ActiveManipulator
begin
call SetActive
call ReleaseFingers
end
if timeout
begin
call WaitForController timeout
end
return none
end
else
begin
return call Mo... | def OpenHand(self, value=0., timeout=None):
if self.simulated:
robot = self.manipulator.GetRobot()
p = openravepy.KinBody.SaveParameters
with robot.CreateRobotStateSaver(p.ActiveDOF | p.ActiveManipulator):
self.manipulator.SetActive()
robot.ta... | Python | nomic_cornstack_python_v1 |
import sys
set input = lambda -> right strip read line stdin
set tuple h w = map int split input
set a = list
for _ in range h
begin
append a list map int split input
end
set ans = list
set flag = 1
for i in range h
begin
if flag
begin
for j in range w
begin
if j == w - 1
begin
set flag = flag ? 1
if i != h - 1 and ... | import sys
input = lambda: sys.stdin.readline().rstrip()
h,w=map(int,input().split())
a=[]
for _ in range(h):
a.append(list(map(int,input().split())))
ans = []
flag = 1
for i in range(h):
if flag:
for j in range(w):
if j == w - 1:
flag ^= 1
if i != h - 1 and... | Python | zaydzuhri_stack_edu_python |
comment Отсортируйте данный массив, используя встроенную сортировку.
comment Первая строка входных данных содержит количество элементов в списке N.
comment Далее идет N целых чисел, выведите эти числа в порядке неубывания (это как по возрастанию, термин "неубывание" используется чтобы избежать неоднозначного понимания ... | # Отсортируйте данный массив, используя встроенную сортировку.
#
# Первая строка входных данных содержит количество элементов в списке N.
# Далее идет N целых чисел, выведите эти числа в порядке неубывания (это как по возрастанию, термин "неубывание" используется чтобы избежать неоднозначного понимания в случае наличия... | Python | zaydzuhri_stack_edu_python |
import unittest
from rpn import my_rpn
class Test_rpn extends TestCase
begin
function __check_rpn_result self expr expected_queue expected_result
begin
set my_rpn_obj = call my_rpn
set queue = call create_rpn expr
assert equal get queue expected_queue
assert equal call calculate_rpn queue expected_result
end function
f... | import unittest
from rpn import my_rpn
class Test_rpn(unittest.TestCase):
def __check_rpn_result(self, expr, expected_queue, expected_result):
my_rpn_obj = my_rpn()
queue = my_rpn_obj.create_rpn(expr)
self.assertEqual(queue.get(), expected_queue)
self.assertEqual(my_rpn_obj.calculat... | Python | zaydzuhri_stack_edu_python |
function __idiv__ self value
begin
return call itkMatrixF44___idiv__ self value
end function | def __idiv__(self, value: 'float const &') -> "void":
return _itkMatrixPython.itkMatrixF44___idiv__(self, value) | Python | nomic_cornstack_python_v1 |
function test_dump_group_nested_2 query_factory
begin
set query_text = string Can I get one curry sauce with my rice ball with house salad
set query = call create_query query_text
set entities = list call from_query query call Span 10 12 entity_type=string sys_number role=string quantity call from_query query call Span... | def test_dump_group_nested_2(query_factory):
query_text = "Can I get one curry sauce with my rice ball with house salad"
query = query_factory.create_query(query_text)
entities = [
QueryEntity.from_query(
query, Span(10, 12), entity_type="sys_number", role="quantity"
),
... | Python | nomic_cornstack_python_v1 |
import numpy as np
import tensorflow as tf
import matplotlib as mpl
call use string Agg
import matplotlib.pyplot as plt
from time import time
import os
from models.neuralmodels import BinarySetRegressor , ContinuousSetRegressor , ProbabilisticCSR
from plotting import plot_preds , plot_results , plot_sparse_preds , plot... | import numpy as np
import tensorflow as tf
import matplotlib as mpl
mpl.use('Agg')
import matplotlib.pyplot as plt
from time import time
import os
from models.neuralmodels import (
BinarySetRegressor, ContinuousSetRegressor, ProbabilisticCSR
)
from plotting import (
plot_preds, plot_results, plot_sparse_preds,... | Python | zaydzuhri_stack_edu_python |
comment Two strings str1 and str2 are called isomorphic if there is a one to one mapping possible for every character of str1 to every character of str2. And all occurrences of every character in ‘str1’ map to same character in ‘str2’.
comment Input: str1 = "aab", str2 = "xxy"
comment Output: True
comment 'a' is mapped... | # Two strings str1 and str2 are called isomorphic if there is a one to one mapping possible for every character of str1 to every character of str2. And all occurrences of every character in ‘str1’ map to same character in ‘str2’.
# Input: str1 = "aab", str2 = "xxy"
# Output: True
# 'a' is mapped to 'x' and 'b' is map... | Python | zaydzuhri_stack_edu_python |
function get_comment_data self comment_obj
begin
set data = none
try
begin
set data = dict string comment_id id ; string timestamp call convert_to_epoc_utc created_utc ; string score score ; string submission_id id ; string author_id id
end
except Exception as error
begin
print string Couldn't access comment data: { er... | def get_comment_data(self, comment_obj):
data = None
try:
data = {
"comment_id": comment_obj.id,
"timestamp": self.convert_to_epoc_utc(comment_obj.created_utc),
"score": comment_obj.score,
"submission_id": comment_obj.submission... | Python | nomic_cornstack_python_v1 |
comment latLong.py
comment Purpose: Convert geographic coordinate formats.
function dd2dms ddValue
begin
string Convert from decimal degrees to degrees minutes seconds.
comment Compute degrees
set posDD = absolute ddValue
set posDegs = integer posDD
set degs = posDegs
if ddValue < 0
begin
set degs = - 1 * posDegs
end
c... | # latLong.py
# Purpose: Convert geographic coordinate formats.
def dd2dms(ddValue):
'''Convert from decimal degrees to degrees minutes seconds.'''
# Compute degrees
posDD = abs(ddValue)
posDegs = int(posDD)
degs = posDegs
if ddValue < 0:
degs = -1*posDegs
# Computer minutes
re... | Python | zaydzuhri_stack_edu_python |
import time , replit
from termcolor import cprint as cp
from colorama import *
import MyGlobal.Variables as gv
import MyGlobal.Methods as gm
import dayStart as ds
function displayStats
begin
clear replit
call typePrint string Fetching stats....
sleep 1
call cp string ***STATS*** string green
print string Current Day: +... | import time, replit
from termcolor import cprint as cp
from colorama import *
import MyGlobal.Variables as gv
import MyGlobal.Methods as gm
import dayStart as ds
def displayStats():
replit.clear()
gm.typePrint("Fetching stats....")
time.sleep(1)
cp("***STATS***", "green")
print("Current Day: " + str(gv.cur... | Python | zaydzuhri_stack_edu_python |
function plant_in_service ferc1_raw_dfs ferc1_transformed_dfs
begin
set pis_df = reset index set index call pipe _clean_cols string f1_plant_in_srvce list string utility_id_ferc1 string report_year string amount_type string record_id
comment Gotta catch 'em all!
comment Convert top level of column index into a categori... | def plant_in_service(ferc1_raw_dfs, ferc1_transformed_dfs):
pis_df = (
unpack_table(
ferc1_df=ferc1_raw_dfs["plant_in_service_ferc1"],
table_name="f1_plant_in_srvce",
data_rows=slice(None), # Gotta catch 'em all!
data_cols=[
"begin_yr_bal",
... | Python | nomic_cornstack_python_v1 |
import math
from itertools import groupby
from algebras.mymath import Vector , clip , interpolation
from pygame import Rect
from GUI.camera import Camera
from GUI.pygame_wrapper import config , myroundv , Paint
from GUI.specseq import SpecSeq
class App
begin
string The class for drawing self.expansion is a dictionary w... | import math
from itertools import groupby
from algebras.mymath import Vector, clip, interpolation
from pygame import Rect
from GUI.camera import Camera
from GUI.pygame_wrapper import config, myroundv, Paint
from GUI.specseq import SpecSeq
class App:
"""The class for drawing
self.expansion is a dictionary whe... | Python | zaydzuhri_stack_edu_python |
comment Definition for singly-linked list.
class ListNode
begin
function __init__ self x
begin
set val = x
set next = none
end function
end class
class Solution
begin
function detectCycle self head
begin
comment 染色标记法
comment cur_node = head
comment while cur_node:
comment if cur_node.val != float('inf'):
comment cur_n... | # Definition for singly-linked list.
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
class Solution:
def detectCycle(self, head: ListNode) -> ListNode:
# 染色标记法
# cur_node = head
# while cur_node:
# if cur_node.val != float('inf... | Python | zaydzuhri_stack_edu_python |
function Setup
begin
set build_info = call BuildInfo
set log_file = string %s\%s % tuple call GetLogsPath BUILD_LOG_FILE
call CreateDirectories log_file
set debug_fmt = format string %(levelname).1s%(asctime)s.%(msecs)03d %(process)d {} %(filename)s:%(lineno)d] %(message)s call ImageID
set info_fmt = string %(levelname... | def Setup():
build_info = buildinfo.BuildInfo()
log_file = r'%s\%s' % (GetLogsPath(), constants.BUILD_LOG_FILE)
file_util.CreateDirectories(log_file)
debug_fmt = ('%(levelname).1s%(asctime)s.%(msecs)03d %(process)d {} '
'%(filename)s:%(lineno)d] %(message)s').format(
build_inf... | Python | nomic_cornstack_python_v1 |
function clearHistories self
begin
set argvHistory = list
set wdHistory = list
set envHistory = list
call setValue string DebugInfo/ArgumentsHistory argvHistory
call setValue string DebugInfo/WorkingDirectoryHistory wdHistory
call setValue string DebugInfo/EnvironmentHistory envHistory
end function | def clearHistories(self):
self.argvHistory = []
self.wdHistory = []
self.envHistory = []
Preferences.Prefs.settings.setValue(
'DebugInfo/ArgumentsHistory', self.argvHistory)
Preferences.Prefs.settings.setValue(
'DebugInfo/WorkingDirectoryHistory',... | Python | nomic_cornstack_python_v1 |
import soundfile as sf
comment Reading from a WAV file
set tuple data samplerate = read sf string myfile.wav
comment Let me examine if the code works
comment 1. Imported required modules
comment 2. Read data and samplerate from a WAV file and stored in variables
comment Executing code...
comment Code has been fixed! | import soundfile as sf
# Reading from a WAV file
data, samplerate = sf.read('myfile.wav')
# Let me examine if the code works
# 1. Imported required modules
# 2. Read data and samplerate from a WAV file and stored in variables
# Executing code...
# Code has been fixed!
| Python | flytech_python_25k |
function get_cluster_stats self
begin
call _check_connection_type string get_cluster_stats string Cluster
set params = dict
comment There is no adaptor.
return call send_request string GetClusterStats GetClusterStatsResult params since=1
end function | def get_cluster_stats(
self,):
self._check_connection_type("get_cluster_stats", "Cluster")
params = {
}
# There is no adaptor.
return self.send_request(
'GetClusterStats',
GetClusterStatsResult,
params,
since... | Python | nomic_cornstack_python_v1 |
function getType self
begin
return ELEMENT_TYPE_SECTION
end function | def getType(self):
return ORGElement.ELEMENT_TYPE_SECTION | Python | nomic_cornstack_python_v1 |
for i in call swapcase
begin
print i end=string
end | for i in x.swapcase():
print(i,end="")
| Python | zaydzuhri_stack_edu_python |
comment converts message to morse code
function translate_message
begin
for x in message
begin
print morse_code at x
end
end function
comment converts morse code to message
function translate_morse
begin
set arr = split message string
for x in arr
begin
print list keys morse_code at index list values morse_code x
end
e... | # converts message to morse code
def translate_message():
for x in message:
print(morse_code[x])
# converts morse code to message
def translate_morse():
arr = message.split(" ")
for x in arr:
print(list(morse_code.keys())[list(morse_code.values()).index(x)])
message = input(... | Python | zaydzuhri_stack_edu_python |
comment Le funzioni in Python sono degli oggetti! Tutto è un oggetto in Python!
function primaFunzione
begin
print string Ciao, prima funzione!
end function
comment None se funzione vuota! (like void in java)
print type call primaFunzione
comment Presta attenzione a func()
print type primaFunzione | def primaFunzione(): # Le funzioni in Python sono degli oggetti! Tutto è un oggetto in Python!
print("Ciao, prima funzione!")
print(type(primaFunzione())) # None se funzione vuota! (like void in java)
print(type(primaFunzione)) # Presta attenzione a func()
| Python | zaydzuhri_stack_edu_python |
set timeline = dict string Job A dict string start call datetime 2020 1 15 ; string end call datetime 2020 2 1 ; string Job B dict string start call datetime 2020 5 4 ; string end call datetime 2020 6 30 ; string Job C dict string start call datetime 2020 7 9 ; string end call datetime 2020 8 4 | timeline = {
"Job A": {"start": datetime.datetime(2020,1,15),
"end": datetime.datetime(2020,2,1)
},
"Job B": {"start": datetime.datetime(2020,5,4),
"end": datetime.datetime(2020,6,30)
},
"Job C": {"start": datetime.datetime(2020,7,9),
... | Python | flytech_python_25k |
from typing import *
class Solution
begin
function maximumGap self nums
begin
if length nums < 2
begin
return 0
end
sort nums
set max_val = nums at 1 - nums at 0
for i in range 2 length nums
begin
set max_val = max max_val nums at i - nums at i - 1
end
return max_val
end function
end class
if __name__ == string __main_... | from typing import *
class Solution:
def maximumGap(self, nums: List[int]) -> int:
if len(nums)<2:
return 0
nums.sort()
max_val=nums[1]-nums[0]
for i in range(2,len(nums)):
max_val=max(max_val,nums[i]-nums[i-1])
return max_val
if __name__ == '__main__... | 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.