content stringlengths 5 1.05M |
|---|
from .metrics import register_metrics
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sun May 5 15:14:59 2019
@author: melzanaty
"""
import media
import fresh_tomatoes
def main():
# First Movie
ugly_dolls = media.Movie("Ugly Dolls",
"An animated adventure in which the free-spirited UglyDolls confront ... |
from django.db import models
from django.utils.text import slugify
from lugar.models import Pais
from sorl.thumbnail import ImageField
from noticias.models import Categoria
#Create your models here.
class Tipo(models.Model):
nombre = models.CharField(max_length = 255)
slug = models.SlugField(max_length = 250,... |
#!/usr/bin/python3
def number_keys(a_dictionary):
return len((a_dictionary.keys()))
|
#!/usr/bin/python3
# coding: UTF-8
"""Implements a simple, naïve depth-first search algorithm which
will be used to solve the following simple maze.
+-+-+-+-+
|A B|C D|
+ +-+ + +
|E|F G|H|
+ + +-+ +
|I J|K L|
+ + + + +
|M|N O|P|
+ + +_+-+
|Q R S T|
+-+-+-+-+
An example of a valid path from A to T would be AEIJFGCDHL... |
def binary(s):
return str(s) if s<=1 else bin(s>>1) + str(s&1)
# TEST if COM PORT IS WORKING
# Connect pins 2 and 3 on the female rs232 port and see if you receive what you send (COM PORT LOOPBACK TEST)
# print(x.send("-5000 -5000 5000 5000 setlimit"))
# print(x.send("1 1 setunit")) # x-axis
# print(x... |
from . import ma
from .models import User, Services
class UserSchema(ma.SQLAlchemySchema):
class Meta:
model = User
id = ma.auto_field()
username = ma.auto_field()
email = ma.auto_field()
role = ma.auto_field()
superuser = ma.auto_field()
is_banned = ma.auto_field()
force_pass... |
print len("hello") hello
|
import unittest
import numpy
import chainer
from chainer.backends import cuda
from chainer import functions
from chainer import gradient_check
from chainer import testing
from chainer.testing import backend
def inject_backend_tests(method_names):
decorator = backend.inject_backend_tests(
method_names,
... |
#
# The MIT License (MIT)
#
# This file is part of pairwiseMKL
#
# Copyright (c) 2018 Anna Cichonska
#
# 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 l... |
import tellurium as te
from rrplugins import *
auto = Plugin("tel_auto2000")
r = te.loada (
'''
$Xo -> x; 0.1 + k1*x^4/(k2+x^4);
x -> $w; k3*x;
// Initialization here
k1 = 0.9;
k2 = 0.3;
k3 = 0.7;
'''
)
auto.setProperty("SBML", r.getCurrentSBML())
auto.setProperty("NM... |
# -*- coding: utf-8 -*-
# @Time : 2019/3/15 0015 23:29
# @Author : __Yanfeng
# @Site :
# @File : __init__.py.py
# @Software: PyCharm |
#! /usr/bin/env python
from queue import Queue
import argparse
import sys
import logging
import rospy
from sensor_msgs.msg import JointState
from std_msgs.msg import Header
import time
import numpy as np
import scipy
from scipy import interpolate
import matplotlib.pyplot as plt
from roc.msg import Motion as MotionM... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
# (c) 2019 Jameer Pathan <jameerpathan111@gmail.com>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your op... |
vel = float(input('Informe a velocidade do carro em Km/h'))
if (vel > 80):
print('Você foi multado')
vel -= 80
print('Sua multa é de R${:.2f}'.format(vel * 7.00))
else:
print('Dirija com segunça')
print('Siga em frente') |
import os
import yaml
import string
def clean_tokens(sequence):
"""
This function removes the following:
1. All empty tokens
2. Remove punctuations from the words
:param sequence:
:return:
"""
table = str.maketrans('', '', string.punctuation)
sequence = [x.lower() for x in seque... |
from os import path
import sklearn
from sklearn.cluster import KMeans, DBSCAN
from sklearn.metrics import silhouette_score, calinski_harabasz_score, davies_bouldin_score
from sklearn.neighbors import NearestNeighbors
from config import cfg
from easydict import EasyDict as edict
from edgeConstruction import c... |
# -*- coding: utf-8 -*-
from email.header import Header
from openprocurement.api.utils import get_now
def not_found(self):
response = self.app.get("/contracts/some_id/documents", status=404)
self.assertEqual(response.status, "404 Not Found")
self.assertEqual(response.content_type, "application/json")
... |
from MediaPlayer.Util.Network import read_integer, read_long, write_long, write_int, write_bytes, write_uint, \
write_ushort
from MediaPlayer.Util.Util import check_bytes_length, check_minimal_bytes_length, uri_from_bytes
from Shared.Logger import Logger, LogVerbosity
class TrackerConnectionMessage:
def __in... |
# 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
# "License"); you may not u... |
from rest_framework.test import APIClient
from .test_comment_data import CommentTest
# from authors.apps.articles.tests.base_test import BaseTest
from rest_framework import status
class TestComment(CommentTest):
def test_create_comment(self):
"""
create a comment on an article
"""
... |
# vim: set encoding=utf-8
# Copyright (c) 2016 Intel Corporation
#
# 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 require... |
""" All exceptions for this package."""
class SFDC_Exception(Exception):
"""Base SFDC API Exception """
message = u"Unknown error occured for {url}. Response content: {content}"
def __init__(self, url, status, resource_name, content):
"""Init SFDC_Exception exception
This is the base cl... |
string = 'foo bar'
###### reverse every 2nd word ######
# string = 'foo bar'
# print(string[1]) # prints o
# print(string[:1]) # prints f
# print(string[::1]) # prints foo bar (whole string)
# words = string.split()
# for i in range(len(string)):
# print(words[i]) # print the items in the word (list)
# 1) convert... |
#!/usr/bin/env python
# -*- coding: utf8 -*-
# coding: utf8
# Libs imports
import os
import json
import time
from datetime import datetime
# Rule #1: Always print arguments with str() function
# Rule #2: In order to avoid useless ping, add '_' before any player username if the command can be triggered by someone else... |
import datetime
import json
import logging
import os
import pprint
import re
from PIL import Image
from django.conf import settings
from django.contrib.sites.models import Site
logger = logging.getLogger(__name__)
def log_message(message, **kwargs):
pretty = kwargs.get("pretty", False)
verbosity = kwargs.ge... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Wed Jan 6 10:24:25 2021
@author: dhanley
"""
import os
from PIL import Image
import cv2
import glob
from scipy import ndimage
import numpy as np
import pandas as pd
import xmltodict
import html
from tqdm import tqdm
import torch, torchvision
import keras
i... |
#!/usr/bin/env vpython
# coding=utf-8
# Copyright 2015 The LUCI Authors. All rights reserved.
# Use of this source code is governed under the Apache License, Version 2.0
# that can be found in the LICENSE file.
import base64
import datetime
import json
import logging
import os
import random
import sys
import unittest
... |
# 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 writing, software
# distrib... |
import requests
url = 'http://api.openweathermap.org/data/2.5/forecast?zip=47907,us&APPID=65b145c4c3e9787a31a313f5d742e482'
res = requests.get(url)
data=res.json()
date=data['list'][1]['dt_txt']
weather=data['list'][0]['weather'][0]['main']
with open("weather.txt","a") as text_file:
text_file.write('{}... |
# -*- coding: utf-8-*-
import unittest
import tempfile
import contextlib
import logging
import shutil
import mock
from jessy import vocabcompiler
class TestVocabCompiler(unittest.TestCase):
def testPhraseExtraction(self):
expected_phrases = ['MOCK']
mock_module = mock.Mock()
mock_module.... |
from .channel import Channel
from .client import Client
__all__ = [
Channel,
Client
]
|
import traceback
from pprint import pprint
from cement.core import controller
from colorama import init, Fore, Back, Style
import json
import sys
class Credentials(controller.CementBaseController):
class meta:
interface = controller.IController
label = 'credentials'
description = 'Validates... |
from flask_sqlalchemy import SQLAlchemy
db = SQLAlchemy()
class Product(db.Model):
id = db.Column(db.Integer, primary_key=True)
tag = db.Column(db.String(80), unique=True)
name = db.Column(db.String(80), unique=False)
count = db.Column(db.Float, unique=False)
def __init__(self, tag, name, count = ... |
#!/usr/bin/env python3
"""
Normalization of VCF genotype.
@Author: wavefancy@gmail.com
Usage:
VCFGenotypeNormalize.py
VCFGenotypeNormalize.py -h | --help | -v | --version | -f | --format
Notes:
1. Read vcf file from stdin, and output results to stdout.
2. Normalize g... |
"""
Execute a command and produce the execution result
"""
from openpipe.pipeline.engine import ActionRuntime
from subprocess import Popen, PIPE
class Action(ActionRuntime):
category = "Data Sourcing"
required_config = """
cmd: # The command to be executed
"""
optional_config = """
shell:... |
"""
PyMOL visualization shortcuts that use Rosetta.
"""
__author__ = "Brian D. Weitzner"
__email__ = "brian.weitzner@gmail.com"
import logging
from .utils import rosetta_to_pymol, pymol_to_rosetta
from .selectors import show_interface_residues
logging.basicConfig(level=logging.INFO, format="%(asctime)s %(message)s")
... |
from django.apps import AppConfig
class RecognizeImgConfig(AppConfig):
name = 'recognize_img'
|
from ..utils import Object
class MessageChatChangePhoto(Object):
"""
An updated chat photo
Attributes:
ID (:obj:`str`): ``MessageChatChangePhoto``
Args:
photo (:class:`telegram.api.types.photo`):
New chat photo
Returns:
MessageContent
Raises:
... |
"""Take an input string and produce a bar chart.
Bar chart is produced by printing each letter
dictionary style, followed by showing the amount
of times each letter appeared.
Example: {'a': ['a','a','a','a','a']}
"""
import pprint
from collections import defaultdict
ALPHABET = 'abcdefghijklmnopqrstuvwxyz'
def print... |
def swap_case(s):
return ''.join([c.lower() if c.isupper() else c.upper() for c in s])
|
from plugins import PluginUtil
from plugins.Manifest_File_Checks import ManifestFilePlugin
plugin = ManifestFilePlugin()
def test_regex():
assert PluginUtil.contains(plugin.PATH_USAGE, 'android:path=') is True
def test_regex1():
assert PluginUtil.contains(plugin.PATH_USAGE, 'android:pathPrefix=') is False
d... |
from python.pipeline.common.cleanup_stage import CleanupStage
from python.pipeline.common.dummy_feeder_stage import DummyFeederStage |
import tensorflow as tf
import zfit
from zfit import ztf
from zfit.util import ztyping
from .. import kinematics
def relativistic_breit_wigner(m2, mres, wres):
"""Relativistic Breit-Wigner function.
"""
second_part = tf.complex(ztf.constant(0.), mres) * ztf.to_complex(wres)
below_div = ztf.to_complex... |
# https://www.codewars.com/kata/5cd5ba1ce4471a00256930c0/
'''
Instructions :
Your job is to write function last_digits(n,d) which return the last d digits of an integer n as a list. n will be from 0 to 10^10
Examples:
last_digits(1,1) --> [1]
last_digits(1234,2) --> [3,4]
last_digits(637547,6) --> [6,3,7,5,4,7]
... |
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def buildTree(self, inorder, postorder):
"""
:type inorder: List[int]
:type postorder: List[int]
:rtype: ... |
# -*- coding: utf-8 -*-
from django.conf import settings
from django.urls import include, path
from django.views import defaults as default_views
"""Local URL Configuration"""
urlpatterns = []
if getattr(settings, 'DEBUG', False):
from django.contrib.staticfiles.urls import staticfiles_urlpatterns
from djan... |
from aorist import *
from aorist_recipes import programs
from scienz import (
probprog, subreddit_schema
)
local = SQLiteStorage(
location=SQLiteLocation(file_name='subreddits.sqlite'),
layout=TabularLayout(StaticTabularLayout()),
)
subreddits = probprog.replicate_to_local(
Storage(local), "/tmp/probpro... |
from django.db import models
class Article(models.Model):
title = models.CharField(max_length=100)
pub_date = models.DateTimeField()
text = models.TextField()
def __str__(self):
return self.title
|
import copy
from typing import List
from utils import sample_sort, get_next_molecule, positive_list_difference, sample_helps_projects
from data_holder import State, Robot, Location, Action, Move, Sample
from simulation import simulate_action, movement_matrix
expertise_weight = 10
class Variation:
def __init__(se... |
# coding: utf-8
from __future__ import absolute_import
from bitmovin_api_sdk.common import BaseApi, BitmovinApiLoggerBase
from bitmovin_api_sdk.common.poscheck import poscheck_except
from bitmovin_api_sdk.models.bitmovin_response import BitmovinResponse
from bitmovin_api_sdk.models.player_third_party_licensing import... |
from ast import literal_eval
from math import log
import sys
themes = ["style", "science", "media", "business", "life",
"travel", "economics", "sport", "culture", "forces"]
all_docs = []
for theme in themes:
with open(f"lemm_text_clear_themes/{theme}.txt") as f:
for line in f:
aticle... |
#!/usr/bin/env python3
import argparse
import csv
from enum import Enum
import itertools
import logging
from os import geteuid, path
from string import Template
import subprocess
import time
logger = logging.getLogger(__name__)
class ExitCodes(Enum):
SUCCESS = 0
GENERAL_ERROR = 1
INVALID_USER = 2
USE... |
# PYTHON_ARGCOMPLETE_OK
import argparse
import argcomplete
def main():
parser = argparse.ArgumentParser()
parser.add_argument('arg', choices=['arg'])
argcomplete.autocomplete(parser)
args = parser.parse_args()
print(args.arg)
if __name__ == '__main__':
main()
|
from sqlalchemy.sql.expression import text
from application.extensions import db
class Notification(db.Model):
"A notification."
__tablename__ = 'notification'
id = db.Column('id', db.Integer(), primary_key=True)
message = db.Column('message', db.Text(), nullable=False)
transport = db.Column('t... |
"""
2. Faça um Programa que peça um número e então mostre a mensagem O número informado foi [número].
"""
numero = int(input('Informe um número: '))
print('O número informado foi ' + str(numero) + '.')
|
# Entrada de dados
peso = float(input('Insira o seu peso: '))
altura = float(input('Insira a sua altura: '))
# Processamento
imc = peso / (altura ** 2)
# Saída de dados
print(f'Seu IMC é: {imc:.2f}')
if imc < 17:
print('Muito abaixo do peso')
elif imc < 18.5:
print('Abaixo do peso')
elif imc < 25:
print('Pe... |
import random
from abc import ABC
from django.conf import settings
from django.contrib.auth import get_user_model
from django.urls import reverse
from rest_framework import status
from rest_framework.test import APIClient
from drf_util.utils import get_applications, Colors, gt
fixtures_path = gt(settings, 'FIXTURES_... |
import datetime
from haystack import indexes
from .models import FeedItem
class FeedItemIndex(indexes.SearchIndex, indexes.Indexable):
text = indexes.CharField(document=True, use_template=True)
author = indexes.CharField(model_attr='author')
pub_date = indexes.DateTimeField(model_attr='pubDate')
title ... |
import models
import os
import queue
import shutil
import torch
import torch.nn as nn
from dataset import TASK_SEQUENCES
from models import EnsembleClassifier
class ModelSaver(object):
"""Class to save and load model ckpts."""
def __init__(self, save_dir, iters_per_save, max_ckpts, metric_name='val_loss',
... |
import numpy as np
from scipy import special
def _reshape_lattice_column(arr):
n_components = len(arr)
clonal = np.repeat(arr[0], n_components - 1)
return np.vstack([clonal, arr[1:]])
def _reshape_transition_prob(arr, forward=True):
# stack the diagonal and one of the row/column together for convenien... |
import os
import tensorflow as tf
import numpy as np
import rejection_network
class RejectionSystem():
def __init__(self):
self.dir_path = os.path.dirname(os.path.abspath(__file__))
self._train_dir = os.path.join(self.dir_path, "Data/Train/")
self._valid_dir = os.path.join(self.dir_path, ... |
"""
InfluxDB Alchemy.
"""
import pkg_resources
from influxalchemy.client import InfluxAlchemy # noqa: F401
from influxalchemy.measurement import Measurement # noqa: F401
try:
__version__ = pkg_resources.get_distribution(__package__).version
except pkg_resources.DistributionNotFound: # pragma: no cover
... |
import sys
import numpy as np
from mpi4py import MPI
from rvs import *
def ar_ub_reptod_wcancel(ns, J, S):
EJ, ES = J.mean(), S.mean()
return ns/EJ/ES
ns, d = 10, 2
J = TPareto(1, 10**4, 1.1) # Exp(0.05, D=1) # HyperExp([0.8, 0.2], [1, 0.1] )
S = Dolly() # TPareto(1, 100, 1.2) # Bern(1, 20, 0.2)
N, T = 30, ns*500... |
import os
import spotipy
import json
from spotipy.oauth2 import SpotifyClientCredentials
import youtube_dl as yt
from youtube_search import YoutubeSearch
songs = []
scope = "user-library-read"
_track ="SPOTIFY LIST"
sp = spotipy.Spotify(auth_manager=SpotifyClientCredentials(client_id='CLIENT ID',client_secret='CLIE... |
##
# Copyright 2021 IBM Corp. All Rights Reserved.
#
# SPDX-License-Identifier: Apache-2.0
##
from lnn import (
Model,
And,
Variable,
plot_loss,
plot_params,
TRUE,
FALSE,
UNKNOWN,
UPWARD,
)
def test():
model = Model()
p1, p2 = model.add_predicates(1, "P1", "P2")
model.... |
import os
import sys
import threading
from PyQt5.QtGui import *
from PyQt5.QtCore import QDateTime, Qt, QTimer, QObject, pyqtSignal
from PyQt5.QtWidgets import (QApplication, QDialog, QFileDialog, QGridLayout,
QGroupBox, QHBoxLayout, QLabel, QLineEdit, QMainWindow,
... |
from collections import defaultdict, namedtuple
from pathlib import Path
from typing import Dict, List, Optional, Tuple, Union
import csv
import os
from techiaith.utils.bitext import LanguagePair
from sklearn.model_selection import train_test_split
import numpy as np
import pandas as pd
GroupLabels = namedtuple('Gro... |
from .lens import apply_lens
from .network import mapper_graph
|
"""kde_corner - Corner plots with proper KDE defined uncertainties.
"""
from __future__ import print_function
# may be needed now. IDK
from matplotlib import use
use("PDF")
# Todo, type hints force python >= 3.5
from typing import Union
from itertools import cycle
import numpy as np
import matplotlib.pyplot as plt... |
from flask import render_template
def home_index():
return "hello home index!"
def home_users():
return "hello home users!"
def home_html():
return render_template("index.html")
|
import requests
import codecs
import json
import sys
import gzip
import bz2
import pandas as pd
try:
elasticUrl = sys.argv[1]
indexName = sys.argv[2]
inFilePath = sys.argv[3]
except:
print("Usage: indexer.py <http://localhost:PORT> <index_name> <firewall-log.csv>")
sys.exit(-1)
# What type of obj... |
"""Fixer for operator.{isCallable,sequenceIncludes}
operator.isCallable(obj) -> hasattr(obj, '__call__')
operator.sequenceIncludes(obj) -> operator.contains(obj)
"""
# Local imports
from .. import fixer_base
from ..fixer_util import Call, Name, String
class FixOperator(fixer_base.BaseFix):
methods = "method=('i... |
def bin_to_str_func_style(bin_string):
ascii_string = "".join([chr(int(binary, 2)) for binary in bin_string.split(" ")])
print(ascii_string)
def bin_to_str(bin_string):
binary_values = bin_string.split()
ascii_string = ""
for binary_value in binary_values:
an_integer = int(binary_value, 2)... |
#############################################################################
# Copyright Kitware Inc.
#
# 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/licen... |
"""clustering module"""
from sknetwork.clustering.base import BaseClustering
from sknetwork.clustering.kmeans import KMeans
from sknetwork.clustering.louvain import Louvain
from sknetwork.clustering.metrics import modularity, bimodularity, comodularity, normalized_std
from sknetwork.clustering.postprocess import reinde... |
from abc import ABC, abstractmethod
class Simulation(ABC):
@abstractmethod
def reset():
'''
Reset simulation state
'''
pass
@abstractmethod
def sim_step():
'''
Run one step of the simulation
'''
pass
@abstractmethod
... |
# Import python packages
import sys, math
from typing import List, Tuple, Dict
from time import perf_counter
# Other packages
import numpy as np
import h5py
from colorama import Fore, Style
from prettytable import PrettyTable
from tqdm import tqdm
from numba import prange, jit, njit
# Own components
fro... |
from math import *
from OpenGL.GL import *
from OpenGL.GLU import *
from OpenGL.GLUT import *
def circle(R, n, coef=1):
glBegin(GL_TRIANGLE_FAN)
glVertex3d(0, 0, -0.5)
for i in range(n+1):
glColor3f((0.3+1/(i+1))*coef, (0.3+1/(i+1))*coef, (0.3+1/(i+1))*coef)
glVertex3d(R * cos(2*pi*i/n), R ... |
"""AI module for computer game actions."""
import die
import dicehand
class AI:
"""AI class for game logic."""
scores = []
def __init__(self, difficulty):
"""Initialise object and set difficulty."""
self.difficulty = difficulty
self.turn = dicehand.Dicehand()
... |
from django.db import models
# Create your models here.
class Task(models.Model):
title = models.CharField(max_length=150)
date = models.DateTimeField(auto_now_add=True)
completed = models.BooleanField(default=False)
class Meta:
ordering = ['completed', 'date']
|
from django.urls import path, re_path
from rest_framework import routers
from . import views
router = routers.DefaultRouter()
router.register(r'neighbors', views.NeighborhoodViewSet)
router.register(r'users', views.UserViewSet)
router.register(r'business', views.BusinessViewSet)
urlpatterns=[
path('api/neighbors/'... |
from .entity import ( # noqa: F401
AutoId,
Entity,
NaturalId,
SequenceId,
Uuid4Id,
)
from .repository import Factory # noqa: F401
from .repository import Repository # noqa: F401
from .value_object import ValueObject # noqa: F401
|
# -*- coding: utf-8 -*-
# Copyright 2011 Google 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 require... |
__all__ = ['Query', 'Tag', 'And', 'Or', 'Not']
class Query(object):
"""
Taxon is queried by ``tuple`` objects that represent the syntax tree of the
query. These tuple queries can become unwieldy quickly, so the query DSL is
provided as the main way to query Taxon.
All subclasses of ``Query`` impl... |
from enum import Enum
class EntityType(Enum):
PERSON = 1
ORG = 2
LOCATION = 4
WEB = 8
EMAIL = 16
AMOUNT = 32
|
"""Major methods to create accompanying Excel output file."""
from typing import List
from pathlib import Path
import pandas as pd
def create_excel(
excel: Path,
paths: List[List[str]],
path_info: pd.DataFrame,
separator: str,
start_cell_number: int,
) -> None:
"""Write excel file presentin... |
"""This file contains a class for receiving messages from ScrubCam."""
import asyncio
import logging
import os
import time
import yaml
from scrubdash.asyncio_server.filesystem import (get_most_recent_subdirectory,
get_subdirectories)
from scrubdash.asyncio_server.netw... |
"""
Tests for queryset-filtering.
"""
from django.template import Template, Context
from mock import patch
from tests import case
class FilterUrlTest(case.TestCase):
"""Tests for filter_url template filter."""
@patch("moztrap.view.lists.filters.filter_url")
def test_pass_through(self, mock_filter_url)... |
# -*- coding: utf-8 -*-
# Generated by Django 1.9.9 on 2016-09-25 22:14
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('personas', '0005_auto_20160925_1210'),
]
operations = [
migrations.AlterFiel... |
import wx
import mapnik
import gui
app = wx.App(0)
frame = gui.MainFrame(None)
app.SetTopWindow(frame)
frame.Show()
#frame.LoadMap()
app.MainLoop() |
import numpy as np
import matplotlib.pyplot as plt
# Plot the function
f = lambda x: x ** 3 - 3 * x + 1
xp = np.linspace(-2, 2, 100)
plt.plot(xp, f(xp))
plt.xlabel('x')
plt.ylabel('f(x)')
# Plot extrema and points of inflection
x = np.array([-1, 0, 1])
y = np.array([f(i) for i in x])
plt.scatter(x, y)
for i in x:
... |
# -*- coding: utf8 -*-
from __future__ import unicode_literals
from multiprocessing import Process, Pipe
import time
import random
from mlbExceptions import SolverException
from tools import utils
class Solution(Exception):
"""
Base class for the solution of any problem, found by any type of solver.
Ra... |
# $begin condexp.py$$ $newlinech #$$
# $spell
# condexp
# $$
#
# $section condexp: Example and Test$$
#
# $index conditional, expression$$
# $index condexp, example$$
# $index example, condexp$$
#
# $code
# $verbatim%example/condexp.py%0%# BEGIN CODE%# END CODE%1%$$
# $$
# $end
# BEGIN CODE
# Example using a_float ----... |
from nltk.stem.snowball import SnowballStemmer
from nltk import WordPunctTokenizer
import sys,json,os
en_stem = SnowballStemmer("english")
wpt = WordPunctTokenizer()
script_dir = os.path.dirname(__file__)
json_data=open(script_dir+'/keywords.json')
keywords = json.load(json_data)
json_data.close()
stem_keywords = d... |
import json
import requests
print 'hellow-python'
print 'getapi'
url = 'http://localhost:5984/imagelist/'
key = '6a68cff2f67da8389cef0bb0ca000a3b'
result = requests.get(url+key)
print result.text |
import os
import platform
import csv
import sys
import boto3
import paramiko
import time
def get_instances(instance_file_path):
created_instances = []
with open(instance_file_path, newline='') as csvfile:
# reads each entry
instanceRead = csv.reader(csvfile, delimiter=',', quotechar="|")
# appends that ent... |
import numpy as np
from jax import numpy as jnp
from simtk import unit
from md.barostat.utils import compute_box_volume
from timemachine.constants import kB, ENERGY_UNIT, DISTANCE_UNIT
from typing import Union
non_unitted = Union[float, np.ndarray, jnp.ndarray] # raw value without simtk unit attached
class Potenti... |
from __future__ import absolute_import
from __future__ import print_function
import sys, os, yaml, glob
import subprocess
import pandas as pd
import gzip
import re
import string
import shutil
import numpy as np
from matplotlib import pyplot as plt
from nougat import common, align
from nougat.pdf.peakdetect import peakd... |
"""=============================================================================
Script for training models on Tiger GPU.
============================================================================="""
import argparse
from copy import copy
import datetime
import itertools
import os
import sys
# -------------------... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.