content stringlengths 5 1.05M |
|---|
# Copyright (c) 2020 NVIDIA Corporation. All rights reserved.
# This work is licensed under the NVIDIA Source Code License - Non-commercial. Full
# text can be found in LICENSE.md
import torch
import torch.nn as nn
import torchvision.transforms as transforms
import time
import os
import sys
import math
import numpy a... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import logging
import requests
import json
import app.settings as settings
from typing import Dict
logger = logging.getLogger('server')
class TwitterService:
def __init__(self):
self.conn = None
def get_conversation(self,tweetId:str)->Dict:
twitter_conn... |
#!/usr/bin/env python
f = open('/Users/kosta/dev/advent-of-code-17/day5/input.txt')
#contents = list(map(int, f.readlines()))
contents = [int(i) for i in f.readlines()]
print (contents)
exited = False
cur = 0
step = 0
while(not exited):
next = contents[cur] + cur
if next > len(contents) - 1:
exited =... |
#!/usr/bin/env python
"""
Copyright (C) 2018 Intel Corporation
?
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 ag... |
__author__ = 'efelix'
from rdkit import Chem
from beaker.utils.functional import _apply, _call
from beaker.utils.io import _parseMolData
import beaker.utils.chemical_transformation as ct
import copy
import json
import os.path as path
data_dir = path.abspath(path.join(__file__ , "../../../../data"))
with open('{}/ch... |
import logging.config
import os
from typing import Tuple
from kbc_evaluation.dataset import DataSet, ParsedSet
logconf_file = os.path.join(os.path.dirname(__file__), "log.conf")
logging.config.fileConfig(fname=logconf_file, disable_existing_loggers=False)
logger = logging.getLogger(__name__)
class EvaluatorResult:
... |
# Copyright (c) 2016-2018, University of Idaho
# All rights reserved.
#
# Roger Lew (rogerlew@gmail.com)
#
# The project described was supported by NSF award number IIA-1301792
# from the NSF Idaho EPSCoR Program and by the National Science Foundation.
from os.path import join as _join
from os.path import exists as _e... |
"""Representation of Python function headers and calls."""
import collections
import itertools
import logging
from pytype import datatypes
from pytype import utils
from pytype.abstract import abstract_utils
from pytype.pytd import pytd
from pytype.pytd import pytd_utils
log = logging.getLogger(__name__)
_isinstance ... |
#################
## Created by Engin Cukuroglu
#################
import os,sys,time
import multiprocessing
from multiprocessing import Queue, Process
import subprocess
import socket
from codesOfTools import multiprotSolutionReader, vdwInterfaceDictionaryCreator
def multiprotRunListWork(taskQueue_multiprotRunList, mu... |
import requests
class MyCrawler:
def __init__(self):
pass
@classmethod
def fetchHtml(cls, url):
return requests.get(url).text |
# Used to tokenize tweets and/or process them in terms of politics
import re
class TweetTokenizer:
# Tokenizes tweets
def __init__(self):
# Setup re object for finding emojis
emoji_str = r"""
(?:
[>}]? # Eyebrows (optional)
... |
""" Python class to interact with the APIs. """
import sys
import json
import time
import jwt
from requests import Session
from deepmap_sdk import auth, users, tiles, maps
class DeepmapClient:
""" Python Client for the Deepmap API. """
def __init__(self, api_token, server_url='https://api.deepmap.com'):
... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
#
# Copyright (c) 2013, Roboterclub Aachen e.V.
# 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... |
print('Exercício Python #028 - Jogo da Adivinhação v.1.0')
import random
from time import sleep
r = random.randint(1, 5) #Faz o computador "PENSAR"
print('-=-' * 20)
u = int(input('Escreva um número de 1 a 5? ')) #Jogador tenta adivinhar
print('-=-' * 20)
print('Processando...')
sleep(1)
if u == r:
print('Parabéns!... |
import os
import platform
print("System: {name} {system} {release}".format(name=os.name,
system=platform.system(),
release=platform.release()))
import sys
print("Python: " + sys.version)
import pytest
print("pytest: "... |
# CNO rate module generator
from pyreaclib.networks import PythonNetwork
files = ["c12-pg-n13-ls09",
"c13-pg-n14-nacr",
"n13--c13-wc12",
"n13-pg-o14-lg06",
"n14-pg-o15-im05",
"n15-pa-c12-nacr",
"o14--n14-wc12",
"o15--n15-wc12"]
cno_net = PythonNetwork(fi... |
#!/usr/bin/env python3
#
# Copyright (c) 2019 Two Sigma Open Source, LLC
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to
# deal in the Software without restriction, including without limitation the
# rights ... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Copyright(C) 2021 cGIfl300 <cgifl300@gmail.com>
from django.contrib.auth.models import User
from django.db import IntegrityError
from store.models import UserFollows
def follow(user_to_follow, request):
# Get actual user
actual_user = User.objects.filter(user... |
import sys
print(sys.version) |
# Copyright 2021 Kamil Sroka
# 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, sof... |
--- mesonbuild/mesonlib.py.orig 2019-11-28 17:37:44 UTC
+++ mesonbuild/mesonlib.py
@@ -672,7 +672,7 @@ def default_libdir():
return 'lib/' + archpath
except Exception:
pass
- if is_freebsd():
+ if is_freebsd() or is_dragonflybsd:
return 'lib'
if os.path.isdir('... |
# Classifying movie genres with k-Nearest Neighbors
import kNN
group, labels = kNN.createDataSet()
print(group)
print(labels)
result = kNN.classify0([0, 0], group, labels, 3)
print(result)
|
# -*- coding: utf-8 -*- #
# Copyright 2017 Google LLC. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless requir... |
# terrascript/template/d.py
import terrascript
class template_file(terrascript.Data):
pass
class template_cloudinit_config(terrascript.Data):
pass
|
"""
SystemC serializer serializes HDL objects to systemC code.
"""
|
from robotchef.plugin import Chef
class Cook(Chef):
def make(self, food=None):
print("I can cook " + food)
|
import json
import io
from pathlib import Path
import xml.etree
import pyproj
import pytest
import rasterio.coords
import stac_vrt
HERE = Path(__name__).parent.absolute()
@pytest.fixture
def response():
with open(HERE / "tests/response.json") as f:
resp = json.load(f)
return resp
def assert_vrt_... |
#!/usr/bin/env python3
import os
import re
import logging
import requests
log = logging.getLogger(__name__)
baseurl = os.environ.get("UNIFI_BASEURL", "https://unifi:8443")
username = os.environ.get("UNIFI_USERNAME")
password = os.environ.get("UNIFI_PASSWORD")
site = os.environ.get("UNIFI_SITE", "default")
fixed_only ... |
"""
* Copyright (C) Caleb Marshall - All Rights Reserved
* Written by Caleb Marshall <anythingtechpro@gmail.com>, April 23rd, 2017
* Licensing information can found in 'LICENSE', which is part of this source code package.
"""
import string
import random
import struct
class DataBuffer(object):
def __init__(se... |
import logging
from django.conf import settings
logger = logging.getLogger(__name__)
if settings.SMS_PROVIDER == 'nexmo':
from nexmo import Client as BaseClient
else:
class BaseClient:
def __init__(self, **kwargs):
self.messages = []
def send_message(self, message):
... |
import math
import time
import numpy as np
#accuracy, precision, recall and f1 score calculations
def scores(labels_test,predicted_labels,time):
TP = 0
TN = 0
FP = 0
FN = 0
for n in range(0,len(labels_test)):
if predicted_labels[n] == 1 and labels_test[n] == 1:
TP +=1
... |
from django.conf.urls import url
from structure.views import *
from structure import views
from django.conf import settings
from django.views.generic import TemplateView
from django.views.decorators.cache import cache_page
urlpatterns = [
url(r'^$', cache_page(60*60*24)(StructureBrowser.as_view()), name='... |
# -*- coding: utf-8 -*-
import scrapy
from ..items import CrudeoilpricingItem
class MyspdSpider(scrapy.Spider):
name = 'myspd'
allowed_domains = ['https://www.macrotrends.net/2516/wti-crude-oil-prices-10-year-daily-chart']
start_urls = ['https://www.macrotrends.net/2516/wti-crude-oil-prices-10-year-daily-... |
from __future__ import print_function
from __future__ import division
from . import _C
import torch
import torch.nn.functional as F
from fuzzytools.strings import xstr
from . import exceptions as ex
import numpy as np
import pandas as pd
################################################################################... |
import pygal
from datetime import datetime, date
from pygal.style import Style
invis_style = Style(background = 'transparent')
def generate(libraries, metric, chart_type):
# default for chart_type is default chart to be created
chart = None
if metric == 'popularity':
if chart_type == 'default' or chart_type == ... |
# isinstance("10", str)
# isinstance(10, int)
# isinstance({"name":"Mrx"}, dict)
# isinstance(["name","Mrx"], list)
def isList(data):
return isinstance(data, list)
def isDict(data):
return isinstance(data, dict)
def isString(data):
return isinstance(data, str)
def isInt(data):
retur... |
# conditional probability density function python
# https://www.google.com/search?q=conditional+probability+density+function+python&sxsrf=ALeKk01hnlyDVUrgQH2JuGrK7fkCeVELvQ%3A1621257267286&ei=M2yiYKD4ENPemAWJ9ICoCQ&oq=conditional+probability+density+function+python&gs_lcp=Cgdnd3Mtd2l6EAMyBggAEBYQHjoHCCMQsAMQJzoHCAAQRxC... |
import uuid
from django.conf import settings
from django.db import models
from pagseguro.signals import notificacao_recebida
from .managers import CartManager, PurchaseManager
def generate_code():
return uuid.uuid4()
class BaseModel(models.Model):
id = models.UUIDField(primary_key=True, editable=False, de... |
import csv
import ast
from .gate import Gate
from .net import Net
from copy import deepcopy
class Board:
"""
handles loading of gates, nets and grid
main methods for use in algorithms
"""
def __init__(self, print_csv, netlist_csv):
self.gates = {}
self.gate_locations = []
... |
#!/usr/bin/env python3
"""
Update Wikifeat couchdb databases from 0.3a to 0.4.0a
Note: Requires python3
Changes:
1. Added by name search to user query design document
"""
import json
import common
import sys
user_ddoc = 'user_queries'
usersByName = dict()
usersByName['map'] = """
function(doc){
... |
from .base_manager import BaseManager
from .one_a import ManagerOneA
from .one_b import ManagerOneB
from .two import ManagerTwo
from .three import ManagerThree
|
import cv2
import numpy as np
import argparse, sys, os
##from GUIdriver import *
import pandas as pd
def endprogram():
print ("\nProgram terminated!")
sys.exit()
text = str(ImageFile)
print ("\n*********************\nImage : " + ImageFile + "\n*********************")
img = cv2.imread(text)
img = cv2.r... |
#DejaVuSansCondensed.ttf
#DejaVuSansCondensed.pkl
#DejaVuSansCondensed.cw127.pkl
#The above files help this file run. The purpose of these files is to use unicode characters.
#If you do not want to use these files, activate the comment line and delete the add_font line. Replace 'Dejavu' in set_font with 'Times'.
import... |
# Generated by Django 2.0.1 on 2018-02-14 19:18
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('accounts', '0005_auto_20180202_1116'),
]
operations = [
migrations.AlterModelOptions(
name='user',
options={'verbose... |
from wordcloud import WordCloud
from collections import Counter
import matplotlib as mpl
import matplotlib.pyplot as plt
import matplotlib.font_manager as fm
import numpy as np
import seaborn as sns
import missingno as msno
import os
# To Do: 1) 시각화 default setting 설정
def test():
print('\n', )
print('domain >... |
from .parse import parse_expression, ParseException
from .tokenize import tokenize, TokenizeException
from .node import Node, CalculationException
|
#!/usr/bin/python
# -*- coding: utf-8 -*-
# (c) 2017, Ansible by Red Hat, inc
#
# This file is part of Ansible by Red Hat
#
# Ansible is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the Li... |
# coding: utf-8
from __future__ import absolute_import
from datetime import date, datetime # noqa: F401
from typing import List, Dict # noqa: F401
from tapi_server.models.base_model_ import Model
from tapi_server.models.tapi_common_bandwidth_profile import TapiCommonBandwidthProfile # noqa: F401,E501
from tapi_se... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from datetime import datetime
# Bubble Sort 冒泡排序
# 冒泡排序只会操作相邻的两个数据。
# 自然界中, 气泡的密度比水小,在水中,越大的气泡受到的浮力也就越大, 就会先到达水面
# 冒泡排序只会操作相邻的两个数据。
# 每次冒泡操作都会**对相邻的两个元素进行比较,看是否满足大小关系要求**。如果不满足就让它俩互换。
# 一趟冒泡会让至少一个元素移动到它应该在的位置,重复 n 趟,就完成了 n 个数据的排序工作。
# #### 分析
# 1. 原地排序算法: 只涉及相邻数据的交换, 需要一个... |
import time
from js9 import j
JSBASE = j.application.jsbase_get_class()
class TIMER(JSBASE):
def __init__(self):
self.__jslocation__ = "j.tools.timer"
JSBASE.__init__(self)
@staticmethod
def execute_until(callback, timeout=60, interval=0.2):
"""
Check periodicly if callback... |
from msal import ConfidentialClientApplication
class AzureAdAppFactory:
@classmethod
def create(cls, **kwargs) -> ConfidentialClientApplication:
client_id = kwargs["client_id"]
client_secret = kwargs["client_secret"]
authority = kwargs["authority"]
return ConfidentialClientApp... |
import hashlib
import pytest
import random
from two1.crypto.ecdsa_base import Point
from two1.crypto import ecdsa_openssl
from two1.crypto import ecdsa_python
def make_low_s(curve, p, rec_id):
new_p = p
if p.y >= (curve.n // 2):
new_p = Point(p.x, curve.n - p.y)
rec_id ^= 0x1
return new_... |
#!/usr/bin/env python
# Copyright (C) 2015 The Android Open Source Project
#
# 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 __future__ import division
import numpy as np
import tensorflow as tf
# components
from tensorflow.python.ops.nn import dropout as drop
from cnn import conv_layer as conv
from cnn import conv_relu_layer as conv_relu
from cnn import pooling_layer as pool
from cnn import fc_layer as fc
from cnn import fc_relu_laye... |
import unittest
from fastapi.testclient import TestClient
from core.api.controller import create_app
from core.api.request.judge_request import JudgeRequest
from core.api.request.eval_request import EvalRequest
from core.api.request.reading_request import ReadingRequest
class TestAPI(unittest.TestCase):
DAJARE_J... |
#!/usr/bin/python3
# -*- coding: utf-8 -*-
import survey
class Baby(survey.Record):
"""Represent a baby record """
class Babies(survey.Table):
"""Represents the Babies table."""
def __init__(self):
survey.Table.__init__(self)
self.startflg = False
def GetFilename(self):
retur... |
from abc import ABCMeta, abstractmethod
class Attack(metaclass=ABCMeta):
@abstractmethod
def attack(self, model, adj, features, **kwargs):
"""
:param model:
:param features:
:param adj:
:param kwargs:
:return:
"""
class ModificationAttack(Attack):
... |
"""Quality-time specific types."""
from typing import Any, Dict, List, NewType, Optional, Sequence, Union
Entity = Dict[str, Union[int, str]] # pylint: disable=invalid-name
Entities = List[Entity]
ErrorMessage = Optional[str]
Job = Dict[str, Any]
Jobs = List[Job]
Namespaces = Dict[str, str] # Namespace prefix to N... |
from combus.command import Command
from combus.command_bus import CommandBus
from combus.command_handler import CommandHandler
def test_it_will_handle_a_command():
class Bar(object):
def __init__(self):
self._foo = None
@property
def foo(self):
return self._foo
... |
import glob
import itertools
import json
import os
import re
from functools import partial
from math import isclose
import ConfigSpace as CS
import ConfigSpace.hyperparameters as CSH
import matplotlib.pyplot as plt
import numpy as np
import seaborn as sns
from ConfigSpace.read_and_write import json as config_space_jso... |
supported_resolutions = [
(640, 350, 70),
(640, 350, 85),
(640, 400, 70),
(640, 400, 85),
(640, 480, 60),
(640, 480, 73),
(640, 480, 75),
(640, 480, 85),
(640, 480, 100),
(720, 400, 85),
(768, 576, 60),
(768, 576, 72),
(768, 576, 75),
(768, 576, 85),
(768, 576... |
__version__ = '0.1.2'
from mini_api.api import Server, HTTPStatus
|
import os
import logging
from util import kubernetes
from util import config
from temporal.workerfactory import WorkerFactory
from temporal.workflow import workflow_method, Workflow, WorkflowClient
logging.basicConfig(level=logging.INFO)
kube = kubernetes.Cluster()
paul_config = config.Configuration()
worker_config... |
from collections import namedtuple
from datetime import date
from dateutil.relativedelta import relativedelta
from flask import redirect, url_for, flash, render_template
from flask.blueprints import Blueprint
from flask_login import current_user
from flask_login.utils import login_required
from loguru import logger
imp... |
"""Tests
>>> arr = ['G', 'B', 'R', 'R', 'B', 'R', 'G']
>>> sort_rgb(arr)
>>> print(arr)
['R', 'R', 'R', 'G', 'G', 'B', 'B']
>>> arr = ['R', 'B', 'G']
>>> sort_rgb(arr)
>>> print(arr)
['R', 'G', 'B']
"""
from typing import List
def sort_rgb(arr: List[str]):
offset = _sort_key... |
import argparse
import os
import cv2
from . import models
from . import profile
def plot_correction(img, disk_attr, args, plotter):
stack = profile.extract_stack(img, disk_attr, args['slices'])
stack_clean = profile.clean_stack(stack)
intensity_profile = profile.compress_stack(stack_clean)
model = m... |
import unittest
import numpy as np
from neet.boolean import ECA, RewiredECA
from neet.network import Network
from neet.boolean.network import BooleanNetwork
class TestRewiredECA(unittest.TestCase):
"""
Unit tests of the RewiredECA class
"""
def test_is_network(self):
"""
Ensure that R... |
'''Preprocessing data.'''
import os
import numpy as np
import cv2
from tensorflow.python.keras.preprocessing.image import DirectoryIterator as Keras_DirectoryIterator
from tensorflow.python.keras.preprocessing.image import ImageDataGenerator as Keras_ImageDataGenerator
from tensorflow.python.keras.preprocessing.image... |
'''
Author: Karan Sharma
Probleum:
Page 28 at [link]
'''
import hashlib as hasher
from core import create_genesis_block, Block
import datetime as date
class BlockChain:
def __init__(self):
self.headBlock = Block("Genesis Block")
self.headHash = self.headBlock.hashMe()
def add_block(self,data... |
import matplotlib.pyplot as plt
import pandas as pd
import plotly.graph_objects as go
import numpy as np
import plotly.io as pio
pio.renderers.default = "browser"
df = pd.read_csv("../Dataset.csv")
x = df["Area"]
y = df["Price"]
f = go.FigureWidget([go.Scatter(x=x, y=y, mode='markers')])
scatter = f.data[0]
color... |
# -*- coding: utf-8 -*-
import tensorflow as tf
import sys
def negative_l1_distance(x1, x2, axis=1):
"""
Negative L1 Distance.
.. math:: L = - \\sum_i \\abs(x1_i - x2_i)
:param x1: First term.
:param x2: Second term.
:param axis: Reduction Indices.
:return: Similarity Value.
"""
... |
import ipaddress
import itertools
import logging
from collections import deque
from ipaddress import IPv4Address, IPv6Address
from typing import Dict, List, Optional, Union
from h2.config import H2Configuration
from h2.connection import H2Connection
from h2.errors import ErrorCodes
from h2.events import (
Event, C... |
from django.db import models
# Create your models here.
class Ganador(models.Model):
DEPARTAMENTOS = (
(0, 'Ninguno'),
(1, 'Atlántida'),
(2, 'Choluteca'),
(3, 'Colón'),
(4, 'Comayagua'),
(5, 'Copán'),
(6, 'Cortes'),
(7, 'El Paraíso'),
(8, 'Fra... |
class Restaurant:
def __init__(self, name, cuisine_type):
self.name = name
self.type = cuisine_type
def describe_restaurant(self):
print(f"{self.name} is a restaurant that sells {self.type} food")
def open_restaurant(self):
print("The restaurant is open")
bob = Restaurant... |
# Math Module Part 2
import math
# Factorial & Square Root
print(math.factorial(3))
print(math.sqrt(64))
# Greatest Common Denominator GCD
print(math.gcd(52, 8))
print(math.gcd(8, 52))
print(8/52)
print(2/13)
# Degrees and Radians
print(math.radians(360))
print(math.degrees(math.pi * 2))
|
# coding: utf-8
"""
Emby Server API
Explore the Emby Server API # noqa: E501
OpenAPI spec version: 4.1.1.0
Generated by: https://github.com/swagger-api/swagger-codegen.git
"""
from __future__ import absolute_import
import re # noqa: F401
# python 2 and python 3 compatibility library
import ... |
#!/usr/bin/env python
"""MPUSensorTest.py: Receives raw data from MPU 9DOF click IMU+Magnetometer and displays it."""
import smbus
import math
# Power management registers
power_mgmt_1 = 0x6b
power_mgmt_2 = 0x6c
def read_byte(adr):
return bus.read_byte_data(address, adr)
def read_word(adr):
high = bus.read... |
import re
import discord
from src.utils import *
class Pokeutilities:
def __init__(self, user_id: int=0, preferred_catch_type: str="base"):
self.deriver_id = 704130818339242094
self.user_id = user_id
self.preferred_catch_type = preferred_catch_type
if self.preferr... |
# Copyright 2017 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or ag... |
import torch
from torch.nn import functional as F
def swish(input, inplace=False):
return input * torch.sigmoid(input)
def mish(input, inplace=False):
return input * torch.tanh(F.softplus(input))
def hard_swish(input, inplace=False):
return input * hard_sigmoid(input)
def hard_sigmoid(input, inplace... |
from dataclasses import dataclass
from typing import List
import numpy as np
import tensorflow as tf
from active_learning_ts.experiments.blueprint_element import BlueprintElement
from active_learning_ts.knowledge_discovery.discover_tasks.prim.prim import PRIM
from active_learning_ts.knowledge_discovery.knowledge_disc... |
from filters import returnPercentIndex
import numpy as np
from scipy.signal import butter,filtfilt
import matplotlib.pyplot as plt
def baseline(x, y, fs, order = 2, cutoff=1, addPlot=False):
my = butter_lowpass_filter(y, cutoff, fs, order)
return touchBaselineRightToLeft(x, y, my,addPlot=addPlot)
def getRight... |
DB_PATH = 'db.sqlite'
ADMIN_ID = 0
BOT_USERNAME = ''
API_ID = 0
API_HASH = ''
BOT_TOKEN = ''
PROXY = None
|
# Import module
import tensorflow as tf
import pickle
import re
class Model:
def __init__(self):
self.model = None
self.vocab = None
self.appos = {
"aren't": "are not",
"can't": "cannot",
"cant": "cannot",
"couldn't": "could not",
... |
# Setup paths for module imports
from _unittest.conftest import local_path, scratch_path
# Import required modules
from pyaedt.generic.filesystem import Scratch
from pyaedt.generic.LoadAEDTFile import load_entire_aedt_file
import base64
import filecmp
import os
import sys
def _write_jpg(design_info, scratch):
""... |
import pytest
@pytest.fixture
def variable_factory(db):
"""
Returns a Variable instance.
"""
from persistent_settings.models import Variable
def factory(value, name="FOO"):
return Variable.objects.create(name=name, value=value)
return factory
@pytest.fixture
def request_obj(client)... |
import logging
import os
from pywps import FORMATS, ComplexInput, ComplexOutput, Format, LiteralInput, LiteralOutput, Process
from pywps.app.Common import Metadata
from pywps.response.status import WPS_STATUS
from pywps.inout.literaltypes import AllowedValue
from pywps.validator.allowed_value import ALLOWEDVALUETYPE
... |
from ..app import App
from ..model import Collection
from .base import AggregateProvider
class StorageAggregateProvider(AggregateProvider):
def aggregate(self, query=None, group=None, order_by=None, limit=None):
return self.storage.aggregate(
query, group=group, order_by=order_by, limit=limit
... |
import pygame as pg
vec = pg.math.Vector2
#Colors
RED = (255, 0, 0)
GREEN = (0, 255, 0)
#Game Settings
WIDTH = 1200
HEIGHT = 900
FPS = 120
#Arrow Settings
SPEED = [600, 1000] |
import requests
# Link to request data about the characters
url = 'http://anapioficeandfire.com/api/characters?name='
# Get the character name to search for
name = input('Enter a name to search for: ')
url += name
# Make an HTTP request and the API will respond with a JSON output
response = requests.get(url)
# Get... |
# Copyright (c) 2013, FinByz Tech Pvt. Ltd. and contributors
# For license information, please see license.txt
from __future__ import unicode_literals
import frappe
from frappe.utils import flt
from frappe import msgprint, _
def execute(filters=None):
return _execute(filters, additional_table_columns=[
dict(fieldt... |
"""Django REST Framework like model viewsets."""
from functools import update_wrapper
from inspect import getmembers
from django.core.exceptions import ImproperlyConfigured
from django.utils.decorators import classonlymethod
from django.views.generic.base import TemplateResponseMixin, View
from . import mixins
clas... |
if __name__ == '__main__':
import numpy as np
import pandas as pd
import os
print('\n Memory Pressure Test Starts...\n')
for i in os.listdir():
if 'mprofile_' in i:
df = pd.read_csv(i, sep=' ', error_bad_lines=False)
df.columns = ['null', 'memory', 'time']
df.drop('nu... |
## patch the interface of Neutron::Events boost python binding
from mcni.mcnibp import vector_Event, Position_double, Velocity_double, NeutronState, NeutronSpin
original__str__ = vector_Event.__str__
def __str__(self):
if len(self)>10: return original__str__(self)
return ', '.join( [ '%s' % n for n in self ... |
rooms = {}
def save(room_id, room):
rooms[room_id] = room
def delete(room_id):
return rooms.pop(room_id)
def update(room_id, room):
save(room_id, room)
def get(room_id):
return rooms[room_id] |
import itertools
import numpy as np
from sklearn.linear_model import SGDClassifier, SGDRanking
from sklearn import metrics
from minirank.compat import RankSVM as MinirankSVM
from scipy import stats
def transform_pairwise(X, y):
"""Transforms data into pairs with balanced labels for ranking
Transforms a n-cl... |
from django import template
from django.db.models import Q
from notifications.models import Notification
register = template.Library()
@register.simple_tag
def notifications(user):
return (Notification.objects.filter(user=user)
.order_by('-created_at'))[:8]
@register.simple_tag
def notifs_unread(use... |
from google.appengine.ext import ndb
class User(ndb.Model):
username = ndb.StringProperty(required=True)
hash = ndb.StringProperty(required=True)
created = ndb.DateTimeProperty(auto_now_add=True)
|
"""
LTI consumer CMS plugin
"""
from django.utils.translation import gettext_lazy as _
from cms.plugin_base import CMSPluginBase
from cms.plugin_pool import plugin_pool
from richie.apps.core.defaults import PLUGINS_GROUP
from .forms import LTIConsumerForm
from .models import LTIConsumer
@plugin_pool.register_plugi... |
# Copyright (c) 2017, MD2K Center of Excellence
# 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 notice, this
# list of conditio... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.