code
stringlengths
10
2.58M
original_code
stringlengths
3
3.18M
original_language
stringclasses
1 value
source
stringclasses
7 values
import numpy as np from scipy.integrate import quad import matplotlib.pyplot as plt function E z begin return 0.28 * 1 + z ^ 3 + 0.72 ^ 0.5 end function function func z begin return 1.0 / 1 + z * call E z end function set tH = 13.6 set zs = linear space 0 20 100 set tL = list for z in zs begin append tL tH * call quad...
import numpy as np from scipy.integrate import quad import matplotlib.pyplot as plt def E(z): return (.28*(1+z)**3+.72)**(.5) def func(z): return (1./((1+z)*E(z))) tH = 13.6 zs = np.linspace(0,20,100) tL = [] for z in zs: tL.append(tH*quad(func,0,z)[0]) plt.plot(zs,tL) plt.xlabel('Z (R...
Python
zaydzuhri_stack_edu_python
try begin set money = integer input string Enter store money: if money > 0 begin set balance = balance + money if money >= 1000 begin set bonus = bonus + 1 end end else begin print string 你這不是叫我扣你款嗎 兄弟 end end except any begin print string Valid input value bro!!! end print string After print string Number: %s, Balance...
try: money = int(input('Enter store money: ')) if money > 0: balance += money if money >= 1000: bonus += 1 else : print('你這不是叫我扣你款嗎 兄弟') except: print('Valid input value bro!!!') print('After') print('Number: %s, Balance: %d, Bonus: %d ' % (number, balance, ...
Python
zaydzuhri_stack_edu_python
function check_correct_answer message begin if channel != channel begin return false end set msg_lower = lower content if msg_lower == lower correct_answer begin return true end if id == host_id begin return msg_lower in stop_phrases or msg_lower in skip_phrases end end function
def check_correct_answer(message): if message.channel != self.channel: return False msg_lower = message.content.lower() if msg_lower == self.correct_answer.lower(): return True if message.author.id == self.host_id: return (m...
Python
nomic_cornstack_python_v1
class UppercaseException extends Exception begin pass end class set words = list string enee string meene string miny string MO for word in words begin if is upper word begin raise call UppercaseException word end end
class UppercaseException(Exception): pass words = ['enee', 'meene', 'miny', 'MO'] for word in words: if word.isupper(): raise UppercaseException(word)
Python
zaydzuhri_stack_edu_python
function create_dir directory begin make directories directory exist_ok=true end function
def create_dir(directory): os.makedirs(directory, exist_ok=True)
Python
nomic_cornstack_python_v1
class Stream begin string A lazily computed linked list. class empty begin function __repr__ self begin return string Stream.empty end function end class set empty = call empty function __init__ self first compute_rest=lambda -> empty begin assert callable compute_rest msg string compute_rest must be callable. set fir...
class Stream: """A lazily computed linked list.""" class empty: def __repr__(self): return 'Stream.empty' empty = empty() def __init__(self, first, compute_rest=lambda: empty): assert callable(compute_rest), 'compute_rest must be callable.' ...
Python
zaydzuhri_stack_edu_python
function _momentum candle record=none begin if candle at string freq != string 5m begin return none end set periods = rules at string z-score at string periods set z = call z_score candle periods set ema = call ema_pct_change candle set client = call Client string string set ob = call get_orderbook_ticker symbol=candl...
def _momentum(candle, record=None): if candle['freq'] != '5m': return None periods = rules['z-score']['periods'] z = signals.z_score(candle, periods) ema = signals.ema_pct_change(candle) client = Client("","") ob = client.get_orderbook_ticker(symbol=candle['pair']) snapshot = { ...
Python
nomic_cornstack_python_v1
function clamp value lower upper begin return max lower min upper value end function
def clamp(value, lower, upper): return max(lower, min(upper, value))
Python
nomic_cornstack_python_v1
function trio_as_aio proc loop=none begin return call Trio_Asyncio_Wrapper proc loop=loop end function
def trio_as_aio(proc, *, loop=None): return Trio_Asyncio_Wrapper(proc, loop=loop)
Python
nomic_cornstack_python_v1
if n > 0 begin set nes = list generator expression integer i for i in split input for i in nes begin set p at i = i * count nes i / length nes end end if sum values p != 0 begin print string { sum nes / n / sum values p } end else begin print string divide by zero end
if n > 0: nes = list(int(i) for i in input().split()) for i in nes: p[i] = (i*(nes.count(i)/len(nes))) if sum(p.values()) != 0: print(f"{sum(nes)/n/sum(p.values()):0.2f}") else: print("divide by zero")
Python
zaydzuhri_stack_edu_python
import os import subprocess import dbus import re import sys function getPID begin string Determines if a supported music player is currently running set processes = decode check output string ps -A shell=true set software_list = list string banshee string rhythmbox set process_exists = false set player = none for soft...
import os import subprocess import dbus import re import sys def getPID(): """Determines if a supported music player is currently running""" processes = subprocess.check_output('ps -A', shell=True).decode() software_list = ['banshee', 'rhythmbox'] process_exists = False player = None for software in software_lis...
Python
zaydzuhri_stack_edu_python
while true begin print string Hi! My name is Travis. print string What is your name? set name = capitalize strip input string --> print format string Thank you {}! name if name in known_users begin print format string Hello {}! name print string Would you like to be removed from our system (y/n)? set remove = lower str...
while True: print("Hi! My name is Travis.") print("What is your name?") name = input("-->").strip().capitalize() print("Thank you {}!".format(name)) if name in known_users: print("Hello {}!".format(name)) print("Would you like to be removed from our system (y/n)?") remove = ...
Python
zaydzuhri_stack_edu_python
function needs_update_check_modify_time self *unnamed_args **named_args begin set tuple it task = call get_param_iterator *unnamed_args keyword named_args comment print >> sys.stderr, [p for (p, param2) in it(None)], "??" return list comprehension call needs_update_check_modify_time *p task=task job_history=call open_j...
def needs_update_check_modify_time(self, *unnamed_args, **named_args): it, task = self.get_param_iterator(*unnamed_args, **named_args) #print >> sys.stderr, [p for (p, param2) in it(None)], "??" return [needs_update_check_modify_time(*p, task=task, ...
Python
nomic_cornstack_python_v1
comment !/usr/bin/env python import pandas , sys , os string Takes in an output folder of files from MDSeq where DV genes are ranked by padj from least to greatest and then outputs a trimmed file where there are no genes with padj > 0.05 in the same directory as the input USAGE: trim_SDV.py <DeSeq_out_dirName> Updated ...
#!/usr/bin/env python import pandas, sys, os """ Takes in an output folder of files from MDSeq where DV genes are ranked by padj from least to greatest and then outputs a trimmed file where there are no genes with padj > 0.05 in the same directory as the input USAGE: trim_SDV.py <DeSeq_out_dirName> Updated 180522 ...
Python
zaydzuhri_stack_edu_python
function cnt_pairs_wirth_diff_g_t_k sorted_nums k begin set cnt_pairs = 0 set last = 0 for first in range length sorted_nums begin while last < length sorted_nums and sorted_nums at last - sorted_nums at first <= k begin set last = last + 1 end set cnt_pairs = cnt_pairs + length sorted_nums - last end return cnt_pairs ...
def cnt_pairs_wirth_diff_g_t_k(sorted_nums, k): cnt_pairs = 0 last = 0 for first in range(len(sorted_nums)): while last < len(sorted_nums) and sorted_nums[last] - sorted_nums[first] <= k: last += 1 cnt_pairs += len(sorted_nums) - last return cnt_pairs print(cnt_pairs_wirth_...
Python
zaydzuhri_stack_edu_python
function compare_dictionaries d1 d2 begin for key in d1 begin if key not in d2 or d1 at key != d2 at key begin return false end end return true end function
def compare_dictionaries(d1, d2): for key in d1: if key not in d2 or d1[key] != d2[key]: return False return True
Python
jtatman_500k
for i in s begin if i == string 0 begin set ans = ans + string 0 end else if i == string 1 begin set ans = ans + string 1 end else if ans != string begin set ans = ans at slice : length ans - 1 : end end print ans
for i in s: if i == '0': ans += '0' elif i == '1': ans += '1' elif ans != '': ans = ans[:len(ans) - 1] print(ans)
Python
zaydzuhri_stack_edu_python
string 1. На улице встретились N друзей. Каждый пожал руку всем остальным друзьям (по одному разу). Сколько рукопожатий было? Примечание. Решите задачу при помощи построения графа. Принцип. Строим граф друзей. Создаем словарь, в котором ключ - номер друга, а значание - номера друзей, с которыми здоровался и дополнитель...
""" 1. На улице встретились N друзей. Каждый пожал руку всем остальным друзьям (по одному разу). Сколько рукопожатий было? Примечание. Решите задачу при помощи построения графа. Принцип. Строим граф друзей. Создаем словарь, в котором ключ - номер друга, а значание - номера друзей, с которыми здоровался и дополнительно...
Python
zaydzuhri_stack_edu_python
import pandas as pd from funcionalidades.testaEntrada import procuraTabela , testaEntrada function infHospitais df begin while true begin set exec = upper input string Informe o nome do executante: comment testa se o usuário digitou algo ou deu uma entrada com números if call testaEntrada exec begin break end end set f...
import pandas as pd from funcionalidades.testaEntrada import procuraTabela, testaEntrada def infHospitais(df): while True: exec = input('Informe o nome do executante: ').upper() if(testaEntrada(exec)): # testa se o usuário digitou algo ou deu uma entrada com números break fina...
Python
zaydzuhri_stack_edu_python
function dL_dtheta self begin set dL_dtheta = call dK_dtheta dL_dKmm Z if has_uncertain_inputs begin set dL_dtheta = dL_dtheta + call dpsi0_dtheta dL_dpsi0 Z X X_variance set dL_dtheta = dL_dtheta + call dpsi1_dtheta dL_dpsi1 Z X X_variance set dL_dtheta = dL_dtheta + call dpsi2_dtheta dL_dpsi2 Z X X_variance end else ...
def dL_dtheta(self): dL_dtheta = self.kern.dK_dtheta(self.dL_dKmm, self.Z) if self.has_uncertain_inputs: dL_dtheta += self.kern.dpsi0_dtheta(self.dL_dpsi0, self.Z, self.X, self.X_variance) dL_dtheta += self.kern.dpsi1_dtheta(self.dL_dpsi1, self.Z, self.X, self.X_variance) ...
Python
nomic_cornstack_python_v1
comment !/bin/python3 function main begin set buffersize = 10 set infile = open string lines.txt string rb set outfile = open string binary-copy.tmp string wb set buffer = read infile buffersize while length buffer begin write outfile buffer set buffer = read infile buffersize end print string Done. end function if __n...
#!/bin/python3 def main(): buffersize = 10 infile = open('lines.txt', 'rb') outfile = open('binary-copy.tmp', 'wb') buffer = infile.read(buffersize) while len(buffer): outfile.write(buffer) buffer = infile.read(buffersize) print('Done.') if __name__ == "__main__": main()
Python
zaydzuhri_stack_edu_python
function orden_string tekst begin set antw = string while tekst != string begin set kleinste = tekst at 0 set teller = 1 set plaats = 0 while teller < length tekst begin if kleinste > tekst at teller begin set kleinste = tekst at teller set plaats = teller end set teller = teller + 1 end set antw = antw + kleinste se...
def orden_string(tekst): antw = "" while tekst != "": kleinste = tekst[0] teller = 1 plaats = 0 while teller < len(tekst): if kleinste > tekst[teller]: kleinste = tekst[teller] plaats = teller teller += 1 antw += kle...
Python
zaydzuhri_stack_edu_python
comment !/usr/bin/env python3 comment -*- coding: utf-8 -*- from __future__ import print_function import numpy as np class CM begin function __init__ self num_visible num_hidden begin set num_hidden = num_hidden set num_visible = num_visible set debug_print = true string Inicialice una matriz de peso, de dimensiones (n...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- from __future__ import print_function import numpy as np class CM: def __init__(self, num_visible, num_hidden): self.num_hidden = num_hidden self.num_visible = num_visible self.debug_print = True """ Inicialice una ma...
Python
zaydzuhri_stack_edu_python
function locale_id self begin return get pulumi self string locale_id end function
def locale_id(self) -> pulumi.Input[str]: return pulumi.get(self, "locale_id")
Python
nomic_cornstack_python_v1
import unittest import sys insert path 0 string ../src from IVehicle import IVehicle , VEHICLE_TYPE from Car import Car from Truck import Truck class TestTruck extends TestCase begin set truck = call Truck 55 set truck2 = call Truck 70 function test_max_speed self begin assert equal call max_speed 55 assert not equal c...
import unittest import sys sys.path.insert(0, '../src') from IVehicle import IVehicle, VEHICLE_TYPE from Car import Car from Truck import Truck class TestTruck(unittest.TestCase): truck = Truck(55) truck2 = Truck(70) def test_max_speed(self): self.assertEqual(self.truck.max_speed(), 55) s...
Python
zaydzuhri_stack_edu_python
function example_single args model word2idx begin comment 在命令行中加载和分段<目标、(推特内容)>配对 while true begin set target = call raw_input string 问题: set tweet = call raw_input string 回答: set targets = list string target set tweets = list string tweet comment may use lexicon here set seged_tweets = call seg_sentence tweets choice=...
def example_single(args, model, word2idx): #在命令行中加载和分段<目标、(推特内容)>配对 while True: target = raw_input("问题: ") tweet = raw_input("回答: ") targets = [str(target)] tweets = [str(tweet)] seged_tweets = yutils.seg_sentence(tweets, choice="list", place="hpc") # may use lexicon her...
Python
nomic_cornstack_python_v1
function get_contributors org_list begin print string Creating list of contributors. set jsonContributor_list = list set graph = call DiGraph set columns_list = list string organization string repository string login string contributions string html_url string url for org in org_list begin print string Scraping contri...
def get_contributors(org_list): print("\nCreating list of contributors.") jsonContributor_list = [] graph = nx.DiGraph() columns_list = [ 'organization', 'repository', 'login', 'contributions', 'html_url'...
Python
nomic_cornstack_python_v1
import re with open string ./blocklist.xml as f begin for line in read lines f begin set pattern_1 = string blockID="i.+\d".+?\n|blockID="g.+\d".+?\n if search pattern_1 line begin print line end end end
import re with open('./blocklist.xml') as f: for line in f.readlines(): pattern_1 = r'blockID="i.+\d".+?\n|blockID="g.+\d".+?\n' if re.search(pattern_1, line): print(line)
Python
zaydzuhri_stack_edu_python
import time from selenium import webdriver from selenium.webdriver.chrome.options import Options set chrome_options = options call add_argument string --headless set driver = call Chrome options=chrome_options call set_window_size 1900 1900 get driver string https://docs.google.com/spreadsheets/d/12-P5XcVUfZ-jeSKt8btAg...
import time from selenium import webdriver from selenium.webdriver.chrome.options import Options chrome_options = Options() chrome_options.add_argument("--headless") driver = webdriver.Chrome(options=chrome_options) driver.set_window_size(1900,1900) driver.get('https://docs.google.com/spreadsheets/d/12-P5XcVUfZ-jeSKt...
Python
zaydzuhri_stack_edu_python
import random function draw_card begin set cards = list string A 2 3 4 5 6 7 8 9 string J string Q string K set i = random integer 0 length cards - 1 return cards at i end function function print_card card_hand begin set hand = string for card in card_hand begin set hand = hand + string [ + string card + string ], end...
import random def draw_card(): cards = ['A', 2, 3, 4, 5, 6, 7, 8, 9, 'J', 'Q', 'K'] i = random.randint(0, len(cards) - 1) return cards[i] def print_card(card_hand): hand = '' for card in card_hand: hand += "[" + str(card) + "]," return hand def calculate_score(card_...
Python
zaydzuhri_stack_edu_python
class Computer begin function __init__ self begin set __maxprice = 600 end function comment print ("From constructor",self.__maxprice) function sell self begin print format string Selling Price is {} from sell method __maxprice end function function setmaxprice self price begin set __maxprice = price end function end c...
class Computer: def __init__(self): self.__maxprice = 600 # print ("From constructor",self.__maxprice) def sell(self): print ("Selling Price is {} from sell method".format(self.__maxprice)) def setmaxprice(self,price): self.__maxprice=price # print ("it is set {} ...
Python
zaydzuhri_stack_edu_python
function rotate_anaconda_token user project feedstock_config_path drone=true circle=true travis=true azure=true appveyor=true github_actions=true token_name=string BINSTAR_TOKEN drone_endpoints=tuple begin comment we are swallong all of the logs below, so we do a test import here comment to generate the proper errors f...
def rotate_anaconda_token( user, project, feedstock_config_path, drone=True, circle=True, travis=True, azure=True, appveyor=True, github_actions=True, token_name="BINSTAR_TOKEN", drone_endpoints=(), ): # we are swallong all of the logs below, so we do a test import here ...
Python
nomic_cornstack_python_v1
function get_urls self begin for api in INSTALLED_HANDLERS begin call import_string api + string .__name__ end set urlpatterns = list for tuple module param in items _registry begin set m = call import_string module for p in param begin set tuple func name regex params headers desc display = tuple p at string view p a...
def get_urls(self): for api in settings.INSTALLED_HANDLERS: import_string(api + '.__name__') urlpatterns = [] for module, param in self._registry.items(): m = import_string(module) for p in param: func, name, regex, params, headers, desc, disp...
Python
nomic_cornstack_python_v1
comment el %r hara que salga tan cual la forma real puesta entre comillas set formatter = string %r %r %r %r comment hay que poner 4 elementos porque en la variable hemos puesto 4 en la cadena, sino nos saldria %r
# el %r hara que salga tan cual la forma real puesta entre comillas formatter = "%r %r %r %r" #hay que poner 4 elementos porque en la variable hemos puesto 4 en la cadena, sino nos saldria %r
Python
zaydzuhri_stack_edu_python
comment CGPA calculator. comment assigning weight to grades set tuple A B C D E F = tuple 5 4 3 2 1 0 comment for first semester comment collecting grade and unit from user set English = eval upper input string please input your grade in English: set Maths = eval upper input string please input your grade in maths: set...
#CGPA calculator. #assigning weight to grades A, B, C, D, E, F = 5, 4, 3, 2, 1, 0 #for first semester #collecting grade and unit from user English = eval(input("please input your grade in English: ").upper()) Maths = eval(input("please input your grade in maths: ").upper()) Physics = eval(input("please input y...
Python
zaydzuhri_stack_edu_python
function subj_corr_comparison subj1 subj2 data_dir save_dir opacity=0.6 save_fig=true begin set fig = figure figsize=tuple 15 9 set ax = call subplots plot list 0.0 0.16 list 0.0 0.16 string black label=string unity set plot_color = string #2278B5 set corrs = list with call File string %s/%s/%s_STRF_by_binned_pitches_...
def subj_corr_comparison(subj1, subj2, data_dir, save_dir, opacity = 0.6, save_fig=True): fig = plt.figure(figsize=(15,9)) ax = fig.subplots() plt.plot([0.0, 0.16], [0.0, 0.16], 'black', label='unity') plot_color = '#2278B5' corrs = [] with h5py.File('%s/%s/%s_STRF_by_binned_pitches_MT.hf5'% (data_dir, subj1, su...
Python
nomic_cornstack_python_v1
function test_repr self begin add sample_list string Apple Pie string As American as... 6000 set repr_test = string <Dessert, id=1, name="Apple Pie", calories=6000> assert equal call repr sample_list repr_test end function
def test_repr(self): self.sample_list.add("Apple Pie", "As American as...", 6000) repr_test = "<Dessert, id=1, name=\"Apple Pie\", calories=6000>\n" self.assertEqual(repr(self.sample_list), repr_test)
Python
nomic_cornstack_python_v1
from gpiozero import Button import tts import time comment - create our buttons set b1 = call Button 5 pull_up=true comment - button press event callbacks function pressed_b1 begin call speak string ouch. that hurt. end function comment - register callbacks with button set when_pressed = pressed_b1 comment - main loop....
from gpiozero import Button import tts import time # - create our buttons b1 = Button(5, pull_up=True) # - button press event callbacks def pressed_b1() : tts.speak("ouch. that hurt.") # - register callbacks with button b1.when_pressed = pressed_b1 # - main loop. just sleep to keep program alive while True: time....
Python
zaydzuhri_stack_edu_python
import json import numpy as np from inqbus.graphdemo.constants import SPECIAL_JS_TYPES function get_binary_and_json_metadata_for_attr attribute data begin string Create metadata and binary data for binary protocoll :param data: data which should be stored in the attribute :param attribute: name/path of the attribute in...
import json import numpy as np from inqbus.graphdemo.constants import SPECIAL_JS_TYPES def get_binary_and_json_metadata_for_attr(attribute, data): """ Create metadata and binary data for binary protocoll :param data: data which should be stored in the attribute :param attribute: name/path of the attr...
Python
zaydzuhri_stack_edu_python
comment !/usr/bin/env python comment coding: utf-8 comment In[1]: import argparse import imutils import time import cv2 import os from imutils.video import VideoStream import numpy as np set ap = call ArgumentParser comment --cascade :The path to the Haar cascade file on disk comment --output :The path to the output di...
#!/usr/bin/env python # coding: utf-8 # In[1]: import argparse import imutils import time import cv2 import os from imutils.video import VideoStream import numpy as np ap = argparse.ArgumentParser() ##--cascade :The path to the Haar cascade file on disk ##--output :The path to the output directory. Images of faces...
Python
zaydzuhri_stack_edu_python
function max_subarray array begin if length array == 0 begin return 0 end else begin set curr_so_far = array at 0 set max_so_far = curr_so_far for i in range 1 length array begin if curr_so_far < 0 and array at i >= 0 begin set curr_so_far = array at i set max_so_far = max max_so_far curr_so_far end else begin set curr...
def max_subarray(array): if len(array) == 0: return 0 else: curr_so_far = array[0] max_so_far = curr_so_far for i in range(1, len(array)): if curr_so_far < 0 and array[i] >= 0: curr_so_far = array[i] max_so_far = max(max_so_far, curr_so_far) else: curr_so_far = curr_so_far + array...
Python
zaydzuhri_stack_edu_python
function test_login app begin set res = call login app string testuser string somepassword assert status_code == 200 end function
def test_login(app): res = login(app, 'testuser', 'somepassword') assert res.status_code == 200
Python
nomic_cornstack_python_v1
function forward self x begin set orig_type = dtype set ret = call forward type float32 return type orig_type end function
def forward(self, x: torch.Tensor) -> torch.Tensor: orig_type = x.dtype ret = super().forward(x.type(torch.float32)) return ret.type(orig_type)
Python
nomic_cornstack_python_v1
string Duo Ma CS5001 Fall 2020 Homework#8 Ciphers Part 1 this is a program to test if the caesar cipher program works fine from caesar import encrypt from caesar import decrypt function test_encrypt plaintext key expected begin string name: test_encrypt parameter: plaintext (string), key(an integer), another string(exp...
''' Duo Ma CS5001 Fall 2020 Homework#8 Ciphers Part 1 this is a program to test if the caesar cipher program works fine ''' from caesar import encrypt from caesar import decrypt def test_encrypt(plaintext, key, expected): ''' name: test_encrypt parameter: plaintext (string), key(an integer), another str...
Python
zaydzuhri_stack_edu_python
function agg_relworks self begin for record in records begin if string RelatedWorks not in record begin continue end set isbn = record at string ISBN13 set current_idx = isbn13_to_index at isbn set manifestations = set for relwork in record at string RelatedWorks begin if not call is_relevant_work_relation relwork begi...
def agg_relworks(self) -> List[BookWork]: for record in self.records: if "RelatedWorks" not in record: continue isbn = record["ISBN13"] current_idx = self.isbn13_to_index[isbn] manifestations = set() for relwork in record["RelatedWor...
Python
nomic_cornstack_python_v1
function test_delete_user_failure self begin set resp = post string /users/delete follow_redirects=true set html = call get_data as_text=true assert equal status_code 200 assert in string id="not-logged-in-message" html assert in string Access unauthorized. html end function
def test_delete_user_failure(self): resp = self.client.post("/users/delete", follow_redirects=True) html = resp.get_data(as_text=True) self.assertEqual(resp.status_code, 200) self.assertIn('id="not-logged-in-message"', html) self.assertIn("Access unauthorized.", html)
Python
nomic_cornstack_python_v1
function save_iptables rules_file=string /etc/sysconfig/iptables begin string Saves iptables rules to the provided rules file :return: None :raises OSError set log = call getLogger mod_logger + string .save_iptables comment Run iptables-save to get the output set command = list string iptables-save debug string Running...
def save_iptables(rules_file='/etc/sysconfig/iptables'): """Saves iptables rules to the provided rules file :return: None :raises OSError """ log = logging.getLogger(mod_logger + '.save_iptables') # Run iptables-save to get the output command = ['iptables-save'] log.debug('Running comm...
Python
jtatman_500k
function _reduced_vega k t sigma begin set tot_std = sigma * square root t set d_plus = tot_std / 2 - k / tot_std return call _norm_pdf d_plus * square root t end function
def _reduced_vega(k, t, sigma): tot_std = sigma*sqrt(t) d_plus = tot_std/2 - k/tot_std return _norm_pdf(d_plus)*sqrt(t)
Python
nomic_cornstack_python_v1
string 列表 字典 集合 只有这三种数据类型才有推导式 comment 列表推导式 : 用一个表达式创建一个有规律的列表或控制一个有规律的列表 set list1 = list set i = 0 while i < 10 begin append list1 i set i = i + 1 end print list1 clear list1 for i in range 0 10 begin append list1 i end print list1 comment 列表推导式 set list2 = list generator expression i for i in range 10 print string...
""" 列表 字典 集合 只有这三种数据类型才有推导式 """ ####列表推导式 : 用一个表达式创建一个有规律的列表或控制一个有规律的列表 list1 = [] i = 0 while i < 10: list1.append(i) i += 1 print(list1) list1.clear() for i in range(0,10): list1.append(i) print(list1) # 列表推导式 list2 = list(i for i in range(10)) print(f"列表推导式 list2 = {list2}") list3...
Python
zaydzuhri_stack_edu_python
function split self data split_proportion begin set data = random sample frac=1 set training_data = data at slice integer split_proportion * length data : : set test_data = data at slice : integer split_proportion * length data : return tuple training_data test_data end function
def split(self, data, split_proportion): data = data.sample(frac=1) training_data = data[int(split_proportion * len(data)):] test_data = data[:int(split_proportion * len(data))] return training_data, test_data
Python
nomic_cornstack_python_v1
import base64 function str_to_base64 in_str begin string Converts a given string into its Base 64 representation. Args: in_str (str): The string to convert. Returns: str: The Base 64 representation of the string. set encoded_str = base64 encode encode in_str string utf-8 return decode encoded_str string utf-8 end funct...
import base64 def str_to_base64(in_str): """Converts a given string into its Base 64 representation. Args: in_str (str): The string to convert. Returns: str: The Base 64 representation of the string. """ encoded_str = base64.b64encode(in_str.encode("utf-8")) return encoded_str.decode("utf-8...
Python
jtatman_500k
import matplotlib.pyplot as plt import numpy as np import pandas as pd from cycler import cycler set save_name = string WT-MUT-dihedrals-X.png comment Read in data comment header = 0 reads header in first row because Python starts at 0 comment -------- System 1 set d1_a = read csv string rep1/MUT-protein-system-X-dihed...
import matplotlib.pyplot as plt import numpy as np import pandas as pd from cycler import cycler save_name = "WT-MUT-dihedrals-X.png" ## Read in data ## header = 0 reads header in first row because Python starts at 0 ## -------- System 1 d1_a = pd.read_csv('rep1/MUT-protein-system-X-dihedral.dat', \ delim_whitespace...
Python
zaydzuhri_stack_edu_python
function count_frequent_n_items transaction_dict item_count begin for items in values transaction_dict begin for subset_items in keys item_count begin if call issubset items begin set item_count at subset_items = item_count at subset_items + 1 end end end return item_count end function function prune_count item_count m...
def count_frequent_n_items(transaction_dict, item_count): for items in transaction_dict.values(): for subset_items in item_count.keys(): if subset_items.issubset(items): item_count[subset_items] += 1 return item_count def prune_count(item_count, min_support): item_coun...
Python
zaydzuhri_stack_edu_python
function allow_relation self obj1 obj2 **hints begin if app_label == appname or app_label == appname begin return true end return none end function
def allow_relation(self, obj1, obj2, **hints): if obj1._meta.app_label == self.appname or \ obj2._meta.app_label == self.appname: return True return None
Python
nomic_cornstack_python_v1
string 77 Combinations Given two integers n and k, return all possible combinations of k numbers out of 1 ... n. For example, If n = 4 and k = 2, a solution is: [ [2,4], [3,4], [2,3], [1,2], [1,3], [1,4], ] comment great solution https://leetcode.com/problems/combinations/discuss/27024/1-liner-3-liner-4-liner class Sol...
""" 77 Combinations Given two integers n and k, return all possible combinations of k numbers out of 1 ... n. For example, If n = 4 and k = 2, a solution is: [ [2,4], [3,4], [2,3], [1,2], [1,3], [1,4], ] """ # great solution https://leetcode.com/problems/combinations/discuss/27024/1-li...
Python
zaydzuhri_stack_edu_python
function test_execute_consistency_wait_for self mock_settings begin set evc1 = call MagicMock set return_value = true set return_value = false set return_value = false set return_value = false set call_count = 0 set circuits = dict string 1 evc1 set execution_rounds = 0 set WAIT_FOR_OLD_PATH = 1 call execute_consistenc...
def test_execute_consistency_wait_for(self, mock_settings): evc1 = MagicMock() evc1.is_enabled.return_value = True evc1.is_active.return_value = False evc1.lock.locked.return_value = False evc1.check_traces.return_value = False evc1.deploy.call_count = 0 self.napp...
Python
nomic_cornstack_python_v1
function is_hash self line begin set m = match line if m begin set level = length call group 1 set name = strip call group 2 if name begin return tuple level name end end return tuple none none end function
def is_hash(self, line: str) -> tuple[int, str]: m = self.md_hash_pattern.match(line) if m: level = len(m.group(1)) name = m.group(2).strip() if name: return level, name return None, None
Python
nomic_cornstack_python_v1
function max_connections self begin return get pulumi self string max_connections end function
def max_connections(self) -> Optional[pulumi.Input[int]]: return pulumi.get(self, "max_connections")
Python
nomic_cornstack_python_v1
comment 組み込み関数は、内部でdunder(__xxx__)を呼んでいる set ar = list 1 2 3 print length ar print call __len__ comment 関数もオブジェクトである function add a b c begin return a + b + c end function comment 下記は、<class 'function'>と出力される print type add comment 関数呼び出しは、functionクラスに実装された__call_メソッドを呼んでいるだけ。 print add 1 10 100 print call __call__ 1 1...
# 組み込み関数は、内部でdunder(__xxx__)を呼んでいる ar = [1, 2, 3] print(len(ar)) print(ar.__len__()) # 関数もオブジェクトである def add(a, b, c): return a + b + c # 下記は、<class 'function'>と出力される print(type(add)) # 関数呼び出しは、functionクラスに実装された__call_メソッドを呼んでいるだけ。 print(add(1, 10, 100)) print(add.__call__(1, 10, 100)) # Java...
Python
zaydzuhri_stack_edu_python
function __repr__ self begin return call to_str end function
def __repr__(self): return self.to_str()
Python
nomic_cornstack_python_v1
import sys function get_fasta_records lines begin set dna_strings = list set is_first_dna = true set tuple id dna = tuple string string for line in lines begin set line = strip line if line at 0 == string > begin if is_first_dna begin set is_first_dna = false end else begin append dna_strings list id dna end set tup...
import sys def get_fasta_records(lines): dna_strings = [] is_first_dna = True id, dna = '', '' for line in lines: line = line.strip(); if line[0] == '>': if is_first_dna: is_first_dna = False else: dna_strings.append([id, dna]) ...
Python
zaydzuhri_stack_edu_python
string Author: Kangqi Luo Date: 180118 Goal: Generate Embedding & Relation Matching data import numpy as np from kq_schema import CompqSchema from util.fb_helper import load_type_name , load_pred_name , get_domain , get_range , get_item_name from kangqi.util.LogUtil import LogInfo comment from kangqi.util.time_track im...
""" Author: Kangqi Luo Date: 180118 Goal: Generate Embedding & Relation Matching data """ import numpy as np from ..kq_schema import CompqSchema from ...util.fb_helper import load_type_name, load_pred_name, get_domain, get_range, get_item_name from kangqi.util.LogUtil import LogInfo # from kangqi.util.time_track impo...
Python
zaydzuhri_stack_edu_python
function read_experiments self design_name db=none only_pending=false begin set db = if expression db is not none then db else db if db is none begin raise call ValueError string no database to read from end return call ensure_dtypes call read_experiment_all name design_name only_pending=only_pending end function
def read_experiments( self, design_name, db=None, only_pending=False, ): db = db if db is not None else self.db if db is None: raise ValueError('no database to read from') return self.ensure_dtypes( db.read_experiment_a...
Python
nomic_cornstack_python_v1
comment tcp_server.py import socket set server_socket = call socket set host = call gethostname set port = 9999 call bind tuple host port
#tcp_server.py import socket server_socket =socket.socket() host = socket.gethostname() port = 9999 server_socket.bind((host,port))
Python
zaydzuhri_stack_edu_python
comment Faça um programa que leia algo pelo teclado e mostre na tela seu tipo primitivo e todas as informações possíveis sobre ele. comment string-str() #inteiro-int() #float-float() #boolean-bool() set x = input string Digite algo: print string A tipo primitivo desse valor é: type x print string É alfanumérico? is alp...
#Faça um programa que leia algo pelo teclado e mostre na tela seu tipo primitivo e todas as informações possíveis sobre ele. #string-str() #inteiro-int() #float-float() #boolean-bool() x=input('Digite algo: ') print('A tipo primitivo desse valor é:', type(x)) print('É alfanumérico? ', x.isalnum()) print('É somente alf...
Python
zaydzuhri_stack_edu_python
function tfidf_features X_train X_test vectorizer_path=none begin comment Train a vectorizer on X_train data. comment Transform X_train and X_test data. comment Pickle the trained vectorizer to 'vectorizer_path' comment Don't forget to open the file in writing bytes mode. set tfidf_vectorizer = call TfidfVectorizer set...
def tfidf_features(X_train, X_test, vectorizer_path=None): # Train a vectorizer on X_train data. # Transform X_train and X_test data. # Pickle the trained vectorizer to 'vectorizer_path' # Don't forget to open the file in writing bytes mode. tfidf_vectorizer = TfidfVectorizer() X_train = tfid...
Python
nomic_cornstack_python_v1
function __init__ self server rcon_password=string begin set sock = call socket AF_INET SOCK_DGRAM call set_server server call set_rcon_password rcon_password end function
def __init__(self, server, rcon_password=''): self.sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) self.set_server(server) self.set_rcon_password(rcon_password)
Python
nomic_cornstack_python_v1
function comment_add_like request pk begin set comment_seed = get objects id=pk if exists filter call Q user_related_id=id ? call Q comment_related_id=id begin delete end else begin set comment = call Liked_Comment user_related=user set comment_related = comment_seed save if user != user begin call send user recipient=...
def comment_add_like(request, pk): comment_seed = Comment_Seed.objects.get(id=pk) if Liked_Comment.objects.filter(Q(user_related_id=request.user.id) & Q(comment_related_id=comment_seed.id)).exists(): Liked_Comment.objects.filter(Q(user_related_id=request.user.id) & Q(comment_related_id=comment_seed.id))...
Python
nomic_cornstack_python_v1
comment https://www.coursera.org/learn/python-osnovy-programmirovaniya/programming/jqFOL/flaghi/submission comment Флаги comment Напишите программу, которая по данному числу n от 1 до 9 выводит на экран n comment флагов. Изображение одного флага имеет размер 4×4 символов, между двумя comment соседними флагами также име...
# https://www.coursera.org/learn/python-osnovy-programmirovaniya/programming/jqFOL/flaghi/submission # Флаги # Напишите программу, которая по данному числу n от 1 до 9 выводит на экран n # флагов. Изображение одного флага имеет размер 4×4 символов, между двумя # соседними флагами также имеется пустой (из пробел...
Python
zaydzuhri_stack_edu_python
function test_username_getter self begin set user = call create_user string test@example.com assert equal call get_username string test@example.com end function
def test_username_getter(self): user = User.objects.create_user("test@example.com") self.assertEqual(user.get_username(), "test@example.com")
Python
nomic_cornstack_python_v1
from rest_framework.permissions import BasePermission , SAFE_METHODS class AllowAnyCreateOrIsAuthenticated extends BasePermission begin string The request is authenticated as a user, or is a read-only request. function has_permission self request view begin if method == string POST or is_authenticated begin return true...
from rest_framework.permissions import BasePermission, SAFE_METHODS class AllowAnyCreateOrIsAuthenticated(BasePermission): """ The request is authenticated as a user, or is a read-only request. """ def has_permission(self, request, view): if request.method == 'POST' or request.user.is_authent...
Python
zaydzuhri_stack_edu_python
string In Flask applications we can use either sessions or tokens depending on the application we are creating to implement login/logout functionality. 1. Sessions are best suited to applications where you're serving web pages with Flask—i.e. making extensive use of render_template 2. Tokens are best suited to APIs, wh...
''' In Flask applications we can use either sessions or tokens depending on the application we are creating to implement login/logout functionality. 1. Sessions are best suited to applications where you're serving web pages with Flask—i.e. making extensive use of render_template 2. Tokens are best suited to APIs, whe...
Python
zaydzuhri_stack_edu_python
from random import randint function main begin set file = call pickAFile set pic = call makePicture file call choose_function pic show pic end function function choose_function pic begin print string lessRed = 1 lessBlue = 2 lessGreen = 3 moreBlue = 4 moreGreen = 5 darken = 6 clearRed = 7 clearBlue = 8 clearGreen = 9 m...
from random import randint def main(): file = pickAFile() pic = makePicture(file) choose_function(pic) show(pic) def choose_function(pic): print("""\nlessRed = 1 lessBlue = 2 lessGreen = 3 moreBlue = 4 moreGreen = 5 darken = 6 ...
Python
zaydzuhri_stack_edu_python
comment !/usr/bin/python comment fw102.py comment Copyright David Baddeley, 2009 comment d.baddeley@auckland.ac.nz comment This program is free software: you can redistribute it and/or modify comment it under the terms of the GNU General Public License as published by comment the Free Software Foundation, either versio...
#!/usr/bin/python ################## # fw102.py # # Copyright David Baddeley, 2009 # d.baddeley@auckland.ac.nz # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License,...
Python
zaydzuhri_stack_edu_python
function depth_dependent_friction domain default_friction surface_roughness_data verbose=false begin comment James - this was missing, don't know what it should be set default_n0 = 0 comment Create a temp array to store updated depth dependent comment friction for wet elements comment EHR this is outwardly inneficient ...
def depth_dependent_friction(domain, default_friction, surface_roughness_data, verbose=False): default_n0 = 0 # James - this was missing, don't know what it should be # Create a temp array to store updated depth dependent # friction for wet elemen...
Python
nomic_cornstack_python_v1
from db import db , get_or_create_user , save_anketa from telegram import ParseMode , ReplyKeyboardMarkup , ReplyKeyboardRemove from telegram.ext import ConversationHandler from utils import main_keybord function anketa_start update context begin call reply_text string Hello, what's your name? reply_markup=call ReplyKe...
from db import db, get_or_create_user, save_anketa from telegram import ParseMode, ReplyKeyboardMarkup, ReplyKeyboardRemove from telegram.ext import ConversationHandler from utils import main_keybord def anketa_start(update, context): update.message.reply_text( "Hello, what's your name?", reply_mar...
Python
zaydzuhri_stack_edu_python
function get_UHRprofiles begin set datacn = expand user LSD string ~/Dropbiz/Basecamp/BRIP1/2017/2017_003_Data_analysis_BRIP1_paper/profiles_UHR/ set centromereshg38 = call get_centromeres set lo = call get_lift19to38 comment All samples => TODO filter patients that only have whole chromosome gains set samples = call r...
def get_UHRprofiles(): datacn = LSD.expanduser("~/Dropbiz/Basecamp/BRIP1/2017/2017_003_Data_analysis_BRIP1_paper/profiles_UHR/") centromereshg38 = LSD.get_centromeres() lo = LSD.get_lift19to38() # All samples => TODO filter patients that only have whole chromosome gains samples = pd.read_table(...
Python
nomic_cornstack_python_v1
function plotLine self begin set minc = 0 set maxc = 500 set num = 500 set levels = linear space minc maxc num + 1 set title = format call dedent string Orography difference between LGM and Modern ICE-5G data using {0} meter contour interval maxc - minc / num figure call contour difference_in_ice_5g_orography levels=le...
def plotLine(self): minc = 0 maxc = 500 num = 500 levels = np.linspace(minc,maxc,num+1) title = textwrap.dedent("""\ Orography difference between LGM and Modern ICE-5G data using {0} meter contour interval""").format((maxc-minc)/num) plt.figure() p...
Python
nomic_cornstack_python_v1
import serial import time import sys import glob import io function serial_ports begin string Lists serial ports :raises EnvironmentError: On unsupported or unknown platforms :returns: A list of available serial ports if starts with platform string win begin set ports = list comprehension string COM + string i + 1 for ...
import serial import time import sys import glob import io def serial_ports(): """Lists serial ports :raises EnvironmentError: On unsupported or unknown platforms :returns: A list of available serial ports """ if sys.platform.startswith('win'): ports = ['COM' + str(i + 1) f...
Python
zaydzuhri_stack_edu_python
function to_uint8 self y begin set num_bins = 2.0 ^ _num_bits set x = call cast call clip_by_value floor y * num_bins * 256.0 / num_bins 0 255 string uint8 return x end function
def to_uint8(self, y: tf.Tensor) -> tf.Tensor: num_bins = 2.**self._num_bits x = tf.cast( tf.clip_by_value( tf.floor(y * num_bins) * (256. / num_bins), 0, 255), 'uint8') return x
Python
nomic_cornstack_python_v1
async function websocket_reconfigure_node hass connection msg begin set zha_gateway : ZHAGateway = data at DATA_ZHA at DATA_ZHA_GATEWAY set ieee : EUI64 = msg at ATTR_IEEE set device : ZHADevice ? none = call get_device ieee async function forward_messages data begin string Forward events to websocket. call send_messag...
async def websocket_reconfigure_node( hass: HomeAssistant, connection: ActiveConnection, msg: dict[str, Any] ) -> None: zha_gateway: ZHAGateway = hass.data[DATA_ZHA][DATA_ZHA_GATEWAY] ieee: EUI64 = msg[ATTR_IEEE] device: ZHADevice | None = zha_gateway.get_device(ieee) async def forward_messages(dat...
Python
nomic_cornstack_python_v1
function flatten_and_sum nested_list begin set result = 0 for element in nested_list begin if is instance element int begin set result = result + element end else if is instance element list begin set result = result + call flatten_and_sum element end end return result end function set nested_list = list 1 2 list 3 4 l...
def flatten_and_sum(nested_list): result = 0 for element in nested_list: if isinstance(element, int): result += element elif isinstance(element, list): result += flatten_and_sum(element) return result nested_list = [1, 2, [3, 4, [5, 6]], [7, 8]] print(flatten_and_su...
Python
jtatman_500k
comment Write a function that returns the sum of two numbers. comment Example comment For param1 = 1 and param2 = 2, the output should be comment add(param1, param2) = 3. function add param1 param2 begin return param1 + param2 end function comment Given a year, return the century it is in. The first century spans from ...
# Write a function that returns the sum of two numbers. # Example # For param1 = 1 and param2 = 2, the output should be # add(param1, param2) = 3. def add(param1, param2): return param1 + param2 # Given a year, return the century it is in. The first century spans from the year 1 up to and including the year 100, t...
Python
zaydzuhri_stack_edu_python
for start in range 10 begin print start end
for start in range(10): print(start)
Python
flytech_python_25k
function delete_take take_filepath begin comment destination set key_name = string projects/ { take_filepath } call delete_object Bucket=BUCKET Key=key_name print string Successfully deleted take: { key_name } end function
def delete_take(take_filepath): key_name = f"projects/{take_filepath}" #destination boto3.client('s3').delete_object(Bucket=BUCKET, Key=key_name) print(f"Successfully deleted take: {key_name}")
Python
nomic_cornstack_python_v1
function isPackageDirectory dirname begin for ext in zip *imp.get_suffixes() at 0 begin set initFile = string __init__ + ext if exists path join path dirname initFile begin return initFile end end return false end function
def isPackageDirectory(dirname): for ext in zip(*imp.get_suffixes())[0]: initFile = '__init__' + ext if os.path.exists(os.path.join(dirname, initFile)): return initFile return False
Python
nomic_cornstack_python_v1
import numpy as np import pandas as pd import tensorflow as tf import matplotlib.pyplot as plt import pickle as p class prepare_data begin comment methods for one-hot encoding the labels, loading the data in a randomized array and a method for comment flattening an array (since a fully connected network needs an flat a...
import numpy as np import pandas as pd import tensorflow as tf import matplotlib.pyplot as plt import pickle as p class prepare_data: #methods for one-hot encoding the labels, loading the data in a randomized array and a method for # flattening an array (since a fully connected network needs an flat array as...
Python
zaydzuhri_stack_edu_python
function __lineardiff__ x dt params options=none begin if options is none begin set options = dict string solver string MOSEK end set tuple N gamma = params set mean = mean np x set x = x - mean comment Generate the matrix of integrals of x set X = list x for n in range 1 N begin append X call integrate_dxdt_hat X at -...
def __lineardiff__(x, dt, params, options=None): if options is None: options = {'solver': 'MOSEK'} N, gamma = params mean = np.mean(x) x = x - mean # Generate the matrix of integrals of x X = [x] for n in range(1, N): X.append(utility.integrate_dxdt_hat(X[-1], dt)) X ...
Python
nomic_cornstack_python_v1
from assertpy import assert_that import pytest from uuid import uuid1 from faker import Faker from faker.providers import phone_number , person from domain.members.models import MemberProfileDO , MemberId class TestMemberProfileDO extends object begin decorator fixture autouse=true scope=string function function setup ...
from assertpy import assert_that import pytest from uuid import uuid1 from faker import Faker from faker.providers import phone_number, person from domain.members.models import MemberProfileDO, MemberId class TestMemberProfileDO(object): @pytest.fixture(autouse=True, scope="function") def setup(self): ...
Python
zaydzuhri_stack_edu_python
from collections import Counter function main begin set n = integer input set v = list map int split input set odd_v = v at slice 0 : : 2 set even_v = v at slice 1 : : 2 set cnt_odd = counter odd_v set cnt_odd = sorted items cnt_odd key=lambda x -> x at 1 reverse=true set ans_odd = n // 2 - cnt_odd at 0 at 1 set cnt_...
from collections import Counter def main(): n = int(input()) v = list(map(int, input().split())) odd_v = v[0::2] even_v = v[1::2] cnt_odd = Counter(odd_v) cnt_odd = sorted(cnt_odd.items(), key=lambda x:x[1], reverse=True) ans_odd = n // 2 - cnt_odd[0][1] cnt_even = Counter(even_v) ...
Python
zaydzuhri_stack_edu_python
import json from flask import Flask , request , jsonify set app = call Flask __name__ set data = list string Apple string Banana string Carrot decorator call route string /data methods=list string GET function serve_data begin return call jsonify data end function if __name__ == string __main__ begin run end
import json from flask import Flask, request, jsonify app = Flask(__name__) data = ['Apple', 'Banana', 'Carrot'] @app.route('/data', methods=['GET']) def serve_data(): return jsonify(data) if __name__ == '__main__': app.run()
Python
jtatman_500k
function test_update_admin_username self begin set url = reverse string users:detail kwargs=dict string pk id set data = dict string username string new_username_for_admin_user ; string password string new_password_for_admin_user set response = put url data assert equal status_code HTTP_200_OK end function
def test_update_admin_username(self): url = reverse( 'users:detail', kwargs={'pk': self.dublicate_admin_user.id} ) data = { 'username': 'new_username_for_admin_user', 'password': 'new_password_for_admin_user', } response = self.curr...
Python
nomic_cornstack_python_v1
function test_multiple_run self patch_split timer elapsed_100_ns elapsed_1_ms elapsed_1_pt_5_ms begin decorator timer function func begin pass end function with call patch_split elapsed_times=list 100 1000 1500 begin for _ in range 3 begin call func end end assert durations == tuple elapsed_100_ns elapsed_1_ms elapsed_...
def test_multiple_run( self, patch_split: Callable, timer: Timer, elapsed_100_ns: ElapsedTime, elapsed_1_ms: ElapsedTime, elapsed_1_pt_5_ms: ElapsedTime, ) -> None: @timer def func() -> None: pass with patch_split(elapsed_times=[1...
Python
nomic_cornstack_python_v1
string Another Convolutional Network Example using TensorFlow Library Author: Win Woo Based off Aymeric Damien's example at: https://github.com/aymericdamien/TensorFlow-Examples/ Shows how to use TensorFlow input queues and image decoding to train a simple convolutional neural network. The model is also exported. You n...
''' Another Convolutional Network Example using TensorFlow Library Author: Win Woo Based off Aymeric Damien's example at: https://github.com/aymericdamien/TensorFlow-Examples/ Shows how to use TensorFlow input queues and image decoding to train a simple convolutional neural network. The model is also exported. You ...
Python
zaydzuhri_stack_edu_python
function max_building n restrictions begin set restrictions = restrictions + list list 1 0 list n n - 1 sort restrictions for i in range 1 length restrictions begin set restrictions at i at 1 = min restrictions at i at 1 restrictions at i - 1 at 1 + restrictions at i at 0 - restrictions at i - 1 at 0 end for i in range...
def max_building(n, restrictions): restrictions += [[1, 0], [n, n - 1]] restrictions.sort() for i in range(1, len(restrictions)): restrictions[i][1] = min(restrictions[i][1], restrictions[i - 1][1] + restrictions[i][0] - restrictions[i - 1][0]) for i in range(len(restrictions) - 2, -1, -1): ...
Python
jtatman_500k
comment !/usr/bin/env python comment coding: utf-8 comment In[ ]: import os from keras.preprocessing.text import Tokenizer from keras.preprocessing.sequence import pad_sequences from keras.applications.xception import Xception from keras.models import load_model from pickle import load import numpy as np from PIL impor...
#!/usr/bin/env python # coding: utf-8 # In[ ]: import os from keras.preprocessing.text import Tokenizer from keras.preprocessing.sequence import pad_sequences from keras.applications.xception import Xception from keras.models import load_model from pickle import load import numpy as np from PIL import Ima...
Python
zaydzuhri_stack_edu_python
string Created on Dec 19, 2018 @author: K3NN! from NumProgression.Progression import Progression class Fibonacci extends Progression begin string classdocs function __init__ self first=0 second=1 begin string Constructor call __init__ first set _prev = second - first end function function _progress self begin set tuple...
''' Created on Dec 19, 2018 @author: K3NN! ''' from NumProgression.Progression import Progression class Fibonacci(Progression): ''' classdocs ''' def __init__(self, first=0, second=1): ''' Constructor ''' super().__init__(first) self._prev = ...
Python
zaydzuhri_stack_edu_python
function day_per_Month year begin if year % 4 == 0 and year % 100 != 0 or year % 400 == 0 begin return list 31 29 31 30 31 30 31 31 30 31 30 31 end else begin return list 31 28 31 30 31 30 31 31 30 31 30 31 end end function function days date2 begin set dayDiff = 0 set date1 = tuple 1 1 1 set dayPerMonth = call day_per...
def day_per_Month(year): if (year%4 == 0 and year%100 != 0) or year %400 ==0: return [31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31] else: return [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31] def days(date2): dayDiff = 0 date1 = (1, 1, 1) dayPerMonth = day_per_Month(date2[0]) ...
Python
zaydzuhri_stack_edu_python
comment Jack Anderson 2017 import csv import numpy as np import pandas as pd from collections import OrderedDict from sklearn.neighbors import KNeighborsClassifier from sklearn.neighbors import NearestNeighbors from sklearn.cross_validation import train_test_split set NSL_KDD_TRAINING_PATH = string Datasets/NSL-KDD/KDD...
# Jack Anderson 2017 import csv import numpy as np import pandas as pd from collections import OrderedDict from sklearn.neighbors import KNeighborsClassifier from sklearn.neighbors import NearestNeighbors from sklearn.cross_validation import train_test_split NSL_KDD_TRAINING_PATH = "Datasets/NSL-KDD/KDDTrain.csv" NS...
Python
zaydzuhri_stack_edu_python
import time set start = time set limit = 1000000 set length = list 0 * limit set length at 1 = 1 set max_length = list 1 1 for i in range 1 limit begin set tuple n s = tuple i 0 comment not yet registered set to_add = list while n > limit - 1 or length at n < 1 begin append to_add n if n % 2 == 0 begin set n = n / 2 e...
import time start = time.time() limit = 1000000 length = [0] * limit length[1] = 1 max_length = [1,1] for i in range(1,limit): n,s = i,0 to_add = [] # not yet registered while n > limit - 1 or length[n] < 1: to_add.append(n) if n % 2 == 0: n = n/2 else: n =...
Python
zaydzuhri_stack_edu_python