content stringlengths 5 1.05M |
|---|
# -*- coding: utf-8 -*-
import re
import unittest.mock as mock
from django import test
from django.utils import timezone
import testutils.factories as factories
import app.definitions.models as models
import app.revisioner.tasks.v1.core as coretasks
import app.inspector.engines.mysql_inspector as engine
class MySQ... |
# -*- coding: utf-8 -*-
#
# Copyright (c) 2021 HopeBayTech.
#
# This file is part of Tera.
# See https://github.com/HopeBayMobile for further info.
#
# 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 Licens... |
# Copyright (c) 2012-2013 Mitch Garnaat http://garnaat.org/
# Copyright 2012-2013 Amazon.com, Inc. or its affiliates. All Rights Reserved.
#
# 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 wi... |
"""Bastionification utility.
A bastion (for another object -- the 'original') is an object that has
the same methods as the original but does not give access to its
instance variables. Bastions have a number of uses, but the most
obvious one is to provide code executing in restricted mode with a
safe interface ... |
"""
tests for ocd functions.
"""
# pylint: disable=E1101
# pylint: disable=unused-argument
# pylint: disable=unused-variable
# pylint: disable=missing-docstring
# pylint: disable=redefined-outer-name
import random
import torch
import pytest
import numpy as np
from ocd import OCD
@pytest.fixture(scope='module')
def fi... |
from PIL import Image
import torch
import torch.nn as nn
import torch.optim as optim
import torchvision.transforms as transforms
import torchvision.models as models
import torchvision.utils as utils
import matplotlib.pyplot as plt
import sys
import os
import json
from google.cloud import storage
import random
experim... |
"""Define utilities."""
|
# generated from catkin/cmake/template/order_packages.context.py.in
source_root_dir = "/home/graspinglab/Autonomous_racing/Paresh-Soni-F110-2020/Ros-Lab/soni_ws/src"
whitelisted_packages = "".split(';') if "" != "" else []
blacklisted_packages = "".split(';') if "" != "" else []
underlay_workspaces = "/home/graspinglab... |
import glob
import inspect
import logging
import os
import unittest
from pathlib import Path
from securify.solidity import compile_cfg
from securify.staticanalysis import static_analysis
def make_test_case(path_src):
def test_case(self: unittest.TestCase):
cfg, ast, *_ = compile_cfg(path_src)
res... |
__author__ = 'Sergey Osipov <Serega.Osipov@gmail.com>'
import numpy as np
def get_photon_energy(wavelengths):
"""
computes the energy of the photon of a given wavelength
:param wavelengths: [m]
:return: J = W*s
"""
plank_constant = 6.62606957 * 10**-34 # J*s
speed_of_light = 299792458 #... |
from django.db import models
from server_delta_app import models as server_delta_app_models, managers
class SourceIncomeModel(server_delta_app_models.BaseModel):
"""
Model that represent the customer debt registered in app
"""
class Meta:
db_table = "source_income"
value = models.Deci... |
# -*- coding: UTF-8 -*-
# !/usr/bin/python
# @time :2019/7/27 22:15
# @author :Mo
# @function :test func_recursive
from tookit_sihui.ml_common.func_recursive.func_recursive import gen_syn_sentences
if __name__=="__main__":
org_data = ["[你][喜欢|喜爱|爱][虾米|啥子|什么]", "[1|11][2|22][3|33][44|444]", "大漠帝国"]
syn_... |
# Copyright (c) 2012 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 os
from telemetry.core import browser_credentials
from telemetry.core import extension_dict
from telemetry.core import tab_list
from telemetry.cor... |
#!/usr/bin/env python
################# FROM FRANK ###################################
import os,sys
from dcnn_base import DCNN_CONFIG
from dcnn_main import DCNN
from dcnn_logger import setup_script_logging #FB
from dcnn_utils import file_looper,get_args,dict2str,expandvars #FB
__version__= "2020-07... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
import re
import xml.etree.ElementTree
from config import ConfigSectionMap
def dust_from_xml(root):
"""
get arrivals from xml which contains arrival items (n different routes) for specified bus station
:param root: root node of xml response
... |
"""
NSL-KDD
https://www.unb.ca/cic/datasets/nsl.html
http://205.174.165.80/CICDataset/NSL-KDD/Dataset/
"""
import pandas as pd
import os
from pyzhmh import __dirname__, download_one_file, unpack_one_file
__dirname__ = __dirname__()
NSL_KDD_URL = "http://205.174.165.80/CICDataset/NSL-KDD/Dataset/NSL-KDD.zip... |
"""Necessary constants for MQTT."""
NUMBER_OF_PARTITION = 10
|
#!/usr/bin/env python
#
# Copyright 2011 Rodrigo Ancavil del Pino
#
# 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 applica... |
import numpy as np
from manimlib.animation.animation import Animation
from manimlib.constants import *
from manimlib.mobject.svg.tex_mobject import TexMobject
from manimlib.scene.scene import Scene
class RearrangeEquation(Scene):
def construct(
self,
start_terms,
end_terms,
index_... |
# -*- coding: utf-8 -*-
'''
:codeauthor: :email:`Gareth J. Greenaway <gareth@saltstack.com>`
:codeauthor: :email:`David Murphy <dmurphy@saltstack.com>`
'''
# Import Python libs
from __future__ import absolute_import, print_function, unicode_literals
import os
import shutil
import datetime
import time
# Import... |
import requests
from requests.compat import urlencode
from errors import TwitchAPIError
from utils import join_urls
class TwitchSubscribeClient:
"""Streamer event subscriptions manager.
Allows to subscribe to streamer's updates.
Subscribable events:
* Streamer starts following some channe;;
... |
# -*- coding: utf-8 -*-
import pickle
import traceback
from copy import deepcopy
from inspect import signature
from pathlib import Path
import joblib
from joblib._store_backends import concurrency_safe_rename, concurrency_safe_write
from .hashing import CodeObj
from .proxy_backend import Factory, HashProxy
def _con... |
from torch import nn
from torchvision.models.resnet import Bottleneck, BasicBlock
import torch
from neuralpredictors.utils import eval_state
def get_module_output(model, input_shape, neural_set):
"""
Gets the output dimensions of the convolutional core
by passing an input image through all convolution... |
import os
SECRET_KEY = '1234'
MIDDLEWARE_CLASSES = tuple()
WITH_WQDB = os.environ.get('WITH_WQDB', False)
if WITH_WQDB:
WQ_APPS = (
'wq.db.rest',
'wq.db.rest.auth',
)
else:
WQ_APPS = tuple()
INSTALLED_APPS = (
'django.contrib.contenttypes',
'django.contrib.auth',
'data_wizard... |
import os
import argparse
import pandas as pd
from datetime import datetime
import torch
import torch.nn as nn
from torch.utils.data import DataLoader
from detection.engine import train_one_epoch, evaluate
from src.model import FasterRCNN
from src.dataset import SVHN_Dataset
from src.transforms import train_transfor... |
#
# All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or
# its licensors.
#
# For complete copyright and license terms please see the LICENSE at the root of this
# distribution (the "License"). All use of this software is governed by the License,
# or, if provided, by the license below or th... |
import firebase_admin
from firebase_admin import credentials
from firebase_admin import messaging
import flask
def firebase_send_notify(title: str, body: str, data: dict = None,
topic: str = 'all', target_token: str = None):
cred = credentials.Certificate(flask.current_app.config.get('FIR... |
from distutils.core import setup
from Cython.Build import cythonize
setup(
name='Great Circle v2',
ext_modules=cythonize("great_circle_v2.pyx"),
)
|
# Generated by Django 3.0.8 on 2020-09-27 20:27
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('MainComponent', '0010_auto_20200927_2327'),
]
operations = [
migrations.AlterField(
model_name='avaibleinternship',
... |
from .data import ITestData
from .dataset import ITestDataset
__all__ = ['ITestData', 'ITestDataset']
|
from protocols.forms import forms
from core.utils import TIME_UNITS
class ElectrophoreseForm(forms.VerbForm):
name = "Electrophorese"
slug = "electrophorese"
has_machine = True
model = forms.CharField(required = False, label='machine_model')
min_voltage = forms.IntegerField(required = False)
... |
import pytest
from hades_logs.parsing import parse_vlan as parse, ParsingError
def test_correct_untagged():
assert parse('"2hades-unauth"') == "hades-unauth (untagged)"
def test_correct_untagged_unstriped():
assert parse("2Wu5") == "Wu5 (untagged)"
def test_correct_tagged():
assert parse("1toothstone... |
import bisect
import random
class Solution(object):
def __init__(self, w):
"""
:type w: List[int]
"""
self.prefix = w[:]
for i in range(1, len(w)):
self.prefix[i] += self.prefix[i-1]
self.MAX = self.prefix[-1]
def pickIndex(self):
"""
... |
""" Handles webhooks from payment backend """
import time
from django.http import HttpResponse
from .models import Order
from .reports import send_ticket_pdf_email
from .tickets import create_tickets_for_order
# pylint: disable=W0703
# Broad exception: Any error should cause orders to be deleted
# Largely based on t... |
import gym
import numpy as np
import math
import cv2
from gym.spaces.box import Box
def resize(src, new_size):
src = src.astype("float32")
H, W, C = src.shape
new_H, new_W = new_size
dst = np.zeros((new_H, new_W, C))
ratio_h = H / new_H
ratio_w = W / new_W
for i in range(new_H):
... |
import unittest
from year2021.python.day6.day6_func import *
class TestDay6(unittest.TestCase):
def test_correct_spawn_80(self):
# Arrange
fishes = [0, 1, 1, 2, 1, 0, 0, 0, 0]
spawn = FishSpawn()
# Act
numberOfFishes80Days = spawn.spawn(fishes, 80)
# Assert
... |
# -*- coding: utf-8 -*-
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
from color import generateColorFunction
def on(msg):
return generateColorFunction('green')(msg)
def off(msg):
return generateColorFunc... |
"""packer_builder/specs/builders/vmware.py"""
def vmware_builder(**kwargs):
"""VMware specific builder specs."""
# Setup vars from kwargs
builder_spec = kwargs['data']['builder_spec']
distro = kwargs['data']['distro']
vagrant_box = kwargs['data']['vagrant_box']
builder_spec.update({
... |
import pyparsing as pp
import base64
def parse_receipt( text ):
''' Given a plist-based receipt from Apple's storeKit
return a native python datastructure.
'''
# Set up our grammar
identifier = pp.Literal('"').suppress() + pp.Word(pp.alphanums+"-_") + pp.Literal('"').suppress()
value = pp.... |
"""Generate a prediction for a given salient2's submodel and a given deadline date
Example:
$ python src/models/salient2/predict_keras.py -d 20200107 -sn d2wk_cop_sst_20170201
$ python src/models/salient2/predict_keras.py -d 20200121 -sn d2wk_cop_sst_mei_20190731 -r us
Named args:
--deadli... |
import contextlib
import logging
import re
import traceback
from datetime import datetime as dt
from functools import wraps
from typing import Optional
import pandas as pd
from influxdb.exceptions import InfluxDBClientError
from app.models import Series
from app.vendors.influx import InfluxDB
from config import resol... |
#!/usr/bin/env python
######################################################################
# Software License Agreement (BSD License)
#
# Copyright (c) 2010, Rice University
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that t... |
###########################################################################
#
# Copyright 2020 Google LLC
#
# 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
#
# https://www.apache.org/l... |
import pytest
from easel.site.defaults import Defaults
from easel.site.errors import MenuConfigError
from easel.site.menus import LinkPage, LinkURL, Spacer
def test__LinkPage__valid() -> None:
config = {
"label": "TestLinkPage",
"links-to": "/test-link-page",
}
link_page = LinkPage(**co... |
from rest_framework import routers
from .api import *
router = routers.DefaultRouter()
router.register('terms', TermsViewSet)
router.register('marks', MarksViewSet)
router.register('control_types', ControlTypesViewSet)
router.register('records', RecordsViewSet)
urlpatterns = router.urls |
"""
Vorter XSPRESS3 class
Python class for Vortex using EPICS area detector IOC.
:platform: Unix
:synopsis: Python class for Vortex with xspress3
.. moduleauthor:: Douglas Araujo<douglas.araujo@lnls.br>
Luciano Carneiro Guedes<luciano.guedes@lnls.br>
"""
from py4syn.epics.StandardDevice import Sta... |
from django.apps import AppConfig
class PicturesConfig(AppConfig):
name = 'pictures'
|
##################FILE NAME: INTERIOR.py########################
#================================================================
# author: Nitish Anand & Jozef Stuijt |
# :Master Student, |
# :Process and Energy Departmemt, ... |
from engine import TetrisEngine
width, height = 10, 20 # standard tetris friends rules
env = TetrisEngine(width, height)
# Reset the environment
state, character, features = env.clear()
def agent():
print("Please enter the rotation and column for the current tetromino:")
rotation = int(input().strip())
... |
# Generated by Django 3.1.3 on 2020-12-05 06:47
import cloudinary.models
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('hood', '0001_initial'),
]
operations = [
migrations.AddField(
model_name='business',
name='business... |
import math
from .utils import clamp
def linear(t):
return t
def quadratic(t):
return t * t
def bezier(t):
return t * t * (3.0 - (2.0 * t))
def parametric(t):
t2 = t * t
return t2 / (2.0 * (t2 - t) + 1.0)
def spring(mass=1.0, stiffness=100.0, damping=10.0, velocity=0):
# Ported from h... |
#!/usr/bin/env python3
"""
Compare Pipfile.lock packages and versions against a requirements.txt.
Raises AssertionError if packages and versions do not exactly match in both.
"""
import json
import re
from typing import List
import sys
"""
Copyright 2020 James Williams
Licensed under the Apache License, Version 2.0 ... |
###
## * << Haru Free PDF Library 2.0.0 >> -- outline_demo_jp.c
## *
## * Copyright (c) 1999-2006 Takeshi Kanno <takeshi_kanno@est.hi-ho.ne.jp>
## *
## * Permission to use, copy, modify, distribute and sell this software
## * and its documentation for any purpose is hereby granted without fee,
## * provided that... |
#%%
import os
import sys
try:
os.chdir('/Volumes/GoogleDrive/My Drive/python_code/connectome_tools/')
print(os.getcwd())
except:
pass
from pymaid_creds import url, name, password, token
import pymaid
import numpy as np
import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt
# allows text... |
"""
Author: D. van Gent
License: MIT
Description: Simple Python implementation of the Ubiquiti device discovery protocol.
The protocol was "reverse engineered" by capturing traffic from the "WiFiman" Android app,
payload decoding is best-effort and not guaranteed to be correct.
Usage: python3 ubnt-discover.py {ip-add... |
import asyncio
import time
async def count():
print("one")
await asyncio.sleep(1)
print("two")
async def main():
await asyncio.gather(count(), count(), count())
start = time.time()
asyncio.run(main())
print(time.time() - start)
|
import datetime
import json
import logging
import random
from sqlalchemy import func
from trafficdb.blueprint.api import PAGE_LIMIT
from trafficdb.models import *
from .fixtures import (
create_fake_link_aliases,
create_fake_links,
create_fake_observations,
)
from .util import ApiTestCase as TestCase, API... |
from meuusuario import *
from bancodedados import salvar_usuario
def novopoder(usuario, usuario2):
_ = True
while _:
novo_poder = input('Digite seu novo poder [Administrador] ou [Usuario] : ')
if verificapoder(novo_poder):
if usuario2 == 'Administrador':
usuario.nom... |
from nornir import InitNornir
from nornir.plugins.tasks.networking import netmiko_send_command
from nornir.plugins.functions.text import print_result
nr = InitNornir()
result = nr.run(task=netmiko_send_command, command_string="show arp")
print_result(result)
#Nornir checks for hosts.yaml file. Based on that yaml file... |
from .. import fields, manager, model
from ..interaction import GenericInteraction
EVENT_TYPES_WITH_BLANK_VALUE = (
"lead_deleted",
"lead_restored",
"contact_deleted",
"contact_restored",
"company_deleted",
"company_restored",
"customer_deleted",
"entity_merged",
"task_added",
... |
import os
import sys
import json
from flask import Flask
from flask import request
from prediction import Prediction
app = Flask(__name__)
prediction = ""
aijson = ""
@app.route("/model")
def model():
return json.dumps(aijson)
@app.route("/health")
def hello():
return "aibuildpack-api"
@app.route('/', metho... |
# Step by Step Logic Gate Solver. Execute input_equation() to start the program!
def input_equation():
print("Enter equation without whitespaces")
equation = input()
var = []
for character in equation:
if(character.isalpha):
if(character not in var):
var.append(chara... |
# Generated by Django 3.1.5 on 2021-10-12 18:06
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('classes', '0004_auto_20211009_1840'),
('code_analysis', '0017_auto_20211008_2219'),
]
operations = [
... |
# dummy/proxy tz module
import utime
from utime import mktime, localtime
TZ = 1 # UTC+1
def isdst(ts):
return bool(utime.localtime(ts)[8])
def utcoffset(ts=None):
if ts is None:
ts = utime.time()
offset = TZ * 3600
if isdst(ts):
offset += 3600
return offset
|
import numpy as np
from numpy import pi
import logging
import h5py
from numpy import pi
import logging, os
from .Diagnostics import *
from .Saving import *
class Model(object):
""" Python class that represents the barotropic quasigeostrophic
pseudospectral model in a doubly periodic domain. Physical param... |
# Generated by Django 3.1.2 on 2020-12-24 14:21
from django.db import migrations
import phonenumber_field.modelfields
class Migration(migrations.Migration):
dependencies = [
('apis', '0021_auto_20201218_2020'),
]
operations = [
migrations.AlterField(
model_name='userapimodel... |
#!/usr/bin/python
"""
meta.py
Another "thin waist" of the interpreter. It can be happen at compile time!
We are following the code <-> data pattern, and this is the "data" module.
id_kind and asdl are the "code" modules.
Usage:
from osh.meta import Id, Kind, ast, ID_SPEC
"""
from asdl import py_meta
from asdl im... |
import sys
from PyQt5.QtWidgets import QApplication, QWidget
from PyQt5.uic.Compiler.qtproxies import QtGui
import pyqtgraph.opengl as gl
import numpy as np
from pyqtgraph import Vector
class ChartWidget3D(QWidget):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.w = ... |
""" Cisco_IOS_XR_wdsysmon_fd_oper
This module contains a collection of YANG definitions
for Cisco IOS\-XR wdsysmon\-fd package operational data.
This module contains definitions
for the following management objects\:
system\-monitoring\: Processes operational data
Copyright (c) 2013\-2018 by Cisco Systems, Inc.
A... |
#!/usr/bin/env python
# coding: utf-8
# In[2]:
import nltk
from nltk import word_tokenize
import spacy
import en_core_web_sm
from commonregex import CommonRegex
import glob
from nltk.corpus import wordnet
import sys
import os
import errno
import argparse
nltk.download('wordnet')
def openfiles(filename):
with op... |
import datetime
import time
import numpy as np
import tensorflow as tf
import sys
import os
from data_utils import Data
from char_cnn import CharConvNet
if __name__ == '__main__':
#execfile("config.py")
with open('config.py', 'r') as source_file:
exec(source_file.read())
#print "Loading data ....... |
"""This module contains a plugin to test a node's remote shutdown functionality."""
from teatime import Context, Issue, NodeType, Severity
from teatime.plugins.base import IPFSRPCPlugin
class Shutdown(IPFSRPCPlugin):
"""Attempt to list all active P2P listeners.
Severity: Critical
Endpoint: https://docs... |
#! /usr/bin/env python
#adam-does# moves a certain class of files so that it's not in the way screwing up pipeline scripts, but keeping them somewhere in case I need them
#adam-use# for example, after running the stellar suppression you can remove the *OCF.fits files so they don't confuse the processing of the *OCFR.fi... |
from .button import Button
from ..decorators import stere_performer, use_after, use_before
from ..field import Field
@stere_performer('select', consumes_arg=True)
class Dropdown(Field):
"""Represents a dropdown menu.
If the "option" argument is provided with a field,
use that as the dropdown item.
... |
#coding:utf-8
from multiprocessing.connection import Client
import socket, threading
"""IPC通信(送信用)コンソール
"""
print("IPC Connector (Client)")
def main(port):
while True:
command = input(f"localhost:{port}> ")
try:
data = str(command).encode()
length = len(data)
c... |
import html # clean up html strings (such as &)
import json # interact with the Tribe Events API
from datetime import datetime # convert utc time to datetime
from city_scrapers_core.constants import BOARD
from city_scrapers_core.items import Meeting
from city_scrapers_core.spiders import CityScrapersSpider
# r... |
import re
from datetime import datetime
from functools import total_ordering
from typing import Dict, List, Optional, Tuple
from rich.highlighter import RegexHighlighter
from rich.theme import Theme
class TaskHighlighter(RegexHighlighter):
"""Apply style to [Task]s."""
base_style = "task."
highlights = ... |
#!/usr/bin/env python3
import os
import datetime
from pydblite import Base
#db openen via losse functie
SCRIPT_DIR = os.path.dirname(os.path.realpath(__file__))
def sort_high_scores(elem):
return (int(elem['score']), elem['duration'], elem['date'])
def update_user_table(user_id, first_name):
db = Base(os.pat... |
import os
from glob import glob
import pandas as pd
"""A test to check if images are placed correctly"""
psychic_learners_dir = os.path.split(os.getcwd())[0]
image_folder = os.path.join(psychic_learners_dir, 'data', 'image', 'v1_train_nodups_240x240')
train_df = pd.read_csv(os.path.join(psychic_learners_dir, 'data', ... |
from avidaspatial import *
from patch_analysis import *
import sys
import shapely as shp
from shapely.geometry import MultiPoint
from descartes.patch import PolygonPatch
import pandas as pd
df = pd.read_csv("all_task_locs.csv")
env_id = sys.argv[1]
task_id=0
if len(sys.argv) > 2:
task_id = int(sys.argv[2])
draw... |
from settings import Settings, SETTINGS
from ufrc.main import UFRC
def get_file(settings: Settings):
ufrc = UFRC()
ufrc.connect(settings.username, settings.password)
ufrc.get("temp.txt")
if __name__ == "__main__":
get_file(SETTINGS)
|
# -*- coding: utf-8 -*-
# Generated by Django 1.10.7 on 2017-08-05 04:42
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('accounts', '0002_auto_20170803_1446'),
]
operations = [
migrations.AlterFie... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
import django_countries.fields
class Migration(migrations.Migration):
dependencies = [
('conventions', '__first__'),
]
operations = [
migrations.CreateModel(
name='Paymen... |
from core.advbase import *
from module.bleed import Bleed
from slot.a import *
from slot.d import *
def module():
return Patia
class Patia(Adv):
a1 = ('bt',0.35)
a3 = ('primed_crit_chance', 0.10, 5)
conf = {}
conf['slots.a'] = Resounding_Rendition()+Brothers_in_Arms()
conf['slots.poison.a'] =... |
import sys
from fastapi import APIRouter, HTTPException, Request
from fastapi.templating import Jinja2Templates
from linebot import LineBotApi, WebhookHandler
from linebot.exceptions import InvalidSignatureError
from linebot.models import *
from . import message_event, user_event
sys.path.append(".")
import config
... |
# -*- coding: utf-8 -*-
"""Handles the instrospection of REST Framework Views and ViewSets."""
import inspect
import itertools
import re
import yaml
import importlib
from .compat import OrderedDict, strip_tags, get_pagination_attribures
from abc import ABCMeta, abstractmethod
from django.http import HttpRequest
fro... |
import numpy as np
from pygamoo import Player
from copy import deepcopy
class ClonalSelection(Player):
def __init__(self, num, obj_queue, repair_queue, cmd_exchange, npop, nvars, bounds, host, port, player_parm):
self.nclone = player_parm['nclone']
self.mutate_args = tuple(player_parm['mutate_args... |
#! /vagrant/analysis/py36env/bin/python3.6
import psycopg2
from contextlib import contextmanager
from pprint import pprint
def connect():
"""
:return:
"""
return psycopg2.connect("dbname=forum")
@contextmanager
def get_cursor():
conn = connect()
cursor = conn.cursor()
... |
import argparse
import os
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
parser = argparse.ArgumentParser(description='Display an opt_tools hist.')
parser.add_argument('hist_file', type=str, nargs='+', help="Paths to the history files to be displayed.")
parser.add_argument('--smooth', help="Sm... |
import uuid
from datetime import datetime
from flask import current_app
from api import db, bcrypt
class User(db.Model):
__tablename__ = "users"
id = db.Column(db.Integer, primary_key=True)
uuid = db.Column(db.String(255), unique=True, nullable=False)
first_name = db.Column(db.String(120), nullable=... |
import socket
import logging
import sys
from threading import Thread
HOST = "127.0.0.1"
PORT = 8080
ADDR = (HOST, PORT)
BUFFERSIZE = 4096
def print_chat(text):
"""Imprime a mensagem de maneira bonita"""
sys.stdout.write("\u001b[1L\u001b[1A\u001b[1B\u001b[1000D")
sys.stdout.write(text)
sys.stdout.writ... |
import zmq
import threading
import queue
import time
import random
class Router():
"""
Router Limited to localhost
"""
def __init__(self, routes, CURVE=False):
self.routes = routes
# self.connectionTimeout = 2000
self.connectionTimeout = 1800
self.protocol = 'tcp'
... |
"""
Convenience interface for NSDictionary/NSMutableDictionary
"""
__all__ = ()
from objc._convenience_mapping import addConvenienceForBasicMapping
from objc._convenience import container_wrap, container_unwrap, addConvenienceForClass
from objc._objc import lookUpClass
import sys, os, collections.abc
NSDictionary = ... |
import sys
n = int(sys.stdin.readline())
for _ in range(n):
n, k = sys.stdin.readline().strip().split()
n, k = int(n), int(k)
if n % 2 == 0:
# even
if n < k or (k % 2 == 1 and n < 2 * k):
print("NO")
else:
print("YES")
if k % 2 == 0:
... |
# -*- coding: utf-8 -*-
from conans import ConanFile, tools
import os
class TestPackageConan(ConanFile):
def test(self):
if not tools.cross_building(self.settings):
self.run("some_tool --version")
|
# OpenWeatherMap API Key
weather_api_key = "6edbbe4fc8bc867709594d77824c6aed"
# Google API Key
g_key = "AIzaSyC-8Y9a59V9dNpKTAOE3bwfTVS8kcMqANE"
|
import logging
from abc import ABCMeta, abstractmethod
import torch
from torch import nn
from quati import constants
logger = logging.getLogger(__name__)
class Model(torch.nn.Module):
__metaclass__ = ABCMeta
def __init__(self, fields_tuples):
super().__init__()
# Default fields and embeddi... |
from enum import Enum
class Color(Enum):
NoColor = 0
Red = 1
Green = 2
Blue = 3
Yellow = 4
@classmethod
def get_from(cls, color_string: str):
if color_string == 'rouge':
return Color.Red
elif color_string == 'vert':
return Color.Green
elif c... |
# Copyright 2013-2022 Lawrence Livermore National Security, LLC and other
# Spack Project Developers. See the top-level COPYRIGHT file for details.
#
# SPDX-License-Identifier: (Apache-2.0 OR MIT)
import sys
from spack.package import *
class AutodockVina(MakefilePackage):
"""AutoDock Vina is an open-source pro... |
import pytest
from tuneit.graph import Graph, Node, Key
class String(str):
def __init__(self, val):
self.__name__ = val
self.__label__ = val
self.__dot_attrs__ = {}
def __iter__(self):
raise TypeError
def test_graph():
a = Graph()
a["foo"] = String("bar")
b = Nod... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.