id
stringlengths
3
8
content
stringlengths
100
981k
1779020
from pyecharts import Sankey, Page, Style from app.charts.constants import HEIGHT, WIDTH ENERGY = { "nodes": [ { "name": "Agricultural 'waste'" }, { "name": "Bio-conversion" }, { "name": "Liquid" }, { "name": "L...
1779082
import parmed.unit as units from intermol.decorators import accepts_compatible_units from intermol.forces.abstract_bond_type import AbstractBondType class ConnectionBondType(AbstractBondType): __slots__ = ['order', 'c'] @accepts_compatible_units(None, None, order=None, ...
1779123
from context import tkmvvm class TestModel(tkmvvm.model.Model): # properties can be stored either in the Model, or on the ViewModel entry_data = "A quick brown fox jumps over the lazy dog" toggle = False items = []
1779157
import signal import sys import IPython from blocks.extensions import SimpleExtension class EmbedIPython(SimpleExtension): def __init__(self, use_main_loop_run_caller_env=False, **kwargs): super(EmbedIPython, self).__init__(every_n_batches=1) self.sig_raised = False self.use_main_loop_ru...
1779160
from httmock import urlmatch, HTTMock import unittest import json from raco.backends.myria.connection import MyriaConnection from raco.backends.myria.catalog import MyriaCatalog from raco.relation_key import RelationKey from raco.representation import RepresentationProperties import raco.myrial.interpreter as interpr...
1779183
import unittest import numpy as np from numpy.random import RandomState from trojai.datagen.datatype_xforms import ToTensorXForm from trojai.datagen.image_entity import GenericImageEntity class TestDatatypeTransforms(unittest.TestCase): def setUp(self): pass def test_ToTensor1(self): img = G...
1779186
from abc import abstractmethod from typing import Any class IExports: @abstractmethod def chdir(self, __arg0: str) -> None: ... @abstractmethod def chroot(self, __arg0: str) -> None: ... @abstractmethod def close(self, fd: int) -> None: ... ...
1779193
import torch import matplotlib.pyplot as plt import torchvision.transforms as transforms from mpl_toolkits.axes_grid1 import ImageGrid from skimage.exposure import match_histograms from PIL import Image from torchvision.transforms.functional import InterpolationMode from utils import * def train_st(config, dataload...
1779198
import sentencepiece as spm import sys input = sys.argv[1] vocab = sys.argv[2] if len(sys.argv) > 3: opt = sys.argv[3] else: opt = input+".bpe" sp = spm.SentencePieceProcessor() sp.Load(vocab) with open(input, "r", encoding="utf-8") as fin, open(opt, "w", encoding="utf-8") as fout: for line in fin: ...
1779201
import logging import os from files.user_file_storage import UserFileStorage from utils.file_utils import normalize_path RESULT_FILES_FOLDER = 'uploadFiles' LOGGER = logging.getLogger('script_server.file_upload_feature') class FileUploadFeature: def __init__(self, user_file_storage: UserFileStorage, temp_folde...
1779209
from functools import reduce from traceback import format_exc from typing import Any, Callable, Dict, Tuple, Union class Logger(): @staticmethod def error(message: str) -> None: print(f"[\033[91mE\033[0m]: \033[1m{message}\033[0m") @staticmethod def warn(message: str) -> None: print(f...
1779246
import torch import torch.nn as nn import os import time import statistics import copy import numpy as np import gzip import pickle from agents.GTN_base import GTN_Base from envs.env_factory import EnvFactory from agents.agent_utils import select_agent class GTN_Worker(GTN_Base): def __init__(self, id, bohb_id=-1...
1779341
import urllib import urllib.request import re from datetime import datetime from bs4 import BeautifulSoup from pprint import pprint from BaseParser import BaseParser class RIA(BaseParser): """docstring for RIA""" def __init__(self): super(RIA, self).__init__( 'RIA', 'https://ria.ru',...
1779343
import dataclasses import json import logging from dataclasses import dataclass, field from typing import Any, Dict, Optional, Tuple import torch from transformers import MODEL_WITH_LM_HEAD_MAPPING from transformers.training_args import is_torch_tpu_available from transformers.file_utils import cached_prope...
1779345
from .base import * class BoundDropout(Bound): def __init__(self, input_name, name, ori_name, attr, inputs, output_index, options, device): super().__init__(input_name, name, ori_name, attr, inputs, output_index, options, device) self.dropout = nn.Dropout(p=attr['ratio']) self.scale = 1 / (...
1779346
import datetime from lib.model.database.Database import Database from sqlalchemy import Column, Integer, String, Date, DateTime, ForeignKey Base = Database.get_declarative_base() class AntiEmulator(Base): __tablename__ = 'anti_emulator' id = Column(Integer, primary_key=True) property = Column(String) ...
1779399
from __future__ import print_function import argparse import torch import torch.nn as nn import torch.nn.functional as F import torch.optim as optim from torchvision import datasets, transforms import numpy as np import matplotlib.pyplot as plt import tensorflow as tf from torch.utils.data import Dataset, DataLoader fr...
1779430
import os from compas_slicer.utilities import load_from_json from compas_slicer.slicers import PlanarSlicer from compas_viewers.objectviewer import ObjectViewer ######################## Logging import logging logger = logging.getLogger('logger') logging.basicConfig(format='%(levelname)s-%(message)s', level=logging.I...
1779431
import torch import torch.nn as nn import torch.nn.functional as F import dgl from dgl.geometry import farthest_point_sampler ''' Part of the code are adapted from https://github.com/yanx27/Pointnet_Pointnet2_pytorch ''' def square_distance(src, dst): ''' Adapted from https://github.com/yanx27/Pointnet_Point...
1779529
from datetime import datetime from decimal import Decimal import logging, sys, os from shutil import copyfile import sqlalchemy # import sqlalchemy_utils from logic_bank_utils import util as logic_bank_utils (did_fix_path, sys_env_info) = \ logic_bank_utils.add_python_path(project_dir="LogicBank", my_file=__file...
1779545
class ModelConfig(object): def __init__(self, vocab_size, nb_class, kernel_sizes=(7, 7, 3, 3, 3, 3), nb_filter=256, dense_units=(1024, 1024), maxlen=1014, keep_prob=0.5, ): ...
1779550
from pathlib import Path import torch.nn as nn import torch.nn.functional as F import torch.optim as optim from torch.utils.data.dataloader import DataLoader import pytorch_lightning as pl from .datasets import DatasetFromFolder from .networks import SRCNN class SRCNNModel(pl.LightningModule): def __init__(self...
1779556
import logging from unittest.mock import MagicMock import pytest from fixtures.senza import mock_senza # NOQA @pytest.fixture(scope='session') def debug_level(): logging.getLogger().setLevel(logging.DEBUG)
1779626
import os import pandas import numpy from calendar import formatstring from CommonDef.DefStr import * from unittest.mock import inplace def SymbolToPath(symbol, save_dir = "data"): """Return CSV file path given ticker symbol.""" return os.path.join(save_dir, "{}.csv".format(str(symbol))) def CalChange(now, ...
1779636
from api.mon.backends.abstract import AbstractMonitoringBackend from api.mon.backends.abstract.server import AbstractMonitoringServer # noinspection PyAbstractClass class DummyMonitoring(AbstractMonitoringBackend): pass class DummyMonitoringServer(AbstractMonitoringServer): """ Dummy model for represent...
1779644
from datetime import datetime import traceback import flask_restful as restful from flask_restful import reqparse, fields, marshal_with, marshal from sqlalchemy.exc import SQLAlchemyError from flask import g from app.applicationModel.models import ApplicationForm, Question, Section, SectionTranslation, QuestionTrans...
1779674
from maya.api import OpenMaya from mango.fields import generic __all__ = [ "IntegerArrayField", "FloatArrayField", ] class IntegerArrayField(generic.IntegerField): """ The IntegerArrayField can be used to set and retrieve int multi values. If the provided value is not a list containing integer ...
1779684
from subprocess import (Popen, PIPE) import os import csv import json from .ts import (convert_datetime, date_index) import pandas as pd from sensible.loginit import logger log = logger(__name__) #Git Globals GIT_COMMIT_FIELDS = ['id', 'author_name', 'author_email', 'date', 'message'] GIT_LOG_FORMAT = ['%H', '%an',...
1779698
import abc #CLASE ABSTRACTA class Page(metaclass=abc.ABCMeta): @abc.abstractmethod def url(self): pass def folder(self): pass def link(self): pass def titulo(self): pass def desc(self): pass def fromato(self): pass #CLASE BASE IMPLEMENTAMOS C...
1779736
from struct import unpack_from from .. import VendorSpecificEvent from hci.transforms import _bytes_to_hex_string class ATT_HandleValueNotification(VendorSpecificEvent): @property def conn_handle(self): OFFSET, SIZE_OCTETS = 6, 2 conn_handle = self._get_data(OFFSET, SIZE_OCTETS) retur...
1779770
import numpy as np from scipy.special import jv # Bessel Function of the first kind from scipy.linalg import eig from scipy.fftpack import fftn, ifftn, ifft # import progressbar from tqdm import tqdm from scipy.ndimage import filters as fi import math # An implementation of the Optimally Oriented # <NAME> and <NAME>,...
1779783
import os import json import pandas as pd mappings = { "English": "eng", "Japanese": "jpn", "French": "fra", "Italian": "ita", "German": "deu", "Spanish": "spa", "Russian": "rus", "Polish": "pol", "Korean": "kor", "traditional Chinese": "chi_tra", "Simplified Chinese": "chi...
1779804
from bench import bench def fib(n): a, b = 0, 1 for _ in range(n): a, b = b, a b += a return b def test(): fib(20) print(int(bench(10000)))
1779821
from __future__ import unicode_literals import os.path, shutil from django.core.management.base import BaseCommand, CommandError from django.conf import settings from require.conf import settings as require_settings def default_staticfiles_dir(): staticfiles_dirs = getattr(settings, "STATICFILES_DIRS", ()) ...
1779851
from networkx.algorithms.euler import is_eulerian from networkx.algorithms.efficiency_measures import global_efficiency from networkx.algorithms.efficiency_measures import local_efficiency from networkx.algorithms.distance_regular import is_distance_regular from networkx.algorithms.components import number_connected_co...
1779855
import dpath.util def test_search_paths_with_separator(): dict = { "a": { "b": { "c": { "d": 0, "e": 1, "f": 2, }, }, }, } paths = [ 'a', 'a;b', 'a;b;...
1779895
import os from misc.get_samples_ordered_by_order_list import get_samples_ordered_by_order_list def write_summary(out_path, genes_by_merged_signature, meta_genes, global_variables, mde_dict): # append total genes and z scores to data summary_data = {} counter = 1 for key in meta_genes: meta_ge...
1779919
from .sourcemeter import Keithley class K2400(Keithley): def __init__(self, address): super().__init__(address) self.name = "Keithley 2400"
1779959
from dbnd import task def f1(): pass def f2(): pass def f3(): pass def f4(): pass def f5(): pass @task def f6(): pass
1779963
import torch import mmcv import numpy as np import pycocotools.mask as maskUtils import cv2 from mmdet.core import get_classes, tensor2imgs from mmdet.core import bbox2result, bbox_mapping_back, multiclass_nms from ..registry import DETECTORS from .single_stage import SingleStageDetector from mmdet.patches i...
1779998
import pytest from sanic import Sanic from sanic.response import json from sanic.websocket import WebSocketProtocol from sanic_jwt_extended.decorators import jwt_optional from sanic_jwt_extended.jwt_manager import JWT from tests.utils import DunnoValue @pytest.yield_fixture def app(): app = Sanic() with JWT...
1780062
from unittest import TestCase import Aggregator from SmellDetector import Constants as CONSTS, Analyzer class TestAggregator(TestCase): def test_aggregate(self): outFileName = "/Users/Tushar/Documents/Research/PuppetQuality/Puppet-lint_aggregator/testOut.csv" outFile = open(outFileName, 'w') ...
1780071
TEST_TEMPLATE = '{value:.3f} {sign} {delta:.3f} | test {result}' def get_test_result(value, delta): return ['<', 'passed 👌'] if value < delta else ['>=', 'failed 😭'] def format_test_result(value, delta, k=None): template = TEST_TEMPLATE if k: template = 'k = {k} | ' + TEST_TEMPLATE sign, r...
1780072
from PyQt5 import QtCore, QtWidgets, QtMultimedia class AudioDialog(QtWidgets.QDialog): def __init__(self, *args, **kwargs): super(AudioDialog, self).__init__(*args, **kwargs) self.setWindowTitle("Audio Devices") self.device_index = -1 self.device_rate_index = -1 self.device...
1780123
import os import time import logging from bag.io import get_encoding from BPG.abstract_plugin import AbstractPlugin try: import cybagoa except ImportError: cybagoa = None class OAPlugin(AbstractPlugin): def __init__(self, config): AbstractPlugin.__init__(self, config) self.config = confi...
1780189
from pytorch3d.structures import Pointclouds from pytorch3d.renderer import compositing from pytorch3d.renderer.points import rasterize_points import numpy as np import torch from torch import nn import nvdiffrast.torch as dr from utils.defaults import DEFAULTS import os import pytorch3d class RasterizePointsXYsBle...
1780218
import FWCore.ParameterSet.Config as cms MuonTransientTrackingRecHitBuilderESProducer = cms.ESProducer("MuonTransientTrackingRecHitBuilderESProducer", ComponentName = cms.string('MuonRecHitBuilder') )
1780262
import sys import time from orders.models import Order """ Plug-in example for an Orchestration Action at the "Order Approval" trigger point. May change CloudBolt's default approval behavior to implement custom logic or integrate with an external change management system. The context passed to the plug-in includes t...
1780295
from pyFHE.trlwe import trlweSymEncryptlvl2, trlweSymDecryptlvl2 from pyFHE.trgsw import trgswfftSymEncryptlvl2, trgswfftExternalProductlvl2 from pyFHE.key import SecretKey from pyFHE.mulfft import PolyMullvl2Long import numpy as np np.set_printoptions(threshold=5000) for i in range(100): sk = SecretKey(500,2.44e-...
1780344
from playdom import GameState def initializeGame(p, k, s): g = GameState() g.initializeGame(p, k, s) return g def buyCard(c,g): return g.currentPlayer().buy(c,0) def endTurn(g): g.nextPlayer().startTurn() def isGameOver(g): g.isGameOver() def numHandCards(g): return len(g.currentPlayer().hand) def handCard...
1780358
def get_smaller_right(arr): smaller_right_arr = list() for i in range(len(arr)): smaller_count = 0 for j in range(i + 1, len(arr)): if arr[j] < arr[i]: smaller_count += 1 smaller_right_arr.append(smaller_count) return smaller_right_arr # Tests assert g...
1780379
from __future__ import absolute_import, division, print_function import copy import logging import pytest import six import numpy as np from numpy.testing import (assert_equal, assert_array_almost_equal, assert_array_equal, assert_raises) from skbeam.core.fitting.base.parameter_data import ...
1780382
import json from django import forms from django.utils import timezone from u2flib_server import u2f class SecondFactorForm(forms.Form): def __init__(self, *args, **kwargs): self.user = kwargs.pop('user') self.request = kwargs.pop('request') self.appId = kwargs.pop('appId') return ...
1780386
import pandas as pd data = {'age': [38, 49, 27, 19, 54, 29, 19, 42, 34, 64, 19, 62, 27, 77, 55, 41, 56, 32, 59, 35], 'distance': [6169.98, 7598.87, 3276.07, 1570.43, 951.76, 139.97, 4476.89, 8958.77, 1336.44, 6138.85, 2298.68, 1167.92, 676.30, 736.85, 1...
1780407
import logging from .. import Config, Module from .service import LogManIOService # L = logging.getLogger(__name__) # Config.add_defaults( { 'logman.io': { 'url': 'amqps://{username}:{password}@feed.logman.io:5477/{virtualhost}', 'username': 'testuser', 'password': 'password', 'virtualhost': 'playgr...
1780422
import FWCore.ParameterSet.Config as cms ecalMustacheSCParametersESProducer = cms.ESProducer("EcalMustacheSCParametersESProducer", sqrtLogClustETuning = cms.double(1.1), # Parameters from the analysis by <NAME> [https://indico.cern.ch/event/949294/contributions/3988389/attachments/2091573/3514649/2020_08_26_C...
1780433
import serial import time import _thread import sys import os currentdir = os.path.dirname(os.path.realpath(__file__)) parentdir = os.path.dirname(currentdir) sys.path.append(parentdir) import robot_util try: ser = serial.Serial(port='/dev/ttyUSB0', baudrate=115200) except Exception as e: print("serial error ...
1780456
import json import time from threading import Thread import requests class HSocket: """ Client HSocket that communicates with the remote server HSocket """ def __init__(self, host, auto_connect=True): # type: (str, bool) -> None """ Initializes the HSocket :pa...
1780466
import os from pathlib import Path from typing import Optional from basis.cli.services.output import prompt_path def resolve_graph_path( path: Path, exists: bool, create_parents_if_necessary: bool = True ) -> Path: """Resolve an explicitly given graph location to a yaml""" if path.is_dir(): f = p...
1780467
from ledfxcontroller.config import save_config from ledfxcontroller.api import RestEndpoint from aiohttp import web import logging import json _LOGGER = logging.getLogger(__name__) class DevicesEndpoint(RestEndpoint): """REST end-point for querying and managing devices""" ENDPOINT_PATH = "/api/devices" ...
1780508
from datetime import timedelta import airflow from airflow.models import DAG from airflow.operators.bash_operator import BashOperator from airflow.operators.python_operator import PythonOperator # from airflow.operators.papermill_operator import PapermillOperator from src.preprocessing import preprocessing from src.tr...
1780575
import torch.nn as nn import segmentation_models_pytorch as smp import torch from torch.cuda.amp import autocast class seg_qyl(nn.Module): def __init__(self, model_name, n_class): super(seg_qyl,self).__init__() self.model = smp.Unet(# UnetPlusPlus encoder_name=model_name, # c...
1780608
from .dualpol import (DualPolRetrieval, HidColors, get_xyz_from_radar, check_kwargs) from .dualpol import (VERSION, RNG_MULT, DEFAULT_WEIGHTS, BAD, DEFAULT_SDP, DEFAULT_DZ_RANGE, DEFAULT_DR_THRESH, DEFAULT_KW)
1780674
import click import operator import os import time import yaml from . import util from .chute import chute_find_field, chute_resolve_source from .controller_client import ControllerClient @click.group('store') @click.pass_context def root(ctx): """ Publish and install from the public chute store. By def...
1780734
import numpy as np import Utils from copy import deepcopy class CSDS: def __init__(self, total_num, global_positions): self.global_positions = deepcopy(global_positions) self.remain_positions = deepcopy(self.global_positions) self.total_num = total_num self.remain_lis...
1780813
import importlib import argparse import os from os.path import join, isdir from itertools import chain import torch as pt import torch.nn as nn from torch.nn import init from torch.utils.data import DataLoader import numpy as np from optimizer import OptimizerCollection def load_config(file): """ initialize...
1780836
import clr import math clr.AddReference('RevitAPI') from Autodesk.Revit.DB import * clr.AddReference("RevitNodes") import Revit clr.ImportExtensions(Revit.GeometryConversion) items = UnwrapElement(IN[0]) def GetCurvePoints(curve): return curve.GetEndPoint(0).ToPoint(), curve.GetEndPoint(1).ToPoint() def GetLocatio...
1780855
import random flag="ECS{81N4RY_534RCH_50AF9F479667C26EBF4EE74E956371D5}" def genpasswd(l): alphabet="abcdefghijklmnopqrstuvwxyz" return "".join([random.choice(alphabet) for _ in range(l)]) password=genpasswd(20)
1780858
import os import base64 import cv2 import pyotp import pyqrcode import png from pyzbar import pyzbar from cryptography.fernet import Fernet from config import ConfigTempAccess class OneTimePassword(): def __init__(self): self.totp = pyotp.TOTP(ConfigTempAccess.BASE_32_KEY) def get_new_base32_key(self...
1780867
class Link(object): def __init__(self, trexclient): self._client = trexclient self._link_states = {} def set_link(self, payload, port_ids): ports = list(range(len(port_ids))) if payload.port_names is not None and len(payload.port_names) > 0: ports = [] ...
1780898
from lib.elbo_depth import gaussian_log_prob, laplacian_log_prob from lib.utils.torch_utils import apply_dropout from tqdm import tqdm import torch import numpy as np import cv2 import matplotlib.pyplot as plt from time import time def _compute_runtime_mcd_depth(model, X_test, S=50): model.eval() model.apply(apply_...
1780925
from flask import current_app import pytest from tests.test_bootstrap4.test_themes import themes bootstrap5_themes = themes + [ 'morph', 'quartz', 'vapor', 'zephyr', ] @pytest.mark.parametrize('theme', bootstrap5_themes) def test_bootswatch_local(theme, client): current_app.config['BOOTSTRAP_SER...
1780931
import unittest class CircularList(list): ''' A list that wraps around instead of throwing an index error. Works like a regular list: >>> cl = CircularList([1,2,3]) >>> cl [1, 2, 3] >>> cl[0] 1 >>> cl[-1] 3 >>> cl[2] 3 Except wraps around: ...
1780949
import unittest import mock import shutil import tempfile from rime.plugins import markdownify_full from rime.util import struct class TestMarkdownifyProject(unittest.TestCase): def setUp(self): self.tmpdir = tempfile.mkdtemp() project = markdownify_full.Project('project', self.tmpdir, None) ...
1780952
from django.conf import settings from pathlib import Path import os import datetime import logging import time import threading import re from django.urls import reverse import markdown import subprocess def mimetype_to_icon(mimetype): type2icon = { 'image': 'file-picture', 'audio': 'file-music', ...
1780955
import torch import torch.nn as nn import torch.nn.functional as F import torchvision.models as models import numpy as np class FeatureExtraction(nn.Module): def __init__(self, feature_extraction_cnn='vgg16'): super(FeatureExtraction, self).__init__() if feature_extraction_cnn == 'vgg16': ...
1780957
import time import threading import logging import sys from .baseplatform import BasePlatform logger = logging.getLogger(__name__) class DesktopPlatform(BasePlatform): def __init__(self, config): super(DesktopPlatform, self).__init__(config, 'desktop') self.trigger_thread = None self.started = 0 def setu...
1780969
import sys import matplotlib.cm from matplotlib import pyplot as plt import open3d as o3d from model import * from utils import * import argparse import random import numpy as np import torch import h5py import os import visdom sys.path.append("./distance/emd/") import emd_module as emd sys.path.append("./distance/cham...
1780994
import os.path import os import csv from openpyxl import Workbook, load_workbook from openpyxl.styles import Font, PatternFill def get_workbook(file_path): if os.path.isfile(file_path): return load_workbook(filename=file_path) else: wb = Workbook() wb.remove_sheet(wb.active) r...
1781020
import bpy from bpy.props import * from ..node_socket import RenderNodeSocket, SocketBase, RenderNodeSocketmixin, RenderNodeSocketInterface from ..node_socket import update_node class RenderNodeSocketInterfaceMaterial(RenderNodeSocketmixin, RenderNodeSocketInterface, bpy.types....
1781026
from django.conf.urls.defaults import * from views import empty_view urlpatterns = patterns('', url(r'^$', empty_view, name="named-url1"), url(r'^extra/(?P<extra>\w+)/$', empty_view, name="named-url2"), url(r'^(?P<one>\d+)|(?P<two>\d+)/$', empty_view), (r'^included/', include('regressiontests.urlpatter...
1781048
def create_metadata_table(TaXon_table_xlsx, path_to_outdirs): import PySimpleGUI as sg import pandas as pd from pandas import DataFrame import numpy as np import sys, subprocess, os from pathlib import Path def open_table(table): if sys.platform == "win32": os.startfile...
1781050
import pandas as pd import numpy as np import data_utils as utils values = [{ "age": "18", "education": "1. < HS Grad", "health": "1. <=Good", "health_ins": "2. No", "jobclass": "1. Industrial", "logwage": "4.31806333496276", "maritl": "1. Never Married", "race": "1. White", "region...
1781073
class Solution: def rotate(self, nums: List[int], k: int) -> None: def reverse(l, r, nums): while l < r: nums[l], nums[r] = nums[r], nums[l] l += 1 r -= 1 if len(nums) <= 1: return k = k % len(nums) reverse(0, len(nums)-1, n...
1781139
from __future__ import print_function from cython.cimports.cpython.ref import PyObject import sys python_dict = {"abc": 123} python_dict_refcount = sys.getrefcount(python_dict) @cython.cfunc def owned_reference(obj: object): refcount = sys.getrefcount(python_dict) print('Inside owned_reference: {refcount}'....
1781143
import os import numpy as np x = np.load('xnames_val.npy') y = [] for i in range(x.shape[0]): dir_name = "" under_idx = 0 for j in range(len(x[i])): if x[i][j] == '_': under_idx = j break dir_name += x[i][j] dot_idx = 0 for j in range(under_idx, len(x[i])): ...
1781180
import os import flex template = ''' ################################################################################ # # This is a generated file, all edits will be lost! # ################################################################################ namespace Skew { enum TokenKind { %(actions)s } %(yy_acc...
1781190
from random import choice import os, gzip try: import simplejson as json except ImportError: import json import archetype_builder from value_setters import set_value from structures_builder import normalize_keys from pyehr.utils import decode_dict from pyehr.ehr.services.dbmanager.dbservices.wrappers import A...
1781191
import unittest import os import requests import numpy as np from pandas.api.types import is_numeric_dtype, is_object_dtype, is_bool_dtype from pymatgen.core.structure import Structure, Composition from matminer.datasets.tests.base import DatasetTest, do_complete_test from matminer.datasets.dataset_retrieval import l...
1781192
import numpy as np from transonic import jit, boost from transonic.mpi import Path def func0(a): return 2 * a def func(): return 1 func0_jitted = jit(func0) @jit def func1(a: "int[][] or float[]", l: "int list"): tmp = np.exp(sum(l)) result = tmp * a * func0(a) + func() return result @jit...
1781206
from selenium.common.exceptions import WebDriverException from waiting import wait as wait_lib import webium.settings def wait(*args, **kwargs): """ Wrapping 'wait()' method of 'waiting' library with default parameter values. WebDriverException is ignored in the expected exceptions by default. """ ...
1781255
import logging import traceback import matplotlib as mpl from os import sys, path from PyQt5.QtCore import pyqtSignal, QProcess from PyQt5.QtWidgets import QWidget, QPushButton, QGridLayout, QLineEdit, QFileDialog, QComboBox, QVBoxLayout, \ QApplication, QLabel, QRadioButton, QHBoxLayout # https://stackoverflow.c...
1781269
from lark import Lark, Tree import lark_cython def test_minimal(): parser = Lark('!start: "a" "b"', parser='lalr', _plugins=lark_cython.plugins) res = parser.parse("ab") assert isinstance(res, Tree) assert all(isinstance(t, lark_cython.Token) for t in res.children) assert [t.value for t in res.children] == ['a',...
1781321
import numpy as np # linear algebra import pandas as pd # data processing, CSV file I/O (e.g. pd.read_csv) import matplotlib.pyplot as plt import os from RLC.real_chess import agent, environment, learn, tree import chess from chess.pgn import Game opponent = agent.GreedyAgent() env = environment.Board(opponent, FEN...
1781322
import json import os import log as log if not os.path.exists('config/config.json'): log.error("The config.json file is missing") log.warn("-- copy the config.json.template file as config.json") log.warn("-- fill the Details") os._exit(0); from dotmap import DotMap configData = DotMap(json.load(open('config/co...
1781331
from github import Github import configparser # Provide the location of where the config file exists CONFIG_FILE = 'config.ini' def parse_config(): """Parse the configuration file and setup the required configuration.""" config = configparser.ConfigParser() config.read(CONFIG_FILE) if 'github_auth' n...
1781346
import logging import os from experiment.utils import get_custom_properties from redismq.send_consume import RedisReceiver class FooReceiver(RedisReceiver): def handle_body(self, body, **kwargs): instance_name = kwargs.pop('instance_name', '') instance_id = kwargs.pop('instance_id', '') tr...
1781351
from dask import dataframe as dd from datafaucet.data import _Data class Data(_Data): def collect(self, n=1000, axis=0): #check if enough data in partition 0 cnt = self.df.get_partition(0).count().compute().count() if cnt>n: res = self.df[self.columns].head(n) else: ...
1781362
from math import pi import sqlite3 import random from datetime import datetime import os import numpy as np import pandas as pd def make_events(): # For each of 5 distributions, loop through N times, # adding points according to probability at time np.random.seed(1) N = 3 nrecs = 0 day = 60*24...
1781368
import FWCore.ParameterSet.Config as cms process = cms.Process("myprocess") process.TFileService=cms.Service("TFileService",fileName=cms.string('JECplots.root')) ##-------------------- Communicate with the DB ----------------------- process.load('Configuration.StandardSequences.Services_cff') process.load("Configurati...