content stringlengths 5 1.05M |
|---|
import time
import threading
from picamera import PiCamera
from picamera import Color
FILENAME_CAPTURE_IMG = "foo.jpg"
class SensorDataPool:
_interval = None
_imagePath = None
_timer = None
_bmp085 = None
_camera = None
count = 0
sensorData = None
def __init__(self, interval = 2, im... |
from tests import *
from naxxatrapy.naxxatrapy import average_velocity
class TestAverageVelocity(unittest.TestCase):
def test_average_velocity(self):
self.assertEqual(average_velocity(), ...)
|
# grid search cnn for monthly airline passengers dataset
from math import sqrt
from numpy import array
from numpy import mean
from pandas import DataFrame
from pandas import concat
from pandas import read_csv
from sklearn.metrics import mean_squared_error
from keras.models import Sequential
from keras.layers import Den... |
""" setup logging formatters to fit logspout's multiline pattern "^(ERROR|WARNING|INFO|DEBUG|CRITICAL)[:]"
SEE https://github.com/ITISFoundation/osparc-ops/blob/master/services/graylog/docker-compose.yml#L113
"""
# NOTES:
# https://docs.celeryproject.org/en/latest/userguide/signals.html#setup-logging
# https://... |
# Copyright 2019, OpenTelemetry Authors
#
# 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 applicable law or agreed to i... |
# coding: utf-8
from __future__ import unicode_literals
"""
A runnable script to launch a single Rocket (a command-line interface to rocket_launcher.py)
"""
from argparse import ArgumentParser
import os
import signal
import sys
from fireworks.fw_config import LAUNCHPAD_LOC, FWORKER_LOC, CONFIG_FILE_DIR
from fireworks... |
import click
from faker import Faker
from app import db,app
from app.models import Task, Admin
fake=Faker()
def fake_admin():
admin = Admin(
username = "xuedifan",
)
admin.set_password('123456')
db.session.add(admin)
db.session.commit()
def fake_task(count=10):
for i in range(count):
... |
from openmdao.main.case import Case
from openmdao.main.interfaces import implements, ICaseRecorder, ICaseIterator
class CaseArray(object):
"""A CaseRecorder/CaseIterator containing Cases having the same set of
input/output strings but different data. Cases are not necessarily unique.
"""
implemen... |
#!/bin/python3
# Copyright (©) 2015-2016 Lucas Maugère, Thomas Mijieux
# 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... |
# Copyright (c) 2017 - 2020 Kiriti Nagesh Gowda, Inc. All rights reserved.
#
# 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 limitation the rights
# to ... |
import os
import pickle
import collections
import itertools
import numpy as np
from scipy.stats import gaussian_kde # kernel-density estimate
from scipy.interpolate import interp1d
from scipy.fft import fft, fftfreq
from mpl_toolkits import mplot3d
import matplotlib as mpl
import matplotlib.pyplot as plt
mpl.rc('... |
"""Test RFI background estimation."""
from abc import ABC, abstractmethod
import numpy as np
from .. import host
from ...abc import AbstractContext, AbstractCommandQueue
from ...test.test_accel import device_test, force_autotune
from .. import device
_vis = np.array([])
_vis_big = np.array([])
_flags = np.array([]... |
import io
import unittest
from Testing.makerequest import makerequest
class DTMLDocumentTests(unittest.TestCase):
def _getTargetClass(self):
from OFS.DTMLDocument import DTMLDocument
return DTMLDocument
def _makeOne(self, *args, **kw):
return self._getTargetClass()(*args, **kw)
... |
"""
@filename: extract_tweets.py
@author: Matthew Mayo
@modified: 2014-04-25
@description: Extracts tweet text from <tweet_file> and print out
to console; can be redirected to optional <output_file>
@usage: python extract_tweets.py <tweet_file> > <outpu... |
#!/usr/local/bin/python3
import sys
import pickle
def convert_pickle_to_csv(input,output):
f = open(input,"rb")
o = open(output,"w")
data = pickle.load(f)
o.write("Wavelengths,Intensities\n")
for i in range(0,len(data[0])):
o.write(str(data[0][i]) + "," + str(data[1][i]) + "\n")
o.close... |
# import flask,json
# server=flask.Flask(__name__)#__name__代表当前的python文件。把当前的python文件当做一个服务启动
#
# @server.route('/index',methods=['get','post'])#第一个参数就是路径,第二个参数支持的请求方式,不写的话默认是get
# def index():
# res={'msg':'这是我开发的第一个借口','msg_code':0}
# return json.dumps(res,ensure_ascii=False)
#
# server.run(port=7777,debug=Tr... |
# Copyright 2020 The iqt Authors.
#
# 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 applicable law or agreed to in writ... |
""" Module to access the Permissions endpoints """
# pylint: disable=too-many-lines,too-many-locals,too-many-public-methods,too-few-public-methods
from typing import Any, Dict, List, Optional, cast
from ..base import ApiBaseClass
class PermissionsApi(ApiBaseClass):
""" """
def get_ancillary_permissions(
... |
class Person:
def __init__(self, fname, lname):
self.fname = fname
self.lname = lname
def __repr__(self):
return f'{self.fname} {self.lname}'
p1 = Person('John', 'Smith')
class Student(Person):
pass
if __name__ == '__main__':
s = Student('Tom', 'Adams')
print(s)
p... |
import numpy as np
import librosa
import json
from .renderers import (plot_estim, plot_eval, plot_certainty,
roll2audio)
def save_content(content,
summary_op,
placeholder,
writer,
step,
sess):
'''Saves su... |
# -*- coding: utf-8 -*-
"""Top-level package for spiders."""
__author__ = """Jacob Ider Chitham"""
__email__ = 'jacobic@mpe.mpg.de'
__version__ = '0.1.0'
|
from django.shortcuts import render
from .models import Question, Choice
# Question - Display
def index(request):
return render(request, 'polls/templates/polls/index.html')
|
"""
Copyright (c) 2018, salesforce.com, inc.
All rights reserved.
SPDX-License-Identifier: BSD-3-Clause
For full license text, see the LICENSE file in the repo root or https://opensource.org/licenses/BSD-3-Clause
"""
# general packages
import os
import errno # 捕获程序中的标准错误
import argparse
import numpy as np
import... |
from typing import Any, List, Literal, TypedDict
from .FHIR_CodeableConcept import FHIR_CodeableConcept
from .FHIR_dateTime import FHIR_dateTime
from .FHIR_decimal import FHIR_decimal
from .FHIR_Element import FHIR_Element
from .FHIR_Identifier import FHIR_Identifier
from .FHIR_Money import FHIR_Money
from .FHIR_Quant... |
"""DataLad NEXT extension"""
__docformat__ = 'restructuredtext'
import logging
lgr = logging.getLogger('datalad.next')
# Defines a datalad command suite.
# This variable must be bound as a setuptools entrypoint
# to be found by datalad
command_suite = (
# description of the command suite, displayed in cmdline he... |
import ast
import numpy as np
class Griddler:
solved = False
#TODO: If file already has gridd, there will be a problem
def __init__(self, gridd_file):
with open(gridd_file, 'r') as f:
dimensions = ast.literal_eval(f.readline())
row_reqs = ast.literal_eval(f.readline())
... |
#!/usr/bin/env python3
import csv
from io import StringIO
import scrape_common as sc
url = "https://gd.zh.ch/internet/gesundheitsdirektion/de/themen/coronavirus.html"
# get quarantined and isolated from website
dd_iso_q = sc.DayData(canton='ZH', url=url)
d = sc.download(url, silent=True)
d = d.replace(' ', ' ')... |
"""A cog that requires server users to feed the bot in return for benefits."""
import os
import random
import asyncio
import copy
import datetime
import discord
from discord.ext import commands
from __main__ import send_cmd_help
from .utils import checks
from .utils.dataIO import dataIO
SAVE_FILEPATH = "data/KeaneCo... |
"""
hill_cipher.py
@author Elliot and Erica
"""
import random
import numpy as np
from cryptography_utilities import (gcd, extended_gcd)
ALPHABET = 'abcdefghijklmnopqrstuvwxyz'
ALPHABET_SIZE = len(ALPHABET)
N = 3
TOTIENT_26 = 12
def random_matrix(size=N):
"""Generate a NxN matrix filled with random integers"""
... |
import json
from ynServer import DialogueActTagger
import spacy
import numpy as np
from scipy.stats import stats
import datetime
class DefaultSimplifier:
def transform(self, object):
raise NotImplementedError()
class RatingSimplifier(DefaultSimplifier):
def transform(self, conversation_date_rating... |
import os, csv
datadir = "/Users/titlis/cogsci/projects/stanford/projects/overinformativeness/experiments/26_24_without_cup/experiment/data/"
csv_messagenames = [o for o in os.listdir("/Users/titlis/cogsci/projects/stanford/projects/overinformativeness/experiments/26_24_without_cup/experiment/data/message/") if (o.e... |
import numpy as np
class Car:
"""
This Class models the movements and relevant information of the DeepRacer car.
You are not meant to interact directly with objects of this type, but rather it is
used by the DeepRacerEnv
"""
def __init__(s, x, y, view_angle, fps, direction=0):
s.x = x #... |
import uuid
import ujson as json
from .rpc_settings import get_settings
def _format_data_structure(users_data, response_key=None):
return {
'data': users_data,
'id': str(uuid.uuid4()),
'response_key': response_key
}
class RpcClient:
def __init__(self):
self._backend = ge... |
# FMSPy - Copyright (c) 2009 Andrey Smirnov.
#
# See COPYRIGHT for details.
"""
Application factory.
Loading application, dispatching control.
"""
from twisted.plugin import getPlugins
from twisted.python import log
from twisted.internet import defer
from fmspy.application.interfaces import IApplication
from fmspy.... |
"""Common midi_board tools."""
import abc
import importlib
import rospkg # pylint: disable=E0401
import types
import yaml # pylint: disable=E0401
from midi_board.custom_logging import LOGGER
# python 2/3 forward compatibility
if not hasattr(types, 'TypeType'):
types.TypeType = type
if not hasattr(types, 'Unbou... |
name = "pyiva"
|
import sys
sys.stdin = open('18892.txt')
N,K = map(int, input().split())
cand = [0]+list(map(int, input().split()))
length = [0 for _ in range(N+1)]
dl = 0
D = [[0,0] for _ in range(N+1)]
for i in range(1,N+1):
max_length = 0
for j in range(dl+1):
if D[j][1] < cand[i]:
if max_length < D... |
"""
代理抓取器
"""
import json
import re
from IPProxyPool.utils import get_page
from IPProxyPool.logger import logger
from pyquery import PyQuery as pq
class ProxyMetaClass(type):
"""
代理元类,用于收集抓取类中所有定义的站点
"""
def __new__(cls, name, parent, attr):
site_count = 0
attr['__CrawlFunc__'] = []
... |
# Imports: standard library
import datetime
# Imports: third party
import numpy as np
from pytz import timezone
# Imports: first party
from clustering.globals import SIGNAL_PATHS
class HD5FormatError(ValueError):
pass
class IncorrectSignalError(ValueError):
pass
def get_signal_type(signal):
for sour... |
# Leia um valor de comprimento em centimetros e apresente-o convertido em polegadas
# A formula de conversão é: P = C / 2.54
C = float(input("Digite um valor em centimetros: "))
P = C / 2.54
print("O valor convertido é para polegadas é: %0.2f" % P)
|
# Copyright 2021 Pants project contributors (see CONTRIBUTORS.md).
# Licensed under the Apache License, Version 2.0 (see LICENSE).
from __future__ import annotations
import os
from dataclasses import dataclass
from typing import Iterable
from pants.backend.scala.target_types import (
ScalaJunitTestsGeneratorSour... |
#!/usr/bin/env python
# Copyright (c) 2015 Angel Terrones (<angelterrones@gmail.com>)
#
# 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 limitation the r... |
import pytest
import numpy as np
from pyuplift.datasets import make_linear_regression
from pyuplift.model_selection import train_test_split
def test_train_test_split__default():
size = 1000
df = make_linear_regression(size)
X, y, t = df.drop(['y', 't'], axis=1).values, df['y'].values, df['t'].values
X... |
import os
import re
import json
import time
import subprocess
class STLink_USBInterface:
"""
A lower-ish level object that is intended to provide an OS independent (between Windows/Linux)
interface for finding and gathering information on connected STLink programmers.
"""
STLINK_VENDOR_ID = '0483'... |
from marinetrafficapi.query_params import QueryParams
class EV01QueryParams(QueryParams):
"""Query params for EV01 API call."""
time_span = 'timespan', 'The maximum age, in minutes, of the \n' \
'returned port calls. Maximum value is 2880.'
port_id = 'portid', 'The MarineTraf... |
from functools import reduce
import math
import torch.nn as nn
from . import wrapped
from util import log
class Conv2dSublayer(nn.Module):
"""Class representing a single sublayer of the butterfly network.
This module performs a single grouped convolution and then reorders the
channels. Channels are plac... |
import gym
from .GridInterface import *
import numpy
import os
class GridTargetSearchAEnv(gym.Env, GridInterface):
def __init__(self, render = False, view_camera_distance = 1.5, view_camera_angle = -80.0):
gym.Env.__init__(self)
GridInterface.__init__(self, render, view_camera_distance, view... |
#!/usr/bin/env python
import open3d as o3d
import random
NUM_LINES = 10
def random_point():
return [5 * random.random(), 5 * random.random(), 5 * random.random()]
def main():
pts = [random_point() for _ in range(0, 2 * NUM_LINES)]
line_indices = [[2 * i, 2 * i + 1] for i in range(0, NUM_LINES)]
col... |
from functools import partial
from pytest_bdd import scenarios, parsers, given, when, then
import pytest
from .cucumbers import CucumberBasket
# the dict contains all needed extra types for the tests
EXTRA_TYPES = {
'Number': int,
}
# the dict contains the converters between the var names and types
CONVERTERS = ... |
s, m, l = int(input()), int(input()), int(input())
if (1 * s + 2 * m + 3 * l) >= 10:
print("happy")
else:
print("sad")
|
"""
MDI Button
----------
This widget is intended for calling individual MDI commands. Useful for
`Go To Home`, `Tool Change` and similar actions.
The MDI command can include variables to be expanded from widgets present
in the active window. For example, to make a `Change Tool` button you could
add an MDIButton and ... |
# Python test code for sending local DAQ data
# PG 14.06.2018 v.2.0 (extensible frame buffer)
from ctypes import *
#lib="/afs/cern.ch/user/p/petr/daq/ControlHost/lib/libconthost.so"
lib="/usr/local/lib/libconthost.so"
libContHost = CDLL(lib)
#libc = CDLL("/usr/lib64/libc.so.6")
libContHost.connect()
# define the ... |
from wallet import Wallet
wallet = Wallet()
account = wallet.getaccount()
toaddress = raw_input("Enter the address to send coins to: ")
amount = int(input("Enter the balance to transfer to address: "))
balance = 0
for subaccount in account.itervalues():
balance = balance + subaccount['balance']
if balance < amo... |
c = get_config()
c.NbConvertApp.export_format = 'pdf'
c.TemplateExporter.template_path = ['.']
c.Exporter.template_file = 'article'
|
import torch
from torch.testing import assert_allclose
from dsntnn import average_loss, euclidean_losses
def test_euclidean_forward_and_backward():
input_tensor = torch.tensor([
[[3.0, 4.0], [3.0, 4.0]],
[[3.0, 4.0], [3.0, 4.0]],
])
target = torch.tensor([
[[0.0, 0.0], [0.0, 0.0]... |
import pygame
from random import uniform, choice, randint, random, randrange
from constants import *
from tilemap import collide_hit_rect
import pytweening as tween
from itertools import chain
from time import time
from math import sin, sqrt
vec = pygame.math.Vector2
def collide_with_obstacles(sprite, group, dir):
... |
from django.core.exceptions import ValidationError
from django.test import TestCase
from model_bakery import baker
from v1.models.browse_filterable_page import BrowseFilterablePage
from v1.models.images import CFGOVImage
from v1.tests.wagtail_pages.helpers import save_new_page
class TestSocialSharingImage(TestCase)... |
from abc import ABC, abstractmethod
from typing import List
from domain.models.dataset_name import DatasetName
class AbstractDatasetLabelsTypeService(ABC):
@abstractmethod
def get_labels_type(self, dataset_name: DatasetName)-> List[str]: raise NotImplementedError
|
from main import app
from flask import render_template, request
from query import get_votes
from config import FREEZER_BASE_URL
votes = get_votes()
@app.route('/')
def index():
page_title = 'Cabinet Votes 2017'
page_url = FREEZER_BASE_URL.rstrip('/') + request.path
return render_template('content.html',
... |
"""ASNG-NAS."""
import numpy as np
from .asng_util import ranking_based_utility_transformation
class AdaptiveSNG:
"""Adaptive Stochastic Natural Gradient for Categorical Distribution."""
def __init__(self,
categories=None,
integers=None,
alpha=1.5,
... |
import os
import cv2
import torch
import numpy as np
import torch.nn as nn
from tqdm import tqdm
from torch.nn import functional as F
class ResBlock(nn.Module):
def __init__(self, num_channel):
super(ResBlock, self).__init__()
self.conv_layer = nn.Sequential(
nn.Conv2d(num_channel, ... |
import abc
from typing import List
from api.date.window import Window
class MeetingPointProposer(abc.ABC):
@abc.abstractmethod
def propose(self, window: Window, host: str, participants: List[str]) -> List[str]:
pass
|
#
# @lc app=leetcode.cn id=1646 lang=python3
#
# [1646] kth-missing-positive-number
#
None
# @lc code=end |
import logging
from fancy_todo_list.application.usecases.ports import UserRepository
from fancy_todo_list.application.entities import User, RefId
from .config import session
from .models import UserModel
_logger = logging.Logger(__name__)
class SQLiteUserRepository(UserRepository):
def insert(self, user: User) ... |
from typing import List
import numpy as np
from nuplan.common.actor_state.state_representation import ProgressStateSE2, StateSE2
from nuplan.planning.simulation.path.path import AbstractPath
def calculate_progress(path: List[StateSE2]) -> List[float]:
"""
Calculate the cumulative progress of a given path
... |
#!/usr/bin/env python
# Demonstration POST saved_searches/create
# See https://dev.twitter.com/rest/reference/post/saved_searches/create
from secret import twitter_instance
from pprint import pprint
tw = twitter_instance()
# Don't abuse OR.
response = tw.saved_searches.create(query='イルベロ OR イルマティックエンベロープ')
pprint(r... |
import pytesseract
class OCRTool:
def __init__(self, config):
self.config = config
if self.config["tools"]["ocr"]['tesseract_path'] != "":
pytesseract.pytesseract.tesseract_cmd = self.config["tools"]["ocr"]['tesseract_path']
#takes PIL image as input
def readImage(self, image)... |
#!/usr/bin/env python3
import os
import sys
import glob
sys.path.append('../../')
import software
import network
from shared import Remote
import tools
# increase limit for all the parallel pings
os.system('ulimit -Sn 4096')
remotes= [Remote()]
tools.check_access(remotes)
software.copy(remotes, '../../protocols', ... |
import tensorflow as tf
from detext.model.bert import modeling
def create_bert_model(bert_config_path,
is_training,
input_ids,
bert_checkpoint_path=None,
input_mask=None,
token_type_ids=None,
... |
import os
from yacs.config import CfgNode as CN
r"""Learning algorithm settings
"""
_C = CN()
# --------------------------------------------------------------------- #
# computation device & media options #
# --------------------------------------------------------------------- #
... |
from PiGPIO.helper.raspi import * |
#! /usr/bin/env python
# -*- coding: utf-8 -*-
# vim:fenc=utf-8
#
# Copyright (c) 2014 xavier <xavier@laptop-300E5A>
'''Dashboard
Usage:
dashboard -h | --help
dashboard --version
dashboard new --team-dashboard=<loc> --portfolios=<pf> [--templates=<loc>]
Options:
-h --help Show this screen.
--... |
from flask import render_template,abort,request, url_for, redirect, flash
from flask_login import current_user, login_user, logout_user, login_required
from werkzeug.urls import url_parse
from app.models.usuario import User
from app.models.empresa import Empresa
from app.models.rubro import Rubro
from app.forms.resgist... |
# This file contains some unit tests for the logging.basicConfig
# method.
from org.transcrypt.stubs.browser import __pragma__, __envir__
import logging
from utils import TestHandler, resetLogging
def run(test):
"""
"""
resetLogging()
basehdlr = TestHandler(test, 5)
fmt = logging.For... |
import six
class Query(object):
"""
Query is used to build complex queries that have more parameters than just the query string.
The query string is set in the constructor, and other options have setter functions.
The setter functions return the query object, so they can be chained,
i.e. `Query("... |
# -*- coding: utf-8 -*-
# (C) Copyright IBM Corp. 2020.
#
# 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 applicable l... |
#! /usr/bin/env python3
# -*- coding: utf-8 -*-
import corpora
import utility
import path
import matrix_dict
import lexicon
import scorer
######################################
## MODEL 04 PAISA + DE MAURO POLIREMATICHE small lex
######################################
OUTPUT_DIR = path.GHIGLIOTTINA_BASE_FILE_PATH +... |
from machine import Pin
import machine
import utime
import network
import urequests
LEDS = dict(red=Pin(4, Pin.OUT, value=0),
yellow=Pin(0, Pin.OUT, value=0),
green=Pin(2, Pin.OUT, value=0))
BUZZER = Pin(16, Pin.OUT)
BUZZER.off()
# If high: ring the alarm on yellow; if low, only ring on green
... |
import math
import sys
def distance(point1, point2):
return math.sqrt((point1.x - point2.x)**2 + (point1.y - point2.y)**2)
def progress(count, total, suffix=''):
bar_len = 60
filled_len = int(round(bar_len * count / float(total)))
percents = round(100.0 * count / float(total), 1)
bar = '=' * fill... |
SEX_CHOICES=(
('M', "Male"),
('F', "Female")
)
BLOOD_GROUP_CHOICES=(
('A+','A+'),
('A-','A-'),
('B+','B+'),
('B-','B-'),
('AB+','AB+'),
('AB-','AB-'),
('O+','O+'),
('O-','O-'),
('Other','Other')
) |
from django.contrib import admin
from profiles.models import UserProfile
admin.site.register(UserProfile)
|
# Copyright (C) 2013 Lukas Lalinsky
# Distributed under the MIT license, see the LICENSE file for details.
from flask import Blueprint, g, abort
from sqlalchemy.orm import joinedload
from mbdata.models import Place, PlaceGIDRedirect, LinkPlaceURL
from mbdata.utils import get_something_by_gid
from mbdata.api.utils impo... |
from django.conf.urls import url
from . import views
urlpatterns = [
#主页
url(r'^$', views.index,name="index"),
#相册信息管理路由
url(r'^pics/(?P<pIndex>[0-9]+)$', views.pics, name="pics"),#浏览相册信息、数据分页
url(r'^pics/add$', views.picsAdd, name="picsAdd"),#加载添加表单
url(r'^pics/insert$', views.picsInsert, name="... |
import hugectr
import sys
def wdl_test(json_file):
solver = hugectr.CreateSolver(max_eval_batches = 2048,
batchsize_eval = 16384,
batchsize = 16384,
vvgpu = [[0,1,2,3,4,5,6,7]],
lr = 0.001,... |
#!/usr/bin/env python3
import typing
from collections import defaultdict
from typing import Any, List, Tuple, Union, cast
import torch.nn as nn
from torch import Tensor
from torch.nn import Module
from torch.utils.hooks import RemovableHandle
from captum._utils.common import _format_input, _format_output, _is_tuple,... |
import collections
import abc
import colorama
import numpy as np
import scipy
import sklearn.mixture
import scipy.stats
import state
import mposterior
# a named tuple for a more intuitive access to a "exchange tuple"
ExchangeTuple = collections.namedtuple(
'ExchangeTuple', ['i_PE', 'i_particle_within_PE', 'i_neighbo... |
import re
from urllib import request, parse
from bs4 import *
import sqlite3
import ssl
class Crawler:
def __init__(self, dbname):
if hasattr(ssl, '_create_unverified_context'):
ssl._create_default_https_context = ssl._create_unverified_context
self.con = sqlite3.connect(dbname)
... |
import json
import matplotlib.pyplot as plt
with open('report.json', 'r+') as json_file:
data = json.load(json_file)
fp = data['fp']
tp = data['tp']
total = data['total']
fp.sort()
tp.sort()
x = []
y = []
for i in range(len(fp)):
pos = [p for p in tp if p >= fp[i]]
num_fp = len(fp) - i
num_tp = len... |
#!/usr/bin/python
import random
def gen_random_data():
arr = []
for i in range(1000000):
arr.append(random.random())
print("job done")
|
from django.urls import include, path
from django.conf.urls import url
from endpoint.views import (
enroll_user,
validate_recording,
check_redis_health,
redirect_flower_dashboard,
)
urlpatterns = [
path("enroll", enroll_user),
path("validate", validate_recording),
path("redis-healthcheck", ... |
from manager import Marketing_firm
import random
class Sweepstake:
def __init__(self, contest_name):
self.contestants = {}
self.name = contest_name
def get_contestants(self,contestant):
self.contestants.update({f'{contestant.registration}' : contestant})
def get_winner(self... |
# -*- coding: utf-8 -*-
from flask_restful import reqparse
from src.lyrics import exceptions
from src.lyrics.base.endpoints import ResourceBase
from src.web_app import get_api
api = get_api()
class LyricsResource(ResourceBase):
def __init__(self, index_service):
super(LyricsResource, self).__init__()
... |
#!/usr/bin/python
################################################################################
#
# Universal JDWP shellifier
#
# @_hugsy_
#
# And special cheers to @lanjelot
#
# loadlib option by @ikoz
#
import argparse
import json
import logging
import logging.config
import os
import socket
import struct
import s... |
from docker import from_env # type: ignore[import]
from typer import Typer
from kolombo.configuration_files import generate_senders_compose_config
from kolombo.console import error, step
from kolombo.util import (
async_command,
build_kolombo_image,
execute_as_root,
needs_database,
run,
up_all... |
#!/usr/bin/env python
# Exercicio 4.3 - Escreva um programa que leia três números e que imprima o maior e o menor.
print (' ')
n1 = int(input('Digite um valor: '))
n2 = int(input('Digite outro valor: '))
n3 = int(input('Digite mais um valor: '))
# Condições para verificar valor maior
if n1 > n2 and n1 > n3:
maio... |
from __future__ import division
prios = ["boost", "scitbx", "cctbx", "rstbx", "labelit"]
prios = dict(zip(prios, range(len(prios))))
def cmp_so(a, b):
def prio(s):
k = s.split("_")[0]
return prios.get(k, len(prios))
pa, pb = prio(a), prio(b)
result = cmp(pa, pb)
if (result == 0):
result = cmp(a, b)... |
i=333
def add_numbers(start, end):
#write the body of this
#function, similar to the block
#of code we just saw. Hint:
#don’t forget to use return
answer =add_numbers(i,i+=1)
i+=1
print(answer)
|
# --------------
# Importing header files
import numpy as np
import warnings
warnings.filterwarnings('ignore')
#New record
new_record= [[50, 9, 4, 1, 0, 0, 40, 0]]
#Reading file
data = np.genfromtxt(path, delimiter=",", skip_header=1)
print(data.shape)
census = np.concatenate((data, new_record),axi... |
# -*- coding: utf-8 -*-
"""
clihub/repository.py
~~~~~~~~~~~~~~~~~~~~
:copyright: (c) 2012 by Stephane Wirtel <stephane@wirtel.be>
:license: BSD, see LICENSE for more details
"""
import requests
import json
class Repository(object):
@classmethod
def create(cls, account, repository_name, has_i... |
import os
import pickle
import numpy as np
import pandas as pd
from sklearn.model_selection import train_test_split
import torch
from torch.utils.data import Dataset
from file_io import Events, read_2d_spikes
###############################################################################
# This file is adapted from ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.