content stringlengths 0 894k | type stringclasses 2
values |
|---|---|
from distutils.core import setup
setup(
name = 'wthen',
packages = ['wthen'], # this must be the same as the name above
version = '0.1.2',
description = 'A simple rule engine with YAML format',
author = 'Alex Yu',
author_email = 'mltest2000@aliyun.com',
url = 'https://github.com/sevenbigcat/wthen', # use ... | python |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Wed Sep 26 22:03:23 2018
@author: sameermac
"""
#Computing Tanimoto Distance and uniquenesses of 50 molecules from QM9 Database
#from __future__ import print_function
from rdkit import Chem
from rdkit.Chem.Fingerprints import FingerprintMols
from rdkit im... | python |
"""Data preprocessing script for Danish Foundation Models """
from typing import Union
from functools import partial
from datasets.arrow_dataset import Dataset
from transformers import AutoTokenizer, BatchEncoding
from transformers.tokenization_utils_base import PreTrainedTokenizerBase
from transformers.tokenization_u... | python |
import glob
import torch
import tensorflow as tf
from pathlib import Path
from tqdm import tqdm
from itertools import cycle, islice, chain
from einops import rearrange, repeat
import torch.nn.functional as F
class PairTextSpectrogramTFRecords(object):
def __init__(
self,
local_or_gcs_path,
... | python |
# How to work with lists
students = [
"Monika",
"Fritz",
"Luise",
"Andi"
]
print(students)
# Add item to list
students.append("Ronald")
print(students)
# Get the length of the list
print(len(students))
# Get a specific student
print(students[2]) | python |
import numpy as np
from metagraph import translator
from metagraph.plugins import has_grblas, has_scipy
from ..numpy.types import NumpyVector, NumpyNodeMap
from ..python.types import PythonNodeSet
if has_grblas:
import grblas
from .types import (
GrblasEdgeMap,
GrblasEdgeSet,
GrblasGra... | python |
from deeplodocus.utils.version import get_version
name = "deeplodocus"
VERSION = (0, 1, 0, 'alpha', 1)
#__version__ = get_version(VERSION)
__version__ = "0.3.0"
| python |
import time
import logging.config
from scapy.all import get_if_hwaddr, sendp, sniff, UDP, BOOTP, IP, DHCP, Ether
logging.getLogger("scapy.runtime").setLevel(logging.ERROR)
logger = logging.getLogger(name="elchicodepython.honeycheck")
def apply_controls(control_modules, **kwargs):
for control_object in control_... | python |
import re
banner = """ _____ __ __ _____ _____
| __ \\\ \ / / /\ | __ \ | __ \ [Author : Imad Hsissou]
| |__) |\ \_/ / / \ | |__) || |__) | [Author email : imad.hsissou@gmail.com]
| ___/ \ / / /\ \ | _ / | ___/ [https://github.com/imadhsissou]
| | | | / ____ \ | | \ \ | | ... | python |
"""This module tests the parsing logic in card module."""
import unittest
from poker.model import card
class CardTests(unittest.TestCase):
"""Test the card class."""
def test_from_string(self):
"""Test from_string constructs cards correctly."""
test_cases = [
{
... | python |
import IMLearn.learners.regressors.linear_regression
from IMLearn.learners.regressors import PolynomialFitting
from IMLearn.utils import split_train_test
import numpy as np
import pandas as pd
import plotly.express as px
import plotly.io as pio
import matplotlib.pyplot as plt
pio.templates.default = "simple_white"
plt... | python |
"""
batch_size, input_height, input_width, in_channels, out_channels, kernel_height, kernel_width, ClassVector=None, bias=None, dilation=1, stride=1, padding=0
"""
gated_pixelcnn_shape = [
(1, 256, 256, 3, 256, 3, None, None, 1, 1, 0)
] | python |
"""
This program print the matrix in spiral form.
This problem has been solved through recursive way.
Matrix must satisfy below conditions
i) matrix should be only one or two dimensional
ii) number of column of all rows should be equal
"""
def check_matrix(matrix: list[list]) -> bool:
# must... | python |
from datetime import datetime
import os
import random
import sys
import traceback
import types
import gin
import numpy as np
import tensorflow as tf
from stackrl import agents
from stackrl import envs
from stackrl import metrics
from stackrl import nets
@gin.configurable(module='stackrl')
class Training(object):
"... | python |
import os
import re
import nltk
import numpy as np
from sklearn import feature_extraction
from tqdm import tqdm
import codecs
#from embeddings import get_similarity_vector
from sklearn.feature_extraction.text import TfidfVectorizer
from scipy.spatial import distance
_wnl = nltk.WordNetLemmatizer()
import pickle
from ut... | python |
from django import forms
from .models import Artist, Festival
class ArtistAddForm(forms.ModelForm):
class Meta:
model = Artist
fields = ('stage_name',
'first_name',
'description',
'born',
'contry_origin',
'd... | python |
import sqlalchemy as sa
from aiopg.sa import Engine
from sqlalchemy import Table
from app.database.common import resultproxy_to_dict
from app.database.models.category import Category
from app.database.models.entity import Entity
async def get_all_categories(
engine: Engine,
):
table: Table = Category.__... | python |
#!/usr/bin/env python
import numpy as np
import theano
import theano.tensor as T
from scipy.sparse import lil_matrix
from stochastic_bb import svrg_bb, sgd_bb
"""
An example showing how to use svrg_bb and sgd_bb
The problem here is the regularized logistic regression
"""
__license__ = 'MIT'
__author__ = 'Co... | python |
class MinimapCatalog():
single_map = {'Grass': (1, 0),
'House': (2, 0),
'Shop': (3, 0),
'Switch': (4, 0),
'Fort': (5, 0),
'Ruins': (6, 0),
'Forest': (8, 0),
'Thicket': (9, 0),
... | python |
"""
24hourvideo
-----------
A copy of `24 Hour Psycho`_ by Douglas Gordon written in Python.
.. _24 Hour Psycho: https://en.wikipedia.org/wiki/24_Hour_Psycho
"""
from setuptools import setup
import ast
import re
_version_re = re.compile(r'__version__\s+=\s+(.*)')
with open('twentyfourhourvideo/__init__.py', 'r... | python |
from conans.model import Generator
from conans.paths import BUILD_INFO
class DepsCppTXT(object):
def __init__(self, deps_cpp_info):
self.include_paths = "\n".join(p.replace("\\", "/")
for p in deps_cpp_info.include_paths)
self.lib_paths = "\n".join(p.replace(... | python |
from fabric.contrib.files import exists
from fabric.operations import put, get
from fabric.colors import green, red
from fabric.api import env, local, sudo, run, cd, prefix, task, settings
# Server hosts
STAGING_USER = 'ubuntu'
PRODUCTION_USER = 'ubuntu'
STAGING_SERVER = '%s@54.68.3.255' % STAGING_USER
PRODUCTION_SER... | python |
"""
Implements the Temoral Difference Learning algorithm.
This solver contains TD-Lambda methods based on Prof.David Silver Lecture slides.
Note that TD-Lambda can be used as other solver by setting the n-step return and \gamma value accordingly
(c) copyright Kiran Vaddi 02-2020
"""
import numpy as np
import pdb
from ... | python |
"""
This script shows the for code block
"""
NAME = input("Please enter your name: ")
AGE = int(input("How old are you, {0}? ".format(NAME)))
print(AGE)
# if AGE >= 18:
# print("You are old enough to vote")
# print("Please put an X in the box")
# else:
# print("Please come back in {0} years".format(18 - AG... | python |
from django.contrib import admin
from .models import Blog, BlogType
# Register your models here.
class BlogAdmin(admin.ModelAdmin):
list_display = ('title', 'author', 'blog_type', 'created_time')
@admin.register(BlogType)
class BlogTypeAdmin(admin.ModelAdmin):
list_display = ('id', 'type_name')
admin.site.re... | python |
from django.conf.urls import url
from .views import (
CheckoutView,
CheckoutUpdateView,
OrderDeleteView,
CheckoutOrderView,
OrdersView,
AcceptedOrdersView,
RejectedOrdersView,
BuyOrdersView,
BuyThankView,
)
urlpatterns = [
url(r'^order/(?P<id>\d+)/$', CheckoutView.as_view()... | python |
from django import forms
from captcha.fields import CaptchaField
class UserForm(forms.Form):
username = forms.CharField(label="用户",max_length=128,widget=forms.TextInput(attrs={'class':'form-contro','placeholder':'用户'}))
password = forms.CharField(label="密码",max_length=128,widget=forms.PasswordInput(attrs={'cla... | python |
import json
import os
from datetime import datetime
from io import StringIO
from itertools import product
import pytest
from peewee import Model, SqliteDatabase
from orcid_hub import JSONEncoder
from orcid_hub.models import (
Affiliation, AffiliationRecord, AffiliationExternalId, BaseModel, BooleanField, External... | python |
import striga.server.service
import sqlobject
###
class SQLObjectFactory(striga.server.service.ServiceFactory):
def __init__(self, parent, name = 'SQLObjectFactory', startstoppriority = 50):
striga.server.service.ServiceFactory.__init__(self, SQLObjectService, 'SQLObject', 'sqlobject', parent, name, startstopprio... | python |
# Webhooks for external integrations.
from zerver.lib.actions import check_send_stream_message
from zerver.lib.response import json_success
from zerver.decorator import REQ, has_request_variables, api_key_only_webhook_view
from zerver.models import Client, UserProfile
from django.http import HttpRequest, HttpResponse... | python |
from __future__ import division, print_function, absolute_import
import imageio
import numpy as np
from tqdm import tqdm
import warnings
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
from matplotlib.image import imsave
import matplotlib.patheffects as path_effects
from matplotlib.colors impo... | python |
import threading
import time
import pandas as pd
import pandas.testing as tm
class ParallelExperimentBase(object):
@property
def backend(self):
raise NotImplementedError
def test_serial(self, ex):
a = ex.parameter('a')
@ex.result
def id(a):
ex.save_metric(me... | python |
import unittest
from AdvPythonTraining.Eight_Day.P1 import Person as PersonClass
class POneTest(unittest.TestCase):
persone = PersonClass()
user_id = []
user_name =[]
def test_set_name(self):
for i in range(4):
name = 'name' +str(i)
self.user_name.append(name)
... | python |
#!/usr/bin/env python
# Copyright 2008 Rene Rivera
# Distributed under the Boost Software License, Version 1.0.
# (See accompanying file LICENSE_1_0.txt or http://www.boost.org/LICENSE_1_0.txt)
import re
import optparse
import time
import xml.dom.minidom
import xml.dom.pulldom
from xml.sax.saxutils import unescape, e... | python |
# Copyright 2015 Sanghack Lee
#
# 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, sof... | python |
#!/usr/bin/env python
# Copyright (C) 2010
#
# 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 option) any later version.
#
# This program is distri... | python |
#!/usr/bin/env python3
"""
Copyright 2020 The Magma Authors.
This source code is licensed under the BSD-style license found in the
LICENSE file in the root directory of this source tree.
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BAS... | python |
# Generated by Django 2.2.3 on 2019-07-22 11:45
import core.model_fields
import core.validators
from django.db import migrations, models
import django.db.models.deletion
import great_international.panels.great_international
import modelcluster.fields
class Migration(migrations.Migration):
dependencies = [
... | python |
# Generated by Django 3.0.10 on 2020-10-23 10:16
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('project_core', '0142_fix_physicalperson_plural'),
('reporting', '0003_funding_instrument_description'),
]
... | python |
import os
import numpy as np
from utils import map_to_full
class VideoSaver:
def __init__(self, savedir):
try:
os.makedirs(savedir)
except:
pass
self.savedir = savedir
self.id = 0
def save_mp4_from_vid_and_audio(self,
... | python |
# -*- coding: utf-8 -*-
from multiprocessing import Pool
import os
import time
start = time.time()
def f(x):
time.sleep(1)
value = x * x
print('{}s passed...\t{}\t(pid:{})'.format(int(time.time() - start), value, os.getpid()))
return value
timeout = time.time() + 10 # sec
while True:
with Pool(pr... | python |
from turtle import *
import random
import threading
from tkinter import *
# generate random seed
num = random.randint(1897348294, 18495729473285739)
print("\n\nUsing Seed: " + str(num))
# set the seed for all randomization
random.seed(num)
# save the current seed to a text file
with open('current_seed.txt', 'w') as f:... | python |
"""Tests for the models in the ``core`` app of the Marsha project."""
from django.db import transaction
from django.db.utils import IntegrityError
from django.test import TestCase
from safedelete.models import SOFT_DELETE_CASCADE
from ..factories import VideoFactory
class VideoModelsTestCase(TestCase):
"""Test ... | python |
__copyright__ = 'Copyright(c) Gordon Elliott 2017'
"""
"""
from datetime import datetime
from decimal import Decimal
from itertools import product
from a_tuin.metadata.field_group import (
TupleFieldGroup,
ListFieldGroup,
DictFieldGroup,
ObjectFieldGroup,
)
from a_tuin.metadata.field import (
St... | python |
# -*- coding: utf-8 -*-
try: # pragma: no cover
from Cryptodome.Cipher import AES
from Cryptodome import Random
except ImportError: # pragma: no cover
try:
from Crypto.Cipher import AES
from Crypto import Random
except ImportError:
raise ImportError("Missing dependency: pyCrypt... | python |
def count_safe(input, part = 1):
previous_row = list(input)
safe_count = previous_row.count(".")
rows = 400000 if part == 2 else 40
for i in range(1, rows):
current_row = []
for j in range(len(input)):
l = previous_row[j - 1] if j > 0 else "."
c = previous_row[j... | python |
import logging
logger = logging.getLogger(__name__)
import struct
from Crypto.Random import get_random_bytes
from Crypto.Hash import HMAC
from Crypto.Cipher import AES
from jose.exceptions import AuthenticationError
from jose.utils import pad_pkcs7, unpad_pkcs7, sha
def _jwe_hash_str(ciphertext, iv, adata=b''):
... | python |
import os
BASE_DIR = os.getcwd()
TARGET_DIR = os.path.join(BASE_DIR, "target")
| python |
idadetotal = 0
idademedia = 0
contadormulher = 0
homemvelho = 0
lista = []
nomevelho = ''
for p in range(1, 5):
print('=-'*20, f'{p}ª PESSOA', '=-'*20)
nome = str(input('Nome: '))
idade = int(input('Idade: '))
sexo = str(input('M/F: '))
idadetotal += idade
idademedia = idadetotal/4
if sexo i... | python |
import matplotlib.pyplot as plt
import numpy as np
np.random.seed(0)
data = np.random.randn(10_000)
#plt.hist(data, bins=30, alpha=.5, histtype="stepfilled", color="steelblue")
#plt.show()
counts, bin_edges = np.histogram(data, bins=5)
print(counts)
print(bin_edges)
x1 = np.random.normal(0, 0.8, 1000)
x2 = np.random... | python |
from django.core import mail
from django.core.mail import send_mail
from django.conf import settings
from django.template.loader import render_to_string
from django.utils.html import strip_tags
def send_email_order(sale, sender, receiver):
# body = f"Gunakan nomer {sale.sale_number} untuk mengecek pesanan kamu di... | python |
import numpy as np
import numpy.testing as npt
import py.test
from hypothesis import assume
from hypothesis import given
import arlunio.testing as T
from arlunio.math import X
from arlunio.math import Y
@given(width=T.dimension, height=T.dimension)
def test_X_matches_dimension(width, height):
"""Ensure that the ... | python |
from boa3.builtin import public
@public
def Main(value: int) -> int:
a = 0
condition = a < value
while condition:
a = a + 2
condition = a < value * 2
return a
| python |
from random import randint
numeros = (randint(0, 100),
randint(0, 100),
randint(0, 100),
randint(0, 100),
randint(0, 100))
print(sorted(numeros))
print(f'O maior valor sorteado foi {max(numeros)}')
print(f'O menor valor sorteado foi {min(numeros)}')
| python |
from src2docx import *
import tkinter.filedialog
import tkinter.messagebox
import tkinter.ttk
class MainForm(tkinter.Tk):
def __init__(self):
super().__init__()
self.title("src2docx")
self.geometry("220x180")
self.resizable(0, 0)
self.directoryLabel = tkinter.tt... | python |
#!/usr/bin/env python
""" encoding.py
encoding.py (c) 2016 by Paul A. Lambert
licensed under a
Creative Commons Attribution 4.0 International License.
"""
if __name__ == '__main__' and __package__ is None:
from os import sys, path
p = path.abspath(__file__) # ./cryptopy/persona/test/test_cip... | python |
"""
Copyright 2022 Objectiv B.V.
"""
import bach
import pandas as pd
import pytest
from modelhub.stack.util import get_supported_dtypes_per_objectiv_column, check_objectiv_dataframe
from tests_modelhub.data_and_utils.utils import create_engine_from_db_params
def test_get_supported_types_per_objectiv_column() -> None... | python |
import csv
import cv2
import numpy as np
from matplotlib import pyplot as plt
lines=[]
with open("./data/driving_log.csv") as csvfile:
reader=csv.reader(csvfile)
for line in reader:
lines.append(line)
images=[]
measurements=[]
for line in lines:
source_path=line[0]
filename=source_path.split('... | python |
#!/bin/python3
# Complete the 'plusMinus' function below.
#
# The function accepts INTEGER_ARRAY arr as parameter.
def plusMinus(arr):
n = len(arr)
neg, zero, pos = 0, 0, 0
for num in arr:
if num < 0:
neg += 1
elif num == 0:
zero += 1
else:
... | python |
#!/usr/bin/python3
import datetime
window = 15
sourcefile = '/home/lunpin/anom/unsw_nb15/csv/NUSW-NB15_GT.csv'
for count, line in enumerate (open (sourcefile, 'rt')):
if count == 0: continue
try:
ts = int (line [: line.find (',')])
dt = datetime.datetime.fromtimestamp (ts)
addon = '/'.... | python |
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def plusOne(self, head):
"""
:type head: ListNode
:rtype: ListNode
"""
non_nine, cur = None, head
while cur:
... | python |
from django.http import HttpResponse, HttpResponseRedirect, HttpRequest
from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger
from django.shortcuts import render, get_object_or_404
from django.core.urlresolvers import reverse
from django.views import generic
from django.contrib.auth import authentica... | python |
from mitmproxy.test import tutils
from mitmproxy import tcp
from mitmproxy import controller
from mitmproxy import http
from mitmproxy import connections
from mitmproxy import flow
def ttcpflow(client_conn=True, server_conn=True, messages=True, err=None):
if client_conn is True:
client_conn = tclient_conn... | python |
from .imports import *
from .utils.core import *
from .utils.extras import *
def optimizer_params(params, lr, wd):
return {'params': chain_params(params),
'lr': lr,
'wd': wd}
class LayerOptimizer(object):
def __init__(self, optimizer, layer_groups, lrs, wds=None):
if not isins... | python |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
__version__ 1.0.0
"""
#import operator
import random
#import matplotlib.pyplot
import time
def distance_between(a, b):
""" A function to calculate the distance between agent a and agent b.
Args:
a: A list of two coordinates for orthoganol axes.
... | python |
import requests
import requests_cache
import os
import argparse
import json
requests_cache.install_cache("route_cache")
def main():
parser = argparse.ArgumentParser()
parser.add_argument("trip_file",
help="Path to a file containing lines with six comma-separated values: src_id, src_lat, src_lng, ... | python |
from __future__ import print_function, division, absolute_import
import logging
from ..utils import infer_storage_options
from s3fs import S3FileSystem
from . import core
logger = logging.getLogger(__name__)
class DaskS3FileSystem(S3FileSystem, core.FileSystem):
sep = '/'
def __init__(self, key=None, us... | python |
import numpy as np
def neuron_sparse_ratio(x):
return np.sum(x == 0.0) / float(np.prod(x.shape))
def feature_sparse_ratio(x):
assert np.ndim(x) == 2
return np.sum(np.linalg.norm(x, ord=2, axis=1) == 0.0) / float(x.shape[0])
def deepint_stat(estimator):
# Init
stat = {}
embedding_stat = {}
... | python |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
r"""Provide the Cartesian acceleration task.
The Cartesian acceleration task tries to impose a desired pose, velocity and acceleration profiles for a distal
link with respect to a base link, or world frame.
Before presenting the optimization problem, here is a small remin... | python |
from arabic import toArabic as a
from os.path import abspath, dirname
from datetime import date
dirpath = dirname(abspath(__file__))
days_of_the_week_verbose = ["Sunday","Monday","Tuesday","Wednesday","Wenesday","Wendsday","Thursday","Friday","Saturday"]
days_of_the_week_abbreviated = ["Mon","Tue","Wed","Thu","Fri",... | python |
# Generated by the protocol buffer compiler. DO NOT EDIT!
# source: POGOProtos/Networking/Responses/CollectDailyBonusResponse.proto
import sys
_b=sys.version_info[0]<3 and (lambda x:x) or (lambda x:x.encode('latin1'))
from google.protobuf import descriptor as _descriptor
from google.protobuf import message as _... | python |
# Day 3 puzzle: https://adventofcode.com/2020/day/3
# In broad terms, count the passwords validated by the policy in place when created.
from functools import reduce
from puzzles import Puzzle
from supporting import trimmed
class ZeroThree(Puzzle):
TREE = '#'
def __init__(self):
Puzzle.__init__(self, "03... | python |
from django import template
from ssdfrontend.models import Target
from ssdfrontend.models import User
from utils.configreader import ConfigReader
from django.db.models import Sum
register = template.Library()
@register.simple_tag
def get_usedquota(theuser):
try:
user = User.objects.get(username=theuser)
... | python |
from minio import Minio
import requests
import io
from minio.error import S3Error
import youran
class Min:
def __init__(self):
self.minioClient = Minio(f'{youran.MINIOIP}:{youran.MINIOPort}',
access_key='minioadmin',
secret_key='minioadmin',
... | python |
"""This module handles the weight factors and scaling.
An adaptive restraints weight factor calculator is implemented, whereby the
weight factor is doubled if a sufficiently large bond-RMSD is observed.
Conversely, if a sufficiently small bond-RMSD is observed, then the weight
factor is halved.
"""
from __f... | python |
"""
Automatically generate a fairness report for a dataset.
"""
import logging
from itertools import combinations
from typing import Any, List, Mapping, Optional, Sequence, Tuple, Union
import pandas as pd
from . import utils
from .metrics.statistics import sensitive_group_analysis
from .metrics.unified ... | python |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from . import constants
from .utils.strings import version_tuple_to_str
__title__ = 'ocwb'
__description__ = 'A Python wrapper around OpenCWB web APIs'
__url__ = 'https://github.com/tsunglung/OpenCWB'
__version__ = version_tuple_to_str(constants.OCWB_VERSION)
__author__ =... | python |
import json
from urllib3_mock import Responses
from delairstack.core.resources.resource import Resource
from .resource_test_base import ResourcesTestBase
responses = Responses('requests.packages.urllib3')
class TestFlights(ResourcesTestBase):
@staticmethod
def __create_post_response():
return json... | python |
class Solution:
def rebot(self, nums, c, index):
if c == 0:
return True
if index == len(nums) - 1:
return nums[index] == c
res = self.rebot(nums, c, index+1)
if c >= nums[index]:
res = res or self.rebot(nums, c-nums[index], index+1)
re... | python |
import socket
import constants
import subprocess
import uuid
from getmac import get_mac_address
try :
import requests
except ModuleNotFoundError :
import pip
pip.main(['install','requests'])
import requests
def gma() :
mac1=get_mac_address()
mac2=':'.join(['{:02x}'.format((uuid.getnode() >> el... | python |
# Copyright (C) 2016-2018 Virgil Security Inc.
#
# Lead Maintainer: Virgil Security Inc. <support@virgilsecurity.com>
#
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met:
#
# (1) Redistribution... | python |
from django.conf.urls import url
from django.contrib.auth.views import login
from . import views
urlpatterns = [
url(r'^login/$', login, {'template_name': 'login.html'}, name='login'),
url(r'^logout/$', views.logout_view, name='logout'),
url(r'^register/$', views.register, name='register'),
url(r'^pro... | python |
import gpxpy
import gpxpy.gpx
import pandas as pd
import geopandas as gpd
from shapely.geometry import LineString
tabular = pd.read_csv(r'C:\garrett_workspace\tableau\strava_dashboard\activities.csv')
geo_dataframe = gpd.GeoDataFrame(tabular)
geo_dataframe['geometry'] = None
for index in range(len(geo_dataframe)):... | python |
import pyodbc
import operator
import getConnection as gc
def datasetsToColumns(datasets, cnxn):
cursor = cnxn.cursor()
columns_dict = dict()
for dataset in datasets:
cursor.execute("SELECT c.* from datasets d INNER JOIN columns_datasets cd on cd.id_2=d.id INNER JOIN columns c on cd.id_1=c.id WHERE d.id=?",datas... | python |
from django.shortcuts import render, redirect
from firstapp.models import Ariticle, Comment
from firstapp.form import CommentForm
def index(request):
queryset = request.GET.get('tag')
if queryset:
ariticle_list = Ariticle.objects.filter(tag=queryset)
else:
ariticle_list = Ariticle.objects.... | python |
# Generated by the protocol buffer compiler. DO NOT EDIT!
# source: finocial.proto
import sys
_b=sys.version_info[0]<3 and (lambda x:x) or (lambda x:x.encode('latin1'))
from google.protobuf import descriptor as _descriptor
from google.protobuf import message as _message
from google.protobuf import reflection as _refl... | python |
from flask import Blueprint
from flask_restful import Resource, Api
from flask_jwt import JWT, jwt_required
from datetime import datetime
from json import dumps
from users_rest_api import app, db
from users_rest_api.secure_check import authenticate, identity
from users_rest_api.model import User
users_api = Blueprint... | python |
from sqlobject import *
from sqlobject.tests.dbtest import *
from sqlobject.views import *
class PhoneNumber(SQLObject):
number = StringCol()
calls = SQLMultipleJoin('PhoneCall')
incoming = SQLMultipleJoin('PhoneCall', joinColumn='toID')
class PhoneCall(SQLObject):
phoneNumber = ForeignKey('PhoneNumbe... | python |
'''
Module providing `WeaveCodeObject`.
'''
from __future__ import absolute_import
import os
import sys
import numpy
from brian2.codegen.codeobject import check_compiler_kwds
from functools import reduce
try:
from scipy import weave
from scipy.weave.c_spec import num_to_c_types
from scipy.weave.inline_too... | python |
from unittest import TestCase
from glimslib import fenics_local as fenics
from glimslib.simulation_helpers.helper_classes import FunctionSpace, TimeSeriesData
class TestTimeSeriesData(TestCase):
def setUp(self):
# Domain
nx = ny = nz = 10
mesh = fenics.RectangleMesh(fenics.Point(-2, -2),... | python |
import os
from argparse import ArgumentParser
import random
def read_ner(path):
data = [[]]
with open(path, encoding='ISO-8859-1') as f:
for line in f:
line = line.strip()
# New sentence
if len(line) == 0:
if len(data[-1]) > 0:
d... | python |
'''
This file is part of Camarillo.
Copyright (C) 2008 Frederic-Gerald Morcos <fred.morcos@gmail.com>
Camarillo 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 yo... | python |
import itertools
def part1(data):
data = sorted([int(x.strip()) for x in data if x])
pairs = itertools.combinations(data, 2)
for (a, b) in pairs:
if a + b == 2020:
return a * b
def part2(data):
data = sorted([int(x.strip()) for x in data if x])
pairs = itertools.combinations... | python |
from elasticsearch import Elasticsearch
import hashlib
es = Elasticsearch(hosts=[{'host': "127.0.0.1", 'port': 9200}])
res = es.search(index="ssh", body={
"aggs": {
"scripts": {
"terms": {
"field": "originalRequestString",
"size": 10000011
}
}
}
})
count = 0... | python |
"""
Machine shop example
Covers:
- Interrupts
- Resources: PreemptiveResource
Scenario:
A workshop has *n* identical machines. A stream of jobs (enough to
keep the machines busy) arrives. Each machine breaks down
periodically. Repairs are carried out by one repairman. The repairman
has other, less important ... | python |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
('products', '0005_auto_20160119_1341'),
]
operations = [
migrations.RemoveField(
model_name='answer',
... | python |
mandatory = \
{
'article' : ['ENTRYTYPE', 'ID', 'author', 'title', 'journal', 'year', 'volume'],
'book' : ['ENTRYTYPE', 'ID', 'title', 'publisher', 'year'],
'booklet' : ['ENTRYTYPE', 'ID', 'title', 'year'],
'conference' : ['ENTRYTYPE', 'ID', 'author', 'title', 'booktitle', 'publisher', 'year'],
'inbook' : ['... | python |
# 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
# distributed under t... | python |
"""
set of functions for feature extraction
"""
# imports
import numpy as np
import cv2
from skimage.feature import hog
def get_hog_features(img, orient=9, pix_per_cell=8, cell_per_block=2,
vis=False, feature_vec=True):
"""
function to return HOG features
Args:
... | python |
import numpy as np
import sys
from schools3.config import base_config
config = base_config.Config()
config.categorical_columns = [
'sixth_read_pl',
'sixth_math_pl',
'sixth_write_pl',
'sixth_ctz_pl',
'sixth_science_pl',
'seventh_read_pl',
'seventh_math_pl',
'seventh_write_pl',
'eigh... | python |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.