input stringlengths 2.65k 237k | output stringclasses 1
value |
|---|---|
<filename>sintatico.py
from cmath import pi
from glob import glob
pilha = []
global x
#variavel de controle (se permanecer em 0 não é possível empilhar ou reduzir com os simbolos analisados, entao ha um erro no codigo)
global reduzOrEmpilha
#gramaticaItens = [qtd de itens a serem tirados da pilha, não terminal a ser... | |
<filename>RecommenderSystems/dlrm/dlrm_train_eval.py
"""
Copyright 2020 The OneFlow 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/LIC... | |
obj[0]>0:
return 'False'
elif obj[0]<=0:
return 'True'
else: return 'True'
else: return 'False'
elif obj[9]>2.0:
# {"feature": "Passanger", "instances": 7, "metric_value": 0.381, "depth": 10}
if obj[0]>0:
# {"feature": "Time... | |
estimation, especially if using the median statistic.
Returns
-------
a: (1x4) array of slopes for the different regressions: Y|X, X|Y, bisector, orthogonal
b: (1x4) array of intercepts
aerr: (1x4) or (2x4) array of slope uncertainties. (1x4) array for no bias_correction=False and/or symmetric_errors=True.
... | |
<gh_stars>1-10
import datetime
import json
import iso8601
import semantic_version
from base64 import b64encode, b64decode
from flask import url_for, session
from hashlib import sha256
from keyczar.keys import RsaPrivateKey, RsaPublicKey
from sqlalchemy import ForeignKey
from sqlalchemy.orm import remote
from uuid impo... | |
<reponame>dfki-asr/MMIPython-Core<gh_stars>0
#
# Autogenerated by Thrift Compiler (0.13.0)
#
# DO NOT EDIT UNLESS YOU ARE SURE THAT YOU KNOW WHAT YOU ARE DOING
#
# options string: py
#
from thrift.Thrift import TType, TMessageType, TFrozenDict, TException, TApplicationException
from thrift.protocol.TProtocol import TP... | |
+ intDiv({bucketsize}, 2) AS TCPQueryLen,
60 * sum(Cnt)/($to - $from) AS TCPQueryCnt
FROM
(
SELECT
intDiv(QueryLengthMap.Length, {bucketsize})*{bucketsize} AS Len,
sum(toUInt64(QueryLengthMap.Count)) AS Cnt
FROM $table
ARRAY JOIN QueryLengthMap
WHERE $timeFilter
AND TransportTCP=1
AND NodeID IN {nodesel}
AN... | |
<filename>Autocoders/Python/src/fprime_ac/generators/visitors/PortHVisitor.py<gh_stars>1-10
# ===============================================================================
# NAME: PortHVisitor.py
#
# DESCRIPTION: A visitor responsible for the generation of header file
# for each port class.
#
# AUTHOR: reder
# EMAIL:... | |
data files
self.mms.instr = dis_instr
self.mms.mode = dis_mode
self.mms.level = dis_level
self.mms.optdesc = dis_optdesc
dis_files = self.mms.download()
if self.verbose:
print(*dis_files, sep='\n')
"""Read the files"""
# Print the variable names from a sample file
dis_cdf = cdfread.CDF(dis_files[0])
info =... | |
key, value in self.__dict__.items()]
return '%s(%s)' % (self.__class__.__name__, ', '.join(L))
def __eq__(self, other):
return isinstance(other, self.__class__) and self.__dict__ == other.__dict__
def __ne__(self, other):
return not (self == other)
class getPrimaryClientForChannel_args(object):
def read(self, ... | |
each level is marked by what pattern we should see in the next line to either
# go up a level, go down a level, or confirm it is at the same level.
section_delims = [
# First level does not have any prefix.. just plain text.
# So, the level up is the release header, which begins with '##'
# The level down is ' *'.... | |
if j < 4:
# compute [x|j]
gadds(self.args[2 + (4 + j)], c_xor_z[4 + j], selected_d_4bit_block[j])
# connect 4bit block and next 5bit block
selected_d_5bit_block = [program.curr_block.new_reg('sg') for i in range(6)]
for j in range(6):
# compute MUX
gadds(in_mux_right_5[j], d_5bit_block[0][j], d_5bit_block[1][j]... | |
by default all
wcs : ~astropy.wcs.WCS, optional
the projection wcs if provided, by default None
shape : tuple of int
the shape of the resulting map
coord : str, optional
coordinate type, by default "diff"
weights : (None|std|mad|key)
the inter kid weight to use (see Note)
label: str
a label to insert in the m... | |
<reponame>adisbladis/oil
#!/usr/bin/env python2
"""
builtin_process.py - Builtins that deal with processes or modify process state.
This is sort of the opposite of builtin_pure.py.
"""
from __future__ import print_function
import signal # for calculating numbers
from core import ui
from core.util import log
from fro... | |
<reponame>MeganBeckett/great_expectations<gh_stars>0
import copy
import itertools
from abc import ABC, abstractmethod
from dataclasses import asdict, dataclass, make_dataclass
from typing import Any, Callable, Dict, List, Optional, Tuple, Union
import numpy as np
import great_expectations.exceptions as ge_exceptions
... | |
<filename>stompy/grid/multi_ugrid.py
"""
Open ugrid-ish subdomains and approximate a global domain
Currently this is pretty slow, due to the add_grid() step.
The ghost-cell handling is also very basic, and does not
properly distinguish ghost cells along land boundaries.
TODO: handling isel for partitioned dimensions... | |
nb_bodies):
for j in range(0, 3):
out_file.write(' in_out.r_COM_der[{}][{}] = '.format(get_string_enum(joint_id_names[i]), j))
flag_first = 0
for k in range(0, nb_bodies):
if xgj[k][i][j] != 0:
if flag_first:
out_file.write(' + {}*{}'.format(M[k], str(xgj[k][i][j])))
else:
flag_fir... | |
import ast
import os
import pickle
import zipfile
import korbinian
import numpy as np
import pandas as pd
from korbinian import utils as utils
from multiprocessing import Pool
import sys
# import debugging tools
from korbinian.utils import pr, pc, pn, aaa
def run_slice_TMDs_from_homologues(pathdict, s, logging):
"""F... | |
# Copyright 2021, <NAME>
#
# 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 writing, software... | |
"""
A set of objects representing each file extension recognized by ImageIO. If an
extension is not listed here it is still supported, as long as there exists a
supporting backend.
"""
class FileExtension:
"""File Extension Metadata
This class holds information about a image file format associated with a
given e... | |
<filename>net.py
import torch.nn as nn
import torch.nn.functional as F
import torch
from numpy.random import normal
from math import sqrt
import argparse
channel_dim = 3
ndf = 64
class GlobalConvBlock(nn.Module):
def __init__(self, in_dim, out_dim, kernel_size):
super(GlobalConvBlock, self).__init__()
pad0 = (ker... | |
<filename>bbc1/lib/token_lib.py
# -*- coding: utf-8 -*-
"""
Copyright (c) 2018 beyond-blockchain.org.
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
Un... | |
with open(file_path, 'w+') as destination:
test_file_object = File(destination)
output = exe.execute_code(Popen, test_file_object, 'test.py', test_file_object, "['1','2','3']")
shutil.rmtree(temp_dirpath)
# An empty file is actually a valid python file, so 0 should be retcode
self.assertEqual(output[0], 0)
# Der... | |
# This is all extremely WIP, and not in working state.
from salmon_lib.parsers import *
import os
import os.path
import tempfile
import subprocess
import shutil
import glob
import json
import time
import statistics
"""
## .bse:
- Name
- Abbreviation
- Index (just by the order stocks are specified in)
- Production para... | |
"""
QoS SAI feature in SONiC.
Parameters:
--ptf_portmap <filename> (str): file name of port index to DUT interface alias map. Default is None.
In case of a filename is not provided, a file containing port indeces to aliases map will be generated.
--disable_test (bool): Disables experimental QoS SAI test cases. D... | |
<reponame>arthurbaccan/Number
# This is a Python script.
from colored import fg, attr
# some variables to make coding colored text easier, using colored library
reset_color = attr("reset")
yellow_text = fg(3)
green_text = fg(2)
red_text = fg(1)
blue_text = fg(4)
cyan_text = fg(6)
sea_green = fg(78)
orange_t... | |
{},
"ciscoBulkFileMIB.1.1.8": {},
"ciscoBulkFileMIB.1.2.1": {},
"ciscoBulkFileMIB.1.2.2": {},
"ciscoBulkFileMIB.1.2.3": {},
"ciscoBulkFileMIB.1.2.4": {},
"ciscoCBQosMIBObjects.10.4.1.1": {},
"ciscoCBQosMIBObjects.10.4.1.2": {},
"ciscoCBQosMIBObjects.10.69.1.3": {},
"ciscoCBQosMIBObjects.10.69.1.4": {},
"cisco... | |
import asyncio
import random
import re
from abc import ABC
from typing import List, Iterable
from src.entity.proxy_entity import ProxyEntity
from src.enum.common import ProxyCoverEnum, ProxyTypeEnum
from src.log.logger import logger
from src.spider.abs_spider import AbsSpider
from bs4 import BeautifulSoup, Tag
from pyp... | |
"""
Code references:
https://github.com/HRNet/HRNet-Image-Classification/blob/master/lib/models/cls_hrnet.py
https://github.com/HRNet/HRNet-Object-Detection/blob/master/configs/hrnet/faster_rcnn_hrnetv2p_w32_syncbn_mstrain_1x.py
https://github.com/lyrgwlr/HRNet-Facial-Landmark-Detection-v1/blob/master/lib/models/hrn... | |
hitLike / missLike ) if hitLike != 1e-10 else missingVal ) if hitLike != 0.0 else np.nan
for hitLike, missLike in zip( hitLikes, missLikes ) ]
CLR = np.array( [ CLR[0] ] + CLR + [ CLR[-1] ] )
binIds = np.digitize( statVals.values, bins )
st_binSize = ( bins[1] - bins[0] )
st_nbins = len( bins ) -1
binIds2 = np.w... | |
self.id_list:
# Enumerate provided VSAN range
vsans_enumerated_id_range = self.enumerated_id_range_retriever(id_dictionary,
vsans_id_key
)
# Enumerate provided FCoE VLAN range
fcoe_vlans_enumerated_id_range = self.enumerated_id_range_retriever(id_dictionary,
fcoe_vlans_id_key
)
# Match and pair enumer... | |
"""
AbaqusThermal.py
For use with Abaqus 6.13-1 (Python 2.6.2).
Created by <NAME> <<EMAIL>>
- Includes modules which generate loading conditions
for thermal related concepts.
"""
import logging
from random import randint
import cad_library
from abaqus import *
from abaqusConstants import *
i... | |
the :py:mod:`~oci.retry` module. A convenience :py:data:`~oci.retry.DEFAULT_RETRY_STRATEGY`
is also available. The specifics of the default retry strategy are described `here <https://oracle-cloud-infrastructure-python-sdk.readthedocs.io/en/latest/sdk_behaviors/retries.html>`__.
To have this operation explicitly not... | |
k == 'imy':
# imy = val
# else:
# flux_params[k] = val
# return
def get_rate_dpis(self, params):
imx = params['imx']
imy = params['imy']
rate_pdet_ebins = self.get_rates(params, imx=imx, imy=imy)
rt = self.get_rt(imx, imy)
rate_dpis = np.array([rt*rate_pdet for rate_pdet in\
rate_pdet_ebins])
return rat... | |
<gh_stars>1000+
import numpy as np
import pandas as pd
from pandas.api.types import is_numeric_dtype
import pytest
from scipy import sparse
import sklearn.datasets
import sklearn.model_selection
from autosklearn.data.feature_validator import FeatureValidator
# Fixtures to be used in this class. By default all el... | |
from django.contrib import messages
from django.contrib.auth import login
from django.contrib.auth.decorators import login_required
from django.contrib.auth.views import PasswordChangeView
from django.contrib.sites.shortcuts import get_current_site
from django.core.mail import EmailMessage
from django.db import transac... | |
The local IP address of the interface. This field is auto-populated and cannot be changed.
Count (number): Number of elements inside associated multiplier-scaled container object, e.g. number of devices inside a Device Group
DescriptiveName (str): Longer, more descriptive name for element. It's not guaranteed t... | |
0 delrcvwnd: 57
m = p41.match(line)
if m:
group = m.groupdict()
session_transport_dict['rcvwnd'] = int(group['rcvwnd'])
session_transport_dict['rcv_scale'] = int(group['scale'])
session_transport_dict['delrcvwnd'] = int(group['delrcvwnd'])
continue
# SRTT: 1000 ms, RTTO: 1003 ms, RTV: 3 ms, KRTT: 0 ms
m = p42... | |
# -*- coding: iso-8859-1 -*-
"""
MoinMoin - WSGI session handling
To provide sessions, the MoinMoin WSGI application interacts with an
object implementing the `SessionService` API. The interface is quite
straight forward. For documentation of the expected methods, refer
to the documentation of `SessionService` in... | |
a dict containing the response's headers (all header names will
be lowercase)
:raises ClientException: HTTP HEAD request failed
"""
if http_conn:
parsed, conn = http_conn
else:
parsed, conn = http_connection(url)
method = "HEAD"
headers = {'X-Auth-Token': token}
conn.request(method, parsed.path, '', headers)
... | |
start_index in iteritems(table.attrs['first_row'])
}
self._last_rows = {
int(asset_id): end_index
for asset_id, end_index in iteritems(table.attrs['last_row'])
}
self._calendar_offsets = {
int(id_): offset
for id_, offset in iteritems(table.attrs['calendar_offset'])
}
# Cache of fully read np.array for the ca... | |
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.nn import init
import random
import numpy as np
import torch.multiprocessing as mp
from torch.multiprocessing import Queue
def init_emb2pos_index(walk_length, window_size, batch_size):
''' select embedding of positive nodes from a batch of... | |
sample_size)
logging.info("Done.")
return code
def lsh_knn_map(table, field_size, k):
"""Returns k nearest neighbors using Locality Sensitive Hashing (LSH).
Args:
table: the data matrix, numpy 2d array;
field_size: integer parameter that controls number of random hyperplanes
used in LSH;
k: number of neigh... | |
= torch.eye(10)[y].to(device)
loss = model.test({"x": x, "y": y})
test_loss += loss
test_loss = test_loss * test_loader.batch_size / len(test_loader.dataset)
print('Test loss: {:.4f}'.format(test_loss))
return test_loss
# In[12]:
def plot_reconstrunction(x, y):
with torch.no_grad():
z = p.forward(x, y, comp... | |
<reponame>Riemer1818/Cattlelyst_software_2021
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Module for score and compare the difference metabolic engineering strategies
Contains functions to evaluate the engineering strategies on
a set of criteria: consumption rate, production rate, number of
reactions Knock in... | |
to_rgb
def __call__(self, results):
results['img'] = mmcv.imnormalize(results['img'], self.mean, self.std,
self.to_rgb)
results['img_norm_cfg'] = dict(
mean=self.mean, std=self.std, to_rgb=self.to_rgb)
return results
def __repr__(self):
repr_str = self.__class__.__name__
repr_str += '(mean={}, std={}, to_rgb... | |
<gh_stars>0
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
##
# \author <NAME> <<EMAIL>>
# \date 2017-12-12
#
###############################################################################
# This script provides functions which are used to visualize the ProSeCo data
##################################################... | |
<filename>pop/pop_lexer.py
"""
Pop is a programming language that's a mix between C and
Python. I've also added a lot of my own specifications, as well.
The goal is to create a Pythonic language that allows for
low-level functions, while creating a high-level language.
Copyright (c) <NAME> 2014-2016. All Rights R... | |
{ 'accel_cal_factor': { 'comment': 'Accelerometer '
'calibration '
'factor',
'field_name': 'accel_cal_factor',
'field_type': 'uint32',
'ref_field_name': 'sensor_type',
'ref_field_value': { 'accelerometer'},
'units': 'g'},
'gyro_cal_factor': { 'comment': 'Gyro '
'calibration '
'factor',
'field_name': 'gyro_ca... | |
in zip(ch_types_used, ylabels)}
titles = {c: t for c, t in zip(ch_types_used, titles_list)}
picks = np.arange(len(psd_list))
if not spatial_colors:
spatial_colors = color
_plot_lines(psd_list, info, picks, fig, ax_list, spatial_colors,
unit, units=units, scalings=None, hline=None, gfp=False,
types=types, zorder=... | |
or the response type of an API method. For instance: service Foo { rpc
Bar(google.protobuf.Empty) returns (google.protobuf.Empty); } The JSON
representation for `Empty` is empty JSON object `{}`.
"""
class EventsCustomresourcedefinitionsListRequest(_messages.Message):
r"""A EventsCustomresourcedefinitionsListReq... | |
from itertools import izip
import sys
import types
import numpy as np
from pandas.core.frame import DataFrame
from pandas.core.generic import NDFrame, PandasObject
from pandas.core.index import Factor, Index, MultiIndex
from pandas.core.internals import BlockManager
from pandas.core.series import Series
from pandas.c... | |
CONSUMER_MAX_FETCH_SIZE
consumer_auto_offset_reset: str = CONSUMER_AUTO_OFFSET_RESET
producer_compression_type: Optional[str] = PRODUCER_COMPRESSION_TYPE
timezone: tzinfo = TIMEZONE
web_enabled: bool
web_bind: str = WEB_BIND
web_port: int = WEB_PORT
web_host: str = socket.gethostname()
web_in_thread: bool = Fal... | |
{
'help': 'Arguments for this Adventure, '
'JSON string.',
'order': 1
},
'dsl': {
'help': 'Domain Specific Languague for '
'defining adventures. For example: '
'[ {{ "ns": {{}}, "primitive": '
'"download_cookbooks" }} ]',
'order': 2
},
'criteria': {
'help': 'Filter string written in the '
'opencenter filt... | |
Model()
c = ca.MX.sym('c')
p1 = ca.MX.sym('p1')
p2 = ca.MX.sym('p2')
p3 = ca.MX.sym('p3')
p4 = ca.MX.sym('p4')
x = ca.MX.sym('x')
der_x = ca.MX.sym('der(x)')
alias = ca.MX.sym('alias')
y = ca.MX.sym('y')
_tmp = ca.MX.sym('_tmp')
cst = ca.MX.sym('cst')
ref_model.states = list(map(Variable, [x]))
ref_model... | |
import binascii
import os
from io import BytesIO
import pytest
from pyhanko.pdf_utils import generic, misc, writer
from pyhanko.pdf_utils.crypt import (
DEFAULT_CRYPT_FILTER,
STD_CF,
AuthStatus,
CryptFilterConfiguration,
IdentityCryptFilter,
PubKeyAdbeSubFilter,
PubKeyAESCryptFilter,
PubKeyRC4CryptFilter,
Pu... | |
forward(self, *inputs):
x = self.conv1(inputs[0])
x = self.conv2(x)
x = self.conv2_drop(x)
x = x.view(x.size(0), -1)
x = self.fc1(x)
x = self.fc2(x)
return x
net = Net()
model = net.to(torch.device('cpu'))
sim = QuantizationSimModel(model, dummy_input=torch.rand(1, 1, 12, 12))
# Add wrappers again, expect... | |
<filename>CellProfiler/cellprofiler/modules/calculatestatistics.py
"""
CalculateStatistics
===================
**CalculateStatistics** calculates measures of assay quality (V and Z’
factors) and dose-response data (EC50) for all measured features made
from images.
The V and Z’ factors are statistical measures of assa... | |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# region Description
"""
wat.py: Cross platform WiFi attack tool (wat)
Author: <NAME>
License: MIT
Copyright 2020, Raw-packet Project
"""
# endregion
# region Import
from raw_packet.Utils.base import Base
from raw_packet.Utils.wifi import WiFi
from raw_packet.Utils.tm im... | |
<reponame>joye1503/Distributed-Computing-Scripts
#!/usr/bin/env python
# -*- coding: utf-8 -*-
'''
Automatic assignment handler for Mlucas and CUDALucas.
[*] Revised by <NAME> and <NAME> for CUDALucas (2020)
Original Authorship(s):
* # EWM: adapted from https://github.com/MarkRose/primetools/blob/master/mfloop.py
... | |
# do this when creating a clean network instance from a
# shapefile or a geopandas.GeoDataFrame, otherwise a shell
# network instance is created (see `split_arcs()` method)
if in_data is not None:
# set parameters as attributes
self.in_data = in_data
self.vertex_sig = vertex_sig
self.vertex_atol = vertex_atol
... | |
#
# Copyright (c) 2018 Juniper Networks, Inc. All rights reserved.
#
"""
Synopsis:
Collect logs, gcore(optional), introspect logs, sandesh traces and
docker logs from vrouter node.
Collect logs specific to control node.
Usage:
python vrouter_agent_debug_info.py -i <input_file>
Options:
-h, --help Display this hel... | |
<gh_stars>10-100
"""
Module containing class implementations of different TSP solver algorithms.
The classes extend an abstract Solver class, which contains abstract method
solve(), get_next_order(), and get_best_order()
"""
from __future__ import annotations
from abc import ABC, abstractmethod
from heapq import heap... | |
#!/usr/bin/env python3
import pvml
import numpy as np
import matplotlib.pyplot as plt
import argparse
from itertools import zip_longest
_NORMALIZATION = {
"none": lambda *X: (X[0] if len(X) == 1 else X),
"meanvar": pvml.meanvar_normalization,
"minmax": pvml.minmax_normalization,
"maxabs": pvml.maxabs_normalizati... | |
# D:\\PycharmProjects\\SolidityObfuscator\\src\\solidityobf\\T\\sol.g:32:5: ( versionOperator )? VersionLiteral
pass
root_0 = self._adaptor.nil()
# D:\\PycharmProjects\\SolidityObfuscator\\src\\solidityobf\\T\\sol.g:32:5: ( versionOperator )?
alt4 = 2
LA4_0 = self.input.LA(1)
if ((51 <= LA4_0 <= 57)) :
alt4 =... | |
is 'psd'.
'psd'
Returns the power spectral density.
'complex'
Returns the complex-valued frequency spectrum.
'magnitude'
Returns the magnitude spectrum.
'angle'
Returns the phase spectrum without unwrapping.
'phase'
Returns the phase spectrum with unwrapping.
Returns
-------
spectrum : array_like
2-D... | |
<gh_stars>0
from decimal import Decimal
import json
import random
import requests
import uuid
from django.conf import settings
from django.core.mail import send_mail
from django.db.models import Q
from django.template.loader import render_to_string
from django.utils import timezone
from django.utils.translation import... | |
plot
CS = main_axis.contour(contour_x_grid, contour_y_grid, zero_form, 15)
main_axis.clabel(CS, inline=True, fontsize=7)
# colour approperiate boxes
form_2_entry.configure(bg='#FFFFFF')
x_comp_entry.configure(bg='#FFFFFF')
y_comp_entry.configure(bg='#FFFFFF')
# colour the 0-form box
form_0_entry.configure(bg='#... | |
#: FA-18C
from src.client.client_interface import joy, vjoy, action, threshold, sequence, transfer, Filter
from src.helpers.freepie_vars import FreePieVars
def x52_pro_mapping():
### Joystick Builder Settings
joy_name = "X52 Professional H.O.T.A.S."
joy_axis_max = 1000
x52_pro = joy(joy_name, joy_axis_max)
### ... | |
= "yes"
elif get_JAMF_Configuration_Profile_Info_Exclusions == ("no"):
print("\nNot Including Exclusions Data.\n\n")
includeConfigurationProfileExclusionsInfo = "no"
elif get_JAMF_Configuration_Profile_Info == ("no"):
includeConfigurationProfileInfo = "no"
#####################################... | |
# -*- coding: utf-8 -*- #
"""*********************************************************************************************"""
# FileName [ augmentation.py ]
# Synopsis [ Data Augmentation Pipeline ]
# Source [ https://github.com/melwch/s3prl/tree/master/s3prl/preprocess/augmentation ]
# Author [ <NAME>, Melvin ]
... | |
<gh_stars>1-10
#!/usr/bin/env python3
###############################################################################
# #
# RMG - Reaction Mechanism Generator #
# #
# Copyright (c) 2002-2021 Prof. <NAME> (<EMAIL>), #
# Prof. <NAME> (<EMAIL>) and the RMG Team (<EMAIL>) #
# #
# Permission is hereby granted, free of char... | |
<filename>psga/features/spectral_features.py
"""
This is a combination of multiple function to extract spectral features from a
mne Epochs objects. Some of these functions are a from the mne-features packages
(https://github.com/mne-tools/mne-features) with some small modifications and
all the credit goes to the author... | |
<reponame>theoryno3/paulrigoruci-rdfextras
# -*- coding: utf-8 -*-
from __future__ import generators
import rdflib
from rdflib.Graph import ConjunctiveGraph
from rdflib import plugin
from rdflib.store import Store, NO_STORE, VALID_STORE
from rdflib import Namespace
from rdflib import Literal
from rdflib imp... | |
<gh_stars>0
from tkinter import *
def VVIR(user):
vvir = Tk()
vvir.title("VVIR")
vvir.geometry("800x400")
parameters = Label(vvir, text="Parameters")
parameters.grid(row=1, column=1, columnspan=2)
f = font.Font(parameters, parameters.cget("font"))
f.configure(underline=True)
parameters.configure(font=f)
l... | |
<reponame>mjoppich/miRExplore
from collections import defaultdict
import os, sys
sys.path.insert(0, str(os.path.dirname(os.path.realpath(__file__))) + "/../")
import scispacy
import spacy
from spacy import displacy
from textmining.MirGeneRelCheck import MirGeneRelCheck, nlp
#nlp = spacy.load('/mnt/d/spacy/models/en... | |
<reponame>ai-se/parGALE
from consts import METRICS_MAXIMIZE, METRICS_MINIMIZE
from npGIAforZ3 import GuidedImprovementAlgorithm, \
GuidedImprovementAlgorithmOptions
from npGIAforZ3 import setRecordPoint
from z3 import *
import Z3ModelEShopUpdateAllMin as SHP_Min
import Z3ModelEmergencyResponseUpdateAllMin as ERS_Min
i... | |
from __future__ import annotations
import collections
import functools
import operator
from typing import IO, TYPE_CHECKING, Any, Iterable, Literal, Mapping, Sequence
import numpy as np
from cached_property import cached_property
from public import public
import ibis
from ... import util
from ...common import excep... | |
<filename>CIFAR/train.py
# -*- coding: utf-8 -*-
from sklearn.metrics import det_curve, accuracy_score, roc_auc_score
from make_datasets import *
from models.wrn_ssnd import *
import wandb
if __package__ is None:
import sys
from os import path
sys.path.append(path.dirname(path.dirname(path.abspath(__file__))))
'... | |
statistics
_, img_shape, bias, mu_beh, mu_eye, scale = prepare_data(key, readout_key)
models = get_multi_model(key)
adj_model = get_adj_model(models, readout_key, neuron_id, mu_eye=mu_eye)
def get_activation(mei):
with torch.no_grad():
img = torch.Tensor(process(mei[..., None], mu=bias, sigma=scale)[None, ...])... | |
<reponame>hephaex/probability
# Copyright 2018 The TensorFlow Probability Authors.
#
# 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 re... | |
# Author: <NAME>
import unittest
import math
from fractions import Fraction
from logic.tests.conv_test import test_conv
from logic.tests.logic_test import test_macro
from logic import context
from logic import auto
from kernel.proofterm import ProofTerm
from data import real
from syntax import parser
from prover impo... | |
<filename>test/hummingbot/strategy/cross_exchange_market_making/test_cross_exchange_market_making.py
import logging
import unittest
from decimal import Decimal
from math import ceil, floor
from typing import List
import pandas as pd
from nose.plugins.attrib import attr
from hummingbot.connector.exchange.paper_trade.p... | |
# 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 may ... | |
import copy
import logging
import numpy as np
import six
import tensorflow as tf
from functools import wraps
from contextlib import contextmanager
from .backend_base import BackendBase, FunctionBase, DeviceDecorator
try:
from tensorflow.contrib.distributions import fill_triangular
except:
print("Cannot find fill_tri... | |
# Copyright (c) 2021, Oracle and/or its affiliates.
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License, version 2.0,
# as published by the Free Software Foundation.
#
# This program is also distributed with certain software (including
#... | |
<filename>src/zope/dublincore/interfaces.py
##############################################################################
#
# Copyright (c) 2002 Zope Foundation and Contributors.
# All Rights Reserved.
#
# This software is subject to the provisions of the Zope Public License,
# Version 2.1 (ZPL). A copy of the ZPL sho... | |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
""" This file formats Understanding Society variables for using in a microsimulation.
It DOES NOT handle missing data. see US_missing.py.
"""
import pandas as pd
import numpy as np
import argparse
import US_utils
# suppressing a warning that isn't a problem
pd.options.mo... | |
constraints. If no solution was found, a None
disctionary is returned. TO BE USED WHILE CAR IS TRACKING THE WAYPOINTS
IN CARLA ENVIRONMENTS
Parameters
----------
start_w : list
Starting waypoint.
next_w : list
Next Waypoint.
waypts : Numpy array
Next N waypoints
SigmaE : numpy array
Starting Covariance... | |
None')
evt = api.async_call(self, self.sessionUuid)
self.out = evt
return self.out
class GetPrimaryStorageAllocatorStrategiesAction(inventory.APIGetPrimaryStorageAllocatorStrategiesMsg):
def __init__(self):
super(GetPrimaryStorageAllocatorStrategiesAction, self).__init__()
self.sessionUuid = None
self.out = Non... | |
# Hani's get_dG_ratio_to_optimum filter:
# (see files folding_energy.c and matchmaker.c)
# - returns the ratio of the dG for a fold that takes the shape of the "motif" at the specified position relative to the global minimum dG for folding
# - mask motif match with Ns (function lcl_get_surrounding_sequence)
# - make an... | |
return
oprot.writeStructBegin('update_user_info_result')
if self.success is not None:
oprot.writeFieldBegin('success', TType.BOOL, 0)
oprot.writeBool(self.success)
oprot.writeFieldEnd()
if self.e is not None:
oprot.writeFieldBegin('e', TType.STRUCT, 1)
self.e.write(oprot)
oprot.writeFieldEnd()
oprot.writeFiel... | |
import pytest
import numpy as np
from devito import (Constant, Grid, TimeFunction, SparseTimeFunction, Operator,
Eq, ConditionalDimension, SubDimension, SubDomain, configuration)
from devito.ir import FindSymbols, retrieve_iteration_tree
from devito.exceptions import InvalidOperator
def test_read_write():
nt = 10
... | |
in range(3):
diff_grad = scale*(diffuse_grads[i_diff][:npix].as_numpy_array())
p = diffuse_params_lookup[t][i_diff]
diff_grad = p.get_deriv(x[p.xpos], diff_grad)
J[p.xpos] += diff_grad
if eta_params[0].refine:
if SIM.D.has_anisotropic_mosaic_spread:
eta_derivs = SIM.D.get_aniso_eta_deriv_pixels()
else:
eta_de... | |
make_block(values, items, ref_items):
dtype = values.dtype
vtype = dtype.type
klass = None
if issubclass(vtype, np.floating):
klass = FloatBlock
elif issubclass(vtype, np.complexfloating):
klass = ComplexBlock
elif issubclass(vtype, np.datetime64):
klass = DatetimeBlock
elif issubclass(vtype, np.integer):
k... | |
<reponame>AlloSphere-Research-Group/tinc-python
try:
from ipywidgets import interact, interactive, interact_manual, HBox
import ipywidgets as widgets
except:
print("Can't import ipywidgets. Notebook widgets not available")
import unittest
from .cachemanager import VariantValue, VariantType
from .tinc_object import... | |
string.')
if not value:
raise InterpreterException('Assert failed: ' + message)
def set_variable(self, varname, variable):
if variable is None:
raise InvalidCode('Can not assign None to variable.')
if not isinstance(varname, str):
raise InvalidCode('First argument to set_variable must be a string.')
if not sel... | |
FROM
# ocr_blocks b,
# ocr_documents d,
# (
# SELECT
# document_id,
# block,
# word_line,
# word,
# word_text
# FROM
# ocr_entries
# WHERE
# document_id IN
# (
# SELECT document_id FROM ocr_documents WHERE replace(filename, '.jpg', '') IN
# (
# SELECT
# filename
# FROM
# ocr_auto_sample
# WHERE
# ref_or_test = 'te... | |
<filename>train_reaction_graph_with_actions.py
import os
import gc
import sys
import datetime
import argparse
import numpy as np
import pandas as pd
import pickle as pkl
import torch
import torch.nn as nn
import torch.optim as optim
from torch.utils.data import DataLoader
from torch.utils.tensorboard import SummaryWr... | |
205.4, 204.9, 204.5, 204.1, 203.8, 203.6,
203.5, 203.5, 203.4, 203.5, 203.6, 203.7, 203.9, 204.1, 204.2,
204.3, 204.3, 204.4, 204.5, 204.6, 204.3, 204.1, 203.9, 203.6,
203.5, 203.2, 202.9, 202.6, 202.3, 202.4, 202.6, 202.7, 203.1,
200.8, 201. , 201.8, 202.7, 204. , 205.2, 205.8, 206.2, 206.3,
206.3, 206.2, 20... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.