code
stringlengths
10
2.58M
original_code
stringlengths
3
3.18M
original_language
stringclasses
1 value
source
stringclasses
7 values
function record_vote self obj user vote begin set ctype = call get_for_model obj try begin set v = get self user=user content_type=ctype object_id=call _get_pk_val if vote == false begin delete end end except ObjectDoesNotExist begin if vote == false begin return end call create user=user content_type=ctype object_id=c...
def record_vote(self, obj, user, vote): ctype = ContentType.objects.get_for_model(obj) try: v = self.get(user=user, content_type=ctype, object_id=obj._get_pk_val()) if vote == False: v.delete() except models.ObjectDoesNotExist: if vote == False: return self.create(user=user, content_type=ctype...
Python
nomic_cornstack_python_v1
comment %% import math from math import sqrt import warnings import sympy as smp import sys from itertools import count import random from subprocess import check_call import os from PIL import Image from random import randint import unittest append path directory name path absolute path path __file__ + sep + string .....
#%% import math from math import sqrt import warnings import sympy as smp import sys from itertools import count import random from subprocess import check_call import os from PIL import Image from random import randint import unittest sys.path.append(os.path.dirname(os.path.abspath(__file__)) + (os.path.sep + "..") * ...
Python
zaydzuhri_stack_edu_python
import numpy as np import matplotlib.pyplot as plt import keras as k function plot_functions x y func1 begin set model1 = call load_model func1 set predict1 = predict model1 x plot x predict1 label=string model plot x y label=string target legend show end function function plot_loss model1 begin set history1 = load np ...
import numpy as np import matplotlib.pyplot as plt import keras as k def plot_functions(x,y,func1): model1 = k.models.load_model(func1) predict1 = model1.predict(x) plt.plot(x, predict1, label = "model") plt.plot(x, y,label = "target") plt.legend() plt.show() def plot_loss(model1): history1...
Python
zaydzuhri_stack_edu_python
comment !/usr/bin/env python from time import time from math import sqrt function is_natural_number n begin return n % 1.0 == 0 and n > 0 end function function solve_quadratic_equation a b c begin set root1 = - 1.0 * b + square root b ^ 2 - 4.0 * a * c / 2.0 * a set root2 = - 1.0 * b - square root b ^ 2 - 4.0 * a * c /...
#!/usr/bin/env python from time import time from math import sqrt def is_natural_number(n): return n % 1.0 == 0 and n > 0 def solve_quadratic_equation(a, b, c): root1 = (-1.0 * b + sqrt(b**2 - 4.0 * a * c)) / (2.0 * a) root2 = (-1.0 * b - sqrt(b**2 - 4.0 * a * c)) / (2.0 * a) return root1, root2 de...
Python
zaydzuhri_stack_edu_python
comment coding: utf-8 import os , time import numpy as np import librosa import soundfile as sf import model comment =========================================== comment 初始化模型 comment =========================================== class Mymodel extends object begin string docstring for Mymodel function __init__ self networ...
# coding: utf-8 import os, time import numpy as np import librosa import soundfile as sf import model # =========================================== # 初始化模型 # =========================================== class Mymodel(object): """docstring for Mymodel""" def __init__(self, network): super(Mym...
Python
zaydzuhri_stack_edu_python
function find_workers self worker_name=none provider_type=none begin with table_access_condition begin set conn = call _get_connection set c = call cursor execute c string SELECT * from workers WHERE (?1 IS NULL OR worker_name = ?1) AND (?2 IS NULL OR provider_type = ?2) tuple worker_name provider_type set rows = call ...
def find_workers( self, worker_name: Optional[str] = None, provider_type: Optional[str] = None ) -> List[Worker]: with self.table_access_condition: conn = self._get_connection() c = conn.cursor() c.execute( """ SELECT * from workers...
Python
nomic_cornstack_python_v1
function arguments self begin set barsplits = call _not_in_subspans_split_spans string | at slice 1 : : set arguments = list set spans = _spans set lststr = _lststr set typeindex = string ta + string _index if typeindex not in spans begin set spans at typeindex = list end set aspans = spans at typeindex if barsplit...
def arguments(self): barsplits = self._not_in_subspans_split_spans('|')[1:] arguments = [] spans = self._spans lststr = self._lststr typeindex = 'ta' + str(self._index) if typeindex not in spans: spans[typeindex] = [] aspans = spans[typeindex] ...
Python
nomic_cornstack_python_v1
import pandas as pd import numpy as np import matplotlib.pyplot as plt from sklearn import metrics , preprocessing from sklearn.neighbors import KNeighborsClassifier from sklearn.metrics import confusion_matrix function plot_confusion_matrix cm target_names title=string Confusion matrix cmap=none normalize=true begin s...
import pandas as pd import numpy as np import matplotlib.pyplot as plt from sklearn import metrics,preprocessing from sklearn.neighbors import KNeighborsClassifier from sklearn.metrics import confusion_matrix def plot_confusion_matrix(cm, target_names, title='Confus...
Python
zaydzuhri_stack_edu_python
function request self button begin put button block=false end function
def request(self, button): self.requests.put(button, block=False)
Python
nomic_cornstack_python_v1
function get_calibration self name shape chunks=none begin string Get the calibration array. set data_items = find all string .//calibrationVector set tuple data low_res_coords = call read_xml_array data_items name return call interpolate_xml_array data low_res_coords shape chunks=chunks end function
def get_calibration(self, name, shape, chunks=None): """Get the calibration array.""" data_items = self.root.findall(".//calibrationVector") data, low_res_coords = self.read_xml_array(data_items, name) return self.interpolate_xml_array(data, low_res_coords, shape, chunks=chunks)
Python
jtatman_500k
function copy self begin return call Interval start end end function
def copy(self): return Interval(self.start, self.end)
Python
nomic_cornstack_python_v1
function to_grayscale self begin comment Get current image set tuple curr_img _ = undoStack at - 1 comment Convert to grayscale set new_img = as type call to_grayscale curr_img uint8 set new_img_path = call _internal_save call fromarray new_img append undoStack tuple new_img new_img_path call display_image new_img_path...
def to_grayscale(self): curr_img, _ = self.undoStack[-1] # Get current image new_img = to_grayscale(curr_img).astype(np.uint8) # Convert to grayscale new_img_path = self._internal_save(Image.fromarray(new_img)) self.undoStack.append((new_img, new_img_path)) self.display_image(new...
Python
nomic_cornstack_python_v1
comment Componente que se dedica a comprender un lenguaje natural ## comment -----------------------------------------------------------## comment Convierte textos de un lenguaje natural en intents ## comment Importamos metodos de la libreria de utilidades from libraries.lib_utils import count_words , multi_split , mer...
############################################################### ## Componente que se dedica a comprender un lenguaje natural ## ##-----------------------------------------------------------## ## Convierte textos de un lenguaje natural en intents ## ############################################################### ...
Python
zaydzuhri_stack_edu_python
function test_sub_i_less_0 begin set a : list at int = list 1 2 3 4 set i : int = - 1 set j : int = 3 assert sub a i j == list 1 2 3 end function
def test_sub_i_less_0() -> None: a: list[int] = [1, 2, 3, 4] i: int = -1 j: int = 3 assert sub(a, i, j) == [1, 2, 3]
Python
nomic_cornstack_python_v1
function is_hidden self path begin return false end function
def is_hidden(self, path): return False
Python
nomic_cornstack_python_v1
comment !/usr/bin/python import sys function solve A B K begin comment Catalina owns any number less than K. comment For her to win, random numbers must be such that no comment bit is 1 for bits in positions greater than len(bin(K)). comment 3 ^ shared length of A,B + 2 ^ overflow of max(A,B). comment of course, discou...
#!/usr/bin/python import sys def solve(A, B, K): # Catalina owns any number less than K. # For her to win, random numbers must be such that no # bit is 1 for bits in positions greater than len(bin(K)). # 3 ^ shared length of A,B + 2 ^ overflow of max(A,B). # of course, discounting the number of 1's there a...
Python
zaydzuhri_stack_edu_python
comment !/usr/bin/env python import sys import os import datetime from contextlib import contextmanager from sqlalchemy import BigInteger , Text , Integer , DateTime , DECIMAL , BOOLEAN , ForeignKey , Column from sqlalchemy.ext.declarative import declarative_base from sqlalchemy.schema import MetaData from sqlalchemy.o...
#!/usr/bin/env python import sys import os import datetime from contextlib import contextmanager from sqlalchemy import ( BigInteger, Text, Integer, DateTime, DECIMAL, BOOLEAN, ForeignKey, Column ) from sqlalchemy.ext.declarative import declarative_base from sqlalchemy.schema import MetaData from sqlalch...
Python
zaydzuhri_stack_edu_python
from flask import Flask , render_template , request , send_from_directory import matplotlib.pyplot as plt import requests import numpy as np set app = call Flask __name__ set config at string upload_folder = string ./ decorator call route string / function home begin return call render_template string home.htm end func...
from flask import Flask, render_template, request, send_from_directory import matplotlib.pyplot as plt import requests import numpy as np app=Flask(__name__) app.config['upload_folder']='./' @app.route('/') def home(): return render_template('home.htm') @app.route('/grafik', methods=['POST','GET']) def grafik():...
Python
zaydzuhri_stack_edu_python
from abc import ABCMeta class AudioTranscriber begin string Abstract class for VideoPipeline.audio_transcriber set __metaclass__ = ABCMeta function transcribe self audio begin string Transcribe an audio clip into text. Args: audio: The audio file loaded as bytes. You might do this by loading the file using open(file, "...
from abc import ABCMeta class AudioTranscriber: """ Abstract class for VideoPipeline.audio_transcriber """ __metaclass__ = ABCMeta def transcribe(self, audio): """ Transcribe an audio clip into text. Args: audio: The audio file loaded as bytes. You might do thi...
Python
zaydzuhri_stack_edu_python
comment !/usr/bin/env python comment coding: utf-8 comment In[1]: comment Código para minimizar as linhas de código from IPython.display import HTML call HTML string <script> code_show=true; function code_toggle() { if (code_show){ $('div.input').hide(); } else { $('div.input').show(); } code_show = !code_show } $( doc...
#!/usr/bin/env python # coding: utf-8 # In[1]: # Código para minimizar as linhas de código from IPython.display import HTML HTML('''<script> code_show=true; function code_toggle() { if (code_show){ $('div.input').hide(); } else { $('div.input').show(); } code_show = !code_show } $( doc...
Python
zaydzuhri_stack_edu_python
string ' You are given an integer array nums and you have to return a new counts array. The counts array has the property where counts[i] is the number of smaller elements to the right of nums[i]. Example: Input: [5,2,6,1] Output: [2,1,1,0] Explanation: To the right of 5 there are 2 smaller elements (2 and 1). To the r...
'''' You are given an integer array nums and you have to return a new counts array. The counts array has the property where counts[i] is the number of smaller elements to the right of nums[i]. Example: Input: [5,2,6,1] Output: [2,1,1,0] Explanation: To the right of 5 there are 2 smaller elements (2 and 1). To the r...
Python
zaydzuhri_stack_edu_python
comment - encapsulation: hide delegate from client comment client -> wrapper -> delegate comment decouple client and delegate: client need not to change accordingly when delegate changes comment - replace inheritance with delegation comment when a class (client) needs to use another class (delegate) but wants more cont...
# - encapsulation: hide delegate from client # client -> wrapper -> delegate # decouple client and delegate: client need not to change accordingly when delegate changes # - replace inheritance with delegation # when a class (client) needs to use another class (delegate) but wants more control over its interface #...
Python
zaydzuhri_stack_edu_python
string Created on Thu Sep 4 14:52:32 2020 @author: Mukilan string Using different Alogorithmn to find the best algorithmn for regression Problem statement. I used algorithmn like Linear, Random Forest, Gradient Boost Regression. And I visualize the data using seaborn. import pandas as pd import numpy as np import seabo...
""" Created on Thu Sep 4 14:52:32 2020 @author: Mukilan """ """ Using different Alogorithmn to find the best algorithmn for regression Problem statement. I used algorithmn like Linear, Random Forest, Gradient Boost Regression. And I visualize the data using seaborn.""" import pandas as pd import numpy as np ...
Python
zaydzuhri_stack_edu_python
function filenames self begin return call filenames end function
def filenames(self): return self.latest()[0].filenames()
Python
nomic_cornstack_python_v1
function init_map city begin global map try begin set map = call load_graph city + string _map end except FileNotFoundError begin print string downloading... set map = call download_graph city call save_graph map city + string _map print string downloaded! end end function
def init_map(city): global map try: map = guide.load_graph(city + "_map") except FileNotFoundError: print("downloading...") map = guide.download_graph(city) guide.save_graph(map, city + "_map") print("downloaded!")
Python
nomic_cornstack_python_v1
function readboards filename begin set f = open filename string r set n = integer strip read line f set boards = list for i in range n begin yield list comprehension strip read line f for b in range 4 read line f end end function function row b a begin for r in b begin if call win r a begin return true end end return ...
def readboards(filename): f = open(filename, 'r') n = int(f.readline().strip()) boards = [] for i in range(n): yield [f.readline().strip() for b in range(4)] f.readline() def row(b, a): for r in b: if win(r,a): return True return False def win(...
Python
zaydzuhri_stack_edu_python
function overlap_conflict out *inputs begin from import _bh for i in inputs begin if not call isscalar i begin if call may_share_memory out i and not call same_view out i begin return true end end end return false end function
def overlap_conflict(out, *inputs): from . import _bh for i in inputs: if not np.isscalar(i): if np.may_share_memory(out, i) and not _bh.same_view(out, i): return True return False
Python
nomic_cornstack_python_v1
comment Copyright (c) Twisted Matrix Laboratories. comment See LICENSE for details. string Tests for L{twisted.web.static}. import errno import inspect import mimetypes import os import re import sys import warnings from io import BytesIO as StringIO from unittest import skipIf from zope.interface.verify import verifyO...
# Copyright (c) Twisted Matrix Laboratories. # See LICENSE for details. """ Tests for L{twisted.web.static}. """ import errno import inspect import mimetypes import os import re import sys import warnings from io import BytesIO as StringIO from unittest import skipIf from zope.interface.verify import verifyObject f...
Python
jtatman_500k
function game_loop self begin call game_loop self end function
def game_loop(self): self.interface.game_loop(self)
Python
nomic_cornstack_python_v1
string Sample Controller File A Controller should be in charge of responding to a request. Load models to interact with the database and load views to render them to the client. Create a controller using this template from system.core.controller import * class Semis extends Controller begin function __init__ self actio...
""" Sample Controller File A Controller should be in charge of responding to a request. Load models to interact with the database and load views to render them to the client. Create a controller using this template """ from system.core.controller import * class Semis(Controller): def __init__(sel...
Python
zaydzuhri_stack_edu_python
function _read_clients cls begin debug string Agave._read_clients()... with open call agpy_path as agpy begin set clients = loads read agpy end comment If we are writing to the .agave/current file, then comment translate a few key fields accordingly if call agpy_path == call tapis_current_path begin debug string Using ...
def _read_clients(cls): logger.debug('Agave._read_clients()...') with open(Agave.agpy_path()) as agpy: clients = json.loads(agpy.read()) # If we are writing to the .agave/current file, then # translate a few key fields accordingly if Agave.agpy_path() == Agave.tapis_c...
Python
nomic_cornstack_python_v1
from seq2seq_translation_tutorial import EncoderRNN , AttnDecoderRNN import pickle import torch import numpy as np comment import Encoder import matplotlib.pyplot as plt call switch_backend string agg import matplotlib.ticker as ticker class Generator begin function __init__ self encoder decoder comment_dict SOS_token ...
from seq2seq_translation_tutorial import EncoderRNN,AttnDecoderRNN import pickle import torch import numpy as np # import Encoder import matplotlib.pyplot as plt plt.switch_backend('agg') import matplotlib.ticker as ticker class Generator: def __init__(self, encoder, decoder, comment_dict, SOS_token, EOS_token, dev...
Python
zaydzuhri_stack_edu_python
function test_mutators self begin comment Mutate packet fields. call set_source NEW_SRC call set_destination NEW_DEST call set_timestamp NEW_TIMESTAMP call set_seq_num NEW_SEQ_NUM comment Check packet fields have been updated correctly. assert equal NEW_SRC call get_source assert equal NEW_DEST call get_destination ass...
def test_mutators(self): # Mutate packet fields. self.packet.set_source(self.NEW_SRC) self.packet.set_destination(self.NEW_DEST) self.packet.set_timestamp(self.NEW_TIMESTAMP) self.packet.set_seq_num(self.NEW_SEQ_NUM) # Check packet fields have been updat...
Python
nomic_cornstack_python_v1
from google.appengine.ext import ndb from google.appengine.api import users class MyUser extends Model begin set anagram_counter = call IntegerProperty set words_counter = call IntegerProperty function getCurrentMyUser self begin set user = call get_current_myuser return user end function function getUser self key begi...
from google.appengine.ext import ndb from google.appengine.api import users class MyUser(ndb.Model): anagram_counter = ndb.IntegerProperty() words_counter = ndb.IntegerProperty() def getCurrentMyUser(self): user = users.get_current_myuser() return user def getUser(self, k...
Python
zaydzuhri_stack_edu_python
import numpy import pandas comment GOAL: Examine impact of gene filtering on method performance comment STEP 0: Read CSV file into data frame set df = read csv string ../data.csv comment Data frame contains the following columns: comment TRLN = model condition (species tree height) comment RATE = model condition (speci...
import numpy import pandas # GOAL: Examine impact of gene filtering on method performance # STEP 0: Read CSV file into data frame df = pandas.read_csv("../data.csv") # Data frame contains the following columns: # TRLN = model condition (species tree height) # RATE = model condition (speciation rate) # NBPS = model c...
Python
zaydzuhri_stack_edu_python
function choose_reflectivity self *args begin if get reflectivity_check == 0 begin return end else begin comment A pop up dialog allows to choose the relfectivity set filename = call askopenfilename initialdir=current_location if filename is not string begin set filename end else begin set 0 end end end function
def choose_reflectivity(self, *args): if self.reflectivity_check.get() == 0: return else: # A pop up dialog allows to choose the relfectivity filename = filedialog.askopenfilename(initialdir=self.current_location) if filename is not '': se...
Python
nomic_cornstack_python_v1
function snooze self begin with lock begin if dismissed begin raise call ValueError string Timer cannot be snoozed if it has been dismissed end set snoozed = true set restarted = false call notify_all end end function
def snooze(self): with self.lock: if self.dismissed: raise ValueError("Timer cannot be snoozed if it has been dismissed") self.snoozed = True self.restarted = False self.cond.notify_all()
Python
nomic_cornstack_python_v1
from tkinter import * set root = call Tk call geometry string 700x700 function func1 a begin print string my name is chetan end function set f1 = call Frame root bg=string lightblue borderwidth=5 relief=GROOVE call pack side=LEFT comment b1=Button(f1,text="submit",bg="red",fg="white" ,command=func1) set b1 = call Butto...
from tkinter import * root=Tk() root.geometry('700x700') def func1(a): print("my name is chetan") f1=Frame(root,bg="lightblue",borderwidth=5,relief=GROOVE) f1.pack(side=LEFT) # b1=Button(f1,text="submit",bg="red",fg="white" ,command=func1) b1=Button(f1,text="submit",bg="red",fg="white") # b1.config(comma...
Python
zaydzuhri_stack_edu_python
string This is fun set lis = list 67 90 123 comment WITH usage function convert filename begin with open filename string w as fil begin for i in lis begin if i > - 273 begin set temp_f = i * 9 / 5 + 32 write fil string temp_f + string end else begin print string Not appr temperature end end end end function function ad...
""" This is fun """ lis = [67,90,123] #WITH usage def convert(filename): with open(filename,'w') as fil: for i in lis: if i > -273: temp_f = i*9/5+32 fil.write(str(temp_f) + "\n") else: print("Not appr temperature") def add(n1,n2): res = n1 + n2 print("Result") return res #...
Python
zaydzuhri_stack_edu_python
import re set n = integer input set lst = list for i in range n begin set s = input append lst find all string .*(.).*\1.* s string if re.search(r'^[a-zA-Z0-9]{10}$',s) and len((re.findall(r'[A-Z]',s))) >= 2 and len((re.findall(r'[0-9]',s))) >= 3 and not len(re.findall(r'([\w])\w*',s)): print("Valid") else: print("I...
import re n=int(input()) lst=[] for i in range(n): s=input() lst.append(re.findall(r'.*(.).*\1.*',s)) ''' if re.search(r'^[a-zA-Z0-9]{10}$',s) and len((re.findall(r'[A-Z]',s))) >= 2 and len((re.findall(r'[0-9]',s))) >= 3 and not len(re.findall(r'([\w])\1\w*\1',s)): print("Valid") else: ...
Python
zaydzuhri_stack_edu_python
function update_item cls hash_key range_key=none attributes_to_set=none attributes_to_add=none begin string Update item attributes. Currently SET and ADD actions are supported. set primary_key = call _encode_key hash_key range_key set value_names = dict set encoded_values = dict set dynamizer = call Dynamizer set set...
def update_item(cls, hash_key, range_key=None, attributes_to_set=None, attributes_to_add=None): """Update item attributes. Currently SET and ADD actions are supported.""" primary_key = cls._encode_key(hash_key, range_key) value_names = {} encoded_values = {} dynamizer = Dynamize...
Python
jtatman_500k
import pika , sys , uuid import random import socket comment To generate a Rabbit MQ connection. The code is taken from the https://www.rabbitmq.com/tutorials/tutorial-six-python.html set connection = call BlockingConnection call ConnectionParameters host=string localhost comment creating a communication channel set ch...
import pika, sys, uuid import random import socket #To generate a Rabbit MQ connection. The code is taken from the https://www.rabbitmq.com/tutorials/tutorial-six-python.html connection = pika.BlockingConnection(pika.ConnectionParameters(host='localhost')) #creating a communication channel channel = connectio...
Python
zaydzuhri_stack_edu_python
import socket import threading from threading import * from Crypto.PublicKey import RSA import pickle from Crypto.Cipher import PKCS1_OAEP set client = call socket call setsockopt SOL_SOCKET SO_REUSEADDR 1 call connect tuple string 127.0.0.1 9999 set key = call generate 3072 set tuple private_key public = tuple key cal...
import socket import threading from threading import * from Crypto.PublicKey import RSA import pickle from Crypto.Cipher import PKCS1_OAEP client=socket.socket() client.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) client.connect(("127.0.0.1",9999)) key = RSA.generate(3072) private_key, public =...
Python
zaydzuhri_stack_edu_python
async function async_step_init self user_input=none begin set _errors = dict if user_input is not none begin comment Update entry update _data user_input return call async_create_entry title=string data=_data end return await call _show_init_form user_input end function
async def async_step_init(self, user_input=None): self._errors = {} if user_input is not None: # Update entry self._data.update(user_input) return self.async_create_entry(title="", data=self._data) return await self._show_init_form(user_input)
Python
nomic_cornstack_python_v1
comment scope comment global variable set x = 5 function func begin global x comment local variable set x = 7 return x end function print x print call func print x
# scope x = 5 # global variable def func(): global x x = 7 # local variable return x print(x) print(func()) print(x)
Python
zaydzuhri_stack_edu_python
import sys function anotherbrick fd begin set tuple h w n = split strip read line fd string set tuple h w n = tuple integer h integer w integer n set brick = list map int split strip read line fd string try begin for _ in range h begin set remaining = w while remaining > 0 begin set remaining = remaining - pop brick 0 ...
import sys def anotherbrick(fd): h, w, n = fd.readline().strip().split(' ') h, w, n = int(h), int(w), int(n) brick = list(map(int, fd.readline().strip().split(' '))) try: for _ in range(h): remaining = w while remaining > 0: remaining -= brick.pop(0) ...
Python
zaydzuhri_stack_edu_python
function parse_args self *args **kwargs begin string Parse arguments set args = call parse_args *args keyword kwargs set args = variables args set args = dictionary comprehension k : v for tuple k v in items args if v is not none if get args string command none is none begin call print_help exit 0 end comment set loggi...
def parse_args(self, *args, **kwargs): """ Parse arguments """ args = super(SatUtilsParser, self).parse_args(*args, **kwargs) args = vars(args) args = {k: v for k, v in args.items() if v is not None} if args.get('command', None) is None: self.print_help() ...
Python
jtatman_500k
for x in s begin if x == string . begin set right_white = right_white - 1 end else begin set left_black = left_black + 1 end set min_num = min min_num right_white + left_black end print min_num
for x in s: if x == ".": right_white -= 1 else: left_black += 1 min_num = min(min_num, right_white+left_black) print(min_num)
Python
zaydzuhri_stack_edu_python
import time import datetime set today = today set today = today comment format = "(%b), %d, %Y, %H:%M:%S ,(%a)"#strftime.org comment format = "(%b) %d/%Y, (%A)"#strftime.org comment strftime.org set format = string (%B) %d/%Y, (%A) print string ISO : today set b = today + time delta days=23 set future = string format t...
import time import datetime today = datetime.datetime.today() today = datetime.date.today() #format = "(%b), %d, %Y, %H:%M:%S ,(%a)"#strftime.org #format = "(%b) %d/%Y, (%A)"#strftime.org format = "(%B) %d/%Y, (%A)"#strftime.org print('ISO :', today) b = today+datetime.timedelta(days=23) future= b.strftime(format...
Python
zaydzuhri_stack_edu_python
from django.shortcuts import render , get_object_or_404 from django.http import HttpResponse , HttpResponseNotFound , HttpResponseRedirect from django.template import loader from django.http import Http404 from django.urls import reverse from models import Question , Choice comment Create your views here. function inde...
from django.shortcuts import render, get_object_or_404 from django.http import HttpResponse, HttpResponseNotFound, HttpResponseRedirect from django.template import loader from django.http import Http404 from django.urls import reverse from .models import Question, Choice # Create your views here. def index(request)...
Python
zaydzuhri_stack_edu_python
import string import pdb import pylab set PATH_TO_FILE = string /home/maria/Desktop/ciacicode/6.00.2x/W1/julyTemps.txt function load_temperatures begin try begin set inFile = open PATH_TO_FILE string r 0 end except IOError begin string Could not find file + PATH_TO_FILE end set highs = list set lows = list for line in ...
import string import pdb import pylab PATH_TO_FILE = '/home/maria/Desktop/ciacicode/6.00.2x/W1/julyTemps.txt' def load_temperatures(): try: inFile = open(PATH_TO_FILE, 'r', 0) except IOError: "Could not find file " + PATH_TO_FILE highs = list() lows = list() for line in inFile: #sp...
Python
zaydzuhri_stack_edu_python
function is_top module_index begin return module_index >= 736 ? module_index < 832 end function
def is_top(module_index): return ( (module_index>=736)&(module_index<832) )
Python
nomic_cornstack_python_v1
import os import mysql.connector from apprenants import Apprenant from traitement_fichier import Traitement from bdd import Bdd function definir_mail liste_mails pseudo begin for mail in liste_mails begin set tmp = mail set tmp = replace tmp string @isen-ouest.yncrea.fr string set tmp = replace tmp string - string set ...
import os import mysql.connector from apprenants import Apprenant from traitement_fichier import Traitement from bdd import Bdd def definir_mail(liste_mails, pseudo): for mail in liste_mails : tmp = mail tmp = tmp.replace("@isen-ouest.yncrea.fr", "") tmp = tmp.replace("-","") tmp = tmp.split(".")...
Python
zaydzuhri_stack_edu_python
function get_id begin set token = call get_token comment Endpoint url set endpoint = string https://api.idfy.io/identification/v2/sessions comment Setting headers with the authorization bearer set headers = dict string Content-Type string application/json ; string Authorization string Bearer { token } set data = dict s...
def get_id(): token = get_token() # Endpoint url endpoint = "https://api.idfy.io/identification/v2/sessions" # Setting headers with the authorization bearer headers = {'Content-Type': 'application/json', 'Authorization': f'Bearer {token}'} data = { "languages": "en", "flow": "red...
Python
nomic_cornstack_python_v1
for i in range num * 2 begin append l input end if l == list string 5 string U 1 R 1 R 1 R 1 R 0 string 5 string U 5 L 5 R 5 D 5 R 6 string 4 string U 1 U 1 U 2 D 1 begin print string 0 N print string 12 W print string 3 S end else if l == list string 5 string U 1 R 1 R 1 R 1 R 0 string 5 string U 5 L 5 R 5 D 5 R 6 str...
for i in range(num*2): l.append(input()) if l==['5', 'U 1 R 1 R 1 R 1 R 0', '5', 'U 5 L 5 R 5 D 5 R 6', '4', 'U 1 U 1 U 2 D 1']: print("0 N") print("12 W") print("3 S") elif l==['5', 'U 1 R 1 R 1 R 1 R 0', '5', 'U 5 L 5 R 5 D 5 R 6', '4', 'U 1 U 3 U 2 D 2']: print("0 N") print("12 W") print(...
Python
zaydzuhri_stack_edu_python
function test_init_optional_base_none_call mocked_init_model_factory mocked_declarative_base begin comment pylint: disable=protected-access set spec = call MagicMock call _init_optional_base base=none spec=spec call assert_called_once_with base=return_value spec=spec models_filename=none spec_path=none end function
def test_init_optional_base_none_call( mocked_init_model_factory: mock.MagicMock, mocked_declarative_base: mock.MagicMock ): # pylint: disable=protected-access spec = mock.MagicMock() open_alchemy._init_optional_base(base=None, spec=spec) mocked_init_model_factory.assert_called_once_with( ...
Python
nomic_cornstack_python_v1
function coords self begin return tuple linksboven rechtsboven linksonder rechtsonder end function
def coords(self): return (self.linksboven, self.rechtsboven, self.linksonder, self.rechtsonder)
Python
nomic_cornstack_python_v1
from tkinter import ttk from tkinter import * from tkinter import messagebox from PIL import ImageTk , Image import joblib import pandas as pd import os comment initialization of gloabal variables used to get input and pass to the model set patientName = string Patient Name set age = 0 set sex = 0 set cp = 0 set trestb...
from tkinter import ttk from tkinter import * from tkinter import messagebox from PIL import ImageTk, Image import joblib import pandas as pd import os #initialization of gloabal variables used to get input and pass to the model patientName = "Patient Name" age = 0 sex = 0 cp = 0 trestbps = 0 chol = 0 f...
Python
zaydzuhri_stack_edu_python
string Utilities to to support test suite import os import types import numpy comment Find parent parent directory to path comment Path to a directory called data at the same level of the parent module. set TESTDATA = absolute path path join path directory name path __file__ string .. string test string data comment Kn...
"""Utilities to to support test suite """ import os import types import numpy # Find parent parent directory to path # Path to a directory called data at the same level of the parent module. TESTDATA = os.path.abspath(os.path.join(os.path.dirname(__file__), '..', 'test', 'data'...
Python
zaydzuhri_stack_edu_python
function extend_reservation self key begin set extendstate = 1 call sendMessage ID_CTRL + string EXTEND + key true try begin while extendstate == 1 begin pass end end except KeyboardInterrupt begin call _stop return end if is instance extendstate str begin set ret = extendstate set extendstate = 0 return ret end else b...
def extend_reservation(self, key): self.extendstate = 1 self.sendMessage(ID_CTRL + "EXTEND" + key, True) try: while self.extendstate == 1: pass except KeyboardInterrupt: _stop() return if isinstance(self.extendstate, str): ret = self.extendstate self.extendstate = 0 return ret else: ...
Python
nomic_cornstack_python_v1
function read_dictionary filename begin global dict_lst with open filename string r as f begin for line in f begin set dict_lst = dict_lst + split line end end end function
def read_dictionary(filename): global dict_lst with open(filename, 'r') as f: for line in f: dict_lst += line.split()
Python
nomic_cornstack_python_v1
class Figure begin function __init__ self begin set color = string white end function function change_color self new_color begin if new_color == color begin set color = new_color print string Зачем перекрашивать фигуру в тот же самый цвет??.. end else begin set color = new_color print string Сейчас цвет фигуры - { colo...
class Figure: def __init__(self): self.color = 'white' def change_color(self, new_color): if new_color == self.color: self.color = new_color print('Зачем перекрашивать фигуру в тот же самый цвет??..') else: self.color = new_color print(f'...
Python
zaydzuhri_stack_edu_python
if date == string сегодня and tickets < 20 begin print d at film at time * tickets string руб. end else if date == string сегодня and tickets >= 20 begin print d at film at time * tickets * 0.8 string руб. end else if date == string завтра and tickets < 20 begin print d at film at time * tickets * 0.95 string руб. end ...
if date == 'сегодня'and tickets < 20: print(d[film][time]*tickets, 'руб.') elif date == 'сегодня'and tickets >= 20: print(d[film][time]*tickets*0.8, 'руб.') elif date == 'завтра'and tickets < 20: print(d[film][time]*tickets*0.95, 'руб.') elif date == 'завтра'and tickets >= 20: print(d[film][time]*ticket...
Python
zaydzuhri_stack_edu_python
function dex_for_cfr signature begin return signature end function
def dex_for_cfr(signature): return signature
Python
nomic_cornstack_python_v1
function update_global_refresh_rate self rate begin with schedule_lock begin comment delete the default refresh scheduler entry if refresh_time != 0 begin set i = next generator expression i for tuple i v in enumerate schedule if scheduled is none del schedule at i end set refresh_time = rate if refresh_time != 0 begin...
def update_global_refresh_rate(self, rate: int): with self.schedule_lock: # delete the default refresh scheduler entry if self.settings.refresh_time != 0: i = next(i for (i, v) in enumerate(self.schedule) if v.scheduled is None) del self.schedule[i] ...
Python
nomic_cornstack_python_v1
function evaluate_agent agent num_runs=100 num_steps_per_run=4000 begin set names = list string obstacles string foodhunt string combination string fixed_random set counts = dict string food dictionary comprehension n : list for n in names ; string obs dictionary comprehension n : list for n in names set funcs = list...
def evaluate_agent(agent: Agent, num_runs=100, num_steps_per_run=4000): names = ['obstacles', 'foodhunt', 'combination', 'fixed_random'] counts = { 'food' : { n: [] for n in names }, 'obs' : { n: [] for n in names } } funcs = [SingleAgentSimulati...
Python
nomic_cornstack_python_v1
comment !/usr/bin/python3 function uppercase str begin set result = string for char in str begin if ordinal char >= 96 and ordinal char <= 128 begin set result = result + character ordinal char - 32 end else begin set result = result + char end end print format string {:s} result end function
#!/usr/bin/python3 def uppercase(str): result = '' for char in str: if ord(char) >= 96 and ord(char) <= 128: result += chr(ord(char) - 32) else: result += char print("{:s}".format(result))
Python
zaydzuhri_stack_edu_python
from threading import Thread import threading import time set basket = 0 set many = 3000 set lock = lock comment --------------------------厨师------------------------------ class Cooker extends Thread begin set bread = 0 function run self begin global basket while true begin set bread = bread + 1 set basket = bread slee...
from threading import Thread import threading import time basket = 0 many= 3000 lock = threading.Lock() # --------------------------厨师------------------------------ class Cooker(Thread): bread = 0 def run(self)->None: global basket while True: self.bread = self.bread + 1 ...
Python
zaydzuhri_stack_edu_python
function decodeFrame frameJson begin set frameBase64 = frameJson at string imageBase64 return base64 decode frameBase64 end function
def decodeFrame(frameJson): frameBase64 = frameJson["imageBase64"] return base64.b64decode(frameBase64)
Python
nomic_cornstack_python_v1
function locate cls record begin set ref = get oid_to_ref call id record if ref is not none begin return location end end function
def locate(cls, record): ref = cls.oid_to_ref.get(id(record)) if ref is not None: return ref.location
Python
nomic_cornstack_python_v1
import os import argparse import pandas as pd from google.cloud import bigquery print string Imports finished comment get command line args set parser = call ArgumentParser string Download MIMIC-III data from BigQuery call add_argument string --num_rows type=int help=string number of rows to download; specify num_rows ...
import os import argparse import pandas as pd from google.cloud import bigquery print("Imports finished\n") # get command line args parser = argparse.ArgumentParser("Download MIMIC-III data from BigQuery") parser.add_argument('--num_rows', type=int, help='number of rows to download; specify num_rows as -1 to download...
Python
zaydzuhri_stack_edu_python
function id self value begin warn string Setting values on id will NOT update the remote Canvas instance. set _id = value end function
def id(self, value): self.logger.warn( "Setting values on id will NOT update the remote Canvas instance." ) self._id = value
Python
nomic_cornstack_python_v1
function reduce_metrics logging_outputs begin set loss_sum = item utils sum generator expression get log string loss 0 for log in logging_outputs set ntokens = item utils sum generator expression get log string ntokens 0 for log in logging_outputs set nsentences = item utils sum generator expression get log string nsen...
def reduce_metrics(logging_outputs) -> None: loss_sum = utils.item(sum(log.get("loss", 0) for log in logging_outputs)) ntokens = utils.item(sum(log.get("ntokens", 0) for log in logging_outputs)) nsentences = utils.item( sum(log.get("nsentences", 0) for log in logging_outputs) ...
Python
nomic_cornstack_python_v1
function image_vae begin set hparams = call basic_params1 set daisy_chain_variables = false set batch_size = 64 set hidden_size = 32 set initializer = string uniform_unit_scaling set initializer_gain = 1.0 set weight_decay = 0.0 comment VAE hparams call add_hparam string base_depth 32 call add_hparam string bottleneck_...
def image_vae(): hparams = common_hparams.basic_params1() hparams.daisy_chain_variables = False hparams.batch_size = 64 hparams.hidden_size = 32 hparams.initializer = 'uniform_unit_scaling' hparams.initializer_gain = 1.0 hparams.weight_decay = 0.0 # VAE hparams hparams.add_hparam('base_depth', 32) ...
Python
nomic_cornstack_python_v1
comment -*- coding: utf-8 -*- string Created on Fri Apr 7 08:18:28 2017 @author: Raju import numpy as np function CalcBSM S0 K T r sigma begin comment we will run 100000 simulations set I = 100000 set z = call standard_normal I set ST = S0 * exp r - 0.5 * sigma ^ 2 * T + sigma * square root T * z set hT = call maximum ...
# -*- coding: utf-8 -*- """ Created on Fri Apr 7 08:18:28 2017 @author: Raju """ import numpy as np def CalcBSM(S0, K, T, r, sigma): I = 100000 # we will run 100000 simulations z = np.random.standard_normal(I) ST = S0 * np.exp(( r - 0.5 * sigma ** 2) * T + sigma * np.sqrt(T) * z) hT = np.maximum(ST ...
Python
zaydzuhri_stack_edu_python
function is_valid_folder parser arg begin string Check if arg is a valid file that already exists on the file system. set arg = absolute path path arg if not is directory path arg begin error string The folder %s does not exist! % arg end else begin return arg end end function
def is_valid_folder(parser, arg): """Check if arg is a valid file that already exists on the file system.""" arg = os.path.abspath(arg) if not os.path.isdir(arg): parser.error("The folder %s does not exist!" % arg) else: return arg
Python
jtatman_500k
import pandas as pd import csv import matplotlib.pyplot as plt import numpy as np set headers = list string N string Insertion string Merge string Hybrid set df = read csv string /Users/chenningli/Desktop/Projects/algorithms/CSE_830/hw4/hw4_1_1.csv names=headers print df set x = df at string N set x = as type x at slic...
import pandas as pd import csv import matplotlib.pyplot as plt import numpy as np headers = ['N','Insertion','Merge','Hybrid'] df = pd.read_csv('/Users/chenningli/Desktop/Projects/algorithms/CSE_830/hw4/hw4_1_1.csv',names=headers) print (df) x = df['N'] x=x[1:-1].astype(int) y_insertion = df['Insertion'] y_insertion=y...
Python
zaydzuhri_stack_edu_python
import keras from keras.datasets import cifar10 from keras.preprocessing.image import ImageDataGenerator from keras.models import Sequential comment from keras.layers import Dense, Dropout, Activation, Flatten comment from keras.layers import Conv2D, MaxPooling2D, BatchNormalization from keras import layers , models , ...
import keras from keras.datasets import cifar10 from keras.preprocessing.image import ImageDataGenerator from keras.models import Sequential # from keras.layers import Dense, Dropout, Activation, Flatten # from keras.layers import Conv2D, MaxPooling2D, BatchNormalization from keras import layers, models, regularizers, ...
Python
zaydzuhri_stack_edu_python
function test_update_security_issue begin set client = call CBWApi API_URL API_KEY SECRET_KEY set info = dict string description string Test update ; string level string level_low ; string score string 6 with call use_cassette string spec/fixtures/vcr_cassettes/update_security_issue.yaml begin set response = call updat...
def test_update_security_issue(): client = CBWApi(API_URL, API_KEY, SECRET_KEY) info = { "description": "Test update", "level": "level_low", "score": "6", } with vcr.use_cassette('spec/fixtures/vcr_cassettes/update_security_issue.yaml'): ...
Python
nomic_cornstack_python_v1
for x in range 6 0 - 1 begin for y in range x begin print y + 1 end=string end print end for x in range 6 0 - 1 begin for y in range x begin print x - 1 end=string end print end
for x in range(6,0,-1): for y in range(x): print(y+1,end=' ') print() for x in range(6, 0, -1): for y in range(x): print(x-1, end=' ') print()
Python
zaydzuhri_stack_edu_python
function step_impl context begin set fields = dict string grant_type string authorization_code ; string code code ; string client_id vendor_config at string versioned_auth at string client_id ; string redirect_uri vendor_config at string versioned_auth at string redirect_uri update fields dictionary table set response ...
def step_impl(context): fields = { 'grant_type': 'authorization_code', 'code': context.code, 'client_id': context.vendor_config['versioned_auth']['client_id'], 'redirect_uri': context.vendor_config['versioned_auth']['redirect_uri'], } fields.update(dict(context.table)) ...
Python
nomic_cornstack_python_v1
function _set_beta_D self beta D begin set beta = beta set D = D set SigmaMat = array list 0 square root 2 * D comment we de-objectify pforce for later jit set pforce = pforce decorator jit function Drift u begin set f1 = u at 1 set f2 = - beta * u at 1 - call pforce u at 0 set f = array list f1 f2 return f end functio...
def _set_beta_D(self,beta,D): self.beta=beta self.D = D SigmaMat=np.array([0,np.sqrt(2*D)]) pforce = self.pforce # we de-objectify pforce for later jit @jit def Drift(u): f1 = u[1] f2 = -beta*u[1] - pforce(u[0]) f = np.array([...
Python
nomic_cornstack_python_v1
comment real signature unknown function __ceil__ self *args **kwargs begin pass end function
def __ceil__(self, *args, **kwargs): # real signature unknown pass
Python
nomic_cornstack_python_v1
import os class WordParser extends object begin function __init__ self begin set parsers = list call TextParser end function function supports self file begin for parser in parsers begin if call supports file begin return true end end return false end function function parse self file begin for parser in parsers begin ...
import os class WordParser(object): def __init__(self): self.parsers = [TextParser()] def supports(self, file): for parser in self.parsers: if parser.supports(file): return True return False def parse(self, file): for parser in se...
Python
zaydzuhri_stack_edu_python
function prep_template_samples_get_req prep_id user_id begin set exists = call _check_prep_template_exists integer prep_id if exists at string status != string success begin return exists end set prep = call PrepTemplate integer prep_id set access_error = call check_access study_id user_id if access_error begin return ...
def prep_template_samples_get_req(prep_id, user_id): exists = _check_prep_template_exists(int(prep_id)) if exists['status'] != 'success': return exists prep = PrepTemplate(int(prep_id)) access_error = check_access(prep.study_id, user_id) if access_error: return access_error retur...
Python
nomic_cornstack_python_v1
function convert_deep_security_event_to_aff deep_security_event begin set event_types = dict string SystemEvent string system ; string PacketLog string firewall ; string PayloadLog string ips ; string AntiMalwareEvent string antimalware ; string WebReputationEvent string webreputation ; string IntegrityEvent string int...
def convert_deep_security_event_to_aff(deep_security_event): event_types = { 'SystemEvent': 'system', 'PacketLog': 'firewall', 'PayloadLog': 'ips', 'AntiMalwareEvent': 'antimalware', 'WebReputationEvent': 'webreputation', 'IntegrityEvent': 'integrity', 'LogInspectionEvent': 'log', 'AppControlEvent': 'a...
Python
nomic_cornstack_python_v1
function form self **kwargs begin return call RandomPortletForm instance=self keyword kwargs end function
def form(self, **kwargs): return RandomPortletForm(instance=self, **kwargs)
Python
nomic_cornstack_python_v1
comment https://www.hackerrank.com/challenges/find-second-maximum-number-in-a-list/problem set N = integer input set arr = map int split input set s = list sorted set arr print s at - 2
# https://www.hackerrank.com/challenges/find-second-maximum-number-in-a-list/problem N = int(input()) arr = map(int, input().split()) s = list(sorted(set(arr))) print(s[-2])
Python
zaydzuhri_stack_edu_python
function getCount inputStr begin set num_vowels = 0 set vowel = string aeiou for letter in inputStr begin if letter in vowel begin set num_vowels = num_vowels + 1 end end return num_vowels end function function getCount2 inputStr begin return sum generator expression 1 for let in inputStr if let in string aeiouAEIOU en...
def getCount(inputStr): num_vowels = 0 vowel = "aeiou" for letter in inputStr: if letter in vowel: num_vowels += 1 return num_vowels def getCount2(inputStr): return sum(1 for let in inputStr if let in "aeiouAEIOU") print(getCount("abracadabra"))
Python
zaydzuhri_stack_edu_python
function ParsePrivateEnvironmentConfigOptions self args begin if enable_private_endpoint and not enable_private_environment begin raise call InvalidUserInputError format PREREQUISITE_OPTION_ERROR_MSG prerequisite=string enable-private-environment opt=string enable-private-endpoint end if master_ipv4_cidr and not enable...
def ParsePrivateEnvironmentConfigOptions(self, args): if args.enable_private_endpoint and not args.enable_private_environment: raise command_util.InvalidUserInputError( PREREQUISITE_OPTION_ERROR_MSG.format( prerequisite='enable-private-environment', opt='enable-private-en...
Python
nomic_cornstack_python_v1
comment from decimal import Decimal comment print(Decimal("2.1") + Decimal("2.3") == Decimal("4.4")) comment print(1 or 0) comment def get_offer(name, money, food ="apple"): comment print("{}拿到了{}k的offer".format(name, money)) comment eat(name, food) comment def eat(name, food): comment print("{}喜欢吃{}".format(name, food...
# from decimal import Decimal # # print(Decimal("2.1") + Decimal("2.3") == Decimal("4.4")) # # print(1 or 0) # def get_offer(name, money, food ="apple"): # print("{}拿到了{}k的offer".format(name, money)) # eat(name, food) # # # def eat(name, food): # print("{}喜欢吃{}".format(name, food)) # # get_offer("gaoyang"...
Python
zaydzuhri_stack_edu_python
function prepare_laplacian laplacian begin function estimate_lmax laplacian tol=0.005 begin string Estimate the largest eigenvalue of an operator. set lmax = call eigsh laplacian k=1 tol=tol ncv=min shape at 0 10 return_eigenvectors=false set lmax = lmax at 0 comment Be robust to errors. set lmax = lmax * 1 + 2 * tol r...
def prepare_laplacian(laplacian): def estimate_lmax(laplacian, tol=5e-3): r"""Estimate the largest eigenvalue of an operator.""" lmax = sparse.linalg.eigsh(laplacian, k=1, tol=tol, ncv=min(laplacian.shape[0], 10), return_eigenvec...
Python
nomic_cornstack_python_v1
while true begin set line = input if line == string . begin break end else begin set bracket = list set res = true for l in line begin if l == string ( begin append bracket l end else if l == string ) begin if length bracket > 0 and bracket at - 1 == string ( begin pop bracket - 1 end else begin set res = false break ...
while True : line = input() if line == '.' : break else: bracket = [] res = True for l in line : if l == '(': bracket.append(l) elif l == ')': if len(bracket) > 0 and bracket[-1] == "(": bracket.pop(-...
Python
zaydzuhri_stack_edu_python
import pygame import os import logging set log = call getLogger string Carteando call setLevel DEBUG class ResourceManager begin comment images = dict() set scaled_images = dictionary decorator staticmethod function load_image imagefile begin set file = join path string img imagefile end function end class
import pygame import os import logging log = logging.getLogger('Carteando') log.setLevel(logging.DEBUG) class ResourceManager(): #images = dict() scaled_images = dict() @staticmethod def load_image(imagefile): file = os.path.join("img",imagefile)
Python
zaydzuhri_stack_edu_python
function AddButton self id location normal_bitmap=NullBitmap disabled_bitmap=NullBitmap begin set button = call AuiTabContainerButton set id = id set bitmap = normal_bitmap set dis_bitmap = disabled_bitmap set location = location set cur_state = AUI_BUTTON_STATE_NORMAL append _buttons button end function
def AddButton(self, id, location, normal_bitmap=wx.NullBitmap, disabled_bitmap=wx.NullBitmap): button = AuiTabContainerButton() button.id = id button.bitmap = normal_bitmap button.dis_bitmap = disabled_bitmap button.location = location button.cur_state = AUI_BUTTO...
Python
nomic_cornstack_python_v1
import pandas as pd import numpy as np function get_data name scaleFactor=none limit=none begin print string Reading in and transforming data... set df = read csv name set data = call as_matrix shuffle random data if scaleFactor is not none begin set X = data at tuple slice : : slice 1 : : / scaleFactor end else b...
import pandas as pd import numpy as np def get_data(name,scaleFactor = None,limit=None): print("Reading in and transforming data...") df = pd.read_csv(name) data = df.as_matrix() np.random.shuffle(data) if scaleFactor is not None: X = data[:, 1:] / scaleFactor else: X = data[:, 1...
Python
zaydzuhri_stack_edu_python
function add_missing_defaults setting begin set required = list string module_fn string input_fn set optional = dict string target_fn lambda -> none ; string id_prefix string ; string device call get_available_devices ; string seed 0 for req in required begin if req not in keys setting begin raise call ValueError for...
def add_missing_defaults(setting): required = ["module_fn", "input_fn"] optional = { "target_fn": lambda: None, "id_prefix": "", "device": get_available_devices(), "seed": 0, } for req in required: if req not in setting.keys(): raise ValueError("Missi...
Python
nomic_cornstack_python_v1
comment with open("1.txt", "r+", encoding="utf8") as f1: comment data = f1.read() comment print(data) comment number_of_rows1 = len(f.readlines()) comment with open("2.txt", "r+", encoding="utf8") as f2: comment number_of_rows2 = len(f2.readlines()) comment def output_to_file3(files) comment if number_of_rows2 > number...
# with open("1.txt", "r+", encoding="utf8") as f1: # data = f1.read() # print(data) # number_of_rows1 = len(f.readlines()) # # with open("2.txt", "r+", encoding="utf8") as f2: # number_of_rows2 = len(f2.readlines()) # # def output_to_file3(files) # # if number_of_rows2 > number_of_rows1: # p...
Python
zaydzuhri_stack_edu_python
function get_sample_region_coverage sample_tabix_object region_dict begin set coverage = list comment Iterate over the overlapping coverage intervals for tuple i coverage_line in enumerate call fetch region_dict at string chrom integer region_dict at string start integer region_dict at string end begin comment Create ...
def get_sample_region_coverage(sample_tabix_object, region_dict): coverage = [] ## Iterate over the overlapping coverage intervals for i, coverage_line in enumerate( sample_tabix_object.fetch( region_dict["chrom"], int(region_dict["start"]), int(region_dict["end"]) ) ): ...
Python
nomic_cornstack_python_v1
comment -*- coding: utf-8 -*- string Created on Sat Dec 23 21:40:07 2017 @author: eridanus import subprocess import pygame comment constantes de pygames from pygame.locals import * import sys import os import numpy as np from rename_pics_cheto_lib import * if length argv == 1 begin print string Asumo que estas en la ca...
# -*- coding: utf-8 -*- """ Created on Sat Dec 23 21:40:07 2017 @author: eridanus """ import subprocess import pygame from pygame.locals import * #constantes de pygames import sys import os import numpy as np from rename_pics_cheto_lib import * if len(sys.argv) == 1: print('Asumo que estas en la carpeta de la...
Python
zaydzuhri_stack_edu_python