code
stringlengths
10
2.58M
original_code
stringlengths
3
3.18M
original_language
stringclasses
1 value
source
stringclasses
7 values
function SetupViewStates viewSvc rootViewLayer begin debug string Configuring view states debug string Initializing view state service call Initialize rootViewLayer debug string Adding primary views call AddView Login call LoginView call AddView Intro call IntroView call AddView CharacterSelector call CharacterSelector...
def SetupViewStates(viewSvc, rootViewLayer): logger.debug('Configuring view states') logger.debug('Initializing view state service') viewSvc.Initialize(rootViewLayer) logger.debug('Adding primary views') viewSvc.AddView(ViewState.Login, LoginView()) viewSvc.AddView(ViewState.Intro, IntroView()) ...
Python
nomic_cornstack_python_v1
import cv2 import torchvision import toml import numpy as np class Dataset extends VisionDataset begin function __init__ self root train=true transforms=none transform=none target_transform=none begin call __init__ root transforms transform target_transform set root = root set label_path = string { root } /0.toml set l...
import cv2 import torchvision import toml import numpy as np class Dataset(torchvision.datasets.VisionDataset): def __init__(self, root, train=True, transforms=None, transform=None, target_transform=None): super(Dataset, self).__init__(root, transforms, transform, target_transform) self.root = ro...
Python
zaydzuhri_stack_edu_python
import torch import torch.nn as nn set node_embedding = embedding 3 5 comment embedding dimension 5 set path_embedding = embedding 4 5 set starts = tensor list list 1 2 1 list 0 2 0 set paths = tensor list list 1 2 1 list 1 1 2 comment batch size 2 with max_length 3 set ends = tensor list list 1 2 0 list 1 1 0 set embe...
import torch import torch.nn as nn node_embedding = nn.Embedding(3, 5) path_embedding = nn.Embedding(4, 5) # embedding dimension 5 starts = torch.tensor([[1,2,1], [0,2,0]]) paths = torch.tensor([[1,2,1], [1,1,2]]) ends = torch.tensor([[1,2,0], [1,1,0]]) # batch size 2 with max_length 3 embedded_starts = node_embedd...
Python
zaydzuhri_stack_edu_python
comment pylint:disable=unused-argument function test_delete_unknown_user_returns_404 client jwt session begin comment post token with updated claims set headers = call factory_auth_header jwt=jwt claims=updated_test set rv = delete string /api/v1/users/@me headers=headers content_type=string application/json assert sta...
def test_delete_unknown_user_returns_404(client, jwt, session): # pylint:disable=unused-argument # post token with updated claims headers = factory_auth_header(jwt=jwt, claims=TestJwtClaims.updated_test) rv = client.delete('/api/v1/users/@me', headers=headers, content_type='application/json') assert r...
Python
nomic_cornstack_python_v1
string encryption standard GOST 28147-89 set S = list list 4 10 9 2 13 8 0 14 6 11 1 12 7 15 5 3 list 14 11 4 12 6 13 15 10 2 3 8 1 0 7 5 9 list 5 8 1 13 10 3 4 2 14 15 12 7 6 0 9 11 list 7 13 10 1 0 8 9 15 14 4 6 12 11 2 5 3 list 6 12 7 1 5 15 13 8 4 10 9 14 0 3 11 2 list 4 11 10 0 7 2 1 13 3 6 8 5 9 12 15 14 list 13 ...
"""encryption standard GOST 28147-89""" S = [ [4,10,9,2,13,8,0,14,6,11,1,12,7,15,5,3], [14,11,4,12,6,13,15,10,2,3,8,1,0,7,5,9], [5,8,1,13,10,3,4,2,14,15,12,7,6,0,9,11], [7,13,10,1,0,8,9,15,14,4,6,12,11,2,5,3], [6,12,7,1,5,15,13,8,4,10,9,14,0,3,11,2], [4,11,10,0,7,2,1,13,3,6,8,5,9,12,15,14], ...
Python
zaydzuhri_stack_edu_python
import numpy as np import sqlite3 set conn = call connect string Data/database.sqlite3 set c = call cursor set termConn = call connect string ../DataPreparation/Data/artist_term.db set termC = call cursor execute c string CREATE TABLE "mysite_artists" (`id` INTEGER, `name` TEXT, `tags` TEXT, PRIMARY KEY(id)) commit con...
import numpy as np import sqlite3 conn=sqlite3.connect('Data/database.sqlite3') c = conn.cursor() termConn = sqlite3.connect('../DataPreparation/Data/artist_term.db') termC = termConn.cursor() c.execute("CREATE TABLE \"mysite_artists\" (`id` INTEGER, `name` TEXT, `tags` TEXT, PRIMARY KEY(id))") conn.commit() Artist...
Python
zaydzuhri_stack_edu_python
function isValid string begin set stringCounts = dictionary for char in string begin if char in stringCounts begin set stringCounts at char = stringCounts at char + 1 end else begin set stringCounts at char = 1 end end set charCounts = set generator expression v for v in values stringCounts if length charCounts == 1 be...
def isValid(string): stringCounts = dict() for char in string: if char in stringCounts: stringCounts[char] += 1 else: stringCounts[char] = 1 charCounts = set(v for v in stringCounts.values()) if len(charCounts) == 1: return 'YES' if __name__ == ...
Python
zaydzuhri_stack_edu_python
class Gun begin function __init__ self model begin set model = model set bullet = 0 end function function __str__ self begin return string This is a %s gun % model end function function reload self count begin set bullet = bullet + count end function function shoot self begin if bullet <= 0 begin print string Out of ar...
class Gun: def __init__(self, model): self.model = model self.bullet = 0 def __str__(self): return "This is a %s gun" % self.model def reload(self, count): self.bullet += count def shoot(self): if self.bullet <= 0: print("Out of armor! fail to ...
Python
zaydzuhri_stack_edu_python
comment загружаем библиотеку pygame import pygame comment загружаем отдельный файл с цветами from colors import * import os set winposx = 50 set winposy = 50 set environ at string SDL_VIDEO_WINDOW_POS = string %d,%d % tuple winposx winposy set wall = string textures\wall.png set cloud = string textures\cloud3.png set s...
# загружаем библиотеку pygame import pygame # загружаем отдельный файл с цветами from colors import * import os winposx = 50 winposy = 50 os.environ['SDL_VIDEO_WINDOW_POS'] = "%d,%d" % (winposx, winposy) wall = "textures\\wall.png" cloud = "textures\\cloud3.png" sun = "textures\\sun.png" blue_sky = "textures\\sky1.pn...
Python
zaydzuhri_stack_edu_python
from sampler import * function interpolate samples distance begin set length = length samples at string distance set elevation = 0 for i in range length begin set phi = 1 set x_i = samples at string distance at i for j in range length begin if i != j begin set x_j = samples at string distance at j set phi = phi * dista...
from sampler import * def interpolate(samples, distance): length = len(samples["distance"]) elevation = 0 for i in range(length): phi = 1 x_i = samples["distance"][i] for j in range(length): if i != j: x_j = samples["distance"][j] phi ...
Python
zaydzuhri_stack_edu_python
import numpy as np import matplotlib.pyplot as plt function gradientAscent feature_data label_data k maxCycle alpha begin string 梯度下降法训练Softmax模型 :param feature_data: (mat)特征 :param label_data: (mat)标签 :param k: (int)类别的个数 :param maxCycle: (int)最大的迭代次数 :param alpha: (float)学习率 :return: weights(mat)权重 set tuple m n = ca...
import numpy as np import matplotlib.pyplot as plt def gradientAscent(feature_data, label_data, k, maxCycle, alpha): ''' 梯度下降法训练Softmax模型 :param feature_data: (mat)特征 :param label_data: (mat)标签 :param k: (int)类别的个数 :param maxCycle: (int)最大的迭代次数 :param alpha: (float)学习率 :return: weights(mat...
Python
zaydzuhri_stack_edu_python
from aiohttp import web class ItemController extends View begin async function post self begin set body = await json request print body set result = list for i in get body string items begin print i append result dict string id i at string id ; string title i at string title ; string date i at string date_str ; string...
from aiohttp import web class ItemController(web.View): async def post(self): body = await self.request.json() print(body) result = [] for i in body.get("items"): print(i) result.append({ "id": i["id"], "title": i["title"], ...
Python
zaydzuhri_stack_edu_python
import plotille import pandas as pd import numpy as np import random import time from tabulate import tabulate class GeneticAlgorithm begin comment read csv set df_nutrisi = read csv string data_nutrisi.csv function __init__ self target pop_size cr mr num_generation begin set target = target set pop_size = pop_size set...
import plotille import pandas as pd import numpy as np import random import time from tabulate import tabulate class GeneticAlgorithm: #read csv df_nutrisi = pd.read_csv('data_nutrisi.csv') def __init__(self,target,pop_size,cr,mr,num_generation): self.target = target self.pop_size = pop_si...
Python
zaydzuhri_stack_edu_python
comment ac.py comment given an A or C instruction in Hack assembly language, comment output the corresponding Hack machine code for that instruction. comment split a 'C' instruction into 3 parts function split s begin comment default values for dest, comp and jump: comment the input string set comp = s comment (dest is...
# ac.py # given an A or C instruction in Hack assembly language, # output the corresponding Hack machine code for that instruction. # split a 'C' instruction into 3 parts def split(s): # default values for dest, comp and jump: comp = s # the input string dest = '' # (dest is optional) jump = '' # (c...
Python
zaydzuhri_stack_edu_python
function _encode_text_dummy df name begin set dummies = call get_dummies loc at tuple slice : : name for x in columns begin set dummy_name = format string {}-{} name x set loc at tuple slice : : dummy_name = dummies at x end drop df name axis=1 inplace=true end function
def _encode_text_dummy(df, name): dummies = pd.get_dummies(df.loc[:,name]) for x in dummies.columns: dummy_name = "{}-{}".format(name, x) df.loc[:, dummy_name] = dummies[x] df.drop(name, axis=1, inplace=True)
Python
nomic_cornstack_python_v1
function set_native_value self value begin set int_value = integer value if int_value == 0 begin call setter client none return end call setter client int_value end function
def set_native_value(self, value: float) -> None: int_value = int(value) if int_value == 0: self.entity_description.setter(self.coordinator.client, None) return self.entity_description.setter(self.coordinator.client, int_value)
Python
nomic_cornstack_python_v1
import numpy as np import tensorflow as tf from data_shapley import get_shapley_values comment Using MNIST digits dataset. set mnist_dataset = mnist set tuple tuple train_images train_labels tuple test_images test_labels = call load_data comment Filter to binary (2-class) problem. set binary_train_images = train_images...
import numpy as np import tensorflow as tf from data_shapley import get_shapley_values # Using MNIST digits dataset. mnist_dataset = tf.keras.datasets.mnist (train_images, train_labels), (test_images, test_labels) = mnist_dataset.load_data() # Filter to binary (2-class) problem. binary_train_images = train_images[(t...
Python
zaydzuhri_stack_edu_python
import random function encrypt_string_to_byte_array string begin set key_length = length string set keys = list comprehension random integer 0 255 for _ in range key_length set encrypted_bytes = bytearray for tuple i char in enumerate string begin set key = keys at i comment XOR the character with the key set encrypted...
import random def encrypt_string_to_byte_array(string): key_length = len(string) keys = [random.randint(0, 255) for _ in range(key_length)] encrypted_bytes = bytearray() for i, char in enumerate(string): key = keys[i] encrypted_char = chr(ord(char) ^ key) # XOR the character with the ...
Python
jtatman_500k
comment If the numbers 1 to 5 are written out in words: one, two, three, four, five, then there are 3 + 3 + 5 + 4 + 4 = 19 letters used in total. comment If all the numbers from 1 to 1000 (one thousand) inclusive were written out in words, how many letters would be used? comment NOTE: Do not count spaces or hyphens. Fo...
# If the numbers 1 to 5 are written out in words: one, two, three, four, five, then there are 3 + 3 + 5 + 4 + 4 = 19 letters used in total. # If all the numbers from 1 to 1000 (one thousand) inclusive were written out in words, how many letters would be used? # NOTE: Do not count spaces or hyphens. For example, 342 (th...
Python
zaydzuhri_stack_edu_python
async function import_key_material_with_options_async self request runtime begin call validate_model request set query = dict if not call is_unset encrypted_key_material begin set query at string EncryptedKeyMaterial = encrypted_key_material end if not call is_unset import_token begin set query at string ImportToken =...
async def import_key_material_with_options_async( self, request: kms_20160120_models.ImportKeyMaterialRequest, runtime: util_models.RuntimeOptions, ) -> kms_20160120_models.ImportKeyMaterialResponse: UtilClient.validate_model(request) query = {} if not UtilClient.is_u...
Python
nomic_cornstack_python_v1
function set_rail_lights self on begin call set_lights rails=on end function
def set_rail_lights(self, on: bool) -> None: self._sync_hardware.set_lights(rails=on)
Python
nomic_cornstack_python_v1
function sol t room start begin set end = start + room * 6 if t < end begin return room + 1 end else begin while t >= end begin set end = start + room * 6 if start <= t ? t < end begin return room + 1 end else begin set start = end set room = room + 1 call sol t room start end end end end function set n = integer input...
def sol(t, room, start): end = start + (room * 6) if t < end: return room + 1 else: while t >= end: end = start + (room * 6) if start <= t & t < end: return room + 1 else: start = end room += 1 ...
Python
zaydzuhri_stack_edu_python
class Adder begin function __init__ self begin pass end function function define_characters self begin string Defines lines to draw registers with set V = string │ set H = string ─ set Cb = string ■ set X = string ┼ return tuple V H Cb X end function function X self target begin if target == string 0 begin return strin...
class Adder(): def __init__(self): pass def define_characters(self): '''Defines lines to draw registers with''' V = '\u2502' H = '\u2500' Cb = '\u25A0' X = '\u253C' return V,H,Cb,X def X(self, target): if target == '0': ...
Python
zaydzuhri_stack_edu_python
function outward_ticks *axes axis=string both begin if length axes == 0 begin set axes = list call gca end for ax in axes begin if axis == string both begin call tick_params direction=string out end else begin call tick_params axis=axis direction=string out end end end function
def outward_ticks(*axes, axis='both'): if len(axes) == 0: axes = [plt.gca()] for ax in axes: if axis == 'both': ax.tick_params(direction='out') else: ax.tick_params(axis=axis, direction='out')
Python
nomic_cornstack_python_v1
import requests import queue import time from bs4 import BeautifulSoup import threading function g_url q1 begin set number = 0 for i in range 46300 46391 begin if number == 10 begin break end for j in range 0 10 begin if number == 10 begin break end set url = string https://www.youquba.net/xieedongtaitu/2017/1217/ set ...
import requests import queue import time from bs4 import BeautifulSoup import threading def g_url(q1): number=0 for i in range(46300,46391): if number==10: break for j in range(0,10): if number==10: break url = "https://www.youquba.net/xieedong...
Python
zaydzuhri_stack_edu_python
function get_embed self ctx user_id=none color=call gold begin if user_id is none or is_private begin set color = call gold end else begin set member = call get_member user_id if member is not none begin set color = color end else begin set color = color end end set data = call Embed color=color title=string descripti...
def get_embed(self, ctx, user_id=None, color=discord.Color.gold()): if user_id is None or ctx.message.channel.is_private: color = discord.Color.gold() else: member = self.bot.get_member(user_id) if member is not None: color = member.color else: col...
Python
nomic_cornstack_python_v1
function perfect_shuffle even_list begin set result = list set first_half = even_list at slice : length even_list // 2 : set second_half = even_list at slice length even_list // 2 : : for x in range length first_half begin append result first_half at x append result second_half at x end return result end function
def perfect_shuffle(even_list): result = [] first_half = even_list[:len(even_list) // 2] second_half = even_list[len(even_list) // 2:] for x in range(len(first_half)): result.append(first_half[x]) result.append(second_half[x]) return result
Python
nomic_cornstack_python_v1
function biopython_protein_scale inseq scale custom_scale_dict=none window=7 begin string Use Biopython to calculate properties using a sliding window over a sequence given a specific scale to use. if scale == string kd_hydrophobicity begin set scale_dict = kd_hydrophobicity_one end else if scale == string bulkiness be...
def biopython_protein_scale(inseq, scale, custom_scale_dict=None, window=7): """Use Biopython to calculate properties using a sliding window over a sequence given a specific scale to use.""" if scale == 'kd_hydrophobicity': scale_dict = kd_hydrophobicity_one elif scale == 'bulkiness': scale...
Python
jtatman_500k
import time from urllib import request import pytesseract from PIL import Image function main begin set tesseract_cmd = string D:\Program Files\Tesseract-OCR\tesseract.exe while true begin set url = string https://e.coding.net/api/getCaptcha url retrieve url string captcha.png set image = open string captcha.png set te...
import time from urllib import request import pytesseract from PIL import Image def main(): pytesseract.pytesseract.tesseract_cmd = r'D:\Program Files\Tesseract-OCR\tesseract.exe' while True: url = 'https://e.coding.net/api/getCaptcha' request.urlretrieve(url, 'captcha.png') image = I...
Python
zaydzuhri_stack_edu_python
from django.db import models comment Create your models here. comment I want the model to have 3 fields: comment - Name comment - Wins comment - Loses class Score extends Model begin set name = call CharField max_length=20 primary_key=true set wins = call PositiveIntegerField set loses = call PositiveIntegerField funct...
from django.db import models # Create your models here. # I want the model to have 3 fields: # - Name # - Wins # - Loses class Score(models.Model): name = models.CharField(max_length=20, primary_key=True) wins = models.PositiveIntegerField() loses = models.PositiveIntegerField() def __...
Python
zaydzuhri_stack_edu_python
import cv2 as cv2 import numpy as np import imutils import pytesseract comment Capture from web cam set cap = call VideoCapture 0 set tuple _ image = read cap comment You can load a saved file from disk comment image = cv2.imread('test13.jpg') set img = call cvtColor image COLOR_BGR2GRAY set img = call GaussianBlur img...
import cv2 as cv2 import numpy as np import imutils import pytesseract # Capture from web cam cap = cv2.VideoCapture(0) _,image = cap.read() # You can load a saved file from disk # image = cv2.imread('test13.jpg') img = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) img = cv2.GaussianBlur(img, (7,7), 0) # perform edge det...
Python
zaydzuhri_stack_edu_python
function get self dto begin assert using in list keys models set Relation = models at using return first filter recipient == recipient end function
def get(self, dto): assert dto.using in list(self.models.keys()) Relation = self.models[dto.using] return self.session.query(Relation)\ .filter(Relation.purpose == dto.purpose)\ .filter(Relation.sender == dto.sender)\ .filter(Relation.recipient == dto.recipien...
Python
nomic_cornstack_python_v1
comment Teste seu código aos poucos. comment Não teste tudo no final, pois fica mais difícil de identificar erros. comment Use as mensagens de erro para corrigir seu código. set nome = input string Que desgraca tu e? if nome == string cervo begin print format string {} eh patrono do Harry Potter nome end else begin pri...
# Teste seu código aos poucos. # Não teste tudo no final, pois fica mais difícil de identificar erros. # Use as mensagens de erro para corrigir seu código. nome=input("Que desgraca tu e? ") if (nome == "cervo"): print("{} eh patrono do Harry Potter".format(nome)) else: print("{} nao eh patrono do Harry Potter".format...
Python
zaydzuhri_stack_edu_python
function del_none d begin if d is none begin return end for tuple key value in list items d begin if value is none begin del d at key end else if is instance value dict begin call del_none value end else if is instance value list begin for item in value begin if is instance item dict begin call del_none item end end en...
def del_none(d: dict) -> None: if d is None: return for key, value in list(d.items()): if value is None: del d[key] elif isinstance(value, dict): del_none(value) elif isinstance(value, list): for item in value: if isinstance(ite...
Python
nomic_cornstack_python_v1
function build_job_configs self args begin set job_configs = dict set ttype = args at string ttype set tuple roster_yaml sim = call resolve_rosterfile args if roster_yaml is none begin return job_configs end set roster_dict = call load_yaml roster_yaml set astro_priors = args at string astro_priors set channels = args...
def build_job_configs(self, args): job_configs = {} ttype = args['ttype'] (roster_yaml, sim) = NAME_FACTORY.resolve_rosterfile(args) if roster_yaml is None: return job_configs roster_dict = load_yaml(roster_yaml) astro_priors = args['astro_priors'] ...
Python
nomic_cornstack_python_v1
function _get_id self begin return __id end function
def _get_id(self): return self.__id
Python
nomic_cornstack_python_v1
function binary_search list value begin set first = 0 set last = length list - 1 set status = string -1 set found = false while first <= last and not found begin set mid = first + last // 2 if list at mid == value begin set found = true set status = string Wert gefunden end else if value < list at mid begin set last = ...
def binary_search(list, value): first = 0 last = len(list) - 1 status ="-1" found = False while first <= last and not found: mid = (first + last) // 2 if list[mid] == value: found = True status ="Wert gefunden" else: if value < list[mid]: ...
Python
zaydzuhri_stack_edu_python
function send_mass_messages self recipient_list sender message=string subject=string begin try begin for s in recipient_list begin call send_message to=s sender=sender message=message subject=subject end end except TypeError begin return - 1 end return 1 end function
def send_mass_messages(self, recipient_list, sender, message="", subject=""): try: for s in recipient_list: self.send_message(to=s, sender=sender, message=message, subject=subject) except TypeError: return -1 return 1
Python
nomic_cornstack_python_v1
comment !/usr/bin/env python from twython import Twython from twython import TwythonStreamer from dotenv import load_dotenv , find_dotenv import random import os comment List of messages to choose from set messages = list string Hello string Bye string Okay string AI overlords comment Load key, token, secrets from .env...
#!/usr/bin/env python from twython import Twython from twython import TwythonStreamer from dotenv import load_dotenv, find_dotenv import random import os # List of messages to choose from messages = [ "Hello", "Bye", "Okay", "AI overlords" ] # Load key, token, secrets from .env load_dotenv(find_dote...
Python
zaydzuhri_stack_edu_python
function cilent_socket begin set sk = call socket call connect tuple string 127.0.0.1 9008 while true begin set send_data = input string input sending data: call sendall bytes send_data encoding=string utf8 if send_data == string byebye begin break end set accept_data = string call recv 1024 encoding=string utf8 print ...
def cilent_socket(): sk = socket.socket() sk.connect(("127.0.0.1", 9008)) while True: send_data = input("input sending data:") sk.sendall(bytes(send_data, encoding="utf8")) if send_data == "byebye": break accept_data = str(sk.recv(1024), encoding="utf8") p...
Python
nomic_cornstack_python_v1
comment -*- coding:utf-8 -*- string bug: File "demo_退位减法.py", line 123, in <module> synapse_h_update += np.atleast_2d(prev_layer_1).T.dot(layer_1_delta) ValueError: shapes (16,1) and (16,16) not aligned: 1 (dim 1) != 16 (dim 0) import copy , numpy as np comment 固定随机数生成器的种子,可以每次得到一个值 seed 0 comment 定义sigmoid激活函数 functio...
# -*- coding:utf-8 -*- ''' bug: File "demo_退位减法.py", line 123, in <module> synapse_h_update += np.atleast_2d(prev_layer_1).T.dot(layer_1_delta) ValueError: shapes (16,1) and (16,16) not aligned: 1 (dim 1) != 16 (dim 0) ''' import copy, numpy as np # 固定随机数生成器的种子,可以每次得到一个值 np.random.seed(0) # 定义sigmoid激活...
Python
zaydzuhri_stack_edu_python
function _matching_hosts self hypervisor_properties resource_properties count_range start_date end_date project_id begin set count_range = split count_range string - set min_host = count_range at 0 set max_host = count_range at 1 set allocated_host_ids = list set not_allocated_host_ids = list set filter_array = list ...
def _matching_hosts(self, hypervisor_properties, resource_properties, count_range, start_date, end_date, project_id): count_range = count_range.split('-') min_host = count_range[0] max_host = count_range[1] allocated_host_ids = [] not_allocated_host_ids = ...
Python
nomic_cornstack_python_v1
function write_dict_to_csv venue_dict file begin comment Convert dictionary to 2D list of rows set venue_list = list comprehension list venue *data for tuple venue data in items venue_dict set headers = list string venue string untappd_url string foursquare_url string address string lat string long string categories st...
def write_dict_to_csv(venue_dict, file): # Convert dictionary to 2D list of rows venue_list = [[venue, *data] for venue, data in venue_dict.items()] headers = ['venue', 'untappd_url', 'foursquare_url', 'address', 'lat', 'long', 'categories', 'in_united_states'] # Write rows to csv, o...
Python
nomic_cornstack_python_v1
function update_status self ingestion_job_status ingestion_job_id begin debug string Updating Job Status For Job: + string ingestion_job_id set job_update_query = format UPDATE_STATUS_QUERY ingestion_job_status ingestion_job_id return call execute_query job_update_query end function
def update_status(self, ingestion_job_status, ingestion_job_id): self.logger.debug("Updating Job Status For Job: " + str(ingestion_job_id)) job_update_query = self.UPDATE_STATUS_QUERY.format(ingestion_job_status, ingestion_job_id) return self.mssql_db_mgr.execute_query(job_update_query)
Python
nomic_cornstack_python_v1
from selenium import webdriver from selenium.webdriver.common.keys import Keys from selenium.webdriver.common.by import By from selenium.webdriver.support.ui import WebDriverWait import selenium.webdriver.support.expected_conditions as EC import datetime from time import sleep from openpyxl import load_workbook import ...
from selenium import webdriver from selenium.webdriver.common.keys import Keys from selenium.webdriver.common.by import By from selenium.webdriver.support.ui import WebDriverWait import selenium.webdriver.support.expected_conditions as EC import datetime from time import sleep from openpyxl import load_workbook ...
Python
zaydzuhri_stack_edu_python
comment encoding=utf8 from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals set __author__ = string 1661 import six from structure_reader.structure_reader import * class StructureGuess extends object begin string it's NOT saf...
# encoding=utf8 from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals __author__ = '1661' import six from structure_reader.structure_reader import * class StructureGuess(object): """it's NOT safe, use it at your risk...
Python
zaydzuhri_stack_edu_python
function set_smoothing_parameters self smoothing_parameters begin if length smoothing_parameters == 9 begin set smoothing_parameters = smoothing_parameters call update_material_field end else begin raise call ValueError string 9 smoothing parameters required end end function
def set_smoothing_parameters(self, smoothing_parameters): if len(smoothing_parameters) == 9: self.smoothing_parameters = smoothing_parameters self.update_material_field() else: raise ValueError('9 smoothing parameters required')
Python
nomic_cornstack_python_v1
comment Auxiliary routines such as integration import numpy as np function Rmm a b func m **kwargs begin string Auxiliary function computing tableau entries for Romberg integration using recursive relation, but implemented non-recursively Parameters ----------------- func - python function object function to integrate ...
# Auxiliary routines such as integration # import numpy as np def Rmm(a, b, func, m, **kwargs): """ Auxiliary function computing tableau entries for Romberg integration using recursive relation, but implemented non-recursively Parameters ----------------- func - python function object ...
Python
zaydzuhri_stack_edu_python
function create_circle_box self x1 y1 x2 y2 begin comment Defaults. set radius = 15 set gap = 0 comment Calculated values. set circumference = radius * 2 set width = x2 - x1 set height = y2 - y1 set cols = integer width / circumference + gap set rows = integer height / circumference + gap comment Build a bunch of circl...
def create_circle_box(self, x1, y1, x2, y2): # Defaults. radius = 15 gap = 0 # Calculated values. circumference = radius * 2 width = x2 - x1 height = y2 - y1 cols = int(width / (circumference + gap)) rows = int(height / (circumference + gap)) ...
Python
nomic_cornstack_python_v1
function main begin set cmdo = call FF2ZIMConsole call cmdloop end function
def main(): cmdo = FF2ZIMConsole() cmdo.cmdloop()
Python
nomic_cornstack_python_v1
comment !/usr/bin/env python comment -*- coding: utf-8 -*- comment orakel debakel comment for socon by matthias schneider comment predicts soccer scores import sys import random import cPickle as pickle comment own classes from data import * from predictor import * set DEBUG = 1 class Main begin function __init__ self ...
#!/usr/bin/env python # -*- coding: utf-8 -*- # orakel debakel # for socon by matthias schneider # predicts soccer scores import sys import random import cPickle as pickle # own classes from data import * from predictor import * DEBUG = 1 class Main: def __init__(self): # init self.pred = Predictor()...
Python
zaydzuhri_stack_edu_python
function test_no_file_csv self begin set rl1 = call load_from_file_csv assert equal rl1 list end function
def test_no_file_csv(self): rl1 = Rectangle.load_from_file_csv() self.assertEqual(rl1, [])
Python
nomic_cornstack_python_v1
function get_anytext bag begin comment list of words if is instance bag list begin return strip join string list comprehension _f for _f in bag if _f end else begin comment xml if is instance bag binary_type or is instance bag text_type begin comment serialize to lxml set bag = call fromstring bag PARSER end comment g...
def get_anytext(bag): if isinstance(bag, list): # list of words return ' '.join([_f for _f in bag if _f]).strip() else: # xml if isinstance(bag, six.binary_type) or isinstance(bag, six.text_type): # serialize to lxml bag = etree.fromstring(bag, PARSER) # get al...
Python
nomic_cornstack_python_v1
async function run self begin set current_status = string Init while expected_status != current_status begin await sleep 1 async_with call ClientSession as session begin async_with get session url as response begin set api_call_result = await json response set current_status = api_call_result at string status end end e...
async def run(self): current_status = "Init" while self.expected_status != current_status: await asyncio.sleep(1) async with aiohttp.ClientSession() as session: async with session.get(self.url) as response: api_call_result = await response.json...
Python
nomic_cornstack_python_v1
comment WAP to add two integers using function. function sum a b begin set s = a + b return s end function function main begin set a = integer input string Enter 1st number: set b = integer input string Enter 2nd number: print string Sum= sum a b end function if __name__ == string __main__ begin call main end
#WAP to add two integers using function. def sum(a,b): s=a+b return s def main(): a=int(input("Enter 1st number:")) b=int(input("Enter 2nd number:")) print("Sum=",sum(a,b)) if __name__=='__main__': main()
Python
zaydzuhri_stack_edu_python
function insert self word begin set node = root for c in word begin if c not in children begin set children at c = call TrieNode end set node = children at c end set is_word = true end function
def insert(self, word): node = self.root for c in word: if c not in node.children: node.children[c] = TrieNode() node = node.children[c] node.is_word = True
Python
nomic_cornstack_python_v1
comment { comment 'student': 'Tina', comment 'fav_food' 'Cheeseburger' comment }
# { # 'student': 'Tina', # 'fav_food' 'Cheeseburger' # } #
Python
zaydzuhri_stack_edu_python
comment -*- coding: utf-8 -*- comment 题目:猴子吃桃问题:猴子第一天摘下若干个桃子,当即吃了一半,还不瘾,又多吃了一个第二天早上又将剩下的桃子吃掉一半,又多吃了一个。 comment 以后每天早上都吃了前一天剩下的一半零一个。到第10天早上想再吃时,见只剩下一个桃子了。求第一天共摘了多少。 comment 程序分析:采取逆向思维的方法,从后往前推断。 comment 10: 1 comment 9: (1+1)*2=4 eat 3 comment 8: (4+1)*2=10 eat 6 set total = 1 set a = 1 for i in range 9 0 - 1 begin se...
# -*- coding: utf-8 -*- # 题目:猴子吃桃问题:猴子第一天摘下若干个桃子,当即吃了一半,还不瘾,又多吃了一个第二天早上又将剩下的桃子吃掉一半,又多吃了一个。 # 以后每天早上都吃了前一天剩下的一半零一个。到第10天早上想再吃时,见只剩下一个桃子了。求第一天共摘了多少。 # 程序分析:采取逆向思维的方法,从后往前推断。 # 10: 1 # 9: (1+1)*2=4 eat 3 # 8: (4+1)*2=10 eat 6 total = 1 a = 1 for i in range(9, 0, -1): total = (total+1)*2 print(total)
Python
zaydzuhri_stack_edu_python
function compute_label sheets begin set label = get environ string TAAS_PR_LABEL none if label is not none begin return label end if sheets is not none begin return join string - sheets end raise call RuntimeError string TAAS_PR_LABEL environment must be set when processing all sheets. end function
def compute_label(sheets): label = os.environ.get("TAAS_PR_LABEL", None) if label is not None: return label if sheets is not None: return "-".join(sheets) raise RuntimeError("TAAS_PR_LABEL environment must be set when processing all sheets.")
Python
nomic_cornstack_python_v1
function CreateShapesWithStyle self useWhidbey begin set tuple sizeX sizeY = tuple aeroguideSizeX aeroguideSizeY if useWhidbey begin set tuple sizeX sizeY = tuple whidbeySizeX whidbeySizeY end if _direction not in list TOP BOTTOM begin set tuple sizeX sizeY = tuple sizeY sizeX end set useAero = useWhidbey and list 2 or...
def CreateShapesWithStyle(self, useWhidbey): sizeX, sizeY = aeroguideSizeX, aeroguideSizeY if useWhidbey: sizeX, sizeY = whidbeySizeX, whidbeySizeY if self._direction not in [wx.TOP, wx.BOTTOM]: sizeX, sizeY = sizeY, sizeX useAero = (useWhidbey and [2] or [1])[...
Python
nomic_cornstack_python_v1
function __init__ self name value rfc2425parameters=none begin set _unused = rfc2425parameters call __init__ self name if upper name != string N begin raise call RuntimeError string VCardName handles only 'N' type end if is instance value xmlNode begin set tuple family given middle prefix suffix = list string * 5 set ...
def __init__(self,name,value,rfc2425parameters=None): _unused = rfc2425parameters VCardField.__init__(self,name) if self.name.upper()!="N": raise RuntimeError("VCardName handles only 'N' type") if isinstance(value,libxml2.xmlNode): self.family,self.given,sel...
Python
nomic_cornstack_python_v1
function learn_patterns self pattern=string random prob=0.5 learning_rule=string hebb nb=10 to_learn=list begin set patterns = none if boolean to_learn begin set patterns = to_learn call v_print string Learning patterns if length learnt_patterns == 0 and learning_rule == string ortho_hebb begin call _learn_ string hebb...
def learn_patterns(self, pattern='random', prob=0.5, learning_rule='hebb', nb=10 , to_learn=[]): patterns= None if bool(to_learn): patterns = to_learn v_print("Learning patterns") if len(self.learnt_patterns)==0 and learning_r...
Python
nomic_cornstack_python_v1
function save self savefile identifier=none begin if precompute_level == string full begin call savez_compressed savefile level=string full identifier=identifier distances=distances const_factors=const_factors matrix=matrix primary_factor=primary_factor end else if precompute_level == string partial begin call savez_co...
def save(self, savefile, identifier=None): if self.precompute_level == "full": np.savez_compressed(savefile, level="full", identifier=identifier, distances=self.distances, const_factors=self.const_factors, matrix=self.matrix, primary_f...
Python
nomic_cornstack_python_v1
class grandf begin function __init__ self task_id dag=none *args **kwargs begin set task_id = task_id set dag = dag end function function say_fuck self begin print string task_is = %s, dag = %s end function end class class person extends grandf begin function __init__ self name *args **kwargs begin call __init__ *args ...
class grandf: def __init__(self, task_id, dag=None, *args, **kwargs): self.task_id = task_id self.dag = dag def say_fuck(self): print(" task_is = %s, dag = %s") class person(grandf): def __init__(self, name, *args, **kwargs): super(person, self).__init__(*args, **kwargs) ...
Python
zaydzuhri_stack_edu_python
import types set a = string string hello set b = call unicode string world print type a if is instance a StringTypes begin print string a is a StringTypes end print type b if is instance b StringTypes begin print string b is a StringTypes end
import types a = str('hello') b = unicode(u'world') print(type(a)) if isinstance(a, types.StringTypes): print("a is a StringTypes") print(type(b)) if isinstance(b, types.StringTypes): print("b is a StringTypes")
Python
zaydzuhri_stack_edu_python
import json set __author__ = string Benjamin Martin set __copyright__ = string Copyright 2018, The University of Queensland set __license__ = string MIT set __version__ = string 1.0.0 set DEFAULT_GAME = string basic class HighScoreManager begin string Manages high scores across multiple game types & persists to file se...
import json __author__ = "Benjamin Martin" __copyright__ = "Copyright 2018, The University of Queensland" __license__ = "MIT" __version__ = "1.0.0" DEFAULT_GAME = 'basic' class HighScoreManager: """Manages high scores across multiple game types & persists to file""" _data = None _top_scores = 10 # The ...
Python
zaydzuhri_stack_edu_python
function position_delta self position_delta begin set _position_delta = position_delta end function
def position_delta(self, position_delta): self._position_delta = position_delta
Python
nomic_cornstack_python_v1
from os import sys , path append path directory name path directory name path absolute path path __file__ class Stack extends object begin string docstring for Stack function __init__ self begin call __init__ set _head = none set _size = 0 end function function length self begin return _size end function function isEmp...
from os import sys, path sys.path.append(path.dirname(path.dirname(path.abspath(__file__)))) class Stack(object): """docstring for Stack""" def __init__(self): super(Stack, self).__init__() self._head = None self._size = 0 def length(self): return self._size def isEmp...
Python
zaydzuhri_stack_edu_python
comment KeywordTable.py comment Created as part of the William and Mary Russian Movie Theater Project, comment this is the work of John Hoskins and Margaret Swift, under the comment direction of Sasha and Elena Prokhorov. comment https://rmtp.wm.edu comment Authored by John Hoskins: jbhoskins@email.wm.edu string A tabl...
# KeywordTable.py # Created as part of the William and Mary Russian Movie Theater Project, # this is the work of John Hoskins and Margaret Swift, under the # direction of Sasha and Elena Prokhorov. # https://rmtp.wm.edu # Authored by John Hoskins: jbhoskins@email.wm.edu """ A table of KeywordInstances, with the incl...
Python
zaydzuhri_stack_edu_python
function hapaxes corpus begin set fd = call freq_dist corpus set length_hapaxes = length call hapaxes return length_hapaxes end function
def hapaxes(corpus): fd = freq_dist(corpus) length_hapaxes = len(fd.hapaxes()) return length_hapaxes
Python
nomic_cornstack_python_v1
function run_agent self begin string The child class is created in order to override the value method which will take into account previous states of the agent. The reward function is made exponential rather than linear, which decreases the probability of agent visiting the state which was already visited. class GraphP...
def run_agent(self): ''' The child class is created in order to override the value method which will take into account previous states of the agent. The reward function is made exponential rather than linear, which decreases the probability of agent visiting the state which was already v...
Python
nomic_cornstack_python_v1
function test_FEMM_periodicity_angle begin set SPMSM_015 = load join DATA_DIR string Machine string SPMSM_015.json assert call comp_periodicity == tuple 9 false 9 true set simu = call Simu1 name=string test_FEMM_periodicity_angle machine=SPMSM_015 comment Definition of the enforced output of the electrical module set I...
def test_FEMM_periodicity_angle(): SPMSM_015 = load(join(DATA_DIR, "Machine", "SPMSM_015.json")) assert SPMSM_015.comp_periodicity() == (9, False, 9, True) simu = Simu1(name="test_FEMM_periodicity_angle", machine=SPMSM_015) # Definition of the enforced output of the electrical module I0_rms = 25...
Python
nomic_cornstack_python_v1
for afkorting in keys week begin print format string Afkorting: {}, lange naam: {} afkorting week at afkorting end
for afkorting in week.keys(): print('Afkorting: {}, lange naam: {}'.format(afkorting, week[afkorting]))
Python
zaydzuhri_stack_edu_python
import wx import threading , os , time import Queue class Note begin function __init__ self begin set sender = string set receiver = string set type = string set message = string end function end class class Node extends Thread begin set modules = dict function __init__ self begin set inNoteQueue = queue set modul...
import wx import threading, os, time import Queue class Note(): def __init__(self): self.sender = "" self.receiver = "" self.type = "" self.message = "" class Node(threading.Thread): modules = {} def __init__(self): self.inNoteQueue = Queue.Queue() sel...
Python
zaydzuhri_stack_edu_python
function list2consistent_hash lst begin set bstr = dumps sorted lst return hex digest sha256 bstr end function
def list2consistent_hash(lst): bstr = pickle.dumps(sorted(lst)) return sha256(bstr).hexdigest()
Python
nomic_cornstack_python_v1
function get_client_for_host host begin set backend_name = call extract_host host level=string backend_name set client = call get_client_for_backend backend_name return client end function
def get_client_for_host(host): backend_name = share_utils.extract_host(host, level='backend_name') client = get_client_for_backend(backend_name) return client
Python
nomic_cornstack_python_v1
comment Load libraries import matplotlib.pyplot as plt import seaborn as sns from sklearn import datasets from sklearn.linear_model import LogisticRegression from sklearn.model_selection import train_test_split from sklearn.metrics import confusion_matrix import pandas as pd comment Load data set iris = call load_iris ...
# Load libraries import matplotlib.pyplot as plt import seaborn as sns from sklearn import datasets from sklearn.linear_model import LogisticRegression from sklearn.model_selection import train_test_split from sklearn.metrics import confusion_matrix import pandas as pd # Load data iris = datasets.load_iris() # Create f...
Python
zaydzuhri_stack_edu_python
import unittest from builtins import staticmethod from main import Main from logger import LoggerFake import time class TestClass begin pass end class class Testing extends TestCase begin function test_passing_3p_4produts_2c_4length_return_not_empty_estructure self begin set qtdP = 3 set qtdV = 4 set qtdC = 2 set n = 4...
import unittest from builtins import staticmethod from main import Main from logger import LoggerFake import time class TestClass: pass class Testing(unittest.TestCase): def test_passing_3p_4produts_2c_4length_return_not_empty_estructure(self): qtdP = 3 qtdV = 4 qtdC = 2 n ...
Python
zaydzuhri_stack_edu_python
function undo_reveal self begin set is_revealed = false update self call emit self end function
def undo_reveal(self): self.is_revealed = False self.update() self.revealed.emit(self)
Python
nomic_cornstack_python_v1
function point_to_follow state path sigma_range sigma_bearing begin if state at 0 in path begin set track = path at state at 0 end else begin set track = path at min keys path key=lambda k -> absolute k - state at 0 end set point_to_track = list state at 0 track set dist_head = call distance_to point_to_track state sig...
def point_to_follow(state,path,sigma_range,sigma_bearing): if state[0] in path: track = path[state[0]] else: track = path[min(path.keys(),key=lambda k: abs(k-state[0]))] point_to_track = [state[0],track] dist_head = distance_to(point_to_track,state,sigma_range,sigma_bearing) """...
Python
nomic_cornstack_python_v1
function setUp self begin set adapter = call PostgresAdapter string 127.0.0.1 string postgres end function
def setUp(self): self.adapter = PostgresAdapter('127.0.0.1', 'postgres')
Python
nomic_cornstack_python_v1
from karel.stanfordkarel import * string File: Archway.py ------------------------------ Karel will move up and over the archway. function main begin string You should write your code to make Karel do its task in this function. Make sure to delete the 'pass' line before starting to write your own code. You should also ...
from karel.stanfordkarel import * """ File: Archway.py ------------------------------ Karel will move up and over the archway. """ def main(): """ You should write your code to make Karel do its task in this function. Make sure to delete the 'pass' line before starting to write your own ...
Python
zaydzuhri_stack_edu_python
function push_sample_secondary self ch timep value use_lock=true begin if use_lock begin acquire lock_secondary at ch end set channel_data_secondary at ch at wptr_secondary at ch = value set time_array_secondary at ch at wptr_secondary at ch = timep set wptr_secondary at ch = wptr_secondary at ch + 1 if 0 == buffer_ful...
def push_sample_secondary(self, ch, timep, value, use_lock=True): if use_lock: self.lock_secondary[ch].acquire() self.channel_data_secondary[ch][self.wptr_secondary[ch]] = value self.time_array_secondary[ch][self.wptr_secondary[ch]] = timep self.wptr_secondary[ch] += 1 ...
Python
nomic_cornstack_python_v1
function send_music self user_id url hq_url thumb_media_id title=none description=none account=none begin string 发送音乐消息 详情请参考 http://mp.weixin.qq.com/wiki/7/12a5a320ae96fecdf0e15cb06123de9f.html :param user_id: 用户 ID 。 就是你收到的 `Message` 的 source :param url: 音乐链接 :param hq_url: 高品质音乐链接,wifi环境优先使用该链接播放音乐 :param thumb_medi...
def send_music(self, user_id, url, hq_url, thumb_media_id, title=None, description=None, account=None): """ 发送音乐消息 详情请参考 http://mp.weixin.qq.com/wiki/7/12a5a320ae96fecdf0e15cb06123de9f.html :param user_id: 用户 ID 。 就是你收到的 `Message` 的 source :param url:...
Python
jtatman_500k
try begin set x = a / b end except Exception as e begin print e end
try: x=a/b except Exception as e: print(e)
Python
zaydzuhri_stack_edu_python
function test_all begin for step in test_steps begin if callable step begin step end else begin set test = partial *tuple([run_test] + list(step[1:])) set description = step at 0 yield test end end end function
def test_all(): for step in test_steps: if callable(step): step() else: test = partial(*tuple([run_test] + list(step[1:]))) test.description = step[0] yield test
Python
nomic_cornstack_python_v1
import pandas import tensorflow from tensorflow.contrib.learn.python.learn.preprocessing import text from tensorflow.contrib.learn.python.learn.preprocessing import CategoricalVocabulary function vectorize_using_tensor_flow texts begin comment Based off of text classification example from tensorflow comment https://git...
import pandas import tensorflow from tensorflow.contrib.learn.python.learn.preprocessing import text from tensorflow.contrib.learn.python.learn.preprocessing import CategoricalVocabulary def vectorize_using_tensor_flow(texts): # Based off of text classification example from tensorflow # https://github.com/ten...
Python
zaydzuhri_stack_edu_python
function ComsolUtil version rebuild begin set progid = call _build_progid objtype=string comsolutil version=version try begin set cu = call Dispatch dispatch=progid end except com_error begin raise call VersionError format string Couldn't find COM interface of COMSOL version {!r}. Please check if the requested version ...
def ComsolUtil(version, rebuild): progid = _build_progid(objtype="comsolutil", version=version) try: cu = win32com.client.Dispatch(dispatch=progid) except pythoncom.com_error: raise error.VersionError( "Couldn't find COM interface of COMSOL version {!r}. Please " "che...
Python
nomic_cornstack_python_v1
function layout_batch self begin set rb_single_mode = call RadioButton self - 1 string Single Mode style=RB_GROUP set rb_batch_mode = call RadioButton self - 1 string Batch Mode call Bind EVT_RADIOBUTTON on_single_mode id=call GetId call Bind EVT_RADIOBUTTON on_batch_mode id=call GetId call SetValue not batch_on call S...
def layout_batch(self): self.rb_single_mode = wx.RadioButton(self, -1, 'Single Mode', style=wx.RB_GROUP) self.rb_batch_mode = wx.RadioButton(self, -1, 'Batch Mode') self.Bind(wx.EVT_RADIOBUTTON, self.on_single_mode, id=self.rb_single...
Python
nomic_cornstack_python_v1
function to_structure self begin if _structure is not none begin return _structure end set tuple atoms use_etkdg = tuple atoms use_etkdg set fixed_atoms = list for atom_id in keys fixed_atoms begin if atom_id in _id_to_index begin append fixed_atoms _id_to_index at atom_id end end set tuple bonds improper_ics = tuple ...
def to_structure(self) -> Structure: if self._structure is not None: return self._structure atoms, use_etkdg = self.atoms, self.use_etkdg fixed_atoms = [] for atom_id in self.fixed_atoms.keys(): if atom_id in self._id_to_index: fixed_atoms.append(s...
Python
nomic_cornstack_python_v1
function get_template template_name values begin try begin set values at string ORG_CODE = config at string ORG_CODE set values at string ORG_NAME = config at string ORG_NAME set values at string ORG_LOGO = config at string ORG_LOGO set values at string APP_BASE_URL = config at string APP_BASE_URL return call render_te...
def get_template(template_name: str, values: dict) -> str: try: values["ORG_CODE"] = current_app.config["ORG_CODE"] values["ORG_NAME"] = current_app.config["ORG_NAME"] values["ORG_LOGO"] = current_app.config["ORG_LOGO"] values["APP_BASE_URL"] = current_app.config["APP_BASE_URL"] ...
Python
nomic_cornstack_python_v1
import numpy as np import matplotlib.pyplot as plt comment load data set x = list set y = list for line in open string data_1d.csv begin set tuple xi yi = split line string , comment print(xi) append x decimal xi append y decimal yi end comment turn into numpy arrays set x = array x set y = array y comment plot raw d...
import numpy as np import matplotlib.pyplot as plt # load data x=[] y=[] for line in open('data_1d.csv'): xi,yi = line.split(',') #print(xi) x.append(float(xi)) y.append(float(yi)) # turn into numpy arrays x = np.array(x) y = np.array(y) # plot raw data plt.scatter(x,y) #plt.show() # calculate a a...
Python
zaydzuhri_stack_edu_python
function delete_nuspec_files cls target platform configuration cpu f_type=list string .dll string .pri begin try begin string in order for update to work nuspec must not have xmlns="..." inside the package tag, otherwise files tag will not be found set nuspecName = target + string .nuspec with open nuspecName string rb...
def delete_nuspec_files(cls, target, platform, configuration, cpu, f_type=['.dll', '.pri']): try: """ in order for update to work nuspec must not have xmlns="..." inside the package tag, otherwise files tag will not be found """ nuspecName = target +...
Python
nomic_cornstack_python_v1
comment !/usr/bin/env python3 import os from time import sleep import signal import sys import subprocess import RPi.GPIO as GPIO from tkinter import * import Adafruit_GPIO.SPI as SPI import Adafruit_SSD1306 from PIL import Image from PIL import ImageDraw from PIL import ImageFont comment Fan Pin set fan_pin = 18 comme...
#!/usr/bin/env python3 import os from time import sleep import signal import sys import subprocess import RPi.GPIO as GPIO from tkinter import * import Adafruit_GPIO.SPI as SPI import Adafruit_SSD1306 from PIL import Image from PIL import ImageDraw from PIL import ImageFont fan_pin = 18 # Fan Pin maxTMP = 29 # Max...
Python
zaydzuhri_stack_edu_python
function refund_transaction self transaction payment_method=none begin raise NotImplementedError end function
def refund_transaction(self, transaction, payment_method=None): raise NotImplementedError
Python
nomic_cornstack_python_v1
class Solution begin function __init__ self begin set spin_words = spin_words_01 end function function spin_words_01 self sentence begin set word_lst = list for word in split sentence string begin if length word >= 5 begin append word_lst word at slice : : - 1 end else begin append word_lst word end end return join ...
class Solution(): def __init__(self): self.spin_words = self.spin_words_01 def spin_words_01(self, sentence): word_lst = [] for word in sentence.split(' '): if len(word) >= 5: word_lst.append(word[::-1]) else: word_lst.append(word)...
Python
zaydzuhri_stack_edu_python
comment template for "Guess the number" mini-project comment input will come from buttons and an input field comment all output for the game will be printed in the console import simplegui import random import math set remaining = 7 set range = 100 comment helper function to start and restart the game function new_game...
## template for "Guess the number" mini-project # input will come from buttons and an input field # all output for the game will be printed in the console import simplegui import random import math remaining = 7 range = 100 # helper function to start and restart the game def new_game(): # initialize global varia...
Python
zaydzuhri_stack_edu_python
import forecastio import pylab as pyl import numpy as np set api_key = string fd836b581d833e547d33c1a609f923af set lat = zeros 4 set lng = zeros 4 comment Arlington, TX set lat at 0 = 32.7355556 set lng at 0 = - 97.1077778 comment San Fransico, CA set lat at 1 = 37.773972 set lng at 1 = - 122.431297 comment Des Moines,...
import forecastio import pylab as pyl import numpy as np api_key = "fd836b581d833e547d33c1a609f923af" lat = np.zeros(4) lng = np.zeros(4) lat[0] = 32.7355556 #Arlington, TX lng[0] = -97.1077778 lat[1] = 37.773972 #San Fransico, CA lng[1] = -122.431297 lat[2] = 41.6005556 #Des Moines, IA lng[2] = -93.60888...
Python
zaydzuhri_stack_edu_python
function test_create_weight_type self begin comment DEFINE WEIGHT TYPE PROPERTIES set url = string /weight_types set data = dict string user_id 1 ; string type string DVDs ; string percentage 0.75 comment Make sure request is authenticated call credentials HTTP_AUTHORIZATION=string Token + token comment Initiate reques...
def test_create_weight_type(self): # DEFINE WEIGHT TYPE PROPERTIES url = "/weight_types" data = { "user_id": 1, "type": "DVDs", "percentage": 0.75 } # Make sure request is authenticated self.client.credentials(HTTP_AUTHORIZATION='Token...
Python
nomic_cornstack_python_v1
comment noqa # will be okay after removing old method function get_short_species_abbreviation self taxon_id begin set short_species_abbreviation = string Alliance try begin set short_species_abbreviation = call get_short_name taxon_id end except KeyError begin critical string Problem looking up short species name for %...
def get_short_species_abbreviation(self, taxon_id): # noqa # will be okay after removing old method short_species_abbreviation = 'Alliance' try: short_species_abbreviation = self.rdh2.get_short_name(taxon_id) except KeyError: self.logger.critical("Problem looking up sho...
Python
nomic_cornstack_python_v1