text stringlengths 38 1.54M |
|---|
inputFile = "day1_input.txt"
with open(inputFile) as f:
fileContent = f.readlines()
fileContent = list(map(int, fileContent))
freq = 0
freqs = [0]
found = False
while found == False:
for update in fileContent:
freq += update
if freq in freqs:
print(freq)
found = True
... |
# lowpower.py
# usb frequency wfi stop standby power: USB Vin 3.3v
# GPIO pin config, what peripherals are enabled
import pyb
import stm
def dostop() :
while True :
# LPDS disable regulator, disable ADC DAC ?
pyb.stop() # pin interrupt or RTC could wake
def dostandby() :
while True :... |
# -*- coding: utf-8 -*-
DATA_DIR = '/home/asier/git/nicon/nicon/data'
SUBJECT = 'sub-01'
OUTPUT_DIR = '/home/output_nicon'
WORK_DIR = '/tmp/tmp_nicon'
QC = False
FMRI = True
ICA_RSN = False
DWI = True
DWI_CORRECTION = False
CONFOUNDS_ID = ['FramewiseDisplacement',
'WhiteMatter',
'Glob... |
# Copyright (c) 2014, Jan Varho
#
# Permission to use, copy, modify, and/or distribute this software for any
# purpose with or without fee is hereby granted, provided that the above
# copyright notice and this permission notice appear in all copies.
#
# THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARR... |
'''
Write a script that creates a dictionary of keys, n and values n*n for numbers 1-10. For example:
result = {1: 1, 2: 4, 3: 9, ...and so on}
'''
input_string = input("Enter the elements of the list separated with spaces: ")
split_list = input_string.split()
for i in range(0, len(split_list)):
split_list[i] = i... |
__author__ = 'Eduardo Freire Mangabeira'
__maintainer__ = 'Eduardo Freire Mangabeira'
__email__ = 'edu.mangaba@gmail.com'
import os
def read_entrada(arquivo):
'''
read_entrada(arquivo)
Recebe o arquivo .txt com valores e os retorna numa lista.
'''
try:
with open(arquivo, 'r') as entrada:
valores... |
from coffeescript.storage import CoffeescriptFileStorage
from django.contrib.staticfiles.finders import BaseStorageFinder
class CoffeescriptFinder(BaseStorageFinder):
"""
A staticfiles finder that looks in COFFEESCRIPT_ROOT
for compiled files, to be used during development
with staticfiles development... |
n = int(input('Digite um número: '))
d = n*2
t = n*3
r = n**(1/2)
print('O dobro de {} vale {}! \n O triplo vale {}! \n A raiz quadrada vale {:.2f}.'.format(n, d, t, r)) |
from scipy.integrate import odeint
import numpy as np
import pylab as pl
import lib
i_ext_e = 1.4
i_ext_i = 0.0
g_ei = 0.25
g_ie = 0.25
v_rev_e = 0.0
v_rev_i = -75.0
tau_r_e = 0.5
tau_peak_e = 0.5
tau_d_e = 3.0
tau_r_i = 0.5
tau_peak_i = 0.5
tau_d_i = 9.0
t_final = 200.0
dt = 0.01
# ---------------------------------... |
from google.appengine.ext import ndb
import logging
class SessionAuthEntry(ndb.Model):
"""
This class represents a user's session token.
Each user should have one or more of these entries, parented by a UserEntry.
"""
timestamp = ndb.DateTimeProperty(auto_now_add=True)
class UserEntry(ndb.Model)... |
from django.urls import path
from . import views
urlpatterns = [
path('kids', views.kids, name='kids'),
] |
from tkinter import *
import Keyboard_Control as keyboard
import Windows_Control as windows
import Volume_Control as volume
import Youtube_Control as youtube
def nothing(arg):
pass
Function_Dict = {"rot":volume.Set_Volume ,
"touch": youtube.Open_Youtube,
"light": nothing,
... |
import pandas as pd
def getCountryData(country):
if (country == "US"):
return pd.read_csv("usa_trending_videos.csv")
elif (country == "CA"):
return pd.read_csv("./transformed/CA_trending_videos.csv")
elif (country == "UK"):
return pd.read_csv("./transformed/GB_trending_videos.csv")
... |
import math as mt
#Determine if a coin system is canonical by comparing the greedy and dynamic solutions to the coin change problem.
#Copy the list of denominations from a text file to the list den.
denf = open("denominations.txt")
den =[int(element.strip()) for element in denf]
denf.close()
print(den)
#Functions:
... |
# -*- coding: utf-8 -*-
'''
Created on 2018. 3. 5.
@author: HyechurnJang
'''
import os
import re
from pygics import rest
from model import EPG, EP, MacIP
from core import Tracker
tracker = Tracker(
os.environ.get('APIC_IP'),
os.environ.get('APIC_USERNAME'),
os.environ.get('APIC_PASSWORD'),
... |
"""
ARMA process manipulation
=========================
"""
# %%
# In this example we will expose some of the services exposed by an :math:`ARMA(p,q)` object, namely:
#
# - its AR and MA coefficients thanks to the methods *getARCoefficients,
# getMACoefficients*,
#
# - its white noise thanks to the method *getWhit... |
"""Support for interacting with Spotify Connect."""
from asyncio import run_coroutine_threadsafe
import datetime as dt
from datetime import timedelta
import logging
from typing import Any, Callable, Dict, List, Optional
from aiohttp import ClientError
from spotipy import Spotify, SpotifyException
from yarl import URL
... |
"""Graph expression context."""
from __future__ import absolute_import, division, print_function
from datashape import unify
class ExprContext(object):
"""
Context for blaze graph expressions.
This keeps track of a mapping between graph expression nodes and the
concrete data inputs (i.e. blaze Arra... |
"""
This module contains classes of CouchDB documents.
Part of 'Adaptor' framework.
Author: Michael Pankov, 2012-2013.
Please do not redistribute.
"""
import couchdbkit as ck
# The documents below sometimes correspond to plain records used
# to aggregate data during the work of framework
# (which are defined above... |
import PIL
import tensorflow as tf
import albumentations
import pandas as pd
import os
import torch
import numpy as np
from fastai.vision import nn, models, create_head, AdaptiveConcatPool2d
from imageai.Detection.Custom import CustomObjectDetection
from .patterns.singleton import Singleton
class SiameseBannerRecogni... |
from __future__ import print_function
from __future__ import division
__author__ = 'michael.pearmain'
import pandas as pd
from sklearn.cross_validation import cross_val_score
from sklearn.ensemble import RandomForestClassifier as RFC
from bayesian_optimization import BayesianOptimization
from make_data import make_da... |
from datetime import datetime
from mongoengine import *
from projects.models import BaseDocument
class User(BaseDocument):
no = SequenceField()
user_id = StringField(required=True, unique=True)
user_pw = StringField(required=True)
created_at = DateTimeField(default=datetime.now().replace(microsecond=0... |
import numpy as np
def calc_observed_rmse(r, rHat, mask):
errA = np.where(mask != 0, r, 0)
errB = np.where(mask != 0, rHat, 0)
count = np.sum(mask)
res = np.square(np.subtract(errA, errB)).mean() * np.size(mask) / count
return res
def calc_unobserved_rmse(r, rHat, mask):
errA = n... |
import numpy as np
class KNearestNeighbor(object):
def train(self, X, y):
self.X_train = X
self.y_train = y
def test(self, X, k=1):
dists = self.compute_distances(X)
return self.predict_labels(dists, k=k)
def compute_distances(self, X):
... |
"""Module including useful functions relative to rigid motion.
Functions:
augment_matrix_coord: returns augmented vector
get_rotation_mat_single_axis: computes rotation matrix around specificied axis (x,y or z)
get_rigid_motion_mat_from_euler: computes 4X4 rigid transformation matrix, from the specified se... |
from rgs.ribbons.Ribbon import (Ribbon, squares2ribbon)
def test_Ribbon():
ribbon = Ribbon(0, 0, [0, 0, 0, 0, 1, 1, 1, 0, 1, 0, 1, 1, 1])
assert ribbon.__str__() == "(0,0), [0, 0, 0, 0, 1, 1, 1, 0, 1, 0, 1, 1, 1]"
def test_squares2ribbon():
squares = [(0, 2), (0, 3), (0, 4)]
ribbon = squares2ribbon(... |
import subprocess
import re
import os
import difflib
import json
from subprocess import TimeoutExpired # for some reason this isn't included when importing subprocess
class compileTimeException(Exception):
pass
# Main data structure used to store problems on runtime
answerDict = {}
# Runs a list ... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
import os
import sys
from PySide import QtCore, QtGui
import core
import processing
from ui_main import Ui_Pictor
class Pictor(QtGui.QMainWindow):
def __init__(self, parent):
super(Pictor, self).__init__()
self.ui = Ui_Pictor()
self.ui.setupUi(sel... |
from django.shortcuts import render, redirect
from django.http import HttpResponse
from django.forms import inlineformset_factory
from .models import Post
from django.views.generic import ListView, DetailView, CreateView, UpdateView, DeleteView
from django.urls import reverse_lazy
from django.contrib.auth import authen... |
# -*- coding: utf-8 -*-
"""
Created on Fri May 10 02:08:00 2019
@author: nnamdy-jnr
"""
from elasticsearch import Elasticsearch
import requests
import json
with open('pubmedTest.json') as f:
doc = json.load(f)
#
es=Elasticsearch()
#
#e1={
# "first_name":"nitin",
# "last_name":"panwar",
# "age": 27,
# ... |
# Copyright 2020 by B. Knueven, D. Mildebrath, C. Muir, J-P Watson, and D.L. Woodruff
# This software is distributed under the 3-clause BSD License.
''' Utilities for reading and writing W and
x-bar values in and out of csv files.
Written: DLW July 2019
Modified: DTM Aug 2019
Could stand to be re-fa... |
#113412924 Apr/18/2021 17:50UTC+5.5 Shan_XD 1359B - New Theatre Square PyPy 3 Accepted 467 ms 6300 KB
def white_pavement(pav , x, y):
nx=0
ny=0
for i in pav:
sp = i.split('*')
for j in sp:
if len(j)%2==0:
nx+= len(j)//2
else:
nx += ... |
import numpy as np
npArray = np.arange(1, 27)
indexNum = npArray[19]
print("---Indexing---")
print("npArray:", npArray, " Type Of npArray:", type(npArray))
print("Index(19):", indexNum, " Type Of Index:", type(indexNum))
indexNumAdd = indexNum + 6
print("Index Addition:", indexNumAdd, " Type:", type(indexNumAdd))
indA... |
marks = [(101, 80), (102, 85), (104, 50), (103, 70)]
for t in sorted(marks, key = lambda t: t[1]):
print(t)
|
from botocore.vendored import requests
import json
import boto3
import hashlib
import base64
import logging
import threading
import uuid
import os
ddb = boto3.client('dynamodb')
def timeout(event, context):
raise Exception('Execution is about to time out, exiting...')
def store_deidentified_message(message, ... |
class CircularBuffer:
def __init__(self, size=30):
self.size = size
self.buffer = [None for _ in range(size)]
self.start = 0
def add_frame(self, frame):
self.buffer[self.start] = frame
self.start = (self.start + 1) % self.size
def save(self, video_writer):
... |
import boto3
ec2_client= boto3.client("ec2")
resp = ec2_client.run_instances(
ImageId='ami-0447a12f28fddb066',
InstanceType='t2.micro',
MaxCount=1,
MinCount=1,
)
print("response ", resp)
for ins... |
#!/usr/bin/grython
'''
Beast workflow script
Created on 04/01/2013
@author: markus
'''
from grisu.Grython import serviceInterface as si
from grisu.frontend.model.job import JobObject
from grisu.jcommons.utils import WalltimeUtils
from grisu.model import FileManager, GrisuRegistryManager
from optparse import Option... |
# Teste seu codigo aos poucos.
# Nao teste tudo no final, pois fica mais dificil de identificar erros.
# Nao se intimide com as mensagens de erro. Elas ajudam a corrigir seu codigo.
venda = float(input("VENDAS: "))
Lucro = print(round((venda/100) * 30, 2)) |
# Copyright 2017 Red Hat, Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by appli... |
from guestbook01.models import findall,insert,deletebynoandpw
def test_findall():
results = findall()
for result in results:
print(f"""{result["no"]}:{result["name"]}:{result["reg_date"]}:{result["message"]}""")
def test_instert():
name = "DingDong"
password = "1234"
message = "hola hola!"... |
from kaggle_environments import evaluate, make, utils
import gym
env = make("connectx", debug=True)
#env.render()
def my_agent(observation, configuration):
from random import choice
return choice([c for c in range(configuration.columns) if observation.board[c] == 0])
env.reset()
# Play as the first agent ag... |
from django.conf.urls import url
from . import views
urlpatterns = [
url(r'^add/$', views.add_actor, name='crits-actors-views-add_actor'),
url(r'^add_identifier_type/$', views.new_actor_identifier_type, name='crits-actors-views-new_actor_identifier_type'),
url(r'^tags/modify/$', views.actor_tags_modify, n... |
import taichi as ti
from time import time
import numpy as np
import matplotlib.pyplot as plt
from PIL import Image
import tqdm
ti.init(arch=ti.cpu)
amin = 2
amax = 4
burnin = 8192
NUM_A = 2048
sample_len = 900
da = (amax - amin)/NUM_A
xmin = -.2
xmax = 1.3
xrange = xmax - xmin
pixels = ti.field(ti.u8, (NUM_A,... |
import sys
def parse(file_name):
voc = dict()
with open(file_name) as f:
lines = f.readlines()
for i, line in enumerate(lines):
line = line.strip()
if not line:
print('skip zero line', i)
continue
ls = line.split(',')
# print(ls)
if ... |
# Defines the json data type.
class JsonObject:
""" Represents a json object
"""
jsonNullValue = 'NULL_VALUE'
def __init__(self):
self.__keyvals = {}
def addObject(self, key, obj):
if key in self.__keyvals:
return False
self.__keyvals[key] = obj
return... |
# Copyright (c) Streamlit Inc. (2018-2022) Snowflake Inc. (2022)
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by appl... |
#!/usr/bin/env python
# coding: utf-8
# %codecell
from funcoperators import postfix as to, infix, compose as ov # composition operator
from numpy import *
@infix
def at(func, arg): # evaluate at operator
return list(map(func, [arg]))[0]
return list(map(func, [arg]))[0]
from f... |
# -*- coding: utf-8 -*-
"""
Created on Sun Mar 24 15:46:12 2019
@author: durgesh singh
"""
from torch.utils.data import Dataset
import nltk
from nltk.corpus import treebank
from nltk.corpus import brown
from collections import defaultdict
import torch
class CustomDataset(Dataset):
def __... |
# Program to find +ve numbers in the list
# empty lists
alist = []
newlist = []
# taking input
n = input('Enter some numbers seperated by commas: ')
# creating a list of input
mylist = n.split(',')
# typecasting to integer and entering to a new list 'alist'
for x in mylist:
y = int(x)
alist.app... |
import hashlib
input = "iwrupvqb"
i = 0
found = False
while not found:
hash = hashlib.md5()
hash.update(input + str(i))
found = hash.hexdigest()[:6] == "000000"
if not found:
i += 1
print i, hash.hexdigest(), input + str(i), hash.hexdigest()[:6] == "00000", found
|
import json
from sklearn.naive_bayes import MultinomialNB
from sklearn.feature_extraction.text import TfidfVectorizer
import fileinput
i=-1
testing_data=[]
data = []
with open("test_dataset.txt") as ft:
for line in ft:
data.append(line)
for line in data:
if i==-1:
no_test=int(line.split(" ")[0])
i... |
class AStarState:
def __init__(self, parent, position):
self.parent = parent
self.position = position
self.g = 0
self.h = 0
self.f = 0
def __eq__(self, other):
return self.position == other.position
def show(self):
return str("{("+str(self.position[0]... |
#!/usr/bin/env python
# encoding:utf-8
"""
题目:二维数组中,每行从左到右递增,每列从上到下递增,给出一个数,判断它是否在数组中
方法1:利用python的 num in matrix判断
方法2:利用数组特性,从右上角开始查找,如果小于要查找的num,则往下查找(行加1);否则往前查找(列减1)
"""
def find_integer(matrix, num):
if not matrix:
return False
rows, columns = len(matrix), len(matrix[0])
row, column = 0, co... |
f=[5,3,4,1,2,0];d=[];r=[]
n=int(input())
for i in range(n):d+=[[*map(int,input().split())]]
for i in range(6):
t=[];t+=[d[0][i]];s=0
for j in range(n):k=d[j].index(t[-1]);t+=[d[j][f[k]]]
for j in range(n):
if t[j]!=6 and t[j+1]!=6:s+=6
elif t[j]!=5 and t[j+1]!=5:s+=5
else:s+=4
r+=[s]
print(max(r)) |
import pandas as pd
import numpy as np
import sqlscripts
import pypyodbc
'''This script is a way to get and process SQL Queries so that they are immediately amenable to analytics in a variety of ways. To that end, I've made most variables on the suvey into categorical variables
replaced unanswered portions with 0s (me... |
# Generated by Django 2.0 on 2018-09-30 00:35
import datetime
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('piu', '0001_initial'),
]
operations = [
migrations.RenameField(
model_name='piu',
old_name='cargo',
... |
import torch
index = torch.tensor([[0,1,2],[0,0,1],[0,1,2],[1,0,2]])
# print(index.shape)
onehot = torch.zeros((4,3,3))
# print(index.unsqueeze(1).shape)
print (onehot.scatter_(1,index.unsqueeze(1),1)) |
#!/bin/env python
class Solution(object):
def maxTurbulenceSize(self, A):
"""
:type A: List[int]
:rtype: int
"""
if len(A) == 1: return 1
r = [] # l = Ai < Ai-1, g Ai > Ai-1
for i in range(1,len(A)):
if A[i] < A[i-1]: r.append('l')
elif... |
import re
from djblets.conditions.choices import BaseConditionChoice
from djblets.conditions.errors import ConditionOperatorNotFoundError
from djblets.conditions.operators import (AnyOperator,
BaseConditionOperator,
ConditionOperators,... |
import numpy as np
def unpickle(file):
import cPickle
fo = open(file, 'rb')
dict = cPickle.load(fo)
fo.close()
return dict
class NearestNeighbor(object):
def __init__(self):
pass
def train (self, X, y):
self.Xtr = X
self.ytr = y
def predict(self, X):
n... |
import json
from datetime import datetime
from django.db.models import Sum
from django.shortcuts import render
from dashboard.forms import DateForm
from dashboard.models import Flow, Company, Currency, Account
def main_view(request):
if request.method == 'GET':
date = datetime.strptime('01.09.2020', '%d... |
# https://blog.csdn.net/u012052268/article/details/79560768
# coding:utf-8
import os
import sys
from sklearn import feature_extraction
from sklearn.feature_extraction.text import TfidfTransformer
from sklearn.feature_extraction.text import CountVectorizer
from load_data import read_dataset
from load_data i... |
from utils import *
class NeuralNetwork():
def __init__(self, input_nodes, hidden_nodes, output_nodes, learning_rate=0.1):
self.input_nodes = input_nodes
self.hidden_nodes = hidden_nodes
self.output_nodes = output_nodes
self.weights_input_hidden = np.random.uniform(
-1, ... |
'''
Created on Sep 13, 2018
@author: dduque
'''
#===============================================================================
# import os
# import sys
# #Include all modules of the project when running on shell
# this_path = os.path.dirname(os.path.abspath(__file__))
# parent_path= os.path.abspath(os.path.join(this... |
# -*- coding: utf-8 -*-
import scrapy
from twisted.internet.error import ConnectionRefusedError
class ToScrapeSpiderXPath(scrapy.Spider):
name = 'toscrape-xpath'
start_urls = [
'http://quotes.toscrape.com/',
]
def start_requests(self):
for url in self.start_urls:
yield scr... |
import numpy as np
# pool embeds - (1,768)
def reduce_mean(vector):
sentence_vector = np.mean(vector[0], axis=0)
print(sentence_vector)
print(sentence_vector.shape)
return sentence_vector |
''' Updates movie ids generated with imdbpy with their actual imdb counterparts '''
import sys
sys.path.append('/home/dduoba/code/python-scripts/util')
import database
import pymongo
from sqlalchemy import create_engine, Integer, Table, Column, MetaData
import sqlalchemy.sql
import time
import traceback
XML_NODE_PATH... |
from utils.status import *
from .helper import Plugin,utils
from urllib.parse import urlparse
import threading
import utils.multitask as multitask
class SensitiveFiles(Plugin):
def __init__(self):
self.name = "Sensitive Files"
self.enable = True
self.description = ""
sel... |
import codecs
import itertools
import json
import sys
from lxml import etree
from utils import *
sys.stdout = codecs.getwriter('UTF-8')(sys.stdout)
D = {}
normalizer = createNormalizer(
allow_nonalpha=False,
allow_stopwords=True
)
for line in sys.stdin:
data = json.loads(line)
data['content'] = etree.HTML(data... |
import FWCore.ParameterSet.Config as cms
process = cms.Process("Demo")
process.load("FWCore.MessageService.MessageLogger_cfi")
process.load('Configuration.StandardSequences.Services_cff')
process.load('SimGeneral.HepPDTESSource.pythiapdt_cfi')
process.load('Configuration.EventContent.EventContent_cff')
process.load('... |
import netgen.gui
from ngsolve import *
from netgen.geom2d import SplineGeometry
#from minres import MinRes
from ngsolve.solvers import MinRes
from bramble_pasciak_cg import bramble_pasciak_cg
order = 2
geo = SplineGeometry()
geo.AddRectangle((0, 0), (2, 0.41), bcs=("wall", "outlet", "wall", "inlet"))
geo.... |
from django.contrib.auth.models import User
from django.core.urlresolvers import reverse
from django.test import TestCase
from mock import patch, Mock
from ct.models import Course, Unit, CourseUnit, Role
from views import CourseView
class TestCourseView(TestCase):
def setUp(self):
self.user = User.objects... |
import spidev
import time
import lis3dhh
import numpy as np
import sys
# check for output filename
if len(sys.argv) == 3:
outfilename = sys.argv[1]
mtime = float(sys.argv[2])
else:
outfilename = 'output.csv'
mtime = 1
# init spi interface
spi = spidev.SpiDev()
bus = 0
device = 0
spi.open(bus, device)
... |
from flask import Flask, render_template
application = Flask('myApp')
@application.route("/")
def index():
return render_template('index.html')
if __name__ == '__main__':
application.run(debug = True)
|
import gzip
import json
import os
import random
import sys
import retro
from retro.retro_env import RetroEnv
import numpy as np
# idea: have multiple initial states (one per game level) and reset
# to a different one after reset was called a number of times
# to allow different levels to be accessed within one game
... |
import glob
import os
import argparse
parser = argparse.ArgumentParser(description="Script to combnie all patient features into one file.")
parser.add_argument("-i", "--input-dir", type=str, required=True)
parser.add_argument("-o", "--output-file", type=str, default="features.csv")
def combine_patient_features(input... |
"""Stringliteral"""
class StringLiteral:
"""Stringliteral class.
Inherit your own string literal class from this one.
"""
@classmethod
def contains(cls, value: str) -> bool:
"""Evaluate whether the value belongs to the defined stringliteral."""
evaluated_vals = []
for val... |
from telethon import TelegramClient, events, Button, types
from decouple import config
from ProfanityDetector import detector
import logging
from telethon.tl.functions.channels import GetParticipantRequest
logging.basicConfig(
format="[%(levelname) 5s/%(asctime)s] %(name)s: %(message)s", level=logging.INFO
)
log... |
#!python
import sys
if(len(sys.argv) <= 1):
print("usage: <script> input*csv output*csv")
sys.exit()
print(sys.argv)
|
""" Human resources module
Data table structure:
* id (string): Unique and random generated identifier
at least 2 special characters (except: ';'), 2 number, 2 lower and 2 upper case letters)
* name (string)
* birth_year (number)
"""
# everything you'll need is imported:
# User interface module
i... |
class OwnError(Exception):
def __init__(self, txt):
self.txt = txt
result = []
num = ""
end_input = False
print(input('Для выхода из программы нажмите "Q", для продолжения "Enter": '))
while not end_input:
x = input("Введите число: ")
if x.upper() == 'Q':
end_input = True
print(re... |
import re
import os
import pprint
if 'aniversario_lista.py' in os.listdir('.'):
arquivoNiver = open(os.path.dirname(path) + '\\'+'aniverasario_lista.py')
aniversarios = arquivoNiver.read()
arquivoNiver.close()
else:
aniversarios = {}
#ToDo: fazer o programa criar um arquivo para ser lido pela funçã... |
import pdb
import akintu
import datetime
import os
from const import *
import cProfile, pstats, io
now = datetime.datetime.now()
path = os.path.join(SAVES_PATH, "profile")
if not os.path.exists(path):
os.makedirs(path)
filename = os.path.join(path, str("cprofile_" + str(now.strftime("%d_%H%M")) + ".txt"))
cProfil... |
import pygame
from pygame.locals import *
from src import numbers_gen
import copy
from src import sort_algs
from src import first_screen
import time
def start():
pygame.init()
screen_size = (1070, 650)
start_music = pygame.mixer.Sound("snd/start.wav")
start_music.play(-1)
screen = pygame.display.... |
def merge(s1, s2):
# To store the final string
result = ""
# For every index in the strings
i = 0
while (i < len(s1)) or (i < len(s2)):
# First choose the ith character of the
# first string if it exists
if (i < len(s1)):
result += s1[i]
# ... |
__author__ = 'sjjai'
import networkx as nx
class Helper:
def __init__(self):
pass
# takes absolute path of the features file and returns it as a 2-d list
def parse_data_from_file(self, path):
file = open(path, 'r')
result_list = []
for line in file:
line_list = [... |
import subprocess
import tempfile
import tator
def test_download_temporary_file(host, token, project):
tator_api = tator.get_api(host, token)
with tempfile.NamedTemporaryFile(mode='w',suffix=".txt") as temp:
temp.write("foo")
temp.flush()
for progress, response in tator.util.upload_te... |
import matplotlib.pyplot as plt
import numpy as np
from sklearn.model_selection import train_test_split
from sklearn.datasets import load_breast_cancer
from sklearn.svm import SVC
from sklearn.linear_model import LogisticRegression
from sklearn.tree import DecisionTreeClassifier
from sklearn import tree
import seaborn... |
"""Fake scons environment shutting up pylint on SCons files"""
# Copyright 2016-2023 Intel Corporation
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without... |
#encoding: utf-8
"""
@project = MylubanWeb
@file = run_test
@function =
@author = Cindy
@create_time = 2018/6/12 9:19
@python_version = 3.x
"""
import unittest, os, time, sys
from HTMLTestRunner import HTMLTestRunner
from testcase.models.function import copy_latest_report
# 指定测试用例为当前文件夹下的testcase目录
test_dir = './tes... |
import argparse
import jinja2
template_loader = jinja2.FileSystemLoader(searchpath='.')
template_env = jinja2.Environment(loader=template_loader)
template = template_env.get_template('graphs.html')
if __name__ == '__main__':
parser = argparse.ArgumentParser()
parser.add_argument('-g', '--graphite_server')
... |
from __future__ import print_function
import numpy
import torch
from torch import nn
from torch.autograd import Variable
from torch.nn.init import xavier_normal, constant
from torch.nn.functional import binary_cross_entropy, sigmoid, softplus
from torch.optim import Adam
from sklearn.metrics import average_precision_s... |
#!/usr/bin/python
# Script pour telecharger City
import MySQLdb
file_ = open('city.csv', 'w')
file_.write ('city_id,city,country_id\n')
db = MySQLdb.connect( user='etudiants',
passwd='etudiants_1',
host='192.168.99.100',
db='sakila')
cur = db.cursor... |
# Write a class to hold player information, e.g. what room they are in
# currently.
class Player:
def __init__(self, name, current_room=0):
self.name = name
self.current_room = current_room
self.items = []
def add_items_to_player(self, item):
self.items.append(item)
def mov... |
import requests
import hashlib
import sys
import json
#Header for api key
headers = {'apikey':'ea0ef10476510cfa50a49d37741959a0'}
if len(sys.argv) != 2:
sys.exit('Error: Incorrect arguments\nUsage: opswat.py "filename"')
#calculate hash of the given samplefile.txt
hash = hashlib.sha256()
filename = sys.argv[1]
with ... |
# Generated by Django 3.1.3 on 2020-11-20 22:55
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
('auction', '0004_auto_202... |
from django.urls import path
from kitaplar.api import views as api_views
urlpatterns = [
path('kitaplar/', api_views.KitapListCreateAPIView.as_view(), name='kitap_listesi'),
path('kitaplar/<int:pk>', api_views.KitapDetailAPIView.as_view(), name='kitap_bilgileri'),
path('kitaplar/<int:kitap_pk>/yorum_yap',... |
from django.core.files.storage import FileSystemStorage
class NAFileStorage(FileSystemStorage):
def get_available_name(self, name, max_length=None):
return name
def _save(self, name, content):
if self.exists(name):
# if the file exists, do not call the superclasses _save method
... |
#! /usr/bin/env python
# -.- coding: utf-8 -.-
#
# Zeitgeist Explorer
#
# Copyright © 2012 Manish Sinha <manishsinha@ubuntu.com>
#
# This program is free software: you can redistribute it and/or modify it
# under the terms of the GNU Lesser General Public License as published
# by the Free Software Foundation, either v... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.