text
string
size
int64
token_count
int64
import numpy as np import mujoco_py as mj from mujoco_py_renderer import SimulationError, XMLError, MujocoPyRenderer from mujoco_py import (MjSim, load_model_from_xml,functions, load_model_from_path, MjSimState, ignore_mujoco_warnings, load_model_from...
4,668
2,253
import sys # package need to be installed, pip install docker import docker import time import yaml import os import xlwt auto = False private_registry = "202.114.10.146:9999/" # result result = [["tag", "finishTime", "size", "data"], ] class Puller: def __init__(self, images): self.images_to_pull =...
3,323
1,015
from jiminy.envs import vnc_env from jiminy.spaces import VNCActionSpace class WorldOfGooEnv(vnc_env.VNCEnv): def __init__(self): super(WorldOfGooEnv, self).__init__() # TODO: set action space screen shape to match # HACK: empty keys list fails for some weird reason, give it an 'a' ...
385
126
import copy import logging import random from typing import List, Tuple import numpy as np import torch import wandb from torch.utils.data import ConcatDataset from fedml_api.standalone.fedavg.my_model_trainer import MyModelTrainer from fedml_api.standalone.federated_sgan.ac_gan_model_trainer import ACGANModelTrainer...
5,066
1,494
#!/usr/bin/env python3 import argparse from collections import Counter import pdb import pickle import re import sys import time import numpy as np import torch import torch.nn as nn from torch.autograd import Variable from torch import optim import torch.nn.functional as F import torch.multiprocessing as mp import ...
20,932
6,989
sayi1 = int(input("1. Sayı: ")) sayi2 = int(input("2. Sayı: ")) sayi3 = int(input("3. Sayı: ")) sayi4 = int(input("4. Sayı: ")) sayi5 = int(input("5. Sayı: ")) sayilar=[]; sayilar.append(sayi1) sayilar.append(sayi2) sayilar.append(sayi3) sayilar.append(sayi4) sayilar.append(sayi5) sayilar.sort() print("En büyük sayimiz...
339
162
"""Deep Q learning graph The functions in this file can are used to create the following functions: ======= act ======== Function to chose an action given an observation Parameters ---------- observation: object Observation that can be feed into the output of make_obs_ph stochastic: bool...
8,899
2,679
import sys sys.path.append('../') import LMR_config as cfg import LMR_prior import numpy as np import pytest def test_prior_seed(): cfg_obj = cfg.Config(**{'core':{'seed': 2}}) prior_cfg = cfg_obj.prior prior_source = '20cr' datadir_prior = 'data' datafile_prior = '[vardef_template]_gridded_dat....
2,244
965
import os from dataloader.datasetDHF1K import DHF1K from torch.utils.data import DataLoader from utils.salgan_utils import save_model, get_lr_optimizer from utils.sendTelegram import send from utils.printer import param_print from utils.salgan_generator import create_model, add_bn from evaluation.fast_evaluation impor...
8,719
3,575
# encoding: utf-8 from django.db import models from wagtail.wagtailcore.models import Page from wagtail.wagtailcore.fields import StreamField from wagtail.wagtailcore import blocks from wagtail.wagtailadmin.edit_handlers import FieldPanel, StreamFieldPanel from wagtail.wagtailimages.blocks import ImageChooserBlock ...
782
223
# Copyright (c) 2021-Present (Prashanth Pradeep) # 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...
2,030
583
# -*- coding: utf-8 -*- """ Tencent is pleased to support the open source community by making 蓝鲸智云(BlueKing) available. Copyright (C) 2017 THL A29 Limited, a Tencent company. All rights reserved. Licensed under the MIT License (the "License"); you may not use this file except in compliance with the License. You may obt...
5,703
1,945
""" "멀티프로세싱"절 예시 `multiprocessing` 모듈을 이용해 새로운 프로세스들을 생성하는 방법을 설명한다. """ from multiprocessing import Process import os def work(identifier): print(f'Hey, I am the process ' f'{identifier}, pid: {os.getpid()}') def main(): processes = [Process(target=work, args=(number,)) for number in range(5)] for proc...
455
206
__author__ = '@dominofire' import os from sweeper.cloud import resource_config_combinations from sweeper.cloud.localhost import resource_config_factory as config_factory from sweeper.resource import Resource def possible_configs(num): configs = config_factory.list_configs() combs = resource_config_combinati...
670
212
# Copyright 2021 Google LLC. 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 a...
3,193
1,019
from __future__ import absolute_import, division, print_function import matplotlib import numpy as np import os import subprocess import sys import tempfile matplotlib.use('pdf') import matplotlib.pyplot as plt from abc import abstractmethod, ABCMeta from dragonn.metrics import ClassificationResult from sklearn.svm imp...
17,041
5,267
# -*- coding: utf-8 -*- # Generated by Django 1.11.10 on 2018-03-20 08:34 from __future__ import unicode_literals from django.db import migrations, models import django.db.models.deletion import parler.models class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ ...
3,866
1,046
import logging import random from dgt.graph.graph_matcher import GraphWeightedMatch from dgt.utils import graph_iterations _logger = logging.getLogger(__name__) def find_weight_between(s, first, last): try: start = s.index(first) + len(first) end = s.index(last, start) return s[start:end...
3,921
1,181
import argparse import cv2 import common # from .utils.cropAtCenter import cropImageCenter # from cropAtCenter import cropImageCenter from gabriel_client.websocket_client import WebsocketClient from gabriel_client.opencv_adapter import OpencvAdapter DEFAULT_SERVER_HOST = '128.2.212.50' DEFAULT_ZOOM_FACTOR = 10 def ...
1,528
542
from api import get_result import os import shutil from glob import glob from PIL import Image if __name__ == '__main__': image_files = glob('./test_images/*.*') result_dir = './test_results' if os.path.exists(result_dir): shutil.rmtree(result_dir) os.mkdir(result_dir) txt_file = os.path.j...
719
246
# Copyright (C) 2010-2011 Richard Lincoln # # 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...
4,106
1,571
from __future__ import unicode_literals class ParseError(Exception): def __init__(self, code, *args): self.code = code self.args = args self.message = get_error_message(code, args) def get_error_message(code, args): if code == 'E00001': return 'Generic error' if code == '...
2,432
767
# Copyright 2020 Curtin University # # 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 writi...
16,562
5,473
''' Created on Mar 22, 2018 Edited on Jan 11, 2019 @author: npvance2 @author: curtisd2 Variables that will need to be edited/personalized: monitorID in Variables() (line 27) projectStartDate in Variables() (line 28) projectEndDate in Variables() (line 29) authToken in getAuthToken() (...
14,084
3,793
#! /opt/cloud_sdk/bin/python import asyncio import logging import subprocess import sys import citc_cloud def handle_exception(exc_type, exc_value, exc_traceback): if issubclass(exc_type, KeyboardInterrupt): sys.__excepthook__(exc_type, exc_value, exc_traceback) return log.critical("Uncaugh...
1,286
451
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # # michael a.g. aïvázis # orthologue # (c) 1998-2018 all rights reserved # """ Verify that component registration interacts correctly with the pyre configurator model """ # access # print(" -- importing pyre") import pyre # print(" -- done") def declare(): # dec...
2,300
749
import asyncio from io import BytesIO import pytest from asyncssh.connection import SSHClientConnection from asyncssh.stream import SSHReader from scrapli.exceptions import ScrapliConnectionNotOpened, ScrapliTimeout class DumbContainer: def __init__(self): self.preferred_auth = () def __getattr__(s...
4,199
1,339
from django.shortcuts import get_object_or_404 import jingo import waffle from django.contrib.auth.models import User from challenges.models import Submission, Category from projects.models import Project from blogs.models import BlogEntry from events.models import Event def splash(request, project, slug, template_n...
3,699
1,066
from plotly.subplots import make_subplots import plotly.graph_objects as go import plotly.io as pio from dataProcessor import parseLabels, parseLangs import plotly.io as pio import os years = parseLabels() langs = parseLangs() #make the plotly results fig = make_subplots( rows=1, cols=2, specs=[[{"type": "x...
664
248
# Copyright 2019 BDL Benchmarks 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...
17,209
5,550
# # PySNMP MIB module CXConsoleDriver-MIB (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/CXConsoleDriver-MIB # Produced by pysmi-0.3.4 at Wed May 1 12:32:28 2019 # On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4 # Using Python version 3.7.3 (default...
4,902
1,677
# coding:utf-8 import datetime import json import re import redis from config.conf import get_redis_args redis_args = get_redis_args() class Cookies(object): rd_con = redis.StrictRedis(host=redis_args.get('host'), port=redis_args.get('port'), password=redis_args.get('password'), d...
2,782
961
import base64 import logging import msgpack logger = logging.getLogger(__name__) loadargs = {'use_list': False, 'raw': False} if msgpack.version < (1, 0, 0): loadargs['encoding'] = 'utf-8' else: loadargs['strict_map_key'] = False VSIG = b'MSGVIV'.ljust(8, b'\x00') def vivEventsAppendFile(filename, events)...
1,873
652
"""This forms the core of the pytest plugin.""" import pytest import testing.postgresql from pytest_pgsql import database from pytest_pgsql import ext def pytest_addoption(parser): """Add configuration options for pytest_pgsql.""" parser.addoption( '--pg-extensions', action='store', default='', ...
3,832
1,134
# written by abraham on aug 24 def dyear2date(dyear): year = int(dyear) month_lengths = [31,28,31,30,31,30,31,31,30,31,30,31] days_before_months = [0,31,59,90,120,151,181,212,243,273,304,334] days_into_year_f = (dyear-year)*365 days_into_year_i = int(days_into_year_f) for i in range(12): if days_before_mo...
737
405
import glob from os import walk exclude_folders = [ 'node_modules', 'ios', 'android', '__pycache__' ] exclude_files = [ 'json', 'txt', 'traineddata', 'lstmf', 'yml', 'md' 'log', 'env', 'gitignore', 'dockerignore' ] # get all files in directory dirr = '/home/vik...
752
260
from models.contact import Contact testdata = [Contact(first_name="Firstname", last_name="Lastname", mobile_phone="+12345678", work_phone="12345", home_phone="67890", fax="55443322", email_1="email_1@email.com", email_2="email_2@email.com", email_3="emai...
409
144
# Copyright 2014-2015 Canonical Limited. # # 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 ...
17,617
5,364
"""Implements the generic progress logger class, and the ProgressBar class. """ from tqdm import tqdm, tqdm_notebook from collections import OrderedDict import time SETTINGS = { 'notebook': False } def notebook(turn='on'): SETTINGS['notebook'] = True if (turn == 'on') else False def troncate_string(s, max_l...
13,250
3,861
import gdsfactory as gf from gdsfactory.component import Component yaml = """ name: test_component_yaml_without_cell instances: mmi: component: mmi1x2 bend: component: bend_s connections: bend,o1: mmi,o2 """ def test_component_from_yaml_without_cell() -> Component: """bezier does n...
665
248
from pathlib import Path from types import GeneratorType from typing import AsyncIterable, Iterable, TypeAlias import ujson from cats.errors import MalformedHeadersError try: from django.db.models import QuerySet, Model except ImportError: QuerySet = type('QuerySet', (list,), {}) Model = type('Model', (l...
2,681
860
from __future__ import absolute_import try: import urlparse as _urlparse except ImportError: from urllib import parse as _urlparse def register_scheme(scheme): for method in filter(lambda s: s.startswith('uses_'), dir(_urlparse)): uses = getattr(_urlparse, method) if scheme not in uses: ...
384
117
import setuptools setuptools.setup( name="monet_memory_optimized_training", version="0.0.1", description="Memory Optimized Network Training Framework", url="https://github.com/philkr/lowrank_conv", packages=setuptools.find_packages(include = ['monet', 'monet.*', 'models', 'checkmate', 'gist']), ...
516
165
# -*- coding: utf-8 -*- """ @date Created on Thu Dec 18 13:56:33 2014 @copyright (C) 2014-2015 EOMYS ENGINEERING. @author pierre_b """ from unittest import TestCase from ddt import ddt, data from pyleecan.Classes.Arc1 import Arc1 from pyleecan.Classes.Segment import Segment from pyleecan.Classes.MagnetType11 import...
5,616
2,339
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ """ from operator import mod from tomo_encoders.misc.voxel_processing import modified_autocontrast, TimerGPU from tomo_encoders.reconstruction.recon import recon_patches_3d import cupy as cp import numpy as np from skimage.filters import threshold_otsu from tomo_en...
4,600
1,943
# Generated by Django 2.2.1 on 2019-06-22 11:03 from django.db import migrations, models class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.CreateModel( name='SubscribeModel', fields=[ ('id', models.Aut...
833
246
# -*- coding: UTF-8 -*- import json from django.http import HttpResponse from django.views.decorators.csrf import csrf_exempt import tushare as ts from .publiceClass import DateEncoder @csrf_exempt def sh_margins(request): try: start = request.POST.get('start','')#选填 end = request.POST.get('end','...
793
348
class Camera: """docstring for .""" def __init__(self, brand, sensor, lens, battery): self.brand = brand self.sensor = sensor self.lens = lens self.battery = battery def __str__(self): return self.brand + ' ' + self.sensor + ' ' + self.lens + ' ' + self.battery ...
1,181
358
from mock import patch, MagicMock from django.contrib.auth.models import User from django.test import TestCase from django.core.urlresolvers import reverse from django.utils.datastructures import MultiValueDictKeyError from account.models import Role, Team, Organization from physical.tests.factory import EnvironmentF...
7,332
2,091
# Generated by Django 3.1.4 on 2021-05-05 21:16 from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('Main', '0071_auto_20210506_0004'), ] operations = [ migrations.RemoveField( model_name='product', name='chooseColor', ...
439
150
#!/usr/bin/python3 """ Good morning! Here's your coding interview problem for today. This problem was recently asked by Google. Given a list of numbers and a number k, return whether any two numbers from the list add up to k. For example, given [10, 15, 3, 7] and k of 17, return true since 10 + 7 is 17. Bonus: Can ...
788
265
import json import setuptools with open("template/README.md", "r") as fh: long_description = fh.read() with open('requirements.txt') as fr: requirements = fr.read().strip().split('\n') with open('metadata.json') as fr: metadata = json.load(fr) setuptools.setup( name="", # Name of the repository ...
734
235
""" @Time : 201/21/19 10:41 @Author : TaylorMei @Email : mhy845879017@gmail.com @Project : iccv @File : train_base3.py @Function: """ import datetime import os import torch from torch import nn from torch import optim from torch.autograd import Variable from torch.backends import cudnn from torch.ut...
6,558
2,389
import unittest from app.models import Comment, Pitch from app import db class TestPitchComment(unittest.TestCase): def setUp(self): self.new_pitch = Pitch(post = "doit", category='Quotes') self.new_comment = Comment(comment = "good comment", pitch=self.new_pitch) def test_instance(se...
574
179
from django.shortcuts import render from django.http import HttpResponse from django.contrib.auth.decorators import login_required from django.views.decorators.csrf import csrf_exempt from django.template import loader from django.db import connection from django.http import HttpResponseRedirect import datetime from dj...
3,584
940
import logging import pytest import re from . import text from ... import matchers from ...utils import answer, SimpleTrigger logger = logging.getLogger(__name__) @pytest.mark.asyncio async def test_should_run_story_on_equal_message(): trigger = SimpleTrigger() with answer.Talk() as talk: story = ta...
5,898
1,899
"""Objects representing API interface to Wikibase site.""" # # (C) Pywikibot team, 2012-2022 # # Distributed under the terms of the MIT license. # import datetime import json import uuid from contextlib import suppress from typing import Optional from warnings import warn import pywikibot from pywikibot.data import ap...
33,955
9,441
from flask import Flask from flask import render_template, request from flask import jsonify import requests import json app = Flask(__name__) @app.route("/symbo",methods=['POST']) def symbo(): #import pdb; pdb.set_trace() session = requests.session() token = session.get("https://es.symbolab.com/solver/s...
1,210
461
from pyspark.sql import SparkSession # spark = SparkSession.builder.master("local[*]").getOrCreate() spark = SparkSession.builder.getOrCreate() file_path = "C:\home_work\local_github\Spark-The-Definitive-Guide\data\/flight-data\csv\/2015-summary.csv" # COMMAND ---------- # COMMAND ---------- flightData2015 = spa...
1,584
659
import os import pickle import pytest import pandas as pd from shapely import wkt from intake_postgres import PostgresSource from intake import open_catalog from .util import verify_datasource_interface TEST_DATA_DIR = 'tests' TEST_DATA = [ ('sample1', 'sample1.csv'), ('sample2_1', 'sample2_1.csv'), ('sa...
7,508
2,706
# file = open('C:\\Users\\dks10\\OneDrive\\Desktop\\Projects\\Code\\Python\\PythonCrypto\\Module_3\\eye.png', 'rb') file = open('encrypt_eye.png', 'rb') image = file.read() file.close() image = bytearray(image) key = 48 for index, value in enumerate(image): image[index] = value^key file = open('2eye.png','wb') ...
351
136
import time import logging from ledfxcontroller.effects import Effect from threading import Thread import voluptuous as vol _LOGGER = logging.getLogger(__name__) DEFAULT_RATE = 1.0 / 60.0 @Effect.no_registration class TemporalEffect(Effect): _thread_active = False _thread = None CONFIG_SCHEMA = vol.Schem...
1,702
458
n=int(input()) c = 1 while c**2 < n: print(c**2) c += 1
62
35
import numpy as np class DataGenerator: def __init__(self, inputs, shuffle=True, batch_size=32): assert len(inputs) > 0 self.inputs = inputs self.idx = np.arange(len(inputs[0])) self.shuffle = shuffle self.batch_size = batch_size self.on_epoch_end() def data_le...
1,796
604
from nltk.tokenize import sent_tokenize, word_tokenize from nltk.corpus import stopwords import speech_recognition as sr import nltk from google_images_download import google_images_download response = google_images_download.googleimagesdownload() r = sr.Recognizer() with sr.Microphone() as source: print("Say some...
810
253
from dataclasses import dataclass @dataclass class Request: method: str path: str headers: dict body: bytes @dataclass class Response: status_code: int reason_phrase: str headers: dict body: bytes
231
71
# Copyright (c) 2009-2021 The Regents of the University of Michigan # This file is part of the HOOMD-blue project, released under the BSD 3-Clause # License. """MPI communicator.""" from hoomd import _hoomd import hoomd import contextlib class Communicator(object): """MPI communicator. Args: mpi_c...
6,596
1,833
from config import DataGeneratorCfg from sklearn.datasets.samples_generator import make_blobs import numpy as np def generate(): data, true_labels = make_blobs(n_samples=DataGeneratorCfg.n_samples, centers=DataGeneratorCfg.centers, cluster_std=DataGeneratorCfg.cluster_std, random_state=DataGeneratorCfg.random_stat...
464
151
import _ast from peon.src.project.file.function_def.function import FunctionLint class ReflectionAtLineFixture: empty_node = _ast.Pass is_instance_at_first_lvl = _ast.FunctionDef(id='isinstance', lineno=1) type_at_first_lvl = _ast.FunctionDef(id='type', lineno=1) is_instance_at_second_lvl = _ast.Func...
1,265
464
############################################################################### # # '''Website Database-connection-related features''' # # # ...
4,419
1,091
from minio import Minio import json import os from .Inspector import Inspector from .topic_model import topic_model #def handle(event): def handle(event, context): with open("/var/openfaas/secrets/minio-access-key") as f: access_key = f.read() with open("/var/openfaas/secrets/minio-secret-key") as f: ...
1,169
396
""" Proxmox VE exporter for the Prometheus monitoring system. """ import sys from argparse import ArgumentParser from pve_exporter.http import start_http_server def main(args=None): """ Main entry point. """ parser = ArgumentParser() parser.add_argument('config', nargs='?', default='pve.yml', ...
803
239
#SPDX-License-Identifier: MIT import logging, os, sys, time, requests, json from datetime import datetime from multiprocessing import Process, Queue import pandas as pd import sqlalchemy as s from workers.worker_base import Worker # NOTE: This worker primarily inserts rows into the REPO_INFO table, which serves the pr...
12,692
3,411
# coding: utf-8 from __future__ import print_function from __future__ import division from __future__ import absolute_import from __future__ import unicode_literals import argparse def parse_args_tolerance(): parser = argparse.ArgumentParser(description='just for tolerance') parser.add_argument("--tolerance"...
17,929
5,323
from fbs_runtime.application_context.PyQt5 import ApplicationContext, cached_property from fbs_runtime.platform import is_windows, is_mac # system imports import sys # module imports from PyQt5 import uic, QtWidgets from PyQt5.QtWidgets import QMessageBox import numpy as np import matplotlib.pyplot as plt import matp...
11,482
4,236
import io import logging import os import sys from PyQt5 import QtGui, QtCore, QtWidgets from helpus import icon_file_path from helpus import __version__ LOGGER = logging.getLogger('HelpUs') LOGGER.setLevel(logging.DEBUG) class XStream(QtCore.QObject): _stdout = None _stderr = None messageWritten = QtCo...
9,832
2,878
import math class Schedule(): def __init__(self, total, batch_size): self._batch_size = batch_size self._state = "" self.total = total self.scheduled = 0 self.finished = 0 @property def _batch(self): return math.ceil(self.scheduled / self._batch_size) ...
2,206
682
# -*- coding: utf-8 -*- import asyncio import os import sys root = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) sys.path.append(root + '/python') import ccxt.async as ccxt # noqa: E402 async def test_gdax(): gdax = ccxt.gdax() markets = await gdax.load_markets() await g...
447
181
__author__ = 'Rio'
19
10
from abc import ABCMeta, abstractmethod class DataWrapper: """Interface for access to datasets.""" __metaclass__ = ABCMeta @abstractmethod def next(self): """Returns next minibatch for training.""" return NotImplementedError
261
72
from __future__ import absolute_import import os import shutil import locket import string from toolz import memoize from contextlib import contextmanager from .utils import nested_get, flatten # http://stackoverflow.com/questions/295135/turn-a-string-into-a-valid-filename-in-python valid_chars = "-_.() " + string....
2,307
731
''' model ensemble for cifar10 // input size(32,32) ''' import torch import torchvision import copy import torch.nn as nn from resnetv2 import ResNet50 as resnet50v2 def split_resnet50(model): return nn.Sequential( model.conv1, model.layer1, model.layer2, mode...
1,248
546
# -*- coding: utf-8 -*- """ Function that implement Complement the Complementary Cumulative Distribution Function (CCDF). """ # # written by Chengcheng Shao <sccotte@gmail.com> import numpy as np import pandas as pd def ccdf(s): """ Parameters: `s`, series, the values of s should be variable to be ha...
1,519
556
# -*- coding: utf-8 -*- from __future__ import print_function import numpy as np import pandas as pd from lifelines.fitters import UnivariateFitter from lifelines.utils import _preprocess_inputs, _additive_estimate, StatError, inv_normal_cdf,\ median_survival_times from lifelines.plotting import plot_loglogs cla...
5,335
1,601
import numpy as np from pydmfet import tools from .fermi import find_efermi, entropy_corr from pyscf import ao2mo, gto, scf, dft, lib from pydmfet.qcwrap import fermi import time from functools import reduce def scf_oei( OEI, Norb, Nelec, smear_sigma = 0.0): OEI = 0.5*(OEI.T + OEI) eigenvals, eigenvecs = np.l...
8,498
3,706
#!/usr/bin/env python # # Copyright Amazon.com, Inc. or its affiliates. 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. # A copy of the License is located at # # http://www.apache.org/licenses/LICENS...
2,470
792
# pylint:disable=line-too-long import logging from ...sim_type import SimTypeFunction, SimTypeShort, SimTypeInt, SimTypeLong, SimTypeLongLong, SimTypeDouble, SimTypeFloat, SimTypePointer, SimTypeChar, SimStruct, SimTypeFixedSizeArray, SimTypeBottom, SimUnion, SimTypeBool from ...calling...
91,209
29,357
"""Define the aiolookin package.""" from .device import async_get_device # noqa
81
27
# -*- coding: utf-8 -*- from .common import loadOde from .common import dGeomID from .common import dSpaceID from .common import dVector3 from ctypes import POINTER from ctypes import CFUNCTYPE from ctypes import c_void_p from ctypes import c_int32 dNearCallback = CFUNCTYPE(None, c_void_p, dGeomID, dGeomID) def dSi...
2,067
805
class BSTNode: def __init__(self, data = None) -> None: self.data = data self.left = None self.right = None def __repr__(self) -> str: return(f"BSTNode({self.data})") def __str__(self) -> str: return str(self.data) def __eq__(self, o: object) -> ...
1,563
496
#!/usr/bin/python3 # pip3 install websockets import asyncio import websockets import json import datetime import sys class test_publish: idnum = 1 def __init__( self, sym, price, spread ): self.symbol = sym self.pidnum = test_publish.idnum test_publish.idnum += 1 self.sidnum = test_publish.idnum ...
4,279
1,473
''' Given an array of intervals, merge all overlapping intervals, and return an array of the non-overlapping intervals that cover all the intervals in the input. Input: intervals = [[1,3],[2,6],[8,10],[15,18]] Output: [[1,6],[8,10],[15,18]] Explanation: Since intervals [1,3] and [2,6] overlaps, merge them into [1,6]....
1,866
632
"""Unit tests.""" import inspect import json from mock import Mock import os import sys import uuid import pytest # Add the lambda directory to the python library search path lambda_dir = os.path.join( os.path.dirname(inspect.getfile(inspect.currentframe())), '..') sys.path.append(lambda_dir) import lambdautils...
9,708
3,430
import os from testr.packages import make_regress_files regress_files = ['starcheck.txt', 'starcheck/pcad_att_check.txt'] clean = {'starcheck.txt': [(r'\s*Run on.*[\n\r]*', ''), (os.environ['SKA'], '')], 'starcheck/pcad_att_check.txt': [(os.environ['SKA'], '')]} m...
366
127
""" WSGI config for testsite project. This module contains the WSGI application used by Django's development server and any production WSGI deployments. It should expose a module-level variable named ``application``. Django's ``runserver`` and ``runfcgi`` commands discover this application via the ``WSGI_APPLICATION``...
1,714
501
#!/usr/bin/env python3 -u # -* encoding: utf-8 *- import argparse import asyncore import json import logging import signal import sys import os from types import FrameType from typing import Tuple, Sequence, Any, Union, Optional, List, Dict from concurrent.futures import ThreadPoolExecutor as Pool import daemon from...
11,269
3,333
import requests from bs4 import BeautifulSoup, element class Indeed: def __init__(self, words, location, offset): self.url = "https://www.indeed.com/jobs?as_and={}&l={}&sort=date&start={}".format( "+".join(set(d.strip().lower() for d in words.split(",") if d)), "+".join(list(d.lowe...
2,074
571
from django.conf import settings from django.core.exceptions import ImproperlyConfigured from product_details import settings_defaults def settings_fallback(key): """Grab user-defined settings, or fall back to default.""" try: return getattr(settings, key) except (AttributeError, ImportError, Imp...
748
211
# CPU: 0.06 s possessed, found, condition = map(int, input().split()) possessed += found count = 0 while possessed >= condition: div, mod = divmod(possessed, condition) count += div possessed = div + mod print(count)
229
74
""" Copyright 2017-2018 yhenon (https://github.com/yhenon/) Copyright 2017-2018 Fizyr (https://fizyr.com) 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-...
6,405
2,112