text stringlengths 3.07k 12.6k |
|---|
# 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 copy import deepcopy
class HwDecription:
def __init__(self, param_table, arch, backend):
self.vec_unit_length = param_table['vec_unit_length']
self.max_local_mem_size_per_block = param_table['max_local_mem_size_per_block']
self.max_num_threads = param_table['max_num_threads']
self.max_reg_per_b... |
# coding=utf-8
#
# This file is part of Hypothesis (https://github.com/DRMacIver/hypothesis)
#
# Most of this work is copyright (C) 2013-2015 <NAME>
# (<EMAIL>), but it contains contributions by others. See
# https://github.com/DRMacIver/hypothesis/blob/master/CONTRIBUTING.rst for a
# full list of people who may hold c... |
import torch
import cv2
import time
import argparse
import posenet
import requests
import datetime as dt
import mysql.connector as msql
mydb = msql.connect(host="192.168.12.3", user="netuser", passwd='<PASSWORD>', database='proctoring')
mycursor = mydb.cursor()
parser = argparse.ArgumentParser()
parser.add_argumen... |
from flask import Flask, request, render_template
from flask_socketio import SocketIO, emit
import os
from game import Game, GameState
from log import Log
app = Flask(__name__)
socketio = SocketIO(app)
game = Game()
#
# Messages sent from server to client
#
# Change the users' screen
def change_game_state(game_stat... |
# INTEL CONFIDENTIAL
#
# Copyright (C) 2021 Intel Corporation
#
# This software and the related documents are Intel copyrighted materials, and
# your use of them is governed by the express license under which they were provided to
# you ("License"). Unless the License provides otherwise, you may not use, modify, copy,
... |
from flloat.base.symbols import Symbols
from flloat.base.parsing import Lexer, Parser
from flloat.ldlf import LDLfLogicalTrue, LDLfLogicalFalse, LDLfNot, LDLfOr, LDLfEquivalence, LDLfImplies, \
LDLfAnd, LDLfDiamond, LDLfBox, RegExpTest, RegExpStar, RegExpUnion, RegExpSequence, RegExpPropositional, LDLfEnd, \
L... |
from django.db import models
from django.contrib.auth.models import User
from django.core.urlresolvers import reverse
from django.db.models.signals import post_save, post_delete
ALLOW_ALL, REQUIRE_LOGIN, DISALLOW_ALL = range(3)
SUBSITE_POST_STATUS = (
(ALLOW_ALL, 'Allow All Posts'),
(REQUIRE_LOGIN, 'Require Lo... |
from csv import reader
from munkres import Munkres, print_matrix
import argparse
# Cost pertaining to assignments can be modified in the dictionary below.
COSTS = {
'Preferred': 1,
'Available but not preferred': 5,
'Conflict': 100
}
# The TAs below will each be assigned 2 slots/labs.
TAs_WITH_TWO_LABS = (... |
### IMPORTS ###
from __future__ import annotations
import tkstrap.__imports__ as _
### IMPORTS ###
### DOCUMENTATION ###
"""
"""
### DOCUMENTATION ###
### ARBITRARY CONSTANTS ###
StandardTkOpts = dict
Sta... |
import os
import re
import string
import numpy as np
from ml.clean_tables import tag_actions
from utils.environ import cleaned_tags_dir, generated_data_dir
from utils.file import remove_files, get_json_from_file, \
write_json_to_file
tokenize_attr_names = ['rowspan', 'colspan', 'style', 'align', 'width']
tokenize_... |
from flask import jsonify, request
from flask_restx import Resource, reqparse, fields, marshal_with
import requests
import redis
import os
import logging
import time
import datetime
import json
from app import api, db
from models import User
logger = logging.getLogger(__name__)
logger.setLevel(logging.INFO)
user_fi... |
import numpy as np
import pytest
import xarray as xr
import cf_xarray as cfxr
from . import requires_shapely
@pytest.fixture
def geometry_ds():
from shapely.geometry import MultiPoint, Point
# empty/fill workaround to avoid numpy deprecation(warning) due to the array interface of shapely geometries.
ge... |
"""
Copyright 2020 The OneFlow 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 required by applicable law or agr... |
"""Predict lexical norms, either to evaluate word vectors, or to get norms for unnormed words."""
import numpy as np
import pandas as pd
import sklearn.linear_model
import sklearn.model_selection
import sklearn.preprocessing
import sklearn.utils
import argparse
import os
from .vecs import Vectors
from .utensils import ... |
"""
Find dives
"""
import numpy as np
import pandas as pd
import scipy as sp
import plotly.graph_objects as go
import plotly.express as px
from plotly.subplots import make_subplots
def plotDives(calc_file_path, new_file_path, is_export, min_length = 60, required_depth = None, max_depth = None, interest_variables = []... |
from .utilities import unpackTimecode, findEvenSplit, getDuration, containsAny
class LyricLine:
"""An object that holds a lyric line and it's time"""
def __init__(self, timecode, text=""):
self.hours = 0
self.minutes, self.seconds, self.milliseconds = unpackTimecode(timecode)
self.time... |
#!/usr/bin/env python
# Copyright 2017 gRPC authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law o... |
#!/usr/bin/env python3
from base64 import b64decode, b64encode
from github3 import gists, login, GitHub
from random import randint
from datetime import datetime
class BootStrapper:
def __init__(self) -> None:
self.stage_1 = '''
import json
def run(**args):
print('[$] Enter stage 1')
basic_config... |
# Copyright 2016 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
import argparse
import plistlib
import os
import re
import subprocess
import sys
import tempfile
import shlex
# Xcode substitutes variables like ${PRODUCT_... |
from __future__ import print_function
import array
import string
import operator
# Natural Language Processing Libraries
import nltk
from nltk.tokenize import sent_tokenize, word_tokenize
from nltk.corpus import stopwords
from flask import Flask, render_template, request, jsonify, abort
from flask_cors import CORS
imp... |
#!/usr/bin/env python
# Copyright (c) Meta Platforms, Inc. and affiliates.
# All rights reserved.
#
# This source code is licensed under the BSD-style license found in the
# LICENSE file in the root directory of this source tree.
import distutils.command.clean
import os
import shutil
import subprocess
import sys
from... |
"""
This module provides functions that are used to generate
simple dynamical systems
You can simulate your own systems here!
created: 11/07/18 <NAME> (<EMAIL>)
modified: 11/13/18 <NAME> (<EMAIL>)
12/11/18 <NAME> (<EMAIL>)
"""
import numpy as np
import scipy as sp
from scipy ... |
# Copyright (c) 2016 Cisco Systems 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 re... |
"""
Base Column Genaration Classifier. One needs to extend this for implementing
column generation based classifiers.
"""
from sklearn.base import BaseEstimator, ClassifierMixin
from sklearn.utils.validation import check_X_y
from sklearn.utils.multiclass import unique_labels
from sklearn.preprocessing import LabelEnco... |
from overrides import overrides
from collections import Counter
from allennlp.training.metrics.metric import Metric
from dygie.training.f1 import compute_f1
def _invert_arguments(arguments, triggers):
"""
For scoring the argument, we don't need the trigger spans to match exactly. We just need the
trigge... |
# Copyright (c) 2019 <NAME>
# 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, copy, modify, merge, publish, distribute, s... |
# 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 the... |
# -*- coding: utf-8 -*-
"""
Created on Mon Feb 18 11:39:15 2019
@author: cooneyg
"""
import pandas as pd
from electricitylci.globals import (
data_dir,
output_dir)
from electricitylci.eia923_generation import eia923_download_extract
import electricitylci.PhysicalQuantities as pq
strings = [' air','unspecifi... |
import math
from hippy.builtin import wrap
from hippy.builtin import StringArg
from hippy.builtin import BoolArg
from hippy.builtin import LongArg
from hippy.builtin import Optional
from rpython.rlib import rsocket
def checkdnsrr():
"""Check DNS records corresponding to a given
Internet host name or IP addres... |
"""
Created on Thu Mar 18 19:06:46 2021
@author: Eliott
The solve function implements the variable speed (as a function of x)
with a[i-1] in 1D.
Tests and plots in the same file, for u0 = fwall.
"""
import numpy as np
import scipy.io as sio
import random
import tqdm
import matplotlib.pyplot as plt
#%% Useful funct... |
import requests
import bs4
import re
import parlament_vote
import shutil
DAY_URL = 'https://www.parlament.hu/web/guest/videoarchivum?p_p_id=hu_parlament_cms_pair_portlet_PairProxy_INSTANCE_9xd2Wc9jP4z8&p_p_lifecycle=1&p_p_state=normal&p_p_mode=view&p_auth=qJ6t6jPq&_hu_parlament_cms_pair_portlet_PairProxy_INSTANCE_9xd2... |
import os
import warnings
import subprocess
import torch
import numpy as np
import zipfile
from collections import defaultdict
from typing import Any, Tuple, Optional
from tqdm import tqdm
import soundfile as sf
import torchaudio
torchaudio.set_audio_backend("soundfile")
from torch import Tensor, FloatTensor, IntTens... |
# -*- coding: utf-8 -*-
###
# (C) Copyright [2020] Hewlett Packard Enterprise Development LP
#
# 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
#... |
import os
import json
from enum import Enum
from typing import Any, Dict, Callable, Union
from types import ModuleType
import yaml
import jinja2
import requests
import importlib
from importlib.machinery import SourceFileLoader
from pathlib import Path
from pkg_resources import resource_string
from pydantic import BaseM... |
import asyncio
import logging
import os
from decouple import config
from app.constants import API_VERSION
from app.models.system import (
APIPlatform,
ConnectionInfo,
HealthMessage,
HealthMessagePriority,
HealthState,
SystemInfo,
)
from app.repositories.lightning import get_ln_info
from app.ut... |
from abc import ABCMeta, abstractmethod
class Light(object):
def __init__(self, room=''):
self.room = room
def on(self):
print('{} light is on.'.format(self.room))
def off(self):
print('{} light is off.'.format(self.room))
class GarageDoor(object):
def __init__(self, room... |
# This file is part of Indico.
# Copyright (C) 2002 - 2019 CERN
#
# Indico is free software; you can redistribute it and/or
# modify it under the terms of the MIT License; see the
# LICENSE file for more details.
from __future__ import unicode_literals
from wtforms.fields import BooleanField, SelectField, TextAreaFie... |
"""Memoization decorator that caches a function's return value.
Subsequent calls of the same function with the same arguments will retrieve the
cached value, instead of re-evaluating. Adapted from the Python implementation
of ``lru_cache`` in Python 3.4.
"""
from functools import wraps, partial, _make_key
from collec... |
# -*- coding: utf-8 -*-
# Copyright 2015 Cyan, Inc.
# Copyright 2016, 2017, 2018, 2019 Ciena 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... |
import sys
import re
import copy
from collections import deque
sentence_id,line_number=0,0
not_parasble_sentences_ki,not_parasble_sentences,stack,dependencies,tags,line_state,buffer=[],[],[],[],[],[],[]
def check_orignal_dependencies():
buffer_top = buffer[len(buffer) - 1]
f=1
stack_top = stack[len(stack) - 1]
... |
"""Tests RunMany errors triggered by the print_err function."""
import io
import pathlib
from typing import Dict, Any, Union
from contextlib import redirect_stderr, redirect_stdout
from runmany import runmany
from runmany.util import PathLike, JsonLike
def stderr_of_run(manyfile: Union[PathLike, str], settings: Json... |
''' Estes exercícios fazem parte do curso de Introdução a Algoritmos, ministrado pelo prof. <NAME> e podem ser encontrados no site https://www.cursoemvideo.com/wp-content/uploads/2019/08/exercicios-algoritmos.pdf
31) [DESAFIO] Crie um jogo de JoKenPo (Pedra-Papel-Tesoura) '''
# Testando se o usuário digitou o nú... |
"""Vend.py."""
# -*- coding: utf-8 -*-
# @Author: AnthonyKenny98
# @Date: 2019-11-10 14:09:50
# @Last Modified by: AnthonyKenny98
# @Last Modified time: 2020-01-25 18:19:07
from os import path
import requests
import json
import time
from datetime import datetime
REDIRECT_URI = 'http://127.0.0.1:5000/token'
VEND_C... |
# Copyright (c) 2021 - present / Neuralmagic, 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 b... |
"""
To standardize the tokens based on google n-gram frequencies.
The case study is to segment words that are glued together.
The basic idea can be explained with an example.
Suppose there is a token "senatoradmits", we want to segment it as "senator" and "admits" if
`count("senator") + count("admits") > count ("s... |
import torch
import os
import numpy as np
import MinkowskiEngine as ME
import datetime
import time
import pickle
def save_obj(file_path,obj):
with open(file_path, 'wb') as f:
pickle.dump(obj, f, pickle.HIGHEST_PROTOCOL)
def compute_Acc(IoU,result_dict):
pred_conf=result_dict["pred_conf"].squeeze(1)
... |
from __future__ import absolute_import
from ocrd_cis import get_ocrd_tool
import re
import sys
import os.path
import json
import subprocess
from ocrd_utils import (
getLogger, concat_padded, points_from_x0y0x1y1,
MIMETYPE_PAGE
)
from ocrd_modelfactory import page_from_file
from ocrd_models.ocrd_page import ... |
# 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... |
import cv2
import numpy as np
def find_features(n_imgs, imgset):
"""
Reads in n_imgs images from a directory and returns lists of keypoints and
descriptors each of dimensions (n_imgs x n_kpts).
:param n_imgs: Number of images to read in and process.
:param imgset: String. Name of image set to read... |
#!/usr/bin/env python3
# Start 8:00, snowblowed until 9ish
# Part1: 9:27
# Part2: 10:45, wasted about an hour figuring out that I was rendering all pixels as white regardless of value
move_dict = { 'u': (0, 1),
'd': (0, -1),
'l': (-1, 0),
'r': (1, 0)
}
next_... |
"""
Copyright 2021 Nirlep_5252_
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
d... |
import json
import math
def compute_cos_angle(point1,point2,point3):
point1 = point1[0:2]
point2 = point2[0:2]
point3 = point3[0:2]
vector21 = [point1[0] - point2[0], point1[1] - point2[1]]
vector23 = [point3[0] - point2[0], point3[1] - point2[1]]
#print('Math: ', vector21[0] ** 2 + vector21[1... |
# BSD 3-Clause License.
#
# Copyright (c) 2019-2022 <NAME>. 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. Redistributions of source code must retain the above copyright notice, this li... |
from pyspark.sql import SparkSession
from pyspark.sql.types import *
from pyspark.ml.feature import PCA
from pyspark.ml.clustering import KMeans
from pyspark.ml.linalg import Vectors
from pyspark.ml.feature import VectorAssembler
from pyspark.sql.functions import monotonically_increasing_id
from pyspark.sql import Row
... |
# sktensor.tucker - Algorithms to compute Tucker decompositions
# Copyright (C) 2013 <NAME> <<EMAIL>>
#
# 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 ... |
import random
import re
from jtr.jack.data_structures import QASetting
from jtr.preprocess.map import deep_map
__pattern = re.compile('\w+|[^\w\s]')
def tokenize(text):
return __pattern.findall(text)
def token_to_char_offsets(text, tokenized_text):
offsets = []
offset = 0
for t in tokenized_text:
... |
import sys
from operator import itemgetter
from keyword import iskeyword
def _tuplegetter(index, doc):
return property(itemgetter(index), doc=doc)
# From: https://github.com/python/cpython/blob/master/Lib/collections/__init__.py
def future_namedtuple(typename, field_names, *, rename=False, defaults=None, module... |
import random
import json
from projectfiles.util import spark_weights
from learning.model import *
from projectfiles.game_history_generator import *
import numpy as np
import pickle
class QLearningAlgorithm:
def __init__(self, mdp, eta, explore_prob, function_approximator):
self.mdp = mdp
self.eta = eta
self... |
"""``pytest`` command-line options and fixtures."""
import os
import string
import pytest
DEFAULT_GLOTTOLOG_TAG = 'v4.4'
RUN_WRITES = '--run-writes'
SKIP_SLOW = '--skip-slow'
SKIP_PANDAS = '--skip-pandas'
SKIP_SQLPARSE = '--skip-sqlparse'
GLOTTOLOG_TAG = '--glottolog-tag'
EXCLUDE_RAW = '--exclude-raw'
def py... |
"""
Manages the list of addresses for the wallet, including labels and derivation paths
"""
import os
from .persistence import write_csv, read_csv
import logging
logger = logging.getLogger(__name__)
def to_bool(v):
if isinstance(v, bool):
return v
if isinstance(v, int):
return bool(v)
ret... |
from scipy.spatial import Delaunay
import prody as pr
import numpy as np
from .pointTriangleDistance import pointTriangleDistance as distance
from numba import jit
import copy
@jit("f8(f8[:],f8[:],f8[:],f8[:])", nopython=True, cache=True)
def vol(a, b, c, d):
M = np.zeros((3, 3))
M[0, :] = np.subtract(a, d)
... |
import os
import random
import sys
import time
_version = sys.version_info
if _version < (3, 7):
time.time_ns = lambda: int(time.time * 1e6)
class BuildException(Exception):
pass
# build functions
def build_lib(base_dir, to, filetype, file_filter, entry_sep, quiet):
"""
Generates a library file
... |
import requests
import datetime
import json
from dateutil.parser import parse
from bs4 import BeautifulSoup
HUB_LINK = "http://www.planecrashinfo.com/database.htm"
all_data_raw = []
"""Data Format:
{
"date": datetime.date,
"time": datetime.time,
"location": (locationRaw:str, locationSpecific:... |
from datetime import datetime
from discord import Embed
from discord.ext import commands
from sqlalchemy import *
from sqlalchemy.orm import Session
from Helix.utils.config import Config, ConfigDefaults
from Helix.utils.db_tools import BlackList, Users, Bots
class Mod(commands.Cog):
"""
This module handles ... |
import numpy as np
import sys
import matplotlib.pyplot as plt
from torch.utils.tensorboard import SummaryWriter
from .quadcopter_env import QuadcopterEnv, G, M, K, omega_0, control_feedback
from time import time
from .utils import NormalizedEnv, OUNoise
from .ddpg import DDPGagent
from time import time
from numpy.lina... |
import ability
import dice
import spell
import skill
from elements import Elements
# DISPLAY #
def red(txt):
return '```diff\n- {}```'.format(txt)
def yellow(txt):
return '```fix\n{}```'.format(txt)
def green(txt):
return '```diff\n+ {}```'.format(txt)
def blue(txt):
return '```ini\n[{}]```'.f... |
# Copyright 2018 Google 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/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, ... |
from nose.tools import assert_true, assert_raises, assert_false
from networkx import is_connected, neighbors
from networkx.generators.internet_as_graphs import random_internet_as_graph
def almost_equal(x, y, eps=0.5):
if abs(x - y) < eps:
return True
return False
class TestInternetASTopology():
... |
"""
Get AWS spot price information
"""
import datetime
import time
import boto3
import pandas as pd
from decisionengine.framework.modules import Transform
# default values
REGION = "us-west-2"
INSTANCE_TYPES = ["m3.2xlarge", "c3.2xlarge"]
HISTORY_OBSERVATION_TIME = 3600 # observe spot price for the last hour
# HIS... |
# Code for "TSM: Temporal Shift Module for Efficient Video Understanding"
# arXiv:1811.08383
# <NAME>*, <NAME>, <NAME>
# {jilin, <EMAIL>, <EMAIL>
#
# 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 ... |
from pathlib import Path
import aiofiles
import asyncio
from inflection import underscore
import aiodocker
import os
import re
from prodict import Prodict
import ujson
import subprocess
from pprint import pprint
from .. import logger
"""
links:
http://aiodocker.readthedocs.io/en/latest/
https://docs.docker.com/engine... |
import numpy as np
from ptsnet.epanet.util import EN
from ptsnet.simulation.constants import TOL
class ModelError(Exception):
pass
def check_compatibility(wn, ss):
min_degree = min(wn.get_graph().degree)
if min_degree[1] == 0:
raise ModelError("node '%s' is isolated" % min_degree[0])
not_in... |
#!/usr/bin/env python
import math
from numpy.core.numeric import NaN
import cv_bridge
import numpy as np
import cv2
import rospy
from sensor_msgs.msg import Image
from geometry_msgs.msg import Point
from nav_msgs.msg import Odometry
def euler_from_quaternion(x, y, z, w):
"""
Convert a quaternion into euler a... |
#
# Copyright (c) 2020 <NAME> <<EMAIL>>
#
# Permission to use, copy, modify, and distribute this software for any
# purpose with or without fee is hereby granted, provided that the above
# copyright notice and this permission notice appear in all copies.
#
# THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL... |
# -*- coding: utf-8 -*-
import mysql.connector
db_config = {'user': 'root', 'password': '<PASSWORD>', 'database': 'wx_monitor'}
def select_id_by_account(account_name):
return _db_template(_select_id_by_account, account_name=account_name)
def _select_id_by_account(_, cursor, account_name):
cursor.execute('S... |
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
import numpy as np
import matplotlib.pyplot as plt
def conv_loss(domain_size=32):
"convolutional loss function based on steady heat equation"
"Neumann condition version"
h = L / (domain_size-3)
kernel = torch... |
# -*- coding: utf-8 -*-
#
# This file is part of BridgeDB, a Tor bridge distribution system.
#
# :authors: <NAME> 0xA3ADB67A2CDB8B35 <<EMAIL>>
# please also see AUTHORS file
# :copyright: (c) 2014-2017, Isis Lovecruft
# (c) 2007-2017, The Tor Project, Inc.
# (c) 2007-2017, all entities... |
from datenguidepy.query_builder import Query
from datenguidepy.query_execution import QueryExecutioner, ExecutionResults
from typing import Dict, Any, cast, Optional, List
import pandas as pd
from functools import partial
import os
dir_path = os.path.dirname(os.path.realpath(__file__))
ALL_REGIONS: pd.DataFrame = pd... |
import json
import time
import multiprocessing.dummy as mp
from restb.sdk import *
from restb.sdk.api import service
# set allotted number of requests per second
# this is defined here as it could be retrieved through some external mechanism
__requests_per_second = 4
__waiting_threads = 10
# lambda helper for gett... |
"""
Copyright 2015 <NAME>
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 json
import numpy as np
import os
from neat.genome import DefaultGenome
from neat.genes import DefaultNodeGene, DefaultConnectionGene
from math import floor
def parse_controller(controller_filename, c_id=0, vis=False):
names_list = ['T Distance', 'T Bearing', 'Obstacle', 'W Distance', 'W Bearing', 'Bias']... |
import os
import re
from flask import request, g, send_from_directory
from flask_restful import reqparse, abort, Resource, fields, marshal_with
from werkzeug import secure_filename
from api.models import File, Folder
from api.utils.decorators import login_required, validate_user, belongs_to_user
BASE_DIR = os.path.a... |
from constraint import *
#We will divide the problem into two subproblems.
#First problem: assigning Subjects to days
#Second subproblem: assigning Teachers to subjects
Scheduling = Problem()
#Therefore, we can define a constraint network as a tuple (X, D, R)
#The set of variables X is defined as follows:
Schedulin... |
import compas_rhino
from compas.datastructures import Network
from compas.datastructures import Mesh
from compas.datastructures import mesh_subdivide_catmullclark
from compas.datastructures import mesh_subdivide_quad
from compas.utilities import geometric_key
from compas.utilities import reverse_geometric_key
from comp... |
"""Sorting templatetags."""
from django import template
from django.contrib.admin.utils import label_for_field
from django.utils.html import format_html
from django.utils.safestring import mark_safe
from django_sorting_bootstrap.sort import sort_queryset
register = template.Library()
# based on contrib.admin.templa... |
import json
from grandpy.apiwikipedia import Apiwikipedia
def mock_requestget(*args, **kwarg):
data_structure_geo_search = {
"batchcomplete": "",
"query": {
"geosearch": [
{
"pageid": 1359783,
"ns": 0,
"title... |
#!/usr/bin/env python
import os
import fileinput
import shutil
import json
import argparse
import sys
import subprocess
def reset_parameters():
return {
"FIELD_FILE": None,
"FIELD_TOL": None,
"H5_FIELD_FREQ": None,
"H5_PARCEL_FREQ": None,
"H5_FIELD_STATS_FREQ": None,
... |
import sys
import os
import warnings
import numpy as np
import pandas as pd
from scipy.stats import spearmanr
from collections import Counter
from netanalytics.io import to_ORCA
from netanalytics.utils import _normalize_degree_distribution
def graphlet_degree_vectors(nodes_list, edges_list, graphlet_size=5):
i... |
from typing import Optional
from flask import Response
from backend.api.handlers.decorators import api_authenticated, validate_keys
from backend.api.handlers.helpers.add_alliance_status import add_alliance_status
from backend.api.handlers.helpers.model_properties import (
filter_event_properties,
filter_match... |
# -*- coding: utf-8 -*-
from scipy.interpolate import interp2d
from delight.utils import *
from astropy.cosmology import FlatLambdaCDM
from delight.utils import approx_flux_likelihood
from delight.posteriors import gaussian, gaussian2d
from delight.utils_cy import approx_flux_likelihood_cy
from delight.utils_cy import... |
"""
Flash embedding Panel
@license: Apache License Version 2.0
@copyright: 2009 <NAME>
@author: <NAME>
@contact: <EMAIL>
"""
from pyjamas import DOM
from pyjamas.ui.Panel import Panel
from pyjamas import log
from __pyjamas__ import wnd
import pyjd
if not pyjd.is_desktop:
from __javascript__ import Array, Object, ... |
def from_bytes(bytes):
return int.from_bytes(bytes, byteorder='little')
def read_block(bytes, offset, size):
assert len(bytes) >= offset + size
return bytes[offset:offset+size]
def read_block_until_end(bytes, offset):
assert len(bytes) >= offset
return bytes[offset:]
def read_null_terminated(byte... |
#https://adventofcode.com/2021/day/1
import copy
from bisect import bisect_left
import re, os, sys
from itertools import chain
import math
from typing import DefaultDict, final
import time
from collections import Counter, defaultdict
from threading import Thread, Lock
import numpy
from numpy.lib.polynomial import poly... |
from typing import Tuple, Type
from django.db.models import F, Model, Value
from django.db.models.functions import Coalesce
from django.db.models.query import QuerySet
from datahub.core.query_utils import (
get_choices_as_case_expression,
get_empty_string_if_null_expression,
get_front_end_url_expression,
... |
#!/usr/bin/env python3
"""Generates/interaces common configurations for scripts in the below repo.
This command line tool is used to generate the configurations used by the
scripts in the general-purpose-scripts repo. The configurations are bare and
are expected to be modified by the end user to take full advantage of... |
import errno
import hashlib
import os
import os.path
import numpy as np
from torch.utils.model_zoo import tqdm
def gen_bar_updater():
pbar = tqdm(total=None)
def bar_update(count, block_size, total_size):
if pbar.total is None and total_size:
pbar.total = total_size
progress_bytes... |
"""Generic functions and classes.
.. testsetup::
from flake8_nitpick.generic import *
"""
import collections
from pathlib import Path
from typing import Any, Iterable, List, Optional, Tuple, Union
import jmespath
from jmespath.parser import ParsedResult
from flake8_nitpick.types import JsonDict, PathOrStr
def... |
# Standard Library
import logging
import os
# Pyramid
from pyramid.httpexceptions import HTTPFound
from pyramid.httpexceptions import HTTPInternalServerError
from pyramid.util import DottedNameResolver
# Pyramid Notebook
from pyramid_notebook.notebookmanager import NotebookManager
from pyramid_notebook.proxy import W... |
# Copyright (C) 2015 Catalyst IT 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 applicable law o... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.