text
string
size
int64
token_count
int64
import sys import re import boto3 from botocore.exceptions import ClientError import uuid import time import yaml import os def get_instance_by_name(ec2_name, config): instances = get_all_instances(config) for instance in instances: str = instance['Tags'][0]['Value'] if str == ec2_name: ...
4,175
1,308
# -*- coding: utf-8 -*- """ Created on Fri Aug 31 18:33:58 2018 @author: Marios Michailidis metrics and method to check metrics used within StackNet """ from sklearn.metrics import mean_squared_error, mean_absolute_error, r2_score , mean_squared_log_error #regression metrics from sklearn.metrics import roc_auc_sco...
5,685
1,890
#!/usr/bin/env python # coding=utf-8 # vim:ts=4:sts=4:sw=4:et # # Author: Hari Sekhon # Date: 2017-11-24 21:10:35 +0100 (Fri, 24 Nov 2017) # # https://github.com/harisekhon/nagios-plugins # # License: see accompanying Hari Sekhon LICENSE file # # If you're using my code you're welcome to connect with me on Linke...
5,629
1,774
# -*- coding: utf-8 -*- # # 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 #...
2,412
783
#!/usr/bin/env python # # Copyright 2007 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 o...
1,359
547
from django.http import HttpResponse from django.core.mail import send_mail import json from django.shortcuts import render from django.views.decorators.csrf import csrf_exempt from GestiRED.models import User from GestiRED.models import QualityControl, Phase, Resource, ResourceType,PhaseType from django.core import se...
2,406
683
from maix import nn from PIL import Image, ImageDraw, ImageFont from maix import display, camera import time from maix.nn import decoder def draw_rectangle_with_title(draw, box, disp_str, bg_color=(255, 0, 0, 255), font_color=(255, 255, 255, 255)): # draw = ImageDraw.Draw(img) font = ImageFont.load_defaul...
2,181
975
from dataclasses import dataclass, field from datetime import date, datetime, time, timezone from pathlib import Path from typing import Any, Dict, Optional, Union import ciso8601 import pytest from mashumaro import DataClassDictMixin from mashumaro.exceptions import UnserializableField from mashumaro.types import Se...
10,143
3,690
import pandas as pd from sklearn.model_selection import train_test_split from sklearn.feature_extraction.text import CountVectorizer, TfidfVectorizer from sklearn.metrics import accuracy_score, confusion_matrix from sklearn.feature_extraction.text import TfidfTransformer from sklearn.pipeline import Pipeline from skle...
3,152
1,185
# Copyright 2018 The TensorFlow 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 applica...
7,552
2,499
import ast import re import sys if sys.version_info < (2, 7): import unittest2 as unittest else: import unittest import astunparse from tests.common import AstunparseCommonTestCase class DumpTestCase(AstunparseCommonTestCase, unittest.TestCase): def assertASTEqual(self, dump1, dump2): # undo the ...
729
255
from django.core.management.base import AppCommand, CommandError from django.core.management.sql import sql_reset from django.core.management.color import no_style from django.db import connections class Command(AppCommand): help = "**********\nThis command resets data for any django app, the difference with the b...
1,387
356
from django.apps import AppConfig class WebblogConfig(AppConfig): name = 'webBlog'
89
29
# coding:utf-8 ''' @author = super_fazai @File : requires.py @Time : 2016/8/3 12:59 @connect : superonesfazai@gmail.com ''' install_requires = [ 'ipython', 'wheel', 'utils', 'db', 'greenlet==0.4.13', 'web.py==0.40.dev1', 'pytz', 'requests', 'selenium==3.8.0', # 3.8.1及其以上版...
996
453
import subprocess import requests import argparse from concurrent.futures import ThreadPoolExecutor from time import sleep from datetime import datetime ICMP_ATTACK = "ICMP" HTTP_ATTACK = "HTTP" valid_attacks = {HTTP_ATTACK, ICMP_ATTACK} parser = argparse.ArgumentParser(description="DoS HTTP") parser.add_argument('-P...
2,433
756
from django.apps import apps from django.db import models from django.db.models.signals import post_save, pre_delete from typing import Type, Optional, List, cast, TYPE_CHECKING from maestro.backends.django.settings import maestro_settings from maestro.backends.django.contrib.factory import create_django_data_store fro...
3,444
1,075
from django.urls import include, path from .views import home, bike urlpatterns = [ path("", home), path("bike/<int:number>", bike) ]
142
49
""" Remove Fragments not in Knowledgebase """ __author__ = "Michael Suarez" __email__ = "masv@connect.ust.hk" __copyright__ = "Copyright 2019, Hong Kong University of Science and Technology" __license__ = "3-clause BSD" from argparse import ArgumentParser import numpy as np import pickle parser = ArgumentParser(desc...
2,421
913
"""Tests for core.billing. Run this test from the project root $ nosetests core.tests.billing_tests Copyright (c) 2016-present, Facebook, Inc. 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. An additional grant of ...
11,352
3,698
from django.contrib.auth.decorators import user_passes_test from django.utils.decorators import method_decorator from data_interrogator.admin.forms import AdminInvestigationForm, AdminPivotTableForm from data_interrogator.interrogators import Allowable from data_interrogator.views import InterrogationView, Interrogati...
1,106
329
_base_ = './pspnet_r50-d8_512x512_80k_loveda.py' model = dict( backbone=dict( depth=18, init_cfg=dict( type='Pretrained', checkpoint='open-mmlab://resnet18_v1c')), decode_head=dict( in_channels=512, channels=128, ), auxiliary_head=dict(in_channels=256, channel...
327
143
from typing import Dict, Any class ResponseObject: def __init__(self, data: Dict[str, Any]): self.payload = data for k, v in data.items(): setattr(self, k, v)
191
61
from django import forms from django.forms import ModelForm from django.contrib.auth import get_user_model from django.core.exceptions import ValidationError from .choices import ActionChoice from .choices import StatusApproval from .models import GreencheckIp from .models import GreencheckIpApprove from .models impor...
4,880
1,330
#!/usr/bin/env python # -*-coding:utf-8-*- from tld import get_tld __author__ = "Allen Woo" def get_domain(url): ''' 获取url中的全域名 :param url: :return: ''' res = get_tld(url, as_object=True) return "{}.{}".format(res.subdomain, res.tld)
263
117
#!/usr/bin/env python # -*- coding: utf-8 -*- # SPDX-License-Identifier: BSD-3-Clause # Copyright © 2017-2019, GoodData Corporation. All rights reserved. """ FreeIPA Manager - entity module Object representations of the entities configured in FreeIPA. """ import os import re import voluptuous import yaml from abc imp...
23,904
6,588
# pylint: skip-file from athena_glue_service_logs.catalog_manager import BaseCatalogManager def test_class_init(mocker): mocker.patch.multiple(BaseCatalogManager, __abstractmethods__=set()) base_catalog = BaseCatalogManager('us-west-2', 'dbname', 'tablename', 's3://somewhere') assert base_catalog.databas...
1,580
516
from twisted.internet import reactor reactor.listenTCP(8789, factory) reactor.run()
83
31
import pandas as pd import numpy as np import matplotlib.pyplot as plt def visualize(dataframe, balltype): df = dataframe #Filter by balltype res = df[df["pitch_type"] == balltype] #Group by results groups = res.groupby("description") for name, group in groups: if name ==...
2,362
936
# -*- coding: utf-8 -*- """ Created on Sat May 25 13:17:49 2019 @author: Toonw """ import numpy as np def vlen(a): return (a[0]**2 + a[1]**2)**0.5 def add(v1,v2): return (v1[0]+v2[0], v1[1]+v2[1]) def sub(v1,v2): return (v1[0]-v2[0], v1[1]-v2[1]) def unit_vector(v): vu = v / np.linalg.norm(v) ...
790
402
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.apps import AppConfig class ChatsConfig(AppConfig): name = 'apps.chats' def ready(self): from actstream import registry registry.register(*self.get_models())
262
82
import os import time from utils.eye import Eye from utils.finger import Finger class Ghost: """class to navigate the app, with Eye and Finger""" def __init__(self, adb_path, temp_path, sleep_sec=2): self.eye = Eye(adb_path, temp_path) self.finger = Finger(adb_path, sleep_sec=sleep_sec) ...
3,472
1,214
#!/usr/bin/env python # -*- coding: UTF-8 -*- import random from ete2 import Tree, TreeStyle, NodeStyle, faces, AttrFace, CircleFace, TextFace def layout(node): if not node.is_root(): # Add node name to laef nodes #N = AttrFace("name", fsize=14, fgcolor="black") #faces.add_face_to_node(N, node, 0) #pass fa...
3,686
1,593
from __future__ import annotations import re import time from typing import get_args, Literal, TYPE_CHECKING, Union from lxml import html from compass.core.interface_base import InterfaceBase from compass.core.logger import logger from compass.core.schemas import member as schema from compass.core.settings import Se...
28,719
8,323
from django.urls import path from . import views urlpatterns = [ path('', view=views.SuraListView.as_view(), name='sura-list'), path('<int:sura_num>/<int:number>/', view=views.AyahTextView.as_view(), name='ayah-detail'), path('<int:sura_num>/<int:number>', view=views.AyahTextVie...
336
122
from konnection.settings.base import * from pathlib import Path import os import dotenv # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent.parent # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True SECRET_KEY = 'temporaryKey'...
1,623
555
import random from evaluation import Evaluator from generator import generator from mutate import mutateset from deap import base from deap import creator from deap import tools from parameter_group import ParameterGroup import gaussian_output from analysis import Analysis from gaussian_input import GaussianInput from ...
8,205
2,560
import unittest #import tempfile try: from StringIO import StringIO except: from io import StringIO import pyx12.error_handler from pyx12.errors import EngineError # , X12PathError import pyx12.x12context import pyx12.params from pyx12.test.x12testdata import datafiles class X12fileTestCase(unittest.TestCas...
23,614
9,552
# -*- coding: utf-8 -*- import re,urlparse,cookielib,os,urllib from liveresolver.modules import client,recaptcha_v2,control,constants, decryptionUtils from liveresolver.modules.log_utils import log cookieFile = os.path.join(control.dataPath, 'finecastcookie.lwp') def resolve(url): #try: try: ...
1,460
564
# Copyright 2008-2015 Nokia Solutions and Networks # # 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 appl...
5,161
1,390
#!/usr/bin/env python import os import json import tornado.ioloop import tornado.log import tornado.web from google.oauth2 import id_token from google.auth.transport import requests as google_requests import jwt import requests API_KEY = os.environ.get('OPEN_WEATHER_MAP_KEY', None) PROJECT_ID = os.environ.get('PRO...
3,520
1,124
# AUTOGENERATED BY: ProsperCookiecutters/ProsperFlask # TEMPLATE VERSION: {{cookiecutter.template_version}} # AUTHOR: {{cookiecutter.author_name}} """PyTest fixtures and modifiers""" import pytest from {{cookiecutter.library_name}}.endpoints import APP @pytest.fixture def app(): """flask test hook for dry-runni...
352
126
from typing import Iterator, NamedTuple, Tuple from cached_property import cached_property from cv2 import Rodrigues from pyquaternion import Quaternion class Coordinates(NamedTuple): """ :param float x: X coordinate :param float y: Y coordinate """ x: float y: float class ThreeDCoordinate...
3,341
1,073
# coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for # license information. # # Code generated by Microsoft (R) AutoRest Code Generator. # Changes ...
2,988
854
# -*- encoding: utf-8 -*- # Module iagradm def iagradm(f, Bdil=None, Bero=None): from ia870 import iasubm,iadil,iaero,iasecross if Bdil is None: Bdil = iasecross() if Bero is None: Bero = iasecross() y = iasubm( iadil(f,Bdil),iaero(f,Bero)) return y
274
129
import pytest from api.models.utils import rankings @pytest.fixture def test_data(): return [1, 11, 101] def test_rankings(test_data): """Tests if ranking works e.g. 1 returns 1st 11 returns 11th 101 return 101st """ assert rankings(test_data[0]) == "1st" assert rankings(t...
388
155
from flask import Flask, request, redirect, url_for import os import random import string import time # lemonthink clean = time.time() app = Flask(__name__) chars = list(string.ascii_letters + string.digits) @app.route('/') def main(): return open("index.html").read() @app.route('/generate', methods=['POST']) de...
721
241
# Your task is to make a function that can take any non-negative integer as an argument and return it with its digits in descending order. Essentially, rearrange the digits to create the highest possible number. # Função que recebe um número inteiro (não negativo) como argumento e o retorna com os dígitos em ordem des...
816
251
import sqlite3 import os import datetime __all__ = ['DMARCStorage', 'totimestamp'] def totimestamp(datetime_object): if datetime_object.utcoffset() is not None: utc_naive = datetime_object.replace(tzinfo=None) - datetime_object.utcoffset() else: utc_naive = datetime_object return (utc_nai...
8,981
2,568
from setuptools import setup, find_packages setup( name="sumologic-sdk", version="0.1.9", packages=find_packages(), install_requires=['requests>=2.2.1'], # PyPI metadata author="Yoway Buorn, Melchi Salins", author_email="it@sumologic.com, melchisalins@icloud.com", description="Sumo Logi...
557
186
# -*- coding: utf-8 -*- # # Configuration file for the Sphinx documentation builder. # # This file does only contain a selection of the most common options. For a # full list see the documentation: # http://www.sphinx-doc.org/en/master/config # -- Path setup ------------------------------------------------------------...
8,025
2,355
"""Import required Metric.""" from .metrics import IV_scorer __all__ = ["IV_scorer"]
86
31
import copy from django.conf import settings from django.test.utils import override_settings from rest_framework import status, test class PermissionsTest(test.APITransactionTestCase): """ Abstract class for permissions tests. Methods `get_urls_configs`, `get_users_with_permission`, `get_users_witho...
5,297
1,435
""" CutBlur Copyright 2020-present NAVER corp. MIT license """ import os import glob import data class BenchmarkSR(data.BaseDataset): def __init__(self, phase, opt): root = opt.dataset_root self.scale = opt.scale dir_HQ, dir_LQ = self.get_subdir() self.HQ_paths = sorted(glob.glob(o...
1,121
421
from ..utils import Object class UpdateChatIsPinned(Object): """ A chat was pinned or unpinned Attributes: ID (:obj:`str`): ``UpdateChatIsPinned`` Args: chat_id (:obj:`int`): Chat identifier is_pinned (:obj:`bool`): New value of is_pinned ...
917
316
import io import time import todoist def test_stats_get(api_endpoint, api_token): api = todoist.api.TodoistAPI(api_token, api_endpoint) response = api.completed.get_stats() assert 'days_items' in response assert 'week_items' in response assert 'karma_trend' in response assert 'karma_last_upda...
30,162
10,660
from setuptools import setup import iotio with open("README.md", "r") as fh: long_description = fh.read() setup( name="iot.io", version=iotio.__version__, packages=["iotio"], author="Dylan Crockett", author_email="dylanrcrockett@gmail.com", license="MIT", description="A management API ...
990
324
import os import requests from trellominer.config import yaml class HTTP(object): def __init__(self): self.config = yaml.read(os.getenv("TRELLO_CONFIG", default=os.path.join(os.path.expanduser('~'), ".trellominer.yaml"))) self.api_url = os.getenv("TRELLO_URL", default=self.config['api']['url'])...
1,820
635
import numpy as np import tensorflow as tf import os from scipy.io import savemat from scipy.io import loadmat from scipy.misc import imread from scipy.misc import imsave from alexnet_face_classifier import * import matplotlib.pyplot as plt plt.switch_backend('agg') class backprop_graph: def __init__(self, num_...
2,337
933
"""Registry and RegistryMixin tests.""" from types import SimpleNamespace import pytest from coaster.db import db from coaster.sqlalchemy import BaseMixin from coaster.sqlalchemy.registry import Registry # --- Fixtures ------------------------------------------------------------------------- @pytest.fixture() def...
18,729
5,511
# -*- coding: utf-8 -*- # Generated by Django 1.9.13 on 2018-02-06 16:25 from __future__ import unicode_literals from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('wagtailcore', '0028_merge'), ('home', '0009_remove_...
1,311
419
import pytest from nesta.packages.misc_utils.guess_sql_type import guess_sql_type @pytest.fixture def int_data(): return [1,2,4,False] @pytest.fixture def text_data(): return ['a', True, 2, ('A very long sentence A very long sentence A ' 'very long sentence A very long sentence'), 'd...
900
343
# -*- coding: utf-8 -*- '''活动管理接口''' from flask import request from model.db import database, Activity, ActivityMember, Demand, ActivityBase, ProjectMember, User from model.role import identity from flask_jwt_extended import (fresh_jwt_required) def demand_activity_add(activity_id, data): '''添加活动需求''' for d...
4,239
1,261
# Easy # https://leetcode.com/problems/palindrome-number/ # Time Complexity: O(log(x) to base 10) # Space Complexity: O(1) class Solution: def isPalindrome(self, x: int) -> bool: temp = x rev = 0 while temp > 0: rev = rev * 10 + temp % 10 temp //= 10 return re...
326
120
from .manager import Manager # NOQA from .call_manager import CallManager # NOQA from . import fast_agi # NOQA
114
38
# -*- coding: utf-8 -*- """ Python library for Paessler's PRTG (http://www.paessler.com/) """ import logging import xml.etree.ElementTree as Et from urllib import request from prtg.cache import Cache from prtg.models import Sensor, Device, Status, PrtgObject from prtg.exceptions import BadTarget, UnknownResponse cl...
4,762
1,284
import tensorflow as tf from tensorflow.python.training.session_run_hook import SessionRunArgs # Define data loaders ##################################### # See https://gist.github.com/peterroelants/9956ec93a07ca4e9ba5bc415b014bcca class IteratorInitializerHook(tf.train.SessionRunHook): """Hook to initialise data...
3,303
982
parsers = ['openmm.unit', 'pint', 'unyt'] def digest_parser(parser: str) -> str: """ Check if parser is correct.""" if parser is not None: if parser.lower() in parsers: return parser.lower() else: raise ValueError else: from pyunitwizard.kernel import default...
359
103
''' Copyright (c) Facebook, Inc. and its affiliates. All rights reserved. This source code is licensed under the license found in the LICENSE file in the root directory of this source tree. Code taken from: https://github.com/facebookresearch/wsd-biencoders/blob/master/wsd_models/util.py ''' import os import re impo...
6,606
2,620
#!/usr/bin/env python3 from typing import Dict, AnyStr from pathlib import Path from ontopy import get_ontology import dlite from dlite.mappings import make_instance # Setup dlite paths thisdir = Path(__file__).parent.absolute() rootdir = thisdir.parent.parent workflow1dir = rootdir / '1-simple-workflow' entitiesdir...
2,825
912
from flask_wtf import FlaskForm from flask_wtf.file import FileField, FileAllowed, FileRequired from wtforms import StringField, PasswordField, BooleanField, TextAreaField, SubmitField, RadioField, HiddenField from wtforms.fields.html5 import DateField, IntegerField from wtforms.validators import ValidationError, DataR...
6,479
1,784
from builtins import range from ..base import MLClassifierBase from ..utils import get_matrix_in_format from sklearn.neighbors import NearestNeighbors import scipy.sparse as sparse import numpy as np class BinaryRelevanceKNN(MLClassifierBase): """Binary Relevance adapted kNN Multi-Label Classifier.""" def __i...
3,381
1,041
"""Constants about the Gro ontology that can be imported and re-used anywhere.""" REGION_LEVELS = { 'world': 1, 'continent': 2, 'country': 3, 'province': 4, # Equivalent to state in the United States 'district': 5, # Equivalent to county in the United States 'city': 6, 'market': 7, 'o...
931
381
""" Period benchmarks that rely only on tslibs. See benchmarks.period for Period benchmarks that rely on other parts fo pandas. """ from pandas import Period from pandas.tseries.frequencies import to_offset class PeriodProperties: params = ( ["M", "min"], [ "year", "mont...
1,535
522
#/usr/bin/python #-*- coding: utf-8 -*- #Refer http://www.wooyun.org/bugs/wooyun-2015-0137140 #__Author__ = 上善若水 #_PlugName_ = whezeip Plugin #_FileName_ = whezeip.py def assign(service, arg): if service == "whezeip": return True, arg def audit(arg): raw = ''' POST /defaultroot/custom...
1,894
863
# Use zip() to create a new variable called names_and_dogs_names that combines owners and dogs_names lists into a zip object. # Then, create a new variable named list_of_names_and_dogs_names by calling the list() function on names_and_dogs_names. # Print list_of_names_and_dogs_names. owners = ["Jenny", "Alexus", "Sa...
535
197
# -*- coding: utf-8 - # # This file is part of couchdbkit released under the MIT license. # See the NOTICE for more information. import os import sys if not hasattr(sys, 'version_info') or sys.version_info < (2, 5, 0, 'final'): raise SystemExit("couchdbkit requires Python 2.5 or later.") from setuptools import ...
1,593
515
from typing import Optional from complexheart.domain.criteria import Criteria from sqlalchemy import create_engine from sqlalchemy.engine import Engine from sqlalchemy.orm import sessionmaker from to_do_list.tasks.domain.models import Task from to_do_list.tasks.infrastructure.persistence.relational import RelationalT...
1,934
584
from jinja2.ext import Extension from jinja2 import nodes from jinja2 import Markup from wagtail.wagtailadmin.templatetags.wagtailuserbar import wagtailuserbar as original_wagtailuserbar from wagtail.wagtailimages.models import Filter, SourceImageIOError class WagtailUserBarExtension(Extension): tags = set(['wag...
2,934
823
from rta.provision.utils import * from rta.provision.passwd import * from rta.provision.influxdb import * from rta.provision.grafana import * from rta.provision.kapacitor import *
180
63
""" $lic$ Copyright (C) 2016-2020 by Tsinghua University and The Board of Trustees of Stanford University This program is free software: you can redistribute it and/or modify it under the terms of the Modified BSD-3 License as published by the Open Source Initiative. This program is distributed in the hope that it wi...
14,694
5,399
from django.urls import path from .views import DivisionListCreateAPIView, DivisionRetrieveUpdateDestroyAPIView, MainDivisionListAPIView urlpatterns = [ path('division/', DivisionListCreateAPIView.as_view()), path('division/<division_pk>', DivisionRetrieveUpdateDestroyAPIView.as_view()), path('division/m...
365
113
from sympy import (Derivative as D, Eq, exp, sin, Function, Symbol, symbols, cos, log) from sympy.core import S from sympy.solvers.pde import (pde_separate, pde_separate_add, pde_separate_mul, pdsolve, classify_pde, checkpdesol) from sympy.testing.pytest import raises a, b, c, x, y = symbols('a b c x y') def...
9,077
4,483
import torch import torch.nn.functional as F import pandas as pd import numpy as np from torch_geometric.data import Data from torch_geometric.nn import GCNConv, PairNorm from torch_geometric.utils.undirected import to_undirected import random import matplotlib.pyplot as plt data_name = 'citeseer' # 'cora' or 'ci...
6,376
2,430
import datetime import json from django.conf import settings from django.http import Http404 from django.utils import timezone from django.views import generic from .models import Event, FlatPage, News class HomeView(generic.ListView): """ View for the first page called 'Home'. """ context_object_na...
3,724
1,029
from dotenv import load_dotenv load_dotenv() from flask import Flask, flash, request, redirect, url_for from flask_ngrok import run_with_ngrok from flask_cors import CORS from werkzeug.utils import secure_filename import tensorflow as tf from tensorflow import keras from tensorflow.keras.applications import vgg16 fro...
3,509
1,250
import random import matplotlib.pyplot as plt import wandb import hydra import torch import torch.utils.data as data_utils from model import ChessPiecePredictor from torch import nn, optim from google.cloud import storage from torch.utils.data import DataLoader from torchvision import transforms from torchvision.datas...
4,555
1,478
# Copyright (c) Facebook, Inc. and its affiliates. # # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. import importlib import os from abc import ABC, abstractmethod from fairseq import registry from omegaconf import DictConfig class BaseSco...
1,386
449
import copy import unittest import networkx as nx import numpy as np from scipy.special import erf from dfn import Fluid, FractureNetworkThermal class TestFractureNetworkThermal(unittest.TestCase): def __init__(self, *args, **kwargs): super(TestFractureNetworkThermal, self).__init__(*args, **kwargs) ...
10,817
4,410
""" Author: Gustavo Amarante """ import numpy as np import pandas as pd from datetime import datetime class TrackerFeeder(object): """ Feeder for the trackers of the FinanceHub database. """ def __init__(self, db_connect): """ Feeder construction :param db_connect: sql connec...
10,775
3,335
from configparser import ConfigParser CONFIG_INT_KEYS = { 'hadoop_max_nodes_count', 'hadoop_ebs_volumes_count', 'hadoop_ebs_volume_size', 'spark_max_nodes_count', 'spark_ebs_volumes_count', 'spark_ebs_volume_size' } def read_config(config_path): parser = ConfigParser() parser.read(con...
569
189
from flask import Blueprint from .hooks import admin_auth from ...api_utils import * bp_admin_api = Blueprint('bp_admin_api', __name__) bp_admin_api.register_error_handler(APIError, handle_api_error) bp_admin_api.register_error_handler(500, handle_500_error) bp_admin_api.register_error_handler(400, handle_400_error)...
609
234
import pandas as pd import numpy as np import os import tensorflow as tf import functools ####### STUDENTS FILL THIS OUT ###### #Question 3 def reduce_dimension_ndc(df, ndc_df): ''' df: pandas dataframe, input dataset ndc_df: pandas dataframe, drug code dataset used for mapping in generic names return:...
6,083
2,033
import matplotlib.pyplot as plt import matplotlib as mpl import numpy as np import copy from core_tools.utility.plotting.plot_settings import plot_layout, graph_settings_1D, _1D_raw_plot_data from core_tools.utility.plotting.plot_general import _data_plotter class plotter_1D(_data_plotter): def __init__(self, plt_la...
5,354
2,515
# last edit date: 2016/11/2 # author: Forec # LICENSE # Copyright (c) 2015-2017, Forec <forec@bupt.edu.cn> # Permission to use, copy, modify, and/or distribute this code for any # purpose with or without fee is hereby granted, provided that the above # copyright notice and this permission notice appear in all copies. ...
5,110
1,536
from gdb.models import *
25
9
from .base import ArticleView, ArticlePreviewView, ArticleListView, SearchView, LandingView, \ CategoryView, TagView, SubscribeForUpdates, UnsubscribeFromUpdates from .ajax import GetArticleSlugAjax, TagsAutocompleteAjax from .errors import page_not_found, server_error
274
76
# by MrSteyk & Dogecore # TODO: extraction instructions & testing import json import os.path from typing import List import bpy loaded_materials = {} MATERIAL_LOAD_PATH = "" # put your path here # normal has special logic MATERIAL_INPUT_LINKING = { "color": "Base Color", "rough": "Roughness", "spec": ...
3,167
956
from django.db import models TASK_STATUS = ( ("c", "created"), ("p", "progress"), ("s", "success"), ("f", "failed") ) class TaskModel(models.Model): lastrunned = models.DateTimeField( "lastrunned", auto_now=False, auto_now_add=False) taskname = models.CharField("taskname", max_lengt...
636
223
# Copyright (c) 2018 European Organization for Nuclear Research. # 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/LIC...
3,291
876
import glob import numpy as np class Data: def __init__(self, path, random=False): """ input: path: path to the folder with subfolders: DSM, PAN, LABEL max_num: int, num of samples random: bool, to load samples randomly or from 0 to num_max ...
3,171
1,283