content stringlengths 5 1.05M |
|---|
#!/usr/bin/env python3
#
# Copyright 2013 The Flutter Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""Copy a Dart package into a directory suitable for release."""
import argparse
import os
import shutil
import sys
def main():
... |
def write_lines(file_path, lines):
with open(file_path, 'w') as file:
for line in lines:
file.write(line + '\n')
def read_line(file_path):
with open(file_path) as file:
return file.readline().strip()
def read_lines(file_path):
lines = []
with open(file_path) as file:
... |
from flask import Flask, request, abort
from requests import post
from concurrent.futures import ThreadPoolExecutor
import os
tp = ThreadPoolExecutor()
app = Flask(__name__)
bots = {x for x in os.environ.get("BOTS", "").split(" ") if x != ''}
event_types = {x for x in os.environ.get("EVENT_TYPES", "").split(" ") if x... |
import pyjion
import gc
pyjion.enable()
from test.libregrtest import main
main()
gc.collect()
pyjion.disable()
print("Disabling JIT")
print(pyjion.stats()) |
import joblib
import numpy as np
import matplotlib as mpl
import matplotlib.pyplot as plt
from seaborn import color_palette
import pandas as pd
from celer.plot_utils import configure_plt
from mtl.utils_plot import _plot_legend_apart
configure_plt()
label_mapping = {
"lambda_map": r"$\lambda$-MAP",
"spatial_... |
from sqlalchemy import Column, UnicodeText, LargeBinary, Numeric
from userbot.plugins.sql_helper import SESSION, BASE
class Snips(BASE):
__tablename__ = "snips"
snip = Column(UnicodeText, primary_key=True)
reply = Column(UnicodeText)
snip_type = Column(Numeric)
media_id = Column(UnicodeText)
m... |
# -*- coding: utf-8 -*-
#
# Copyright 2012-2014 Romain Dorgueil
#
# 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... |
# Generated by the protocol buffer compiler. DO NOT EDIT!
# source: history_delete_directive_specifics.proto
from google.protobuf import descriptor as _descriptor
from google.protobuf import message as _message
from google.protobuf import reflection as _reflection
from google.protobuf import descriptor_pb2
# @@protoc... |
from .danmf import DANMF
from .mnmf import MNMF
from .ego_splitter import EgoNetSplitter
from .nnsed import NNSED
|
# -*- coding: utf-8 -*-
"""Main module.
We should be able to have workers that are just generators - they continuously yield to the pipeline.
We should also be able to have workers that do one thing then return.
"""
import sys
import asyncio
import struct
# import typing
class Master:
"""Master class, coordi... |
import test_utils
import unittest
class TestUtilsTestCase(unittest.TestCase):
def setUp(self):
pass
def test_cost(self):
gt = "test"
self.assertLess(
test_utils.cost("test", gt),
test_utils.cost("text", gt))
self.assertLess(
test_utils.cos... |
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import tensorflow as tf
import numpy as np
from model import modeling_bert
def shape_list(x, out_type=tf.int32):
"""Deal with dynamic shape in tensorflow cleanly."""
static = x.shape.as_list()
dynamic = ... |
"""
author rufeng
date 2021/11/14/9:36
description
"""
import base64
import binascii
import logging
import time
from abc import ABCMeta
import qrcode
import requests
from Crypto.Cipher import AES
from Crypto.Util.Padding import pad
from core import headers, Login
from exceptions import LoginFailedException
from m... |
from django.conf.urls import include, url
from tastypie.api import Api
from parameters.api import (
PVInverterResource, PVModuleResource, CECModuleResource)
from pvfree import views as pvfree_views
from parameters import views as param_views
from django.contrib import admin
from pvfree.api import (
solarpositio... |
from datetime import datetime
from ecat.constants import COMMON_COLS
import cx_Oracle
import logging
import numpy as np
import pandas as pd
from typing import Union, Optional, List
logger = logging.getLogger(__name__)
format = '%(asctime)s %(message)s'
datefmt='%d %b %y %H:%M:%S'
logging.basicConfig(level=logging.INF... |
from google.appengine.ext import vendor
vendor.add('lib')
from google.appengine.api import memcache
from google.appengine.ext.appstats import recording
import GlobalUtilities as tools
from gaesessions import SessionMiddleware
# suggestion: generate your own random key using os.urandom(64)
# WARNING: Make sure you ru... |
from zipfile import ZipFile
import zipfile
import argparse
import os
def keywords(args=None):
print("""
_______ _ __ __ _ ___| | __
|_ / __| '__/ _` |/ __| |/ /
/ / (__| | | (_| | (__| <
/___\___|_| \__,_|\___|_|\_\\
""")
parser = argparse.ArgumentParser(description='Brutforcing Zip files')
parser.add_argume... |
from .loss import * |
import sys
import datetime
from libffpy import LibffPy, BigNum
n = int(sys.argv[1])
l = LibffPy(n)
g2 = l.gen2()
g1 = l.gen1()
start = datetime.datetime.now()
bg = [BigNum() for _ in xrange(n - 1)]
end = datetime.datetime.now()
print "BigNum creation ellapsed: %s" % (end - start)
s = reduce((lambda x,y: x + y), b... |
#! /usr/bin/python
##
# @file
# This file is part of SeisSol.
#
# @author Sebastian Rettenberger (sebastian.rettenberger AT tum.de, http://www5.in.tum.de/wiki/index.php/Sebastian_Rettenberger)
#
# @section LICENSE
# Copyright (c) 2014-2016, SeisSol Group
# All rights reserved.
#
# Redistribution and use in source and b... |
#!/usr/bin/env python2.7
import os
import subprocess
# should be a symlink to the root
# could also add the git rev to this?
version_file = open(os.path.join('.', 'VERSION'))
version_number = version_file.read().strip()
__version__ = version_number
|
''' NavigationMDP.py: Contains the NavigationMDP class. '''
# Python imports.
from __future__ import print_function
import numpy as np
from collections import defaultdict
from simple_rl.tasks import GridWorldMDP
from simple_rl.planning import ValueIteration
from simple_rl.tasks.grid_world.GridWorldStateClass import Gr... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
"""
Created on Thursday 21 September 2017
Pipe toolbox for determinig properties of pipe
to install type: setup.py install
@author: Christopehr Bridge
"""
|
# X0,Y0 is end of arrow, X1,Y1 is the tip point of the arrow.
import math
def make_arrow(X0,Y0,X1,Y1,Len):
Dx = X1-X0
Dy = Y1-Y0
if Dx==0:
X2 = X1-(Len/2)
X3 = X1+(Len/2)
if Dy>0:
Y2 = Y1-Len
Y3 = Y1+Len
else:
Y3 = Y1-Len
Y2 =... |
"""
The main module; the entry point of the bot.
"""
import discord
import os
from discord.ext import tasks, commands
from dotenv import load_dotenv
import logging
from logging.handlers import RotatingFileHandler
from discord_sentry_reporting import use_sentry
from botforces.utils.api import get_all_problems, get_al... |
import argparse
import json
import sys, os, time
sys.path.append(os.path.dirname(os.path.realpath(__file__))+"/libs")
from mgr import *
def config():
print("PID: " + str(os.getpid()))
m = Manager(p4name="main")
mc_pipe0_ports = [0<<7|i for i in range(0, 61, 4)]
mc_pipe1_ports = [1<<7|i for i in range(0, 61... |
from gym.envs.registration import registry
# re-register custom envs to replace gym's default ones
def register(id, **kwargs):
if id in registry.env_specs:
registry.env_specs.pop(id)
return registry.register(id, **kwargs)
register(
id='Reacher-v2',
entry_point='envs.mujoco:ReacherEnv',
max... |
from collections import Counter
import string
def real_rooms(rooms):
count = 0
for room in rooms:
tokens = room.split('-')
letters = ''.join(tokens[:-1])
c = Counter(letters)
common_sorted = sorted(c.items(), key=lambda x: (-x[1], x[0]))
compare = ''.join([x[0] for x in... |
# Third-party
from astropy.time import Time
import astropy.units as u
from astropy.tests.helper import catch_warnings
import numpy as np
import pytest
# Project
from ..elements import KeplerElements, TwoBodyKeplerElements
from ..orbit import KeplerOrbit
from ..units import UnitSystem
def test_kepler():
# Valid ... |
# -*- coding: utf-8 -*-
"""
Created on Tue May 06 09:47:05 2014
Ballistic trajectories Case 2 Drag
@author: etodorov
"""
import math
import matplotlib.pyplot as plt
v0 = 50. #m/s
x0 = 0.
y0 = 0.
deg = math.pi/180.
g = -9.81
dt = .01 #time step
cD = .47 #drag c
A = 0.8 # m^2
m =... |
# coding=utf-8
# *** WARNING: this file was generated by the Pulumi Terraform Bridge (tfgen) Tool. ***
# *** Do not edit by hand unless you're certain you know what you are doing! ***
import warnings
import pulumi
import pulumi.runtime
from typing import Any, Mapping, Optional, Sequence, Union, overload
from . import ... |
#!/usr/bin/env python3
"""
Author: Serg Kolo , <1047481448@qq.com>
Date: December, 21,2016
Purpose: script for setting wallpaper, the pythonic way
Written for: http://askubuntu.com/q/66914/295286
"""
from gi.repository import Gio
import os,sys,random
def gsettings_set(schema, path, key, value):
"""Set value of gse... |
#
# 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 us... |
#!/usr/bin/env python
background_image_filename = 'sushiplate.jpg'
import pygame
from pygame.locals import *
from sys import exit
pygame.init()
screen = pygame.display.set_mode((640, 480), 0, 32)
pygame.display.set_caption("Move a Background Using Keyboard")
background = pygame.image.load(background_image_filename)... |
import numpy as np
from tensorflow.keras.preprocessing import image
def InputImageGenerator(path):
IMAGE_SIZE = [299 , 299]
image1 = image.load_img(path , target_size=IMAGE_SIZE)
img_tensor = image.img_to_array(image1)
img_tensor = np.expand_dims(img_tensor , axis=0)
img_tensor /= 255.
retur... |
import unittest
from sqlalchemy import Column, Integer, String
from sqlalchemy.ext import declarative
from sqlalchemy.orm.scoping import scoped_session
from sqlalchemy.orm import sessionmaker
from wtoolzargs.common import exceptions
from wtoolzargs.common import mapping
from wtoolzargs.filtering import interpreter
fr... |
from numpy import union1d, array, zeros, argmax, setdiff1d
def NaiveSelection(u,data,objective,k_max=None):
# Naive routine for n_-choose-k selection problems, leading to sub-optimal
# results.
# INPUTS
# u :[vector](1 x n_) vector of indices
# data :[struct] struct with data neede... |
from __future__ import print_function, division, with_statement
__author__ = 'Vlad Popovici'
__version__ = 0.15
def img_to_raw():
pass
|
# Suppress warnings
import warnings
warnings.filterwarnings(
'ignore',
message='^`NoneType` object ',
module='^dataclasses_json\.',
category=RuntimeWarning)
import sys
from . import arguments
from . import config
def main():
result = arguments.parse(sys.argv[0], sys.argv[1:])
if not result.s... |
'''author@esilgard'''
#
# Copyright (c) 2015-2016 Fred Hutchinson Cancer Research Center
#
# Licensed under the Apache License, Version 2.0: http://www.apache.org/licenses/LICENSE-2.0
#
import re
import global_strings as gb
__version__ = 'iscn_string_cleaner1.0'
def get(original_text, karyo_offset):
'''
clean... |
"""Define and implement the callback interface."""
from .base import Callback, CallbackList, CallbackListFactory
from .checkpoint import ModelCheckpoint
from .logger import TxtLogger, StdoutLogger
|
import ltspice
import matplotlib.pyplot as plt
import numpy as np
import os
l = ltspice.Ltspice(os.path.dirname(__file__)+'/02_Rectifier.raw')
# Make sure that the .raw file is located in the correct path
l.parse()
time = l.getTime()
V_source = l.getData('V(source)')
V_cap_max = []
plt.plot(time, V_source)
for i i... |
'''
Lab5
'''
#3.1
alien_color = 'red'
if alien_color == "green":
print('you have earned 5 points')
#3.2
alien_color = 'yellow'
if alien_color == "green":
print('you have earned 5 points')
else:
print('you have earned 10 points')
#3.3
favoriate_fruits = ['apple', 'banana', 'orange']
if 'mang... |
import chardet
import codecs
import os
import re
import shutil
import tempfile
import urlparse
import urllib2
from bs4 import BeautifulSoup
from gputils import *
BINARY_EXTS = set(['pdf', 'jpg', 'gif', 'xls', 'doc', 'png', 'zip', 'swf', 'tif', 'dot', 'jpeg', 'xlsx'])
BLOCKSIZE = 1048576 # or some other, desired siz... |
"""
A lightweight library for serialization of arbitrary Python objects into dicts.
"""
import re
from setuptools import setup
def find_version(fname):
"""
Attempts to find the version number in the file names fname.
Raises RuntimeError if not found.
"""
version = ""
with open(fname, "r") as f... |
from django.urls import path, include
from django.conf import settings
from django.conf.urls.static import static
from . import views
app_name = 'account'
urlpatterns = [
path('', views.Login.as_view(), name="login"),
path('logout/', views.Logout.as_view(), name='logout'),
path('signup/', views.UserRegis... |
import sys
def getNextFreeId(elements):
highest = -1
for element in elements:
id = element.get("id")
assert id.find(".") != -1, id
lastPart = id.rsplit(".",1)[-1]
assert len(lastPart) > 1, id
number = int(lastPart[1:])
if number > highest:
highest = n... |
# -*- coding: utf-8 -*-
"""Console script for chutie."""
import collections
import json
import pprint
import sys
from pathlib import Path
import click
from syncer import sync
from chutie import chutie
@click.group()
def main(args=None):
"""Console script for chutie."""
# click.echo("See the 'screenshots' ... |
from django.test import TestCase
from .models import Editor,Category,Location,Image
# Create your tests here.
class EditorTestClass(TestCase):
#Set up method
def setUp(self):
self.vickie= Editor(editor_name = 'vickie', email = 'desastrecaliente@gmail.com')
# Testing instance
def test_instanc... |
import numpy as np
from visual import Visual
from plot_visual import process_coordinates
from galry import get_color, get_next_color
class SpriteVisual(Visual):
"""Template displaying one texture in multiple positions with
different colors."""
def initialize(self, x=None, y=None, color=None, autoc... |
# -*- coding: utf-8 -*-
class Import(object):
def __init__(self):
super(Import,self).__init__()
# self.logger = logger()
def importClass(self,packageName,className):
importString = "from %s import %s as Class"%(packageName,className)
exec importString
Object = Class()
... |
from django.db import models
import requests
import json
import re
import xml.etree.ElementTree as ET
import urllib
from home.models import Home
from datetime import datetime, timedelta
import pytz
class Post(models.Model):
CallNum=models.CharField(max_length=140)
Barcode=models.CharField(max_length=140)
Genre=model... |
from arena import *
from config import *
from display_board import DisplayBoard
class TABoard(DisplayBoard):
"""
TABoard object
Shows students' questions with button to dequeue individual questions. If the button is pressed then student teleports to the TA)
@param scene: scene to display
@param bo... |
#!/usr/bin/python
import socket
import sys
import time
import os
HOST, PORT = "10.2.121.2", 7000
def send_recived(data):
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
received = ''
try:
sock.connect((HOST, PORT))
sub = 'SOPORT'
while True:
sock.sendall((bytes... |
from __future__ import unicode_literals
from django.contrib.auth.models import User
from django.db import models
def question_image_path(instance, filename):
import string
from random import choice
chars = string.letters + string.digits
return 'wordwars/questions/'+ ''.join(choice(chars) for _ in xrange(8))
class... |
#! /usr/bin/env python
# -*- coding:utf-8 -*-
import os
import sys
from wordsegment import load, segment
import Levenshtein
from nltk.parse.stanford import StanfordDependencyParser
from nltk.corpus import wordnet as wn
res = []
FLAG = False
HANDLE_ABBR = False
# predicates list
PREDICATES = [
'get.v.01',
... |
from .rgb_support import *
import random
def cop(rounds=None, direction=None, delay=0.5, color=None, speed=10):
rounds = 4
print("Cop: ", rounds, " rounds")
counter = 0
rounds_counter = 0
flash = 3
led1 = [
red, blue, blue,
blue,
red, red, blue
]
led2 = [
... |
# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
# SPDX-License-Identifier: MIT-0
#
# 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 ... |
from hlt import *
from networking import *
# Times out on turn 10.
myID, gameMap = getInit()
sendInit("Timeout10Bot")
turn = 1
hasMultipleSquares = False;
while True:
moves = []
gameMap = getFrame()
if turn == 10:
while(True):
pass
sendFrame(moves)
turn += 1
|
import os
import yaml
import numpy as np
ideal_structures = None
def distance(p1, p2):
return np.sqrt((p1[0] - p2[0]) ** 2 + (p1[1] - p2[1]) ** 2 + (p1[2] - p2[2]) ** 2)
def resize_structure(structure, center=(0, 0, 0), resize_distance=1.0):
resized_structure = []
max_distance = max([distance(coordinat... |
from __future__ import annotations
from typing import TYPE_CHECKING
import os
from dataclasses import dataclass
from bap.consts import REPO_DIR
if TYPE_CHECKING:
from typing import Optional, List
def check_for_repolist() -> None:
repolist_path = os.path.join(REPO_DIR, 'repolist')
if not os.path.exists(... |
import matplotlib
matplotlib.use('TkAgg')
import matplotlib.pyplot as plt
import numpy as np
import sys
sys.path.append('/home/groups/ZuckermanLab/copperma/cell/celltraj')
import celltraj
import h5py
import pickle
import os
import subprocess
import time
sys.path.append('/home/groups/ZuckermanLab/copperma/msmWE/Bayesian... |
import logging
import requests as re
import infapy
import json
# infapy.log = logging.getinfapy.log(__name__)
# print(infapy.log)
class GetAuditLog:
"""This class is a handler for fetching
the Audit Logs from IICS
"""
def __init__(self,v2,v2BaseURL,v2icSessionID):
self._v2 = v2
self._v2... |
# Generated by Django 2.2.5 on 2019-12-01 18:49
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),
('core', '0005_categoria_s... |
""" Compact OwnCloud/NextCloud WebDAV client parse classes
Author: hevp
"""
import re
import copy
from lxml import etree
from dateutil.parser import parse as dateparse
from common import makeHuman, relativePath
class ParserFactory():
@staticmethod
def getParser(p, data, options):
if p.get('scop... |
import numpy as np
import pandas as pd
import lightgbm as lgb
from sklearn.compose import make_column_transformer
from sklearn.datasets import load_boston as sk_load_boston
from sklearn.impute import SimpleImputer
from sklearn.model_selection import GridSearchCV
from sklearn.model_selection import train_test_split
fro... |
from mpi4py import MPI
import numpy as np
from pySDC.core.Errors import DataError
class pmesh_datatype(object):
"""
Mesh data type with arbitrary dimensions, will contain PMESH values and communicator
Attributes:
values (np.ndarray): contains the ndarray of the values
comm: MPI communica... |
#!/usr/bin/env python3
#
# Copyright 2020-2021 PSB
#
# 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 ... |
"""options.py
This file is part of sutils
Implements configuration options.
"""
import exceptions
import warnings
warnings.warn(
"Module options is deprecated. Use configoptions instead",
DeprecationWarning
)
GROUPS_ = {
'general': GeneralGroup,
}
OPTIONS_ = [
]
# exceptions
class UnknownConfigOptio... |
#!/usr/bin/env python3
import argparse
import gym
import time
import torch
import sys
import pickle
import numpy as np
from torch_rl.utils.penv import ParallelEnv
from gym_recording.wrappers import TraceRecordingWrapper
try:
import gym_minigrid
except ImportError:
pass
import sys
sys.path.append(".")
import ... |
import numpy as np
import networkx as nx
def Crear_matriz(n,ws):
matriz=np.zeros((n,n))
edges=ws.edges()
for e in edges:
matriz[e[0]][e[1]]=1
matriz[e[1]][e[0]]=1
return matriz
def Energia_vertice(valores,vectores):
vectores, w= np.linalg.qr(vectores)
e_v=[]
if len(valo... |
# 使用Python copy一个文件,从a目录,copy文件到b目录
import os
from pathlib import Path
import shutil
src_path=Path('a/test')
dst_path=Path('b/test')
with open(src_path,'w') as src_file:
src_file.write('abcd\n1234')
shutil.copy(src_path,dst_path)
print(os.stat(src_path))
print(os.stat(dst_path)) |
#!/usr/bin/env python3
import pymongo
import logging
class Mongo_Handler:
def __init__(self, database, database_obj, **kwargs):
self.logger = logging.getLogger("PEP_ENGINE")
self.modified = []
self.__dict__.update(kwargs)
self.myclient = pymongo.MongoClient('localhost', 27017)
... |
from setuptools import setup
setup(
name='splunk_handler',
version='2.2.1',
license='MIT License',
description='A Python logging handler that sends your logs to Splunk',
long_description=open('README.md').read(),
long_description_content_type='text/markdown',
author='Zach Taylor',
autho... |
# cli/cli_tools.py
# This module provides tools for cli interface
#
# @author: mike
# @created: 2020-07-19
import sys, argparse, os
from enum import IntEnum
from lib_piglet.utils.tools import eprint
# Describe parameters in arg parser result. For IDE convenient.
class args_interface:
problem: str
framework: ... |
from .preprocessing import preprocess_input
from .models import ResNet50, ResNet101
|
import os
import sys
#add parent and grandparent and great-grandparent to path
currentdir = os.path.dirname(os.path.realpath(__file__))
parentdir = os.path.dirname(currentdir)
sys.path.append(parentdir)
parentdir = os.path.dirname(parentdir)
sys.path.append(parentdir)
parentdir = os.path.dirname(parentdir)
sys... |
class net():
def __error(error):
return ("\033["+str(31)+"m"+str(error)+"\033[0m")
def load_data(url,filename=None):
try:
import requests
r = requests.get(url)
if filename==None:
return (r.content)
else:
with open(filename,'wb') as f:
f.write(r.content)
return True
except Exception... |
# Exercício Python 34: Crie um programa que leia dois valores e mostre um menu na tela:
#[ 1 ] somar
#[ 2 ] multiplicar
#[ 3 ] maior
#[ 4 ] novos números
#[ 5 ] sair do programa
#Seu programa deverá realizar a operação solicitada em cada caso.
n1 = float(input('Digite um número: '))
n2 = float(input('Digite outro núme... |
from pyramda.function.curry import curry
@curry
def identity(x):
return x
|
import numpy as np
import robot_sim._kinematics.jlchain as jl
import robot_sim.robots.robot_interface as ri
import rrt
import rrt_star as rrts
class XYBot(ri.RobotInterface):
def __init__(self, pos=np.zeros(3), rotmat=np.eye(3), name='XYBot'):
super().__init__(pos=pos, rotmat=rotmat, name=name)
s... |
#!/usr/bin/env python
# @lint-avoid-python-3-compatibility-imports
from __future__ import print_function
from bcc import BPF
sample_freq = 100
bpf_text = """
#include <uapi/linux/ptrace.h>
#include <linux/sched.h>
BPF_PERF_OUTPUT(events);
int do_perf_event (struct bpf_perf_event_data *ctx) {
}
"""
b = BPF(text=b... |
# -*- coding: utf-8 -*-
"""
Author: Paschalis Giakoumoglou
Date: Thu Jun 17 19:16:15 2021
"""
import numpy as np
import math
import sympy as symb
import pandas as pd
def lagrange(f, x):
""" 4.3 Lagnrance (p.71) """
a = pd.Series(data=[[i for i in range(len(x))],x,f], index=['i','x','f(x)'])
... |
# DO NOT EDIT
# Autogenerated from the notebook discrete_choice_example.ipynb.
# Edit the notebook and then sync the output with this file.
#
# flake8: noqa
# DO NOT EDIT
#!/usr/bin/env python
# coding: utf-8
# # Discrete Choice Models
# ## Fair's Affair data
# A survey of women only was conducted in 1974 by *Redbo... |
import logging
import os
import re
import tempfile
from jinja2 import Environment, FileSystemLoader, BaseLoader
from airflow.configuration import conf
from airflow.hooks.hive_hooks import HiveCliHook
from airflow.operators.email_operator import EmailOperator
from airflow.utils.decorators import apply_defaults
class... |
import collections
from sourmash_lib.lca import lca_utils
taxonomy_levels = ['superkingdom', 'phylum', 'class', 'order', 'family',
'genus', 'species', 'strain']
def summarize_taxonomic_purity(minhash_collections, lca_db, verbose=False,
filenames=None):
if filenam... |
#!/usr/bin/env python3
import shelve
import sys
print("saw filename of", sys.argv[1])
with shelve.open(sys.argv[1], flag='r') as d:
for k in sys.argv[2:]:
print(k, ',', d.get(k))
|
#!/usr/bin/env python3
from setuptools import setup, find_packages
NAME = "my-duka"
VERSION = '0.2.1'
setup(
name=NAME,
packages=find_packages(),
install_requires=['requests>=2.9.1'],
version=VERSION,
description='Dukascopy Bank SA historical data downloader',
author='Giuseppe Pes',
autho... |
# -*- coding: utf-8 -*-
import re
REGEX_TYPE = re.compile('^([\w\_\:]+)')
REGEX_DBNAME = re.compile('^(\w+)(\:\w+)*')
REGEX_W = re.compile('^\w+$')
REGEX_TABLE_DOT_FIELD = re.compile(r'^(\w+)\.(\w+)$')
REGEX_TABLE_DOT_FIELD_OPTIONAL_QUOTES = r'^"?(\w+)"?\."?(\w+)"?$'
REGEX_NO_GREEDY_ENTITY_NAME = r'(\w+?)'
REGEX_UPLO... |
"""
The L{config} module contains the L{FedexConfig} class, which is passed to
the Fedex API calls. It stores useful information such as your Web Services
account numbers and keys.
It is strongly suggested that you create a single L{FedexConfig} object in
your project and pass that to the various API calls, rather tha... |
"""
Requires matplotlib
pipenv install matplotlib
python plot.py
"""
import yaml
import numpy
import matplotlib.pyplot as plt
from connected_conics import conic, helpers
fullspec = """
- r: [8]
e: [0.0]
d: 6.0
- r: [9]
e: [0.5]
d: 10.0
- r: [11]
e: [1.1]
d: 12.0
"""
fullspec_dict = yaml.safe_load(fullspec)... |
"""
FEniCS tutorial demo program: Diffusion of a Gaussian hill.
u'= Laplace(u) + f in a square domain
u = u_D on the boundary
u = u_0 at t = 0
u_D = f = 0
The initial condition u_0 is chosen as a Gaussian hill.
"""
from __future__ import print_function
from fenics import *
import ti... |
class Verifier:
def __init__(self):
pass
def get_data_from_file(self, file_path):
# Load a JSON file into a Python dictionary that
# can live on memory temporarily
try:
import json
with open(file_path) as f:
payload = json.load(f)
... |
import unittest
import torch
from robosat.transforms import JointCompose, JointTransform, ImageToTensor, MaskToTensor
import mercantile
from robosat.datasets import SlippyMapTiles, SlippyMapTilesConcatenation
class TestSlippyMapTiles(unittest.TestCase):
images = "tests/fixtures/images/"
def test_len(self)... |
from lib.constants import SELECT_CURRENT_GAME, INSERT_GAME, UPDATE_GAME, SELECT_CURRENT_GAME_NULL_MESSAGE
class Game():
def __init__(self, id:int, url:str = None, message_id:str = None, title:str = None, start_week:str = None):
self.__id = id
self.__url = url
self.__message_id = message_id... |
from collections import defaultdict, namedtuple, Counter
MAX_SCORE = 10
import logging
import pickle
import os
import operator
from DIE_Exceptions import DbFileMismatch
from DIE.Lib.db_DataTypes import dbDebug_Values, dbFuncArg, \
dbFunction, dbFunction_Context, dbParsed_Value, dbRun_Info, dbThread
import ida... |
import blah
def test_blah():
blah.dostuff()
|
from conans import ConanFile, AutoToolsBuildEnvironment, RunEnvironment, tools
import os
class OpenEXRConan(ConanFile):
name = "OpenEXR"
description = "OpenEXR is a high dynamic-range (HDR) image file format developed by Industrial Light & " \
"Magic for use in computer imaging applications.... |
"""Main program for displaying ingredients list for shopping with the recipes liked"""
# Standard library imports
import sys
# Third party imports
from colorama import Fore, Style
# Local application imports
from ingredients_input import IngredientsInput
from search_recipes_by_ingredients import SearchRecipesByIngre... |
from datetime import datetime
import gevent.lock
import structlog
from raiden.storage.sqlite import SerializedSQLiteStorage
from raiden.transfer.architecture import Event, State, StateChange, StateManager
from raiden.utils.typing import Callable, Generic, List, Tuple, TypeVar
log = structlog.get_logger(__name__) # ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.