input stringlengths 2.65k 237k | output stringclasses 1
value |
|---|---|
<filename>cinder/volume/drivers/datera.py<gh_stars>10-100
# Copyright 2016 Datera
# 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... | |
buffers into one template. The resulting template will be stored on both
buffers.
:return: Fingerprint set response.
:rtype: FpResponseSet
"""
return self._command_set(command=FpCommand.TEMPLATE_CREATE)
def template_load(self, buffer: tp.Union[int, FpBufferID], index: int = 0) -> FpResponseValue:
"""
Loads an... | |
# Do not edit this file; it was automatically generated.
import ctypes
import numpy
from nidaqmx._lib import lib_importer, ctypes_byte_str, c_bool32
from nidaqmx.scale import Scale
from nidaqmx.errors import (
check_for_error, is_string_buffer_too_small, is_array_buffer_too_small)
from nidaqmx._task_modules.channels... | |
import numpy as np
from collections import defaultdict as ddict
from ptsnet.arrays import Table2D, Table, ObjArray
from ptsnet.parallel.partitioning import even, get_partition
from ptsnet.simulation.constants import MEM_POOL_POINTS, PIPE_START_RESULTS, PIPE_END_RESULTS, NODE_RESULTS, CLOSED_PROTECTION_RESULTS, POINT_P... | |
import csv
import json
import pymongo
import math
import numpy as np
import sys
sys.path.append(".")
sys.path.append("..")
from nlppack.word_cut import parse
from data.item_feature import blacklist
myclient = pymongo.MongoClient("mongodb://localhost:27017/")
mydb = myclient["paopao"]
words = mydb['dicts'].find()
word... | |
.. code-block:: python
# Group jobs by state point parameter 'a'.
for key, group in project.groupby('a'):
print(key, list(group))
# Find jobs where job.sp['a'] is 1 and group them
# by job.sp['b'] and job.sp['c'].
for key, group in project.find_jobs({'a': 1}).groupby(('b', 'c')):
print(key, list(group))
# Gr... | |
from django.forms import forms
from django.test.testcases import SimpleTestCase
from django.utils.safestring import mark_safe
from form_tags.templatetags.forms import (
fieldholder,
fieldholder_combined,
fieldholder_inline,
)
from .mixins import DummyFormMixin, SvgIconsMixin
class FormFieldholderTestCase(DummyFo... | |
from .rainbow import *
import batman as batman
class SimulatedRainbow(Rainbow):
def __init__(
self,
signal_to_noise=100,
tlim=[-2.5, 2.5] * u.hour,
dt=10 * u.minute,
time=None,
wlim=[0.5, 5] * u.micron,
R=20,
dw=None,
wavelength=None,
star_flux=None,
):
"""
Create a simulated rainbow object.
Parameter... | |
<reponame>allegrocy/gwascalon<gh_stars>0
import discord
from discord.ext import commands
from redbot.core import checks
import urllib
import aiohttp
import async_timeout
from bs4 import BeautifulSoup, SoupStrainer
import time
import asyncio
import datetime
from fuzzywuzzy import fuzz
from fuzzywuzzy import process
from... | |
env = gym.wrappers.Monitor(env, monitor_path, resume=True)
return env
self.env = wrap(self.env)
def make_env(vector_index):
return wrap(
env_creator(
env_context.copy_with_overrides(
vector_index=vector_index, remote=remote_worker_envs)))
self.tf_sess = None
policy_dict = _validate_and_canonicalize(policy, ... | |
if not np.isnan(intensity_range[0]):
if fill_value is None:
voxel_grid[voxel_grid < intensity_range[0]] = intensity_range[0]
else:
voxel_grid[voxel_grid < intensity_range[0]] = fill_value[0]
# Upper boundary
if not np.isnan(intensity_range[1]):
if fill_value is None:
voxel_grid[voxel_grid > intensity_range[1]]... | |
custom math fonts.''').tag(config=True, kind='')
mathtext_default = Unicode('regular', help=r'''The default font to use for math. Can be any of the LaTeX font
names, including the special name "regular" for the same font used in regular text.''').tag(config=True, kind='')
#
# AXES
# default face and edge color, de... | |
# coding: utf-8
# # An Example Python Client for the demo-echo API
#
# When using [OAuth 2.0](https://tools.ietf.org/html/rfc6749) (no matter what the flow), the client app (this notebook) gets an *access token* (and optionally some other tokens like *refresh\_token* and even an OpenID Connect *id\_token* which iden... | |
<filename>tests/unit/test_font.py
import sys
from unittest import TestCase, skipUnless
from unittest.mock import call, patch
from path import Path
from dakara_player.font import (
FontLoaderLinux,
FontLoaderNotAvailableError,
FontLoaderWindows,
get_font_loader_class,
)
class GetFontLoaderClassTestCase(TestCase)... | |
+ str(num)
student_circuits_sorted = sorted(check_pins)
good_circ_sorted = sorted(good_circ.input_pins)
sm = difflib.SequenceMatcher(None, student_circuits_sorted, good_circ_sorted)
res_ratio = sm.ratio()
if res_ratio > 0.99:
out_str += '<font color="green"> {} : PERFECT MATCH!<br> </font>'.format(circ_to_grade)... | |
<reponame>SquidRo/acc-bpf
#!/usr/bin/python3
#
# Licensed under the Apache License, Version 2.0 (the "License")
from bcc import BPF
from bcc import libbcc, table
import pyroute2, time, sys, argparse, ctypes, os
c_text = """
#include <uapi/linux/bpf.h>
#include <uapi/linux/gtp.h>
#include <linux/in.h>
#include <linux/... | |
str(step) + "_vox.ply")
write_ply_triangle(self.result_dir + "/" + str(step) + "_vox.ply", vertices, triangles)
# update base sample points for next iteration.
# base_mesh = Meshes(verts=[vertices])
# self.base_sample_points = sample_points_from_meshes(meshes=base_mesh, num_samples=int(1e5))
return z_base.grad
... | |
<reponame>platforminternetstandaarden/dashboard-internet.nl<filename>dashboard/internet_nl_dashboard/logic/report_to_spreadsheet.py
# SPDX-License-Identifier: Apache-2.0
import itertools
import logging
from string import ascii_uppercase
from tempfile import NamedTemporaryFile
from typing import Any, Dict, List, Union
... | |
ident, else ``False``.
"""
for c in ident:
if c in 'ABCDEFGHIJKLMNOPQRSTUVWXYZ':
return True
return False
def matchIdentBearingDistance(db, ov, station):
"""Use reg-ex to try to match ``/OV`` field to an ident and bearing/distance.
Perform a regular expression match to see if the ``/OV`` field matches the
id... | |
traceback):
"""
Method used for with statement
"""
self.screen.close()
if sys.platform == "win32":
import win32con
import win32console
import win32event
import win32file
import pywintypes
class _WindowsScreen(Screen):
"""
Windows screen implementation.
"""
# Virtual key code mapping.
_KEY_MAP = {
wi... | |
:param usage_date:
:type usage_date: ~datetime.date
:param user_principal_name:
:type user_principal_name: str
"""
_attribute_map = {
'id': {'key': 'id', 'type': 'str'},
'additional_properties': {'key': '', 'type': '{object}'},
'completed_black_and_white_job_count': {'key': 'completedBlackAndWhiteJobCount', 't... | |
self.__innerwire.GetEndpoint()
@property
def Direction(self):
"""
The direction of the wire
Wires may be declared "readonly" or "writeonly" in the service definition file. (If neither
is specified, the wire is assumed to be full duplex.) "readonly" wires may only send packets from
service to client. "... | |
= Linear([rf], [output_dim], output_dim, random_state=random_state,
name=proj_o_name, init=init, scale=scale, biases=biases, bias_offset=bias_offset,
strict=strict)
return out, att
def TransformerBlock(value, key, query_and_passthrough, output_dim, n_heads=8, mask=False, random_state=None, name=None, debug=False):... | |
<filename>src/picolo/shapes/shapes.py<gh_stars>1-10
"""
@package shapes
@author <NAME>
@version 0.1
@brief Contains classes for Shape, FourierShape, ZernikeShape, UnitCellShape,
and factory methods shape_factory_from_values and shape_factory_from_coords
"""
# import from standard library
import math
import copy
impor... | |
#! /usr/bin/env python
"""
Script to download sitemaps and check if they have obvious text in them.
Reports success and failures and number of docs that have text
"""
import asyncio
import json
import os
import re
from asyncio import Semaphore
from collections import defaultdict, Counter
from datetime import datetime
... | |
<filename>aiida/orm/computers.py
# -*- coding: utf-8 -*-
###########################################################################
# Copyright (c), The AiiDA team. All rights reserved. #
# This file is part of the AiiDA code. #
# #
# The code is hosted on GitHub at https://github.com/aiidateam/aiida-core #
# For furt... | |
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved
import inspect
from typing import Dict, List, Optional, Tuple, Union
import torch
import copy
from torch import nn
import math
import numpy as np
import torch.nn.functional as F
from torch.autograd.function import Function
from detectron2.modeling.... | |
RQ(dim, par)
class GaussianProcessModel(Model):
"""
Gaussian process regression model of the integrand in the Bayesian quadrature.
Parameters
----------
dim : int
Number of input dimensions.
kern_par : ndarray
Kernel parameters in matrix.
kern_str : str
Acronym of the covariance function of the Gaussian ... | |
<reponame>CrafterSvK/liberapay.com<gh_stars>0
from base64 import b64decode, b64encode
from binascii import hexlify, unhexlify
from datetime import date, datetime, timedelta
import errno
import fnmatch
from hashlib import sha256
import hmac
from operator import getitem
import os
import re
import socket
from urllib.parse... | |
"""
Helper Methods
Author: Austin Transportation Department, Data and Technology Services
Description: The purpose of this script is to provide any methods that
assist any script associated to this application.
"""
import sys
import glob
import csv
import io
import json
import re
import datetime
from dateutil import ... | |
from sympy import symbols, lambdify, diff, sqrt, I
from sympy import besselj, hankel1, atan2, exp, pi, tanh
import scipy.special as scp
import numpy as np
from scipy.sparse.linalg import gmres
# gmres iteration counter
# https://stackoverflow.com/questions/33512081/getting-the-number-of-iterations-of-scipys-gmres-ite... | |
#
# Copyright 2021 Xilinx, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in... | |
import numpy as np
import gzip
from Bio import SeqIO
from pathlib import Path
import os
import subprocess
import tarfile
from io import BytesIO
#for parallel computing
from joblib import Parallel, delayed
import multiprocessing
num_cores_energy = multiprocessing.cpu_count()
from tqdm import tqdm
import pandas as pd
imp... | |
F = GF(5); MS = MatrixSpace(F,2,2)
sage: G = MatrixGroup([MS(1), MS([1,2,3,4])])
sage: G
Matrix group over Finite Field of size 5 with 2 generators (
[1 0] [1 2]
[0 1], [3 4]
)
sage: G.gens()
(
[1 0] [1 2]
[0 1], [3 4]
)
"""
return tuple(self.element_class(self, x, check=False, convert=False)
for x in sel... | |
= Var(within=Reals,bounds=(0,None),initialize=0.0333333333333333)
m.x597 = Var(within=Reals,bounds=(0,None),initialize=0.0333333333333333)
m.x598 = Var(within=Reals,bounds=(0,None),initialize=0.0333333333333333)
m.x599 = Var(within=Reals,bounds=(0,None),initialize=0.0333333333333333)
m.x600 = Var(within=Reals,bounds=(0... | |
<gh_stars>0
#!/usr/bin/env python3
#
# Copyright (c) 2017, Intel Corporation
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# Redistributions of source code must retain the above copyright not... | |
or entry[1] > metric_max:
metric_max = entry[1]
if (i+1) % aggrgeate_by ==0:
# Append aggregated data
end_time_dt = entry[2]
avg_time_dt = dt_from_s(s_from_dt(start_time_dt) + ((s_from_dt(end_time_dt) - s_from_dt(start_time_dt))/2)).astimezone(profile_timezone)
timestamp_dygraphs_avg = '{}/{:02d}/{:02d} {:02d... | |
"""Sub-classes for vtk.vtkRectilinearGrid and vtk.vtkImageData."""
import pathlib
import logging
import numpy as np
import pyvista
from pyvista import _vtk
from pyvista.utilities import abstract_class
from .dataset import DataSet
from .filters import _get_output, UniformGridFilters
log = logging.getLogger(__name__)... | |
<filename>tapiriik/services/Pulsstory/pulsstory.py
from tapiriik.settings import PULSSTORY_CLIENT_ID, PULSSTORY_CLIENT_SECRET
from tapiriik.services.service_base import ServiceAuthenticationType, ServiceBase
from tapiriik.services.service_record import ServiceRecord
from tapiriik.services.stream_sampling import StreamS... | |
{},
"csbSIPMthdCurrentStatsReqOut": {},
"csbSIPMthdCurrentStatsResp1xxIn": {},
"csbSIPMthdCurrentStatsResp1xxOut": {},
"csbSIPMthdCurrentStatsResp2xxIn": {},
"csbSIPMthdCurrentStatsResp2xxOut": {},
"csbSIPMthdCurrentStatsResp3xxIn": {},
"csbSIPMthdCurrentStatsResp3xxOut": {},
"csbSIPMthdCurrentStatsResp4xxIn": ... | |
from pypy.module.micronumpy.test.test_base import BaseNumpyAppTest
class AppTestSupport(BaseNumpyAppTest):
spaceconfig = dict(usemodules=["micronumpy", "struct", "binascii", "mmap"])
def setup_class(cls):
BaseNumpyAppTest.setup_class.im_func(cls)
cls.w_NoNew = cls.space.appexec([], '''():
from numpy import ndar... | |
#
#############################################################################
#
# Author: <NAME>
#
# Copyright: <NAME>, TSRI 2011
#
#############################################################################
"""
Collection of helper functions used in different code for Virtual Screening and
other applications
v.0... | |
# -*- coding: utf-8 -*-
import django
from django.contrib import admin
from django.contrib.contenttypes.models import ContentType
from django.urls import reverse
from django.utils import translation
from django.http import HttpResponseForbidden, HttpResponseRedirect, QueryDict
from urllib.parse import urlparse
from hva... | |
fits.Header))
def test_dir_with_no_fits_files(self, tmpdir):
empty_dir = tmpdir.mkdtemp()
some_file = empty_dir.join('some_file.txt')
some_file.dump('words')
with catch_warnings() as w:
collection = ImageFileCollection(location=empty_dir.strpath,
keywords=['imagetyp'])
assert len(w) == 1
assert str(w[0].messa... | |
as a numpy array. It specifies the number of stars in each
block in each zone to make it easy to seek to the right place.
"""
# noinspection SpellCheckingInspection
self.index = np.genfromtxt(self._index_file, dtype=[('start', np.uint32), ('nstars', np.uint16)],
usecols=[0, 1])
@staticmethod
def get_zone_block... | |
#!/usr/bin/env python
from __future__ import print_function, unicode_literals
import appdirs
import configargparse
import datetime
import io
import json
import lxml.etree
import os
import pycountry
import six
import sys
# If this script is renamed to 'xml2rfc.py' on a Windows system, the import
# of the real xml2rfc... | |
<reponame>jonathanschilling/idf<gh_stars>0
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Wed Oct 9 22:49:47 2019
@author: <NAME> (<EMAIL>)
"""
#%% prepare for code generation
def indented(tabs, lines, indentationChar="\t"):
indentation = ""
for i in range(tabs):
indentation += indentationChar
in... | |
<reponame>paddybu/xsbs<filename>src/pyscripts/sqlalchemy/databases/postgres.py
# postgres.py
# Copyright (C) 2005, 2006, 2007, 2008, 2009 <NAME> <EMAIL>
#
# This module is part of SQLAlchemy and is released under
# the MIT License: http://www.opensource.org/licenses/mit-license.php
"""Support for the PostgreSQL databa... | |
# print('download OMNI2 data from')
# omni2_url='ftp://nssdcftp.gsfc.nasa.gov/pub/data/omni/low_res_omni/omni2_all_years.dat'
# print(omni2_url)
# try: urllib.request.urlretrieve(omni2_url, 'data/omni2_all_years.dat')
# except urllib.error.URLError as e:
# print(' ', omni2_url,' ',e.reason)
else:
#if omni2 hourly... | |
if pos >= len(s):
raise IndexError("`pos` %d not in string" % pos)
# *don't* count last '\n', if it is at pos!
line = s.count('\n',0,pos)
if line:
return line + 1, pos - s.rfind('\n',0,pos) - 1
else:
return 1, pos
#_. TERMINAL OUTPUT FUNCTIONS
def prin(*args, **kwargs):
r"""Like ``print``, but a function. I.e... | |
set consumer to read from start.
etl_config_path = os.path.join(_get_project_dir_path(project_name), 'working_dir/etl_config.json')
if not os.path.exists(etl_config_path):
etl_config = {
"input_args": {
"auto_offset_reset": "earliest",
"fetch_max_bytes": 52428800,
"max_partition_fetch_bytes": 10485760,
"max_pol... | |
<filename>src/game/engine.py
import asyncio
import math
import random
import time
import traceback
import pygame
import pymunk
import pymunk.pygame_util
from . import category, collision_type
from .entities.ball import Ball
from .entities.border import Border
from .entities.entity_type import EntityType
... | |
import re
import unittest
from unittest.mock import Mock
from pyats.topology import Device
from genie.metaparser.util.exceptions import SchemaEmptyParserError
from genie.libs.parser.asa.show_interface import ShowInterfaceSummary, \
ShowInterfaceIpBrief, \
ShowInterfaceDetail
# ============... | |
adj_list and in_degree.
# For each pair of adjacent words...
for first_word, second_word in zip(words, words[1:]):
for c, d in zip(first_word, second_word):
if c != d:
if d not in adj_list[c]:
adj_list[c].add(d)
in_degree[d] += 1
break
else: # Check that second word isn't a prefix of first word.
if len(second... | |
tmp5[i] = 1 {id=insn6,conflicts=g1}
""", name="nosync")
orig_prog = lp.set_temporary_scope(orig_prog, "tmp3", "local")
orig_prog = lp.set_temporary_scope(orig_prog, "tmp5", "local")
# No dependency present - don't add nosync
prog = lp.add_nosync(orig_prog, "any", "writes:tmp", "writes:tmp2",
empty_ok=True)
ass... | |
#!/usr/bin/env python3
#
# Copyright (c) 2017 Intel Corporation
# Copyright (c) 2020 Nordic Semiconductor NA
#
# SPDX-License-Identifier: Apache-2.0
"""Translate generic handles into ones optimized for the application.
Immutable device data includes information about dependencies,
e.g. that a particular sensor is cont... | |
mu: Population size of the GA
:param lambda_: Offpsring size of the GA
:param population: Initial population of candidates to be used by the MIES
:param parameters: Parameters object to be used by the GA
"""
def __init__(self, n, fitnessFunction, budget, mu, lambda_, population, parameters=None):
if parameters ... | |
#! /usr/bin/env python3
###############################################################################
#
# Package: RoadNarrows Robotics Laelaps System V Init.d Console
#
# Link: https://github.com/roadnarrows-robotics/laelaps
#
# File: laelaps_init.d
#
## \file
##
## $LastChangedDate: 2016-03-18 09:57:27 -0600 (Fri... | |
defined in subset_lists_file (see above).
limit_to: Limit the dataset to the first #limit_to frames (after other
filters have been applied).
limit_sequences_to: Limit the dataset to the first
#limit_sequences_to sequences (after other sequence filters have been
applied but before frame-based filters).
pick_sequen... | |
# emacs: -*- mode: python; py-indent-offset: 4; indent-tabs-mode: nil -*-
# vi: set ft=python sts=4 ts=4 sw=4 et:
#
# Copyright 2021 The NiPreps Developers <<EMAIL>>
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a ... | |
otherwise.
def decode(self, frame):
# mp3 version
version = (frame[1] >> 3) & 0x1
# channel mode.
mode = (frame[3] >> 6) & 0x3
# Find the start of the Xing header.
if version:
# +4 in all of these to skip initial mp3 frame header.
if mode != 3:
pos = 32 + 4
else:
pos = 17 + 4
else:
if mode != 3:
pos = 1... | |
str,
chunk_size: Optional[int] = None,
timeout: Optional[int] = DEFAULT_TIMEOUT,
num_max_attempts: Optional[int] = 1,
) -> bytes:
"""
Downloads a file from Google Cloud Storage.
When no filename is supplied, the operator loads the file into memory and returns its
content. When a filename is supplied, it writes... | |
+ [self.no_im]
if hint is None:
hint = ['']
else:
hint = hint + ['']
for k_env in range(0, j + 1 - i):
if indic_dr_env[k_env] or self.read_indication_deathroom[i + k_env]:
self.read_indication_deathroom[i + k_env] = True
if indication_deathroom is None:
indication_deathroom = [self.indication_deathroom]
e... | |
<reponame>wx-b/dm_robotics
# Copyright 2020 DeepMind Technologies 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 b... | |
from starling_sim.basemodel.trace.trace import Traced
from starling_sim.basemodel.trace.events import InputEvent
from starling_sim.basemodel.agent.operators.operator import Operator
from starling_sim.utils.utils import json_load, validate_against_schema, \
add_defaults_and_validate
from starling_sim.utils.constants im... | |
in self.loaded_years[:-2]:
button.state = "normal"
# Check if we have selected at least one Year and one Region.
def check_if_ry(self, *args):
c = 0
for keylist in self.loaded_regions.values():
for item in keylist:
if item.state == "down":
c = 1
break
if c == 1:
break
for j in self.loaded_years:
if j.sta... | |
<reponame>bkolosk1/bkolosk1-CrossLingualKeywords
import re
def parse_to_latex():
configs = ['nolm', 'lm', 'maskedlm', 'lm+bp', 'lm+pos', 'lm+rnn', 'lm+bpe+rnn', 'lm+bpe+crf']
datasets = ['kp20k', 'inspec', 'krapivin', 'nus', 'semeval', 'kptimes', 'jptimes', 'duc']
config_dict = {}
with open('class_results-FINAL.t... | |
"""
Created by <NAME> on Apr 24 2021
purpose: easily compare values between helita and aux vars from a simulation.
Highest-level use-case: compare all the aux vars with their helita counterparts!
#<< input:
from helita.sim import aux_compare as axc
from helita.sim import ebysus as eb
dd = eb.EbysusData(...) # you... | |
Death Mountain Ledge (West)', 'Turtle Rock Ledge Exit (West)', player)
connect_two_way(world, 'Dark Death Mountain Ledge (East)', 'Turtle Rock Ledge Exit (East)', player)
def unbias_some_entrances(world, Dungeon_Exits, Cave_Exits, Old_Man_House, Cave_Three_Exits):
def shuffle_lists_in_list(ls):
for i, item in enum... | |
<filename>python-package/xgboost/sklearn.py
# coding: utf-8
# pylint: disable=too-many-arguments, too-many-locals, invalid-name, fixme, R0912, C0302
"""Scikit-Learn Wrapper interface for XGBoost."""
import copy
import warnings
import json
import os
from typing import Union, Optional, List, Dict, Callable, Tuple, Any, T... | |
import os
import pandas as pd
from glob import glob
import numpy as np
from joblib import Parallel, delayed
from joblib import Memory
import logging
from pymeg import atlas_glasser
memory = Memory(cachedir=os.environ['PYMEG_CACHE_DIR'], verbose=0)
backend = 'loky'
class Cache(object):
"""A cache that can prevent ... | |
device_enrollment_disown_body: DeviceEnrollmentDisownBody
:param async_req: Whether to execute the request asynchronously.
:type async_req: bool, optional
:param _preload_content: if False, the urllib3.HTTPResponse object will
be returned without reading/decoding response
data. Default is True.
:type _preload_con... | |
"""Drawable objects
"""
from math import cos, pi, sin
from typing import ClassVar, List, Tuple
import pyglet
from .geometry import Point
C3F = Tuple[float, float, float]
C4F = Tuple[float, float, float, float]
C3I = Tuple[int, int, int]
C4I = Tuple[int, int, int, int]
class GeoDrawer:
"""A static class containe... | |
<filename>resources/dot_PyCharm/system/python_stubs/-762174762/PySide/QtCore/Qt.py<gh_stars>1-10
# encoding: utf-8
# module PySide.QtCore
# from C:\Python27\lib\site-packages\PySide\QtCore.pyd
# by generator 1.147
# no doc
# imports
import Shiboken as __Shiboken
class Qt(__Shiboken.Object):
# no doc
def __init__(s... | |
otherwise the header provided
"""
if row['Field Name'] in short_cols:
return short_cols[row['Field Name']]
return row['Field Name']
def add_field_name_to_value(row):
""" Combine the field name and value provided into one string.
Args:
row: the dataframe row containing information about a cell, including the h... | |
(FileDropResource, "POST", None, {u"mimeType": "TKBX"}, "reader", 200),
(Recovery, "POST", None, {u"email": "826S"}, None, 200),
(Recovery, "POST", None, {u"email": "826S"}, "devtable", 200),
(Recovery, "POST", None, {u"email": "826S"}, "freshuser", 200),
(Recovery, "POST", None, {u"email": "826S"}, "reader", 200),... | |
<gh_stars>0
## aen_attack.py -- attack a network optimizing elastic-net distance with an en decision rule
## when autoencoder loss is applied
##
## Copyright (C) 2018, <NAME> <<EMAIL>>
## <NAME> <<EMAIL>>
## <NAME> <<EMAIL>>
## Copyright (C) 2017, <NAME> <<EMAIL>>.
## Copyright (C) 2016, <NAME> <<EMAIL>>.
##
#... | |
sample in range(K):
# Update excluded_ids.
if neg_sample_one_hot is not None:
excluded_ids = excluded_ids + neg_sample_one_hot * -10000
if use_softmax_sample:
uniform_noise = paddle.rand(
logits.shape, dtype=paddle.get_default_dtype())
gumbel_noise = -paddle.log(-paddle.log(uniform_noise + 1e-9) +
1e-9)
else:
... | |
from __future__ import absolute_import
from __future__ import division
import os.path
import datetime
import csv
import copy
import socket
from itertools import dropwhile
import numpy as np
import scipy.interpolate as interpolate
from sunpy.net import hek
from sunpy.time import parse_time
from sunpy import config
fr... | |
626, 830, 969, 809, 522, 539],
[910, 121, 228, 803, 443, 4, 341, 64, 60, 438, 964],
[320, 135, 26, 700, 58, 741, 111, 944, 580, 855, 195],
[2, 802, 971, 42, 232, 432, 910, 803, 694, 46, 826],
[612, 974, 539, 639, 21, 878, 809, 246, 218, 331, 974],
[804, 448, 962, 406, 439, 556, 826, 109, 798, 609, 867],
[260, 335... | |
<gh_stars>1-10
"""
Misc. utility routines.
"""
import os
import sys
import itertools
import inspect
import warnings
import importlib
from importlib import import_module
from configparser import ConfigParser
from fnmatch import fnmatch
from os.path import join, dirname, basename, isfile, abspath, split, splitext
fro... | |
<gh_stars>10-100
# IMPORTS
import numpy as np
import pandas as pd
from rdkit import Chem
from rdkit.Chem import Descriptors, DataStructs
from rdkit.Chem import AllChem
from rdkit.Chem import MACCSkeys
from itertools import chain
from os import listdir
from sklearn.manifold import TSNE
import matplotlib.pyplot as p... | |
#!/usr/bin/env python3
import random
import asyncio
import re
import discord
from discord.ext import commands
from Users import Users
from random import choices
def get_hangman_art():
# prepare array of hangman art
art_array = []
with open("db_and_words\hangmen.txt") as my_file:
for line in my_file:
art_array.a... | |
None')
evt = api.async_call(self, self.sessionUuid)
self.out = evt
return self.out
class DetachSecurityGroupFromL3NetworkAction(inventory.APIDetachSecurityGroupFromL3NetworkMsg):
def __init__(self):
super(DetachSecurityGroupFromL3NetworkAction, self).__init__()
self.sessionUuid = None
self.out = None
def run(s... | |
<filename>src/fuzzingtool/interfaces/cli/cli_output.py<gh_stars>0
# Copyright (c) 2020 - present <NAME> <https://github.com/VitorOriel>
#
# 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 witho... | |
#!/usr/bin/env python3
"""
Converts Satisfactory save games (.sav) into a more readable format (.json)
"""
import struct
import functools
import itertools
import csv
import binascii
import sys
import json
import argparse
import pathlib
parser = argparse.ArgumentParser(
description='Converts Satisfactory save games in... | |
#!/bin/env python
#===============================================================================
# NAME: GseApi.py
#
# DESCRIPTION: A basic API of command and telemetry monitoring capabilities.
# AUTHOR: reder
# EMAIL: <EMAIL>
# DATE CREATED: June 17, 2015
#
# Copyright 2015, California Institute of Technology.
# ALL... | |
<gh_stars>0
# coding: utf-8
import os, json, socket, time, random
from log import Log
# 4 actions after receive an message:
# 1. general_process(data): all role will do this
# 2. leader_process(data)
# 3. candidate_process(data)
# 4. follower_process(data)
# The algorithm is based on message driven model, whenever a ... | |
be a pandas Series"):
assert_equal(n1, s1)
with pytest.raises(
AssertionError,
match=r"Actual should be a numpy array"):
assert_equal(s1, n1)
# properly identifies location in dict
with pytest.raises(
AssertionError,
match=r"Error at dictionary location: dict\['a'\]\['a'\]\['a'\].\n"
r"Actual should be a pa... | |
import os, re, traceback;
from mBugId import cBugId;
from mConsole import oConsole;
from mFileSystemItem import cFileSystemItem;
import mGlobals;
from mBugId.mCP437 import fsCP437FromBytesString;
try: # mDebugOutput use is Optional
import mDebugOutput as m0DebugOutput;
except ModuleNotFoundError as oException:
if o... | |
# Copyright 2017-present, Facebook, Inc.
# All rights reserved.
#
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import u... | |
number of subsets
value=0
if (options["-numsubsets"].value==None or options["-numsubsets"].value > numberpredicted):
value=numberpredicted
else:
value=options["-numsubsets"].value
#update the progress bar
if totalforbar.value==value:
update_progress(1)
print "\n"
else:
modify()
if totalforbar.value<value:... | |
uk_153
+ 14400 * uk_154
+ 5359375 * uk_155
+ 6890625 * uk_156
+ 918750 * uk_157
+ 8859375 * uk_158
+ 1181250 * uk_159
+ 1521570 * uk_16
+ 157500 * uk_160
+ 11390625 * uk_161
+ 1518750 * uk_162
+ 202500 * uk_163
+ 27000 * uk_164
+ 3025 * uk_17
+ 7920 * uk_18
+ 1650 * uk_19
+ 55 * uk_2
+ 880 * uk_20
+ 9... | |
self.send_chat_msg('No indexes provided.')
else:
indexes = None
by_range = False
try:
if ':' in to_delete:
range_indexes = map(int, to_delete.split(':'))
temp_indexes = range(range_indexes[0], range_indexes[1] + 1)
if len(temp_indexes) > 1:
by_range = True
else:
temp_indexes = map(int, to_delete.split(','))... | |
# -*- coding: utf-8 -*-
#
"""
Solve the linearized Ginzburg--Landau problem.
"""
from scipy.sparse.linalg import LinearOperator
import time
import numpy as np
import cmath
import matplotlib.pyplot as pp
# from matplotlib import rc
# rc( 'text', usetex = True )
# rc( 'font', family = 'serif' )
import meshplex
import p... | |
<reponame>fderyckere/pgmpy
#!/usr/bin/env python3
import itertools
import networkx as nx
from pgmpy.base import UndirectedGraph
from pgmpy.independencies import Independencies
class DAG(nx.DiGraph):
"""
Base class for all Directed Graphical Models.
Each node in the graph can represent either a random variable,... | |
from __future__ import print_function, division
import numpy as np
import torch
import torch.nn as nn
from torch.utils.data import Dataset, DataLoader
import pytorch_lightning as pl
from torchdiffeq import odeint_adjoint as odeint
import matplotlib.pyplot as plt
import json
class GeneralModeDataset(Dataset):
"""
A P... | |
signature
"""
pass
def addAttribute(*args, **kwargs):
"""
addAttribute(MObject node, MObject attribute) -> self
Adds an operation to the modifier to add a new dynamic attribute to the
given dependency node. If the attribute is a compound its children will
be added as well, so only the parent needs to be... | |
Err(de::Error::missing_field(".tag"))')
with self.block(u'match tag'):
for subtype in struct.get_enumerated_subtypes():
variant_name = self.enum_variant_name(subtype)
if isinstance(subtype.data_type, ir.Void):
self.emit(u'"{}" => Ok({}::{}),'
.format(subtype.name, type_name, variant_name))
elif isinstance(ir.unw... | |
'Joy_13': {'Type': 'Digital', 'x': 1104, 'y': 1500, 'width': 572}, # TGL 1 down
'Joy_14': {'Type': 'Digital', 'x': 1164, 'y': 1304, 'width': 572}, # TGL 2 up
'Joy_15': {'Type': 'Digital', 'x': 1164, 'y': 1360, 'width': 572}, # TGL 2 down
'Joy_16': {'Type': 'Digital', 'x': 1224, 'y': 1168, 'width': 572}, # TGL 3 up
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.