text stringlengths 2 999k |
|---|
import itertools
def alldifferent(k,n):
'''The probability that k random selections from n possibilities
are all different.'''
assert(k<=n)
nums = xrange(n,n-k,-1)
dens = itertools.repeat(n)
fracs = itertools.imap(lambda x,y: float(x)/y, nums,dens)
return reduce(float.__mul__, fracs)
def c... |
import theano
from theano.compat import any
from theano.gradient import DisconnectedType
from theano.gof import Op, Apply, TopoOptimizer
from theano import tensor
import theano.sandbox.cuda as cuda
def get_diagonal_subtensor_view(x, i0, i1):
"""Helper function for DiagonalSubtensor and
IncDiagonalSubtensor
... |
import sys
import time
import pandas as pd
from datetime import datetime
from PyQt5.QtWidgets import *
app = QApplication(sys.argv)
class KiwoomWrapper:
def __init__(self, kiwoom):
self.kiwoom = kiwoom
def get_daily_data(self, code, start='20000101', end='20161218', req_count=None):
self.kiwo... |
"""Implementation of an epsilon-greedy action selection strategy."""
from abc import ABC, abstractmethod
from typing import Callable, ClassVar, Optional
from decuen.actors.strats._strategy import Strategy
from decuen.actors.strats.greedy import GreedyStrategy
from decuen.actors.strats.uniform import UniformStrategy
f... |
from numpy import uint64
from pyteal import *
from algosdk.future import transaction
from algosdk.v2client import algod
import os
import pathlib
from util import deploy, get_private_key_from_mnemonic
#if Resource: application_args = (user_address_bytes, asset_total, asset_unit_name, asset_name, asset_url, asset_metada... |
#!/usr/bin/env python
from number import testNumberTuple
from number.hexadecimal import Hexadecimal
from number.numberSystem import NumberSystem
def main():
try:
while True:
exit = 'exit'
print("||Number Calculator||")
args = input(
' Zahlensysteme: [... |
"""Widget for creating classes from non-numeric attribute by substrings"""
import re
from itertools import count
import numpy as np
from AnyQt.QtWidgets import QGridLayout, QLabel, QLineEdit, QSizePolicy
from AnyQt.QtCore import QSize, Qt
from Orange.data import StringVariable, DiscreteVariable, Domain
from Orange.d... |
"""
Python unit testing framework, based on Erich Gamma's JUnit and Kent Beck's
Smalltalk testing framework (used with permission).
This module contains the core framework classes that form the basis of
specific test cases and suites (TestCase, TestSuite etc.), and also a
text-based utility class for running the tests... |
from django.conf.urls import patterns, url
urlpatterns = patterns('',
url(r'^$', 'suggestionbox.views.list_suggestions', name='suggestion_list'),
url(r'^(?P<top_id>\d+)/$', 'suggestionbox.views.suggestion_detail', name='suggestion_detail'),
)
|
import os
import subprocess
import pyroute2
from pyroute2 import IPRoute, NetNS, IPDB, NSPopen
'''
알아야될 개념 )
NetWork NameSpace, Ethernet interface, IPRoute.link, IPDB, up()
IPRoute vs IPDB :
동기 vs 비동기, 추가적인 스레드 사용여부
NetWork NameSpace :
프로세스를 실행할 때, 시스템의 리소스... |
#!/usr/bin/env python3
import http.server
import socketserver
import json
from urllib.parse import parse_qsl as parse_query, urlparse as parse_url
def run_server(info, port):
response_cache = {}
class MyHandler(http.server.SimpleHTTPRequestHandler):
def respond(self, content, content_type='application/json', code=... |
import queue
import threading
from rprint import print
## An abstraction of a link between router interfaces
class Link:
## creates a link between two objects by looking up and linking node interfaces.
# @param node_1: node from which data will be transfered
# @param node_1_intf: number of the interfa... |
"""
master_config.py -- Contains parameters to configure an end-to-end ARPS-EnKF run
"""
import os
import numpy as np
from datetime import datetime
# Define needed directories and experiment names/tags
# Base project names and directories
scratch_base_dir = '/scratch/rice/s/sharm261'
depot_base_dir = '/depot/rtanama/u... |
# coding=utf-8
r"""
This code was generated by
\ / _ _ _| _ _
| (_)\/(_)(_|\/| |(/_ v1.0.0
/ /
"""
from twilio.base import deserialize
from twilio.base import values
from twilio.base.instance_context import InstanceContext
from twilio.base.instance_resource import InstanceResource
from twilio.base... |
from concurrent.futures import ThreadPoolExecutor
def strike(string):
return f'<strike style="color: red;">{string}</strike>'
def bold(string):
return f'<strong style="color: red;">{string}</strong>'
def format_transcript(transcript, map_):
transcript = transcript.lower().replace(' ', ' ').split()
... |
'''
CKYdet.py
Copyright (c) 2018, Stephen Pollett
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this
list of conditions and the... |
import sys
import networkx as nx
import numpy as np
import pytest
import tensorflow.compat.v1 as tf
from sklearn.preprocessing import StandardScaler
from utils import binary_sampler, enable_reproducible_results, gen_data_nonlinear
import miracle.logger as log
from miracle import MIRACLE
from miracle.third_party impor... |
from time import time
def get_timestamp():
return int(round(time() * 1000)) |
from collections import Counter
from copy import deepcopy
import numpy as np
from sklearn.preprocessing import LabelBinarizer
from keras.models import model_from_yaml
def right_pad(sequences):
"""
Pads sequences with extra "*" characters.
"""
padded_sequences = deepcopy(sequences)
seq_lengths = ... |
"""
topic_store.py file. Part of the Contextualise project.
March 5, 2019
Brett Alistair Kromkamp (brett.kromkamp@gmail.com)
"""
from flask import current_app, g
from topicdb.core.store.topicstore import TopicStore
def get_topic_store():
if "topicstore" not in g:
g.topic_store = TopicStore(
... |
import os
from tqdm import tqdm
import pickle
import numpy as np
import pandas as pd
import cv2
import os
import os
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2'
from deepface.commons import functions, realtime, distance as dst
def face_recognize(faces, db_embeddings, model, model_name, distance_metric):
# threshold ... |
from django.db import models
from rest_framework.viewsets import ModelViewSet
from rest_framework.exceptions import MethodNotAllowed, PermissionDenied
from commons.permissions import (
IsUserCresteListOrSuperuserListDelete,
IsRegularUser
)
from .models import Wallet, CreditCard
from .serializers import (
... |
import cv2
import numpy as np
from scipy.ndimage.filters import gaussian_filter
from scipy.ndimage.interpolation import map_coordinates
def upsample(image, image_size_target):
padding0 = (image_size_target - image.shape[0]) / 2
padding1 = (image_size_target - image.shape[1]) / 2
padding_start0 = int(np.ce... |
# This is open-source software licensed under a BSD license.
# Please see the file LICENSE.txt for details.
"""
Plugin to create image mosaic.
**Plugin Type: Local**
``Mosaic`` is a local plugin, which means it is associated with a
channel. An instance can be opened for each channel.
**Usage**
.. warning:: This ca... |
from django.views.generic.base import View
from django.http import HttpResponse
import json
class RendererAsJson(View):
"A view which is used to get a chart as json."
"Subclasses should create get_context_data, which populates a chart"
def get(self, *args, **kwargs):
context = self.get_context_da... |
#!/Users/andrewpatton/Dropbox/Active Projects/lrboost/lrboost/bin/python
# -*- coding: utf8 -*-
# :Copyright: © 2015 Günter Milde.
# :License: Released under the terms of the `2-Clause BSD license`_, in short:
#
# Copying and distribution of this file, with or without modification,
# are permitted in any medium w... |
# Configuration file for the Sphinx documentation builder.
#
# This file only contains a selection of the most common options. For a full
# list see the documentation:
# https://www.sphinx-doc.org/en/master/usage/configuration.html
# -- Path setup --------------------------------------------------------------
# If ex... |
# -*- coding: utf-8 -*-
# emacs: -*- mode: python; py-indent-offset: 4; indent-tabs-mode: nil -*-
# vi: set ft=python sts=4 ts=4 sw=4 et:
"""
Orchestrating the BOLD-preprocessing workflow
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
.. autofunction:: init_func_preproc_wf
.. autofunction:: init_func_derivatives_wf
""... |
# -*- coding: utf-8 -*-
"""
SkyAlchemy
Copyright ©2016 Ronan Paixão
Licensed under the terms of the MIT License.
See LICENSE for details.
@author: Ronan Paixão
"""
from __future__ import unicode_literals, division, print_function
import sys
import os
import os.path as osp
import re
import pickle
from io import Byte... |
from unittest.mock import Mock, patch, ANY
from dask_pytorch_ddp.data import S3ImageFolder
def test_image_folder_constructor():
fake_file_list = ["d/a.jpg", "c/b.jpg"]
with patch("dask_pytorch_ddp.data._list_all_files", return_value=fake_file_list):
fake_transform = Mock()
fake_target_transf... |
import time
import sys
sys.path.append("..")
from highway.engine import Pipeline
from highway.modules.processing import Noise, Augmentations
from highway.modules.network import ZMQSink, ZMQSource
from highway.augmentations.img import Resize
N = 20
data_shape = (320, 240, 3)
source = Pipeline([Noise(data_shape=dat... |
"""
Copyright 2017, Andrew Lin
All rights reserved.
This software is licensed under the BSD 3-Clause License.
See LICENSE.txt at the root of the project or
https://opensource.org/licenses/BSD-3-Clause
"""
from passphrase.build import scrape_html
def test_scrape_empty():
"""Scrape an empty string"""
words = s... |
#!/usr/bin/env python
#
# Copyright (c) 2009 Andreas Liebschner
#
# 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 use, cop... |
from gibson.envs.env_modalities import CameraRobotEnv, BaseRobotEnv
from gibson.envs.env_bases import *
from gibson.core.physics.robot_locomotors import Turtlebot, JR, JR2
from transforms3d import quaternions
import os
import numpy as np
import sys
import pybullet as p
from gibson.core.physics.scene_stadium import Sing... |
"""
Inventory
=========
Contains an inventory class that serves as an helper for the
adv kpi
.. Copyright:
Copyright 2019 Wirepas Ltd under Apache License, Version 2.0.
See file LICENSE for full license details.
"""
import collections
import datetime
import logging
import math
imp... |
__author__ = 'patras'
from domain_springDoor import *
from timer import DURATION
from state import state, rv
DURATION.TIME = {
'unlatch1': 5,
'unlatch2': 5,
'holdDoor': 2,
'passDoor': 3,
'releaseDoor': 2,
'closeDoors': 3,
'move': 7,
'take': 2,
'put': 2,
}
DURATION.COUNTER = {
... |
import requests
from common.fact_random import load_fact_file
def main():
url = "http://0.0.0.0:8119/respond"
request_data = [["aardvark"]]
possible_results = load_fact_file("./facts_for_animals.json")["aardvark"]
result = requests.post(url, json=request_data).json()
assert result[0][0]["fact"]... |
#!/usr/bin/python3
import sys
import re
from unicodedata import normalize
from pathlib import Path
from flask import Flask, render_template, request, redirect, url_for
from flask_sqlalchemy import SQLAlchemy
from chopro import ChoPro
from config import *
SHORT_LIMIT = 100
app = Flask(__name__)
app.config['SQLALCHE... |
#!/usr/bin/env python3
"""
Train the eccentricity model
"""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from datetime import datetime
import os.path
import time
import numpy as np
np.random.seed(seed=1)
from six.moves import xrange # pylint: disable=r... |
"""
42. Trapping Rain Water
The fundamental idea is all about finding how to calculate the height of water that can be stored in a particular index.
The stored water will be depending upon the left max level and right max level
Also current level should be less than these max levels otherwise the water cannot be st... |
import tqdm
import numpy as np
import tensorflow as tf
import tensorflow.contrib.slim as slim
from .. import attack
class Attack(attack.AttackBase):
"""Optimization-based attack."""
name = 'optimization'
def __init__(self, *args, **kwargs):
super(Attack, self).__init__(*args, **kwargs)
... |
# -*- coding: utf-8 -*-
#
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
#... |
#!/usr/bin/env python
################################################################################
# COPYRIGHT(c) 2018 STMicroelectronics #
# #
# Redistribution and use in source and binary for... |
# coding: utf-8
#
# Copyright 2014 The Oppia Authors. 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 requi... |
# -*- coding: utf-8 -*-
# @Time : 20-7-4 下午2:42
# @Author : smallflyfly
# @FileName: tensorRT_demo.py
import time
import cv2
import torch
from torch.backends import cudnn
from torch2trt import torch2trt
from data import cfg_mnet
from models.retinaface import RetinaFace
from utils.net_utils import load_model, ima... |
#!/usr/bin/python
__author__='''
Suraj Singh bisht
surajsinghbisht054@gmail.com
www.bitforestinfo.com
github.com/surajsinghbisht054
'''
# coding: utf-8
# In[100]:
import json
import os
from hashlib import sha256
from Crypto.PublicKey import RSA
from Crypto.Signature import PKCS1_... |
from unittest import TestCase
from genericclient import GenericClient
import responses
MOCK_API_URL = 'http://dummy.org'
class AuthClientTestCase(TestCase):
def test_401(self):
generic_client = GenericClient(
url=MOCK_API_URL,
)
with responses.RequestsMock() as rsps:
... |
import sys
import numpy as np
from enum import Enum
import pygame
from pygame.locals import * #Difference between "import module" and "from module import": With the second you have to specify which functions to import (if you use *, you import everything),
#but you can use as "function" instead of "module.function".
fr... |
# proxy module
from pyface.splash_screen import *
|
# XXX TypeErrors on calling handlers, or on bad return values from a
# handler, are obscure and unhelpful.
from io import BytesIO
import unittest
from xml.parsers import expat
from xml.parsers.expat import errors
from test.support import sortdict, run_unittest
class SetAttributeTest(unittest.TestCase):
def set... |
# Generated by Django 4.0.4 on 2022-04-19 09:27
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('UI', '0005_remove_profile_username'),
]
operations = [
migrations.AlterField(
model_name='profile',
name='language',... |
from nnf import Var, true, false
from lib204 import Encoding
from random import randint
num_pokemon = 3 # number of pokemon each party has
foe = [] # the foe's party of pokemon
player = [] # the player's party of pokemon
# different pokemon types
types = ["fire", "water", "grass", "electric", "ice", "ground", "flying... |
''' Platform-related configuration utilities '''
import abc
import logging
import platform
import pkg_resources
import nimp.base_platforms
from nimp.utils.python import get_class_instances
_all_platforms = {}
_all_aliases = {}
_all_ue4_platforms = {}
class Platform(metaclass=abc.ABCMeta):
''' Describe a pla... |
from pytest_django.asserts import assertContains
class TestBlogPostDetail:
def test_title(self, client, announcement):
"""blog post detail page should include post title"""
response = client.get(announcement.get_url())
assertContains(
response,
'<h1 property="schema... |
# Copyright 2015 Tesora 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 a... |
import numpy as np
from qubo_nn.problems.problem import Problem
class KnapsackIntegerWeights(Problem):
def __init__(self, cfg, w, c, W, A=10, B=1):
self.w = w
self.c = c
self.W = W
self.A = A
self.B = B
def gen_qubo_matrix(self):
N = self.w.shape[0]
Q =... |
##FİND
self.OwnerMoneyButton.SetEvent(ui.__mem_func__(self.OpenPickMoneyDialog))
##add
if app.ENABLE_FATIH_SAHIN_REDCOIN_SYSTEM:
self.OwnerRedCoin = self.GetChild("Owner_RedCoin_Value")
self.OwnerRedCoinButton = self.GetChild("Owner_RedCoin")
self.OwnerRedCoinButton.SetEvent(ui.__mem_func__(self.OpenPickMoneyDialog... |
sounds_path = "resources/sounds/"
no_plan_alarm = sounds_path + "no_plan_alarm.mp3"
alarm = sounds_path + "alarm.mp3"
|
# Copyright (c) OpenMMLab. All rights reserved.
import numpy as np
import torch
from torch.nn.modules.utils import _pair
from .builder import PRIOR_GENERATORS
@PRIOR_GENERATORS.register_module()
class PointGenerator:
def _meshgrid(self, x, y, row_major=True):
xx = x.repeat(len(y))
y... |
#!/usr/bin/env python
import boto3
import pprint
import argparse
def detect_faces(f):
with open(f, 'rb') as image:
response = client.detect_faces(Image={'Bytes': image.read()})
pprint.pprint(response)
if __name__ == "__main__":
# parse arguments
parser = argparse.ArgumentParser()
pa... |
# Copyright 2020 The PyMC Developers
#
# 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 ag... |
# coding: utf-8
"""
Ed-Fi Operational Data Store API
The Ed-Fi ODS / API enables applications to read and write education data stored in an Ed-Fi ODS through a secure REST interface. *** > *Note: Consumers of ODS / API information should sanitize all data for display and storage. The ODS / API provides reas... |
#!/usr/bin/env python3
#
# Copyright 2019 ROBOTIS CO., LTD.
#
# 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 applicabl... |
#!/usr/bin/python3
# -*- coding: utf-8 -*-
#Fahrettin Orkun Incili - 150401013 - Schmidt-Samoa
from random import randint
import math, os
"""
Ek fonksiyonlar:
isprime
lcm
bit_length
string_to_binary
binary_to_decimal
binary_to_string
generate_prime
issame
"""
def isprime(a):
"""bir sayının asal olup olmadığın... |
"""
Assignment 1 Question 3 Part A script
@author Ian Tongs, 27765369
@since 26 April 2020
"""
# Imports:
from scipy.integrate import odeint
import numpy as np
import matplotlib.pyplot as plt
import math
# Functions:
beta = 0.002
eta = 0.05
alpha = 0.1
Lambda = 0.4
mu = 0.0... |
# __init__.py
from .event_util import *
from .util import *
|
from func_tools import *
import pandas as pd
def backtrack(X,func,gX,d,B,alpha=1,gamma=0.01,sigma=0.5):
right = gamma*mat2vec(gX).T.dot(mat2vec(d)) ## first vec than T
## right should not include alpha
func_value = func(X,B)
while func(X+alpha*d,B) - func_value> alpha * right:
alpha = al... |
from django.apps import AppConfig
class WpsclientConfig(AppConfig):
name = 'wpsclient'
|
import numpy as np
from statsmodels.duration.survfunc import SurvfuncRight, survdiff, plot_survfunc
from numpy.testing import assert_allclose
from numpy.testing import dec
import pandas as pd
import os
# If true, the output is written to a multi-page pdf file.
pdf_output = False
try:
import matplotlib.pyplot as p... |
import sys
sys.path.append('../tytus/parser/team27/G-27/execution/abstract')
sys.path.append('../tytus/parser/team27/G-27/execution/expression')
sys.path.append('../tytus/parser/team27/G-27/execution/symbol')
sys.path.append('../tytus/parser/team27/G-27/libraries')
from function import *
from typ import *
from math_fun... |
#!/usr/bin/python
from ntnx_api.client import PrismApi
from ntnx_api import prism
def _api():
return PrismApi(ip_address='192.168.1.44', username='admin', password='fUUif4l0CF!iPVv2mpE6wbT9&Rf5tw')
def test_update_alert_config():
"""Test that alert config can be set"""
result = False
alert_config = ... |
# -*- coding: utf-8 -*-
"""5.22 (binary classification).ipynb
Automatically generated by Colaboratory.
Original file is located at
https://colab.research.google.com/drive/11inZJt6uLzcs_QZw_pAm63fDXA4XDdqg
**1.17.21** notebook
"""
# Commented out IPython magic to ensure Python compatibility.
# import libraries
i... |
from nomics.utils import (
clean_dict_values,
clean_params,
remove_empty_dict_values,
)
def test_remove_empty_dict_values():
dict_with_empty_values = {"a": None, "b": 123, "c": "foo", "d": None}
new_dict = remove_empty_dict_values(dict_with_empty_values)
for value in new_dict.values():
... |
# Lint as: python3
"""Training script for Nerf."""
import functools
import gc
import time
import copy
from absl import app
from absl import flags
from absl import logging
from absl.logging import INFO
import flax
from flax.metrics import tensorboard
from flax.training import checkpoints
import jax
from jax import conf... |
# Copyright (c) 2020 Dell Inc. or its subsidiaries.
# 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
#
# ... |
""" Simple costs to be used for unit tests. """
__authors__ = "Ian Goodfellow"
__copyright__ = "Copyright 2010-2012, Universite de Montreal"
__credits__ = ["Ian Goodfellow"]
__license__ = "3-clause BSD"
__maintainer__ = "LISA Lab"
__email__ = "pylearn-dev@googlegroups"
from functools import wraps
from pylearn2.costs.... |
from __future__ import absolute_import, division, print_function
from BaseHTTPServer import HTTPServer
import cgi, sys
from multiprocessing import Process, current_process
from urlparse import urlparse
from six.moves import range
#backward compatibility with Python 2.5
try: from urlparse import parse_qs
except Excepti... |
# Question 1: Pick One
#
# Define a procedure, pick_one, that takes three inputs: a Boolean
# and two other values. If the first input is True, it should return
# the second input. If the first input is False, it should return the
# third input.
#
# For example, pick_one(True, 37, 'hello') should return 37, and
# pi... |
#!/usr/bin/env python
# Copyright 2021, Kay Hayen, mailto:kay.hayen@gmail.com
#
# Part of "Nuitka", an optimizing Python compiler that is compatible and
# integrates with CPython, but also works on its own.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this fi... |
"""
Module providing easy API for working with remote files and folders.
"""
from __future__ import with_statement
import tempfile
import re
from fabric.api import *
def exists(path, use_sudo=False, verbose=False):
"""
Return True if given path exists on the current remote host.
If ``use_sudo`` is Tru... |
"""
WSGI config for indoorair_front project.
It exposes the WSGI callable as a module-level variable named ``application``.
For more information on this file, see
https://docs.djangoproject.com/en/2.2/howto/deployment/wsgi/
"""
import os
from django.core.wsgi import get_wsgi_application
os.environ.setdefault('DJAN... |
"""
pygments.lexers
~~~~~~~~~~~~~~~
Pygments lexers.
:copyright: Copyright 2006-2022 by the Pygments team, see AUTHORS.
:license: BSD, see LICENSE for details.
"""
import re
import sys
import types
import fnmatch
from os.path import basename
from pygments.lexers._mapping import LEXERS
from pygme... |
from __future__ import print_function
import sys
import os.path
import time
from gen_tzinfo import allzones
from pytz import __version__
boilerplate = r"""msgid ""
msgstr ""
"Project-Id-Version: pytz %s\n"
"POT-Creation-Date: %s\n"
"Content-Type: text/plain; charset=UTF-8\n"
""" % (
__version__,
time.strftim... |
import os
from os import listdir
from os.path import isfile, join
import torch
import pickle
import numpy as np
import matplotlib.pyplot as plt
plt.style.use('ggplot')
def draw_once(thickness_adv_hist, mode='processed', ylim = [0, 1]):
fig, axs = plt.subplots(1, 5, figsize=(25,5))
markers = {"normal": 'o', "... |
"""Provides the Objector class."""
from json import loads
from typing import TYPE_CHECKING, Any, Dict, List, Optional, Union
from .exceptions import ClientException, RedditAPIException
from .models.reddit.base import RedditBase
from .util import snake_case_keys
if TYPE_CHECKING: # pragma: no cover
from .. impor... |
# Кириллов Алексей, ИУ7-12
# Повернуть квадратную целочисленную матрицу F(N,N) по и против часовой стрелки
# без использования дополнительных массивов
#F = [[1,2,3],[8,9,4],[7,6,5]]
#F = [[1,2,3,4],[12,13,14,5],[11,16,15,6],[10,9,8,7]]
#F = [[1,2,3,4,5],[16,17,18,19,6],[15,24,25,20,7],[14,23,22,21,8],[13,12,11,1... |
import numpy
from chainer import cuda
from chainer import optimizer
class RMSpropGraves(optimizer.GradientMethod):
"""Alex Graves's RMSprop.
See http://arxiv.org/abs/1308.0850
"""
def __init__(self, lr=1e-4, alpha=0.95, momentum=0.9, eps=1e-4):
# Default parameter values are the ones in t... |
# Electrum - lightweight Bitcoin client
# Copyright (C) 2012 thomasv@ecdsa.org
#
# 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... |
import django.utils.version
from .constants import DEFAULT_PROTOCOL
from .fields import PickledObjectField
__all__ = 'VERSION', '__version__', 'DEFAULT_PROTOCOL', 'PickledObjectField'
VERSION = (3, 0, 1, 'final', 0)
__version__ = django.utils.version.get_version(VERSION)
|
"""
Base settings for Sigma Pi, Gamma Iota chapter website.
"""
import os
BASE_DIR = os.getcwd()
EC_EMAIL = "gr-sigmapi@wpi.edu"
ACTIVES_EMAIL = "sigmapiactives@wpi.edu"
ALUMNI_EMAIL = "sigmapialumni@wpi.edu"
# Local time zone for this installation. Choices can be found here:
# http://en.wikipedia.org/wiki/List_of_... |
try:
from userbot.modules.sql_helper import SESSION, BASE
except ImportError:
raise AttributeError
from sqlalchemy import Column, String
class KRead(BASE):
__tablename__ = "kread"
groupid = Column(String(14), primary_key=True)
def __init__(self, sender):
self.groupid = str(s... |
#!/usr/bin/env python
# -*- coding: UTF-8 -*-
import sys
import urllib2
import textwrap
import smtplib
from datetime import datetime
import simplejson
from pytz import timezone
try:
conf_fpath = sys.argv[1]
except IndexError:
print >> sys.stderr, 'Usage: %s conf_module.py' % (sys.argv[0],)
sys.exit(1)
co... |
from p2prp.network.packet import packetBase
import p2prp.util.utilStation as util
def printLog(station, *args):
LOG_MARK = '[packetUtil]: '
station.console.addLog(util.toStr(LOG_MARK, *args))
class PackA03RawMsg(packetBase.PacketBase):
def __init__(self, msg=b''):
self.msg = msg
@staticmethod
def getID():
... |
import os
from nose.tools import assert_raises
from pip.download import _get_hash_from_file, _check_hash
from pip.exceptions import InstallationError
from pip.index import Link
def test_get_hash_from_file_md5():
file_path = os.path.join(os.path.dirname(os.path.abspath(__file__)), "packages", "gmpy-1.15.tar.gz")... |
#!/usr/bin/env python3
# Copyright (c) Facebook, Inc. and its affiliates.
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
import logging
import time
import uuid
import os
# Sleep constants
THREAD_SHORT_SLEEP = 0.1
THREAD_MEDIUM_SLEEP = 0.3
#... |
# coding=utf-8
# Copyright © 2018 Computational Molecular Biology Group,
# Freie Universität Berlin (GER)
#
# Redistribution and use in source and binary forms, with or
# without modification, are permitted provided that the
# following conditions are met:
# 1. Redistributions of source code must ret... |
from setuptools import setup
import versioneer
setup(name='PDPbox',
packages=['pdpbox'],
package_data={'pdpbox': ['datasets/*/*']},
version=versioneer.get_version(),
cmdclass=versioneer.get_cmdclass(),
description='python partial dependence plot toolbox',
author='SauceCat',
au... |
from rest_framework.pagination import (
LimitOffsetPagination,
PageNumberPagination,
)
class PostLimitOffsetPagination(LimitOffsetPagination):
default_limit = 100
max_limit = 100
class PostPageNumberPagination(PageNumberPagination):
page_size = 2 |
from django.conf.urls import patterns, include, url
urlpatterns = patterns('',
url(r'^api/v1/', include('checker.urls')),
)
|
import time
import socket
import struct
import sys
import multiprocessing
import datetime
import json
import glob
import random
class NodeManager:
def __init__(self,password):
self.nodelist_current=nodelist_current
self.rf=rf
def localParams():
with open ('localcfg.json','r') as lc:... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.