code
stringlengths
10
2.58M
original_code
stringlengths
3
3.18M
original_language
stringclasses
1 value
source
stringclasses
7 values
comment !/usr/bin/python import RPi.GPIO as GPIO import time import requests import random call setmode BOARD set tremor = 7 comment led = 13; setup GPIO tremor IN comment GPIO.setup(led, GPIO.OUT) set url = string http://192.168.0.2:8000/readings/ set headers = dict string content-type string application/json while tr...
#!/usr/bin/python import RPi.GPIO as GPIO import time import requests import random GPIO.setmode(GPIO.BOARD) tremor = 7; #led = 13; GPIO.setup(tremor, GPIO.IN) #GPIO.setup(led, GPIO.OUT) url = 'http://192.168.0.2:8000/readings/' headers = {'content-type': 'application/json'} while True: tremor = GPIO.wait_for_ed...
Python
zaydzuhri_stack_edu_python
import numpy as np import matplotlib.pyplot as plt set R = 8.3145 set t_values = list set E_values = list for t in range 12 200 begin set diff_temp = 1 / t + 10 - 1 / t set E_a = - R * log 2 / diff_temp append t_values t append E_values E_a end comment Graphing data x label string temperature(K) y label string energy...
import numpy as np import matplotlib.pyplot as plt R = 8.3145 t_values = [] E_values = [] for t in range(12, 200): diff_temp = (1/(t + 10)) - (1/t) E_a = -R*np.log(2)/diff_temp t_values.append(t) E_values.append(E_a) # Graphing data plt.xlabel('temperature(K)') plt.ylabel('energy barrier (J)') plt.title('const...
Python
zaydzuhri_stack_edu_python
function posicioAlParking matricula begin if call _formatMatriculaValid matricula begin set con = call connect string parking.db set cur = call cursor end end function
def posicioAlParking(matricula): if(_formatMatriculaValid(matricula)): con = lite.connect('parking.db') cur = con.cursor()
Python
nomic_cornstack_python_v1
function multiply_matrices A B begin string Multiplies two matrices using a recursive function. Arguments: A -- first matrix B -- second matrix Returns: result -- multiplied matrix set n = length A comment Base case if n == 1 begin return list list A at 0 at 0 * B at 0 at 0 end comment Split matrices into quarters set ...
def multiply_matrices(A, B): """ Multiplies two matrices using a recursive function. Arguments: A -- first matrix B -- second matrix Returns: result -- multiplied matrix """ n = len(A) # Base case if n == 1: return [[A[0][0] * B[0][0]]] # Split matrice...
Python
jtatman_500k
function _get_resized_embeddings self old_embeddings new_num_tokens=none begin if new_num_tokens is none begin return old_embeddings end set tuple old_num_tokens old_embedding_dim = size weight if old_num_tokens == new_num_tokens begin return old_embeddings end comment Build new embeddings set new_embeddings = embeddin...
def _get_resized_embeddings(self, old_embeddings, new_num_tokens=None): if new_num_tokens is None: return old_embeddings old_num_tokens, old_embedding_dim = old_embeddings.weight.size() if old_num_tokens == new_num_tokens: return old_embeddings # Build new embed...
Python
nomic_cornstack_python_v1
function __del__ self begin dump end function
def __del__(self): self.account.dump()
Python
nomic_cornstack_python_v1
string Shared code for both decoding sensor data and responses function decode filename message_type begin string Decode protobuf messages from file set messages = list with open filename string rb as f begin while true begin comment Get size of message, then read that many bytes set size = read f 2 comment eof if siz...
""" Shared code for both decoding sensor data and responses """ def decode(filename, message_type): """ Decode protobuf messages from file """ messages = [] with open(filename, "rb") as f: while True: # Get size of message, then read that many bytes size = f.read(2) ...
Python
zaydzuhri_stack_edu_python
import base64 , hashlib import time comment 生成签名 comment 签名规则如下: str = 请求参数进行顺序排列再进行拼接 comment sign = md5(base64(timestamp) + token + 私密 + str) comment @ param comment request comment HTTP请求 comment @ return 签名 class signature begin function __init__ self begin set timestamp = string integer time set time = base64 enco...
import base64,hashlib import time # 生成签名 # 签名规则如下: str = 请求参数进行顺序排列再进行拼接 # sign = md5(base64(timestamp) + token + 私密 + str) # # @ param # request # HTTP请求 # @ return 签名 class signature: def __init__(self): self.timestamp = str(int(time.time())) self.time = base64.b64encode(bytes(self.timestamp.enco...
Python
zaydzuhri_stack_edu_python
function solve x begin set x = string x if length x != N begin return false end for tuple s c in P begin if x at s - 1 != string c begin return false end end return true end function if __name__ == string __main__ begin set tuple N M = map int split input set P = list comprehension list map int split input for i in ran...
def solve(x): x = str(x) if len(x) != N: return False for s, c in P: if x[s - 1] != str(c): return False return True if __name__ == "__main__": N, M = map(int, input().split()) P = [list(map(int, input().split())) for i in range(M)] ans = 10**N for i in range...
Python
zaydzuhri_stack_edu_python
function tests_by_type results_dir begin set tests = dict for filename in list directory results_dir begin set path = join path results_dir filename set name = call test_name path if name is not none begin set kind = call test_type path if kind not in tests begin set tests at kind = set end add tests at kind join path...
def tests_by_type(results_dir): tests = {} for filename in os.listdir(results_dir): path = os.path.join(results_dir, filename) name = test_name(path) if name is not None: kind = test_type(path) if kind not in tests: tests[kind] = set() ...
Python
nomic_cornstack_python_v1
comment coding: utf-8 comment In[1]: import tensorflow as tf import numpy as np from tensorflow.examples.tutorials.mnist import input_data print string ***MY ENVIRONMENT*** python 2.7.13 tensorflow 1.2.1 comment In[2]: set mnist = call read_data_sets string ./MNIST_data one_hot=false set sess = call InteractiveSession ...
# coding: utf-8 # In[1]: import tensorflow as tf import numpy as np from tensorflow.examples.tutorials.mnist import input_data print("\n \n \n \n ***MY ENVIRONMENT*** python 2.7.13 tensorflow 1.2.1 \n \n \n \n") # In[2]: mnist = input_data.read_data_sets('./MNIST_data', one_hot=False) sess = tf.InteractiveSessi...
Python
zaydzuhri_stack_edu_python
function choose_difficulty begin set valid_difficulty = false while not valid_difficulty begin set difficulty = lower input string Please choose a difficulty. Type 'easy' or 'hard': if difficulty == string easy or difficulty == string hard begin set valid_difficulty = true end else begin print string Invalid Response. ...
def choose_difficulty(): valid_difficulty = False while not valid_difficulty: difficulty = input("Please choose a difficulty. Type 'easy' or 'hard': ").lower() if difficulty == "easy" or difficulty == "hard": valid_difficulty = True else: print("Invalid Response.") return difficulty
Python
nomic_cornstack_python_v1
function readLines begin with open string text/urls.txt string r as f begin set urls = read lines f end comment cleans up the strings set urls = list comprehension replace url string string for url in urls set urls = list comprehension replace url string string for url in urls write lines urls end function
def readLines(): with open("text/urls.txt", "r") as f: urls = f.readlines() # cleans up the strings urls = [url.replace("\n", "") for url in urls] urls = [url.replace(" ", "") for url in urls] writeLines(urls)
Python
nomic_cornstack_python_v1
string Написать калькулятор. Программа должна содержать 4 функции принимающие два аргумента и возвращающие результаты сложения, вычитания, умножения и деления. Реализовать пользовательский интерфейс с бесконечным циклом. Добавить валидацию входных данных. Программа должна состоять из четырех файлов(main.py, func.py, ui...
"""Написать калькулятор. Программа должна содержать 4 функции принимающие два аргумента и возвращающие результаты сложения, вычитания, умножения и деления. Реализовать пользовательский интерфейс с бесконечным циклом. Добавить валидацию входных данных. Программа должна состоять из четырех файлов(main.py, func.py, ui_fun...
Python
zaydzuhri_stack_edu_python
function setUp self begin setup call super set username = string testuser set password = string FatChance! set user1 = call create_user username=username password=password email=string testuser@nowhere.com set first_name = string Tester save comment need a poll question to test voting set q = call create string First P...
def setUp(self): super().setUp() self.username = "testuser" self.password = "FatChance!" self.user1 = User.objects.create_user( username=self.username, password=self.password, email="testuser@nowhere.com") self.user1.first_name = "Tester" ...
Python
nomic_cornstack_python_v1
for x in range integer input begin set s = list input set n = length s if n == 1 begin set result = s at 0 end else begin for i in range n - 1 0 - 1 begin try begin if s at i < s at i - 1 begin set s at i - 1 = d at s at i - 1 set s at slice i : n : = list string 9 * n - i end end except any begin continue end end set...
for x in range(int(input())): s = list(input()) n = len(s) if n == 1: result = s[0] else: for i in range(n - 1, 0, -1): try: if s[i] < s[i - 1]: s[i - 1] = d[s[i - 1]] s[i:n] = ['9'] * (n - i) except: ...
Python
zaydzuhri_stack_edu_python
function nitems_read self *args **kwargs begin return call atsc_depad_sptr_nitems_read self *args keyword kwargs end function
def nitems_read(self, *args, **kwargs): return _atsc_swig.atsc_depad_sptr_nitems_read(self, *args, **kwargs)
Python
nomic_cornstack_python_v1
set income = decimal input string Enter your monthly income: set expenses = decimal input string Enter your total monthly expenses: set net_income = income - expenses print string Your net income for the month is { net_income }
income = float(input('Enter your monthly income: ')) expenses = float(input('Enter your total monthly expenses: ')) net_income = income - expenses print(f'Your net income for the month is {net_income}')
Python
flytech_python_25k
while T > 0 begin set N = integer input set ing = list set Hash = dict for i in range N begin append ing input end end
while T > 0 : N=int(input()) ing=list() Hash={} for i in range(N): ing.append(input())
Python
zaydzuhri_stack_edu_python
import argparse from pathlib import Path from typing import Iterable from heapq import merge from solution import Dataset , get_parser , ParseError function main data_folder_path result_file_name begin print string Perform basic task on files from « { data_folder_path } » directory: for data_file in call iterdir begin ...
import argparse from pathlib import Path from typing import Iterable from heapq import merge from solution import Dataset, get_parser, ParseError def main(data_folder_path: Path, result_file_name: str): print(f'Perform basic task on files from «{data_folder_path}» directory:') for data_file in data_folder_pa...
Python
zaydzuhri_stack_edu_python
comment Creating a binary tree set root = call Node 4 set left = call Node 2 set right = call Node 6 set left = call Node 1 set right = call Node 3 set left = call Node 5 set right = call Node 7 comment Checking if the binary tree is a valid binary search tree set tuple valid leaf_count = call is_valid_bst root print s...
# Creating a binary tree root = Node(4) root.left = Node(2) root.right = Node(6) root.left.left = Node(1) root.left.right = Node(3) root.right.left = Node(5) root.right.right = Node(7) # Checking if the binary tree is a valid binary search tree valid, leaf_count = is_valid_bst(root) print("Is valid binary search tree...
Python
jtatman_500k
function make_consensus ref_file reads_file iteration sampled_reads=10000 mapper=string bwa cons_caller=string own begin import glob set out_file = string cns_%d.fasta % iteration set ranseed = 313 + iteration comment sample reads set cml = split shlex string seqtk sample -s %d %s %d % tuple ranseed reads_file sampled_...
def make_consensus(ref_file, reads_file, iteration, sampled_reads=10000, mapper='bwa', cons_caller='own'): import glob out_file = 'cns_%d.fasta' % iteration ranseed = 313 + iteration # sample reads cml = shlex.split('seqtk sample -s %d %s %d' % (ranseed, reads_file, sampled_r...
Python
nomic_cornstack_python_v1
import gym import dill function main begin set env = call make string FrozenLake-v0 with open string FrozenLake_QLearning10000.pickle string rb as f begin set agent = load dill f end set episodes = 10000 set total_reward = 0 for episode in range episodes begin set curr_state = call reset set episode_reward = 0 set done...
import gym import dill def main(): env = gym.make('FrozenLake-v0') with open("FrozenLake_QLearning10000.pickle", 'rb') as f: agent = dill.load(f) episodes = 10000 total_reward = 0 for episode in range(episodes): curr_state = env.reset() episode_reward = 0 done = ...
Python
zaydzuhri_stack_edu_python
function title self begin comment split CamelCase to Camel Case set title = call _split_camel_case name if not ends with title string s begin set title = title + string s end return title end function
def title(self): # split CamelCase to Camel Case title = self._split_camel_case(self.name) if not title.endswith('s'): title += 's' return title
Python
nomic_cornstack_python_v1
function list_to_str input_str begin return join string list comprehension string val for val in input_str end function
def list_to_str(input_str): return " ".join([str(val) for val in input_str])
Python
nomic_cornstack_python_v1
function from_tiktok self begin set reason = string [!] TikTok timestamps are 19 digits long set ts_type = ts_types at string tiktok try begin if length string tiktok < 19 or not is digit tiktok begin set in_tiktok = false set indiv_output = false set combined_output = false pass end else begin set unix_ts = integer ti...
def from_tiktok(self): reason = "[!] TikTok timestamps are 19 digits long" ts_type = self.ts_types['tiktok'] try: if len(str(self.tiktok)) < 19 or not self.tiktok.isdigit(): self.in_tiktok = indiv_output = combined_output = False pass else:...
Python
nomic_cornstack_python_v1
function _jordan_wigner_mode n begin string Jordan_Wigner mode. Args: n (int): number of modes set a = list for i in range n begin set xv = call asarray list 1 * i + list 0 + list 0 * n - i - 1 set xw = call asarray list 0 * i + list 1 + list 0 * n - i - 1 set yv = call asarray list 1 * i + list 1 + list 0 * n - i - 1...
def _jordan_wigner_mode(n): """ Jordan_Wigner mode. Args: n (int): number of modes """ a = [] for i in range(n): xv = np.asarray([1] * i + [0] + [0] * (n - i - 1)) xw = np.asarray([0] * i + [1] + [0] * (n - i - 1)) yv = np.a...
Python
jtatman_500k
from constants import Orientation from image import Image class Slide begin function __init__ self image1 image2=none begin assert image1 != none set image1 = image1 set image2 = image2 if image2 != none begin if image1 == image2 begin raise call AttributeError string Invalid slide configuration end if orientation == v...
from constants import Orientation from image import Image class Slide(): def __init__(self, image1, image2=None): assert (image1 != None) self.image1 = image1 self.image2 = image2 if (self.image2 != None): if (self.image1 == self.image2): raise Attribute...
Python
zaydzuhri_stack_edu_python
function delete_point_by_coordinates self easting northing altitude=0 begin try begin set easting = decimal easting set northing = decimal northing set altitude = decimal altitude end except ValueError begin raise call ValueError string On of the input coordinates is not of type float! end comment iterate over a copy o...
def delete_point_by_coordinates(self, easting: float, northing: float, altitude: float = 0) -> None: try: easting = float(easting) northing = float(northing) altitude = float(altitude) except ValueError: raise ValueError("On of the input coordinates is not...
Python
nomic_cornstack_python_v1
function __modified self begin call __report_data call __validate call emit call SIGNAL string modified end function
def __modified(self): self.__report_data() self.__validate() self.emit(SIGNAL("modified"))
Python
nomic_cornstack_python_v1
import logging import numpy as np from coders.source.source_coder import SourceCoder from coders.utils import gray_code , int_to_bit_str set logger = call getLogger __name__ class GrayCoder extends SourceCoder begin string Outputs an encoding for each symbol that is equal to its index's gray binary code, padded to equa...
import logging import numpy as np from coders.source.source_coder import SourceCoder from coders.utils import gray_code, int_to_bit_str logger = logging.getLogger(__name__) class GrayCoder(SourceCoder): """ Outputs an encoding for each symbol that is equal to its index's gray binary code, padded to equal l...
Python
zaydzuhri_stack_edu_python
comment 2. Реализовать проект расчета суммарного расхода ткани на производство одежды. Основная сущность (класс) этого проекта — одежда, которая может иметь определенное название. К типам одежды в этом проекте относятся пальто и костюм. У этих типов одежды существуют параметры: размер (для пальто) и рост (для костюма)....
# 2. Реализовать проект расчета суммарного расхода ткани на производство одежды. Основная сущность (класс) этого проекта — одежда, которая может иметь определенное название. К типам одежды в этом проекте относятся пальто и костюм. У этих типов одежды существуют параметры: размер (для пальто) и рост (для костюма). Это м...
Python
zaydzuhri_stack_edu_python
import requests from bs4 import BeautifulSoup as bs import csv set search = input string Что ищем на авито? set search = join string + split search set URL = string https://www.avito.ru/moskva set FILE = string finish_parse.csv set HEADERS = dict string user-agent string Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleW...
import requests from bs4 import BeautifulSoup as bs import csv search = input("Что ищем на авито?\n") search = "+". join(search.split()) URL = "https://www.avito.ru/moskva" FILE = "finish_parse.csv" HEADERS = {"user-agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) " ...
Python
zaydzuhri_stack_edu_python
import numpy as np from functools import reduce function convert_to_int char begin if char == string . begin return 0 end return 1 end function function parse_data filename begin set vect_convert = call vectorize convert_to_int set python_array = list with open filename string r as f begin for line in f begin append p...
import numpy as np from functools import reduce def convert_to_int(char: str) -> int: if char == ".": return 0 return 1 def parse_data(filename: str) -> np.array: vect_convert = np.vectorize(convert_to_int) python_array = [] with open(filename, "r") as f: for line in f: ...
Python
zaydzuhri_stack_edu_python
comment pip install forex-python ! from forex_python.converter import CurrencyRates print string ..Currency Converter From Forex.. set cash = call CurrencyRates set case = call convert string USD string INR 1 print string Convert USD to INR =======> case
# pip install forex-python ! from forex_python.converter import CurrencyRates print("..Currency Converter From Forex..") cash = CurrencyRates() case = cash.convert( "USD" , "INR" , 1 ) print("Convert USD to INR =======> ",case)
Python
zaydzuhri_stack_edu_python
function calculate appliances timeslots begin print string Creating matrixes and constraints comment Helping variables set aux = list set apps = list comment Create coefficients for objective function using the price array for i in range length appliances begin set aux = aux + timeslots end comment Objective function...
def calculate(appliances, timeslots): print("Creating matrixes and constraints") aux =[] # Helping variables apps=[] for i in range(len(appliances)): # Create coefficients for objective function using the price array aux = aux + timeslots c = aux # Objective function coefficients A_eq = [[0...
Python
nomic_cornstack_python_v1
import compression import numpy as np from numba import jit decorator call jit nopython=true function deshuffle pixels pixels_per_compression=16 begin return shuffle compression pixels bits_per_pixel=pixels_per_compression end function decorator call jit nopython=true function decompress pixels bits_per_pixel=10 begin ...
import compression import numpy as np from numba import jit @jit(nopython=True) def deshuffle(pixels: "np.ndarray[int]", pixels_per_compression: int = 16) -> "np.ndarray[int]": return compression.shuffle(pixels, bits_per_pixel=pixels_per_compression) @jit(nopython=True) def decompress(pixels: "np.ndarray[int]", b...
Python
zaydzuhri_stack_edu_python
function gaussian2kp heatmap kp_variance=string matrix clip_variance=none begin set shape = shape comment adding small eps to avoid 'nan' in variance set heatmap = unsqueeze heatmap - 1 + 1e-07 set grid = call unsqueeze_ 0 comment print(grid.shape) comment sys.exit() set mean = sum dim=tuple 3 4 set kp = dict string me...
def gaussian2kp(heatmap, kp_variance='matrix', clip_variance=None): shape = heatmap.shape # adding small eps to avoid 'nan' in variance heatmap = heatmap.unsqueeze(-1) + 1e-7 grid = make_coordinate_grid(shape[3:], heatmap.type()).unsqueeze_(0).unsqueeze_(0).unsqueeze_(0) # print(grid.shape) # s...
Python
nomic_cornstack_python_v1
function reclassify_raster in_tif mask_tif out_tif reclass_df reclass_col ndv begin string Reclassify categorical values in a raster using a mapping in a dataframe. The dataframe index must contain the classes in in_tif and the 'reclass_col' must specify the new classes. Only cells with value=1 in mask_tif are written ...
def reclassify_raster(in_tif, mask_tif, out_tif, reclass_df, reclass_col, ndv): """ Reclassify categorical values in a raster using a mapping in a dataframe. The dataframe index must contain the classes in in_tif and the 'reclass_col' must specify the new classes. Only cells with va...
Python
zaydzuhri_stack_edu_python
import math function calculate_fuel mass begin return floor mass / 3 - 2 end function function part_one masses begin set fuels = list for mass in masses begin set fuel = call calculate_fuel mass append fuels fuel end set total_fuel_req = sum fuels return total_fuel_req end function function total_fuel mass begin if ca...
import math def calculate_fuel(mass): return math.floor(mass / 3) - 2 def part_one(masses): fuels = [] for mass in masses: fuel = calculate_fuel(mass) fuels.append(fuel) total_fuel_req = sum(fuels) return total_fuel_req def total_fuel(mass): if calculate_fuel(mass) <= 0: ...
Python
zaydzuhri_stack_edu_python
function create_plot self parameters data file_path begin set tuple time signal = tuple call tolist call tolist set tuple fig ax1 = call subplots figsize=tuple 9 3 set xlabel=string Time: (UTC) ylabel=string Signal Strength (dB) title=string SuperSID ( + parameters at string Site + string , + parameters at string Count...
def create_plot(self, parameters, data, file_path): time, signal = data.datetime.tolist(), data.signal_strength.tolist() fig, ax1 = plt.subplots(figsize=(9, 3)) ax1.set(xlabel='Time: (UTC)', ylabel='Signal Strength (dB)', title='SuperSID (' + parameters['Site'] +...
Python
nomic_cornstack_python_v1
string **Test Image Segmentation** Reads parking lot space coordinates from a csv file, and stores them in variables in order to generate patches in the image for cropping. The cropped images correspond to the segmentation class ParkingLotSegmentation begin function crop_image img x1 y1 x2 y2 x3 y3 x4 y4 begin set top_...
''' **Test Image Segmentation** Reads parking lot space coordinates from a csv file, and stores them in variables in order to generate patches in the image for cropping. The cropped images correspond to the segmentation ''' class ParkingLotSegmentation(): def crop_image(img, x1, y1, x2, y2, x3, y3, x4, y4): ...
Python
zaydzuhri_stack_edu_python
comment Individual Assignment 3 - SNA Enron comment Predict 452 Winter 2017 comment By: Kevin Wong comment prepare for Python version 3x features and functions from __future__ import division , print_function comment load package into the namespace for this program comment work with MongoDB from pymongo import MongoCli...
# Individual Assignment 3 - SNA Enron # Predict 452 Winter 2017 # By: Kevin Wong # prepare for Python version 3x features and functions from __future__ import division, print_function # load package into the namespace for this program from pymongo import MongoClient # work with MongoDB import pandas as pd ...
Python
zaydzuhri_stack_edu_python
function async_login self begin string Login to Alarm.com. debug string Attempting to log into Alarm.com... comment Get the session key for future logins. set response = none try begin with call timeout 10 loop=_loop begin set response = yield from get _websession ALARMDOTCOM_URL + string /default.aspx headers=dict str...
def async_login(self): """Login to Alarm.com.""" _LOGGER.debug('Attempting to log into Alarm.com...') # Get the session key for future logins. response = None try: with async_timeout.timeout(10, loop=self._loop): response = yield from self._websession.get( ...
Python
jtatman_500k
class Node begin function __init__ self currentVal=none cNodeNext=none begin set currentVal = currentVal set cNodeNext = cNodeNext end function end class set head = call Node listA at 0 comment 1->None for value in listA at slice 1 : : begin set newNode = call Node value set currentNode = head while cNodeNext != none...
class Node: def __init__(self, currentVal = None , cNodeNext = None): self.currentVal = currentVal self.cNodeNext = cNodeNext head = Node(listA[0]) #1->None for value in listA[1:]: newNode = Node(value) currentNode = head while currentNode.cNodeNext!=None: currentNode= currentNo...
Python
zaydzuhri_stack_edu_python
function match self state_data1 state_data2 begin debug format string Running a {} with: state_data1 = [ {} ] state_data2 = [ {} ] __name__ string state_data1 string state_data2 return false end function
def match(self, state_data1, state_data2): logger.debug("Running a {} with:\nstate_data1 = [\n\t{}\n\t ]\nstate_data2 = [\n\t{}\n\t ]\n".format(\ self.__class__.__name__, str(state_data1), str(state_data2))) return False
Python
nomic_cornstack_python_v1
comment !/usr/bin/env python3 import numpy as np import scipy.stats as stats import math function removeNoneEntries data begin return list comprehension a for a in data if a is not none end function function calcCDF sampleData begin set numberOfBins = length sampleData set rangeStart = decimal min sampleData set rangeS...
#!/usr/bin/env python3 import numpy as np import scipy.stats as stats import math def removeNoneEntries(data): return [a for a in data if a is not None] def calcCDF(sampleData): numberOfBins = len(sampleData) rangeStart = float(min(sampleData)) rangeStop = float(max(sampleData)) counts, bin_e...
Python
zaydzuhri_stack_edu_python
comment Name: LeptonPair.py comment CMS Open Data comment Description: sums pairs of leptons and gets their mass, energy, momentum and transverse momentum comment Returns: set __author__ = string Palmerina Gonzalez Izquierdo set __copyright__ = string Copyright (C) 2015 Palmerina G. I. set __license__ = string Public D...
# Name: LeptonPair.py # # CMS Open Data # # Description: sums pairs of leptons and gets their mass, energy, momentum and transverse momentum # # Returns: __author__ = "Palmerina Gonzalez Izquierdo" __copyright__ = "Copyright (C) 2015 Palmerina G. I." __license__ = "Public Domain" __version__ = "1.0" __maintainer__ =...
Python
zaydzuhri_stack_edu_python
comment -*- coding: utf-8 -*- import pandas as pd import os , sys import numpy as np from matplotlib import pyplot as plt class kNN extends object begin function normal_data self file_name begin set ds_path = join path directory name path directory name path __file__ string data set file_dir = join path ds_path file_na...
# -*- coding: utf-8 -*- import pandas as pd import os, sys import numpy as np from matplotlib import pyplot as plt class kNN(object): def normal_data(self, file_name): ds_path = os.path.join(os.path.dirname(os.path.dirname(__file__)), 'data') file_dir = os.path.join(ds_path, file_name) ...
Python
zaydzuhri_stack_edu_python
function untrack begin set contents = call read_file if contents is not none begin set tuple start label = contents set end = now set event = call make_event start end label call send event end call erase_file end function
def untrack(): contents = read_file() if contents is not None: (start, label) = contents end = now() event = make_event (start, end, label) send(event) erase_file()
Python
nomic_cornstack_python_v1
import statistics set example_list = list 4 6 2 6 7 8 2 5 6 8 4 6 7 2 2 set x = mean statistics example_list print x set y = median example_list print y set z = call stdev example_list print z set p = call variance example_list print p
import statistics example_list = [4,6,2,6,7,8,2,5,6,8,4,6,7,2,2] x=statistics.mean(example_list) print(x) y=statistics.median(example_list) print(y) z=statistics.stdev(example_list) print(z) p=statistics.variance(example_list) print(p)
Python
zaydzuhri_stack_edu_python
function findingComputersNames begin for i in commute_list begin set x = call open_file i ComputerNames set y = x end clear ComputerNames for i in y begin set x = call Data_cleansing i append ComputerNames call x i end return ComputerNames end function
def findingComputersNames(): for i in commute_list: x = open_file(i,ComputerNames) y = x ComputerNames.clear() for i in y: x = Data_cleansing(i) ComputerNames.append(x(i)) return ComputerNames
Python
nomic_cornstack_python_v1
function profile_expression expression N=1 gui=string snakeviz begin comment lazy import import cProfile import subprocess set tmpdir = make dir temp set statsfile = join path tmpdir string profile_expression_stats assert is instance expression str msg string expression should be a string if N is none begin set t0 = pe...
def profile_expression(expression: str, N: Optional[int] = 1, gui: str = "snakeviz"): import cProfile # lazy import import subprocess tmpdir = tempfile.mkdtemp() statsfile = os.path.join(tmpdir, "profile_expression_stats") assert isinstance(expression, str), "expression should be a string" i...
Python
nomic_cornstack_python_v1
function splitext self the_path begin set tuple base ext = call splitext the_path if ends with lower base string .tar begin set ext = base at slice - 4 : : + ext set base = base at slice : - 4 : end return tuple base ext end function
def splitext(self, the_path): base, ext = posixpath.splitext(the_path) if base.lower().endswith(".tar"): ext = base[-4:] + ext base = base[:-4] return base, ext
Python
nomic_cornstack_python_v1
from pandas import read_csv from numpy import set_printoptions from sklearn.feature_selection import SelectKBest , chi2 , RFE from sklearn.linear_model import LogisticRegression from sklearn.decomposition import PCA from sklearn.ensemble import ExtraTreesClassifier comment Feature Extraction with Univariate Statistical...
from pandas import read_csv from numpy import set_printoptions from sklearn.feature_selection import SelectKBest, chi2, RFE from sklearn.linear_model import LogisticRegression from sklearn.decomposition import PCA from sklearn.ensemble import ExtraTreesClassifier # Feature Extraction with Univariate Statistical Tests ...
Python
zaydzuhri_stack_edu_python
comment -*- coding: utf-8 -*- string Created on Thu Jan 17 16:21:50 2019 @author: Raghav import numpy as np import cv2 set DIRECTORY = string ./Dataset/ for fname in range 27 63 begin set currentDirectory = DIRECTORY + string fname + string / for cfile in range 1 31 begin set currentFile = currentDirectory + string cfi...
# -*- coding: utf-8 -*- """ Created on Thu Jan 17 16:21:50 2019 @author: Raghav """ import numpy as np import cv2 DIRECTORY = './Dataset/' for fname in range(27,63): currentDirectory = DIRECTORY + str(fname) + '/' for cfile in range(1,31): currentFile = currentDirectory + str(cfile) + '.png' ...
Python
zaydzuhri_stack_edu_python
function loadBeammapFile self beammapFileName begin raise NotImplementedError end function
def loadBeammapFile(self,beammapFileName): raise NotImplementedError
Python
nomic_cornstack_python_v1
function upload_copy aws_access_key_id aws_secret_access_key bucket_name verbose remote_filename mimetype prefix localfile begin global rural_session comment Setup loggers call initialize_loggers verbose comment Output given configuration to debug debug format string AWS Access Key ID: {} aws_access_key_id debug format...
def upload_copy(aws_access_key_id, aws_secret_access_key, bucket_name, verbose, remote_filename, mimetype, prefix, localfile): global rural_session # Setup loggers initialize_loggers(verbose) # Output given configuration to debug log.debug("AWS Access Key ID:\t{}".format(aws_access...
Python
nomic_cornstack_python_v1
import string function string_to_list str begin string Convert string to list :param str: string :return: list set li = list set li at slice : 0 : = str print li return li end function function to_ascii li_str begin string Convert each element of list to ASCII :param li_str: list of string :return: list of ASCII set...
import string def string_to_list(str): ''' Convert string to list :param str: string :return: list ''' li = [] li[:0] = str print(li) return li def to_ascii(li_str): ''' Convert each element of list to ASCII :param li_str: list of string :return: list of ASCII ...
Python
zaydzuhri_stack_edu_python
import time import page from base.base import Base import faker set f = call Faker class PageTransfer extends Base begin comment 点击跨境汇款 function page_click_money_transfer self begin call base_click shop_money_transfer end function comment 收款人 function page_receive self name lastname account amount number begin comment ...
import time import page from base.base import Base import faker f = faker.Faker() class PageTransfer(Base): # 点击跨境汇款 def page_click_money_transfer(self): self.base_click(page.shop_money_transfer) #收款人 def page_receive(self,name,lastname,account,amount,number): # 输入收款人姓名 self....
Python
zaydzuhri_stack_edu_python
comment Problem 1827. Minimum Operations to Make the Array Increasing string You are given an integer array nums (0-indexed). In one operation, you can choose an element of the array and increment it by 1. For example, if nums = [1,2,3], you can choose to increment nums[1] to make nums = [1,3,3]. Return the minimum num...
#Problem 1827. Minimum Operations to Make the Array Increasing ''' You are given an integer array nums (0-indexed). In one operation, you can choose an element of the array and increment it by 1. For example, if nums = [1,2,3], you can choose to increment nums[1] to make nums = [1,3,3]. Return the minimum number of op...
Python
zaydzuhri_stack_edu_python
function _check_inconsistencies self begin comment check if the necessary boolean was requested for the gridpoints. if max_gridpoints > 0 and not report_ngrid begin error string The gridpoint max cutoff was set to %i but report_ngrid was + string not enabled in the input file, set report_ngrid = True! exit 1 end commen...
def _check_inconsistencies(self): # check if the necessary boolean was requested for the gridpoints. if self.options.max_gridpoints > 0 and not self.options.report_ngrid: error("The gridpoint max cutoff was set to %i but report_ngrid was" +" not enabled in the input file,...
Python
nomic_cornstack_python_v1
comment !/usr/bin/env python comment -*- coding: utf-8 -*- comment @Time : 2018/3/6 13:05 comment @Author : MiaFeng comment @Site : comment @File : decisionTree.py comment @Software: PyCharm set __author__ = string MiaFeng from sklearn.cross_validation import train_test_split from sklearn.tree import DecisionTreeClassi...
#!/usr/bin/env python # -*- coding: utf-8 -*- # @Time : 2018/3/6 13:05 # @Author : MiaFeng # @Site : # @File : decisionTree.py # @Software: PyCharm __author__ = 'MiaFeng' from sklearn.cross_validation import train_test_split from sklearn.tree import DecisionTreeClassifier from util.plot_util import plot_dec...
Python
zaydzuhri_stack_edu_python
function transmit self begin comment Like RadioHead library, turn on high power boost if enabled. call set_boost _TEST_PA1_BOOST comment Enable packet sent interrupt for D0 line. set dio_0_mapping = 0 comment Enter TX mode (will clear FIFO!). set operation_mode = TX_MODE end function
def transmit(self) -> None: # Like RadioHead library, turn on high power boost if enabled. self.set_boost(_TEST_PA1_BOOST) # Enable packet sent interrupt for D0 line. self.dio_0_mapping = 0b00 # Enter TX mode (will clear FIFO!). self.operation_mode = TX_MODE
Python
nomic_cornstack_python_v1
class Bill extends object begin function __init__ self amount contributions id=none register_by=none split_share=none begin set amount = amount set contributions = contributions set id = id set split_share = split_share set register_by = register_by set indiviual_user_amount = dict end function function get_amount sel...
class Bill(object): def __init__(self, amount, contributions, id=None, register_by=None , split_share=None): self.amount = amount self.contributions = contributions self.id = id self.split_share = split_share self.register_by = register_by self.indiviual_user_amount =...
Python
zaydzuhri_stack_edu_python
import gym import gym.spaces from gym.utils import seeding from gym.envs.registration import EnvSpec import gym.wrappers import enum import numpy as np import random from pathlib import Path set BATCH_SIZE = 32 set BARS_COUNT = 10 set EPS_START = 1.0 set EPS_FINAL = 0.1 set EPS_STEPS = 1000000 set GAMMA = 0.99 set REPL...
import gym import gym.spaces from gym.utils import seeding from gym.envs.registration import EnvSpec import gym.wrappers import enum import numpy as np import random from pathlib import Path BATCH_SIZE = 32 BARS_COUNT = 10 EPS_START = 1.0 EPS_FINAL = 0.1 EPS_STEPS = 1000000 GAMMA = 0.99 REPLAY_SI...
Python
zaydzuhri_stack_edu_python
import sys , datetime , platform , math comment Apresenta os locais onde o python vai pesquisar os modulos print path comment modulo utilizado para monitorar a plataforma (S.O) que estamos utilizando print now set x = platform set platform = call system print platform print call python_version print call processor set ...
import sys, datetime, platform,math print(sys.path)# Apresenta os locais onde o python vai pesquisar os modulos print(datetime.datetime.now())# modulo utilizado para monitorar a plataforma (S.O) que estamos utilizando x = platform platform = x.system() print(platform) print(x.python_version()) print(x.processor()) ...
Python
zaydzuhri_stack_edu_python
class Student extends object begin decorator property function my_score self begin return 99 end function end class set stu = call Student print my_score
class Student(object): @property def my_score(self): return 99 stu = Student() print(stu.my_score)
Python
zaydzuhri_stack_edu_python
function test_ac_area2 self begin set c = call Rectangle 8 5 assert equal call area 40 end function
def test_ac_area2(self): c = Rectangle(8, 5) self.assertEqual(c.area(), 40)
Python
nomic_cornstack_python_v1
function setUpClass cls begin function run_app port app begin set test_app = APPS at app run host=string localhost port=port end function set server1 = process target=run_app args=tuple 1234 string test_app set server2 = process target=run_app args=tuple 1235 string test2_app set server3 = process target=run_app args=t...
def setUpClass(cls): def run_app(port, app): test_app = APPS[app] test_app.run(host='localhost', port=port) cls.server1 = Process(target=run_app, args=(1234, 'test_app',)) cls.server2 = Process(target=run_app, args=(1235, 'test2_app',)) cls.server3 = Process(targ...
Python
nomic_cornstack_python_v1
function add begin print string You are in function 1 end function add function avg a b begin string This will calculate average set avg = a + b / 2 print avg return avg end function comment v = avg(2,4) comment print(v) print __doc__
def add() : print("You are in function 1") add() def avg(a,b) : """This will calculate average""" avg = (a+b)/2 print(avg) return avg #v = avg(2,4) #print(v) print(avg.__doc__)
Python
zaydzuhri_stack_edu_python
function on_file_search request begin if method == string POST begin comment get Search Key data from search form set search_value = get POST string search_value print string ======================== comment Get all requirements in ON_FILE status if call has_perm string customer.customer_view_others begin set requireme...
def on_file_search(request): if request.method == 'POST': # get Search Key data from search form search_value = request.POST.get('search_value') print("========================") # Get all requirements in ON_FILE status if request.user.has_perm('customer.customer_view_other...
Python
nomic_cornstack_python_v1
function email_ml_unsubscribe self maillist=none maillist_uid=none subscriber=none subscriber_uid=none begin if not maillist and not maillist_uid begin raise call ValueError string Maillist or uid required end if not subscriber and not subscriber_uid begin raise call ValueError string Subscriber or uid required end ret...
def email_ml_unsubscribe(self, maillist=None, maillist_uid=None, subscriber=None, subscriber_uid=None): if not maillist and not maillist_uid: raise ValueError('Maillist or uid required') if not subscriber and not subscriber_uid: raise ValueError('Subscriber or uid required') ...
Python
nomic_cornstack_python_v1
function arena begin global monsters_defeated arena_boss if not arena_boss begin set arena_boss = call random_monster string boss_monsters end end function
def arena(): global monsters_defeated, arena_boss if not arena_boss: arena_boss = items_lists.random_monster('boss_monsters')
Python
nomic_cornstack_python_v1
function main begin if exists path output_file begin print string output file exists: output_file print string skipping return end print string loading file: input_file set df = call read_pickle input_file set df = transform df info memory_usage=string deep call save_as_pickle_gz df output_file print string done end fu...
def main(): if os.path.exists(output_file): print("output file exists:", output_file) print("skipping") return print('loading file:', input_file) df = pd.read_pickle(input_file) df = transform(df) df.info(memory_usage='deep') save_as_pickle_gz(df, output_...
Python
nomic_cornstack_python_v1
comment logarithm comment number of digits in m is comment floor(log(m, 10)) + 1 comment log(n!) = log(n * n-1 * n-2 * ... * 1) comment log(n!) = log(n) + log(n-1) + log(n-2) + ... + log(1) comment so create an array of log(i, 10) where log(0, 10) = -1 comment then compute the array upto max value of n comment then com...
# logarithm # number of digits in m is # floor(log(m, 10)) + 1 # log(n!) = log(n * n-1 * n-2 * ... * 1) # log(n!) = log(n) + log(n-1) + log(n-2) + ... + log(1) # so create an array of log(i, 10) where log(0, 10) = -1 # then compute the array upto max value of n # then compute prefix sum of that array from 1 to n, excl...
Python
zaydzuhri_stack_edu_python
function Comparison_1 begin set is_male = false set is_tall = false if is_male and is_tall begin print string You are a male and you are tall !! end else if is_male and not is_tall begin print string You are a male but you are not tall !! end else if not is_male and is_tall begin print string You are a female and you a...
def Comparison_1(): is_male = False is_tall = False if is_male and is_tall: print("You are a male and you are tall !!") elif is_male and not(is_tall): print("You are a male but you are not tall !!") elif not(is_male) and is_tall: print("You are a female and you are ...
Python
zaydzuhri_stack_edu_python
function test_scale_factor begin set N_RANDOM = 1000 seed 0 comment Create alphabet with two symbols comment and a identity substution matrix for it set alph = call Alphabet list string A string B set matrix = call SubstitutionMatrix alph alph call identity length alph comment Important: contrast factor must be 0 set s...
def test_scale_factor(): N_RANDOM = 1000 np.random.seed(0) # Create alphabet with two symbols # and a identity substution matrix for it alph = Alphabet(["A", "B"]) matrix = SubstitutionMatrix(alph, alph, np.identity(len(alph))) # Important: contrast factor must be 0 score_func = gecos.D...
Python
nomic_cornstack_python_v1
function OddEven begin try begin set num = integer input string Bana kontrol etmek üzere bir sayı ver: end except ValueError begin print string lütfen sayı giriniz. end try begin set check = integer input string böleceğim sayıyı ver: end except ValueError begin print string lütfen sayı giriniz. end if num % 4 == 0 begi...
def OddEven(): try: num = int(input("Bana kontrol etmek üzere bir sayı ver: ")) except ValueError: print("lütfen sayı giriniz.") try: check = int(input("böleceğim sayıyı ver: ")) except ValueError: print("lütfen sayı giriniz.") if num % 4 == 0: print(num, "4...
Python
zaydzuhri_stack_edu_python
comment MaNo - Segundo Parcial, Tema 2 function hhmm2min hora begin string Convierte un horario hhmm en minutos set hh = integer hora at slice : 2 : set mm = integer hora at slice 2 : : return hh * 60 + mm end function function min2hhmm minutos begin string Convierte minutos en horas y minutos set horas = minutos // ...
# MaNo - Segundo Parcial, Tema 2 def hhmm2min(hora): """ Convierte un horario hhmm en minutos """ hh = int(hora[:2]) mm = int(hora[2:]) return hh*60 + mm def min2hhmm(minutos): """ Convierte minutos en horas y minutos """ horas = minutos // 60 min = minutos % 60 return f"{horas:02} hor...
Python
zaydzuhri_stack_edu_python
comment !/usr/bin/env python string Where does a URL redirect? ========================== Author: Laszlo Szathmary, 2011 (jabba.laci@gmail.com) Website: http://pythonadventures.wordpress.com/2010/12/21/where-does-a-page-redirect-to/ GitHub: https://github.com/jabbalaci/Bash-Utils This script tells you where a webpage r...
#!/usr/bin/env python """ Where does a URL redirect? ========================== Author: Laszlo Szathmary, 2011 (jabba.laci@gmail.com) Website: http://pythonadventures.wordpress.com/2010/12/21/where-does-a-page-redirect-to/ GitHub: https://github.com/jabbalaci/Bash-Utils This script tells you where a webpage redire...
Python
zaydzuhri_stack_edu_python
function modularity_spectrum G begin import scipy as sp if call is_directed begin return call eigvals call directed_modularity_matrix G end else begin return call eigvals call modularity_matrix G end end function
def modularity_spectrum(G): import scipy as sp if G.is_directed(): return sp.linalg.eigvals(nx.directed_modularity_matrix(G)) else: return sp.linalg.eigvals(nx.modularity_matrix(G))
Python
nomic_cornstack_python_v1
function futures_coin_change_margin_type self **params begin return call _request_futures_coin_api string post string marginType signed=true data=params end function
def futures_coin_change_margin_type(self, **params): return self._request_futures_coin_api( "post", "marginType", signed=True, data=params )
Python
nomic_cornstack_python_v1
for line in f begin append array strip line end close f set f = open string POSpos.txt for line in f begin set words = split line string for word in words begin if string #VA in word or string #JJ in word begin set word = replace replace word string #VA string string #JJ string if word in array begin if word in POSarra...
for line in f: array.append(line.strip()) f.close() f=open('POSpos.txt') for line in f: words=line.split(" ") for word in words: if '#VA' in word or '#JJ' in word: word=word.replace("#VA","").replace("#JJ","") if word in array: if word in POSarray: POSarray[word]= POSarray[word]+1 else: P...
Python
zaydzuhri_stack_edu_python
comment Definition for a binary tree node. comment class TreeNode: comment def __init__(self, val=0, left=None, right=None): comment self.val = val comment self.left = left comment self.right = right comment BFS class Solution begin function largestValues self root begin if not root begin return list end set queue = d...
# Definition for a binary tree node. # class TreeNode: # def __init__(self, val=0, left=None, right=None): # self.val = val # self.left = left # self.right = right # BFS class Solution: def largestValues(self, root: TreeNode) -> List[int]: if not root: return [] ...
Python
zaydzuhri_stack_edu_python
function partition thelist n begin string Break a list into ``n`` pieces. The last list may be larger than the rest if the list doesn't break cleanly. That is:: >>> l = range(10) >>> partition(l, 2) [[0, 1, 2, 3, 4], [5, 6, 7, 8, 9]] >>> partition(l, 3) [[0, 1, 2], [3, 4, 5], [6, 7, 8, 9]] >>> partition(l, 4) [[0, 1], ...
def partition(thelist, n): """ Break a list into ``n`` pieces. The last list may be larger than the rest if the list doesn't break cleanly. That is:: >>> l = range(10) >>> partition(l, 2) [[0, 1, 2, 3, 4], [5, 6, 7, 8, 9]] >>> partition(l, 3) [[0, 1, 2], [3, 4, ...
Python
jtatman_500k
function test_PoloidalFieldCoilSet_incorrect_pf_coil begin solid end function
def test_PoloidalFieldCoilSet_incorrect_pf_coil(): paramak.PoloidalFieldCoilCaseSetFC( pf_coils=20, casing_thicknesses=[5, 5, 10, 10], rotation_angle=180).solid
Python
nomic_cornstack_python_v1
comment coding:utf8 comment The Fibonacci sequence is defined by the recurrence relation: comment Fn = Fn−1 + Fn−2, where F1 = 1 and F2 = 1. comment Hence the first 12 terms will be: comment F1 = 1 comment F2 = 1 comment F3 = 2 comment F4 = 3 comment F5 = 5 comment F6 = 8 comment F7 = 13 comment F8 = 21 comment F9 = 34...
#coding:utf8 # The Fibonacci sequence is defined by the recurrence relation: # # Fn = Fn−1 + Fn−2, where F1 = 1 and F2 = 1. # Hence the first 12 terms will be: # # F1 = 1 # F2 = 1 # F3 = 2 # F4 = 3 # F5 = 5 # F6 = 8 # F7 = 13 # F8 = 21 # F9 = 34 # F10 = 55 # F11 = 89 # F12 = 144 # The 12th term, F12, is the first term...
Python
zaydzuhri_stack_edu_python
function acosh self begin if call check_stack 1 string acosh begin set value = pop stack call add_stack call acosh value end end function
def acosh(self): if self.check_stack(1, "acosh"): value = self.stack.pop() self.add_stack(math.acosh(value))
Python
nomic_cornstack_python_v1
function _handle_control_dependence self target_node begin string Based on control dependence graph, pick all exits (statements) that lead to the target. :param target_node: A CFGNode instance. :returns: A set of new tainted code locations. set new_taints = set comment Query the CDG and figure out all control flow tran...
def _handle_control_dependence(self, target_node): """ Based on control dependence graph, pick all exits (statements) that lead to the target. :param target_node: A CFGNode instance. :returns: A set of new tainted code locations. """ new_taints = set() ...
Python
jtatman_500k
function print_area self begin return _print_area end function
def print_area(self): return self._print_area
Python
nomic_cornstack_python_v1
function is_complete_team self begin set list_val = call get_values self set cond_champ = list for role in roles begin append cond_champ call is_complete_champ end return all list_val and all cond_champ end function
def is_complete_team(self): list_val = self.get_values(self) cond_champ = [] for role in roles: cond_champ.append(getattr(self, role).is_complete_champ()) return all(list_val) and all(cond_champ)
Python
nomic_cornstack_python_v1
function _warn_if_too_large self fileinfo begin if size and size > MAX_UPLOAD_SIZE begin set file_path = call relative_path src set warning_message = string File { file_path } exceeds s3 upload limit of { call human_readable_size MAX_UPLOAD_SIZE } . set warning = call create_warning file_path warning_message skip_file=...
def _warn_if_too_large(self, fileinfo: FileInfo) -> None: if fileinfo.size and fileinfo.size > MAX_UPLOAD_SIZE: file_path = relative_path(fileinfo.src) warning_message = ( f"File {file_path} exceeds s3 upload limit of " f"{human_readable_size(MAX_UPLOAD_SI...
Python
nomic_cornstack_python_v1
function GetName self begin set callResult = call _Call string GetName if callResult is none begin return none end return callResult end function
def GetName(self): callResult = self._Call("GetName", ) if callResult is None: return None return callResult
Python
nomic_cornstack_python_v1
string A Pythagorean triplet is a set of three natural numbers, a b c, for which, a2 + b2 = c2 For example, 32 + 42 = 9 + 16 = 25 = 52. There exists exactly one Pythagorean triplet for which a + b + c = 1000. Find the product abc. comment pyth_triples = [(a, b, c) for a in xrange(1, 1001) for b in xrange(a, 1001) for c...
""" A Pythagorean triplet is a set of three natural numbers, a b c, for which, a2 + b2 = c2 For example, 32 + 42 = 9 + 16 = 25 = 52. There exists exactly one Pythagorean triplet for which a + b + c = 1000. Find the product abc. """ #pyth_triples = [(a, b, c) for a in xrange(1, 1001) for b in xrange(a, 1001) for c ...
Python
zaydzuhri_stack_edu_python
comment Python program to display calendar of comment given month of the year comment import module import calendar comment //This code use for find only 1 month calender comment yy = 2021 comment mm = 9 comment # display the calendar comment print(calendar.month(yy, mm)) print string The calendar of year 2018 is : pri...
# Python program to display calendar of # given month of the year # import module import calendar # //This code use for find only 1 month calender # yy = 2021 # mm = 9 # # # display the calendar # print(calendar.month(yy, mm)) print ("The calendar of year 2018 is : ") print (calendar.calendar(2021, 2, 1, 6))
Python
zaydzuhri_stack_edu_python
function tag_raise self *args begin call tuple _w string raise + args end function
def tag_raise(self, *args): self.tk.call((self._w, 'raise') + args)
Python
nomic_cornstack_python_v1
import random set wins = 0 set ties = 0 set losses = 0 print string Welcome to Rock, Paper, Scissors print string Wins: %s, Ties: %s, Losses: %s % tuple wins ties losses set computer = random integer 1 3 set user = input string 1. Rock, 2. Paper, 3. Scissors, 9. Quit while user != 9 begin if wins == 3 or ties == 3 or l...
import random wins = 0 ties = 0 losses = 0 print("Welcome to Rock, Paper, Scissors") print("Wins: %s, Ties: %s, Losses: %s" % (wins, ties, losses)) computer = random.randint(1, 3) user = input("1. Rock, 2. Paper, 3. Scissors, 9. Quit") while user != 9: if wins == 3 or ties == 3 or losses == 3: break ...
Python
zaydzuhri_stack_edu_python
with open string nginx_logs.txt string r encoding=string utf-8 as f begin for el in f begin set content_tuple = tuple split el string - - at 0 split split el string ] " at 1 string / at 0 split split el string HTTP at 0 string at 6 append content content_tuple end end for el in content begin append content_ip el at 0 p...
with open("nginx_logs.txt", "r", encoding="utf-8") as f: for el in f: content_tuple = (el.split(' - -')[0], el.split('] "')[1].split(' /')[0], el.split(' HTTP')[0].split(' ')[6]) content.append(content_tuple) for el in content: content_ip.append(el[0]) print(el) ip_set = set(content_ip) fo...
Python
zaydzuhri_stack_edu_python
comment !/usr/bin/Python2 import time import webbrowser set option = string Press1- google search Press2- google images Press3- Enter anything Press4- Enter anything Press5- Enter anything Press6- Enter anything Press7- Enter anything
#!/usr/bin/Python2 import time import webbrowser option= ''' Press1- google search Press2- google images Press3- Enter anything Press4- Enter anything Press5- Enter anything Press6- Enter anything Press7- Enter anything '''
Python
zaydzuhri_stack_edu_python