content stringlengths 5 1.05M |
|---|
#!/usr/bin/env python3
import hashlib
import os
import re
import shutil
import numpy as np
import h5py
import tensorflow as tf
import torch
def main():
pytorch_root = 'https://download.pytorch.org/models'
tf_root = 'https://storage.googleapis.com/tensorflow/keras-applications/resnet'
model_dir = os.enviro... |
expected_output={'active_tenants_num': 20,
'max_tenants': 24,
'tenant_name': {'Tenanttest12': {'tenant_id': 20, 'tenant_vpnid': 1037},
'Tenanttest13': {'tenant_id': 20, 'tenant_vpnid': 1037},
'apple': {'tenant_id': 20, 'tenant_vpnid': 1037},
'ciscov-DEEP1': {'tenant_... |
# Make a program that plays Odds or Evens with the computer. The game will only be stopped when the player loses,
# showing the total number of consecutive victories he has won at the end of the game.
from random import randint
print('=-' * 12)
print('LET`S PLAY ODDS OR EVENS')
print('=-' * 12)
vic = 0
while True:
... |
from humplib import __version__, hump2underline, json_hump2underline
from humplib import underline2hump
def test_version():
assert __version__ == '0.1.1'
def test_underline2hump():
assert underline2hump("hello_word") == "helloWord"
def test_hump2underline():
assert hump2underline("helloWord") == "hell... |
"""
A CLI command to initialize the database if it isn't already initialized.
Usage:
initdb conf/development.ini
"""
import sys
from pyramid.paster import bootstrap
def initdb():
# Initialise the pyramid environment, which is enough to trigger the
# initialisation code in `lms.db.__init__.py` to setup ... |
import os
import sys
from django.apps import apps
from django.conf import settings
from django.core.management import call_command
from django.core.management.base import BaseCommand
from django.utils.translation import activate as activate_translation
from parler.models import TranslatableModel
from polib import pofi... |
class Node:
def __init__(self, data):
self.data = data
self.next = None
class LinkedList:
def __init__(self):
self.head = None
def add(self, data):
node = Node(data)
# if list is empty
if not self.head:
self.head = node
else:
... |
# *****************************************************************
# Copyright 2011 MIT Lincoln Laboratory
# Project: SPAR
# Authors: OMD
# Description: unit tests for RandomInt
#
# Modifications:
# Date Name Modification
# ---- ---- -------... |
import tensorflow as tf
import argparse
from itertools import chain
import json
import pickle
import os
import logging
from scipy.stats import norm
import numpy as np
################# Compute Unpopularity Matching #################
def unpop_matching_score(user_unpop, pos_unpop, neg_unpop, pos_unpop_norm, neg_unpop_... |
import numpy as np
from cma import CMAOptions
from cma import optimization_tools as ot
from cma.evolution_strategy import cma_default_options, CMAEvolutionStrategy
from cma.utilities import utils
from cma.utilities.math import Mh
import time
all_stoppings = [] # accessable via cma.evolution_strategy.all_stoppings, bo... |
'''
Loading IOC codes DataFrame
Your task here is to prepare a DataFrame ioc_codes from a comma-separated values (CSV) file.
Initially, ioc_codes has 200 rows (one for each country) and 3 columns: 'Country', 'NOC', & 'ISO code'.
For the analysis that follows, you want to keep only the useful columns from ioc_codes: ... |
from discord.ext import commands
import discord
import asyncio
class ClearCommand(commands.Cog):
def __init__(self, bot: commands.Bot):
self.bot = bot
@commands.command(name="์ฒญ์", aliases=['clear'])
async def clear(self, ctx:commands.Context, cnt:str = None):
if not cnt:
await c... |
"""
Decorator to convert units of functions in /physics methods
"""
__all__ = ["angular_freq_to_hz"]
import astropy.units as u
import functools
import inspect
from plasmapy.utils.decorators.helpers import preserve_signature
def angular_freq_to_hz(fn):
"""
A decorator that adds to a function the ability to c... |
import turtle as trt
tortue = trt.Turtle() # utiliser le module d'abord trt
# avant prรฉsenter forward, backward, left right, done et Turtle() et import
tortue.forward(70)
tortue.left(90)
tortue.forward(70)
tortue.left(90)
tortue.forward(70)
tortue.left(90)
tortue.forward(70)
tortue.left(90)
trt.done()
|
import collections
from nixui import api, slot_mapper
Update = collections.namedtuple('Update', ['option', 'old_value', 'new_value'])
class StateModel:
def __init__(self):
self.update_history = []
self.current_values = api.get_option_values_map()
# TODO: is including the slotmapper ove... |
from django.test import TestCase
# from django.contrib.auth.models import User
from blog.models import Post, Comment
import blog.tests.helper as h
class CommentTestCase(TestCase):
def setUp(self):
self.user = h.create_user()
self.post = h.create_post(self.user)
self.comment = h.create_c... |
"""
Animates the Guided Search solution of a maze.
If you set `refresh_rate` to zero, then it will remove all delays. As it is, the
small 0.01 refresh rate shows the progress of the search.
if you set `stop_end` to be True, the search will terminate at the target
"""
import time
import random
from ch07.maze import M... |
with open("input.txt") as file:
increases = -1
number = 0
for line in file:
if(int(line) > number):
increases += 1
number = int(line)
print("Number of Increases: " + str(increases)) |
""" Class description goes here. """
from collections import namedtuple
import logging
from dataclay.commonruntime.Runtime import getRuntime
__author__ = 'Alex Barcelo <alex.barcelo@bsc.es>'
__copyright__ = '2016 Barcelona Supercomputing Center (BSC-CNS)'
logger = logging.getLogger(__name__)
DCLAY_PROPERTY_PREFIX... |
# Copyright 2020 Mycroft AI 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 writin... |
from django.conf import settings
from telegram import Bot as TelegramBot, Update
from telegram.ext import Dispatcher, Updater
class Bot:
def __init__(self, token, url=settings.SITE_DOMAIN):
self.bot = TelegramBot(token)
self.dispatcher = None
if settings.DEBUG:
self.updater = ... |
# Copyright 2017-2020 TensorHub, 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 writ... |
"""This module contains njitted routines for building histograms.
A histogram is an array with n_bins entry of type HISTOGRAM_DTYPE. Each
feature has its own histogram. A histogram contains the sum of gradients and
hessians of all the samples belonging to each bin.
"""
import numpy as np
from numba import njit
HISTOG... |
class ActionGroups:
def new(self, name):
pass
def remove(self, action_group):
pass
|
from scipy.spatial import distance as distance_metric
import numpy as np
from fashiondatasets.utils.list import parallel_map
def find_top_k(queries, gallery, most_similar, k=20):
reverse = not most_similar
distances = distance_metric.cdist(queries, gallery, "sqeuclidean")
list_of_idxs = []
for dista... |
##+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
## Created by: Hang Zhang
## ECE Department, Rutgers University
## Email: zhang.hang@rutgers.edu
## Copyright (c) 2017
##
## This source code is licensed under the MIT-style license found in the
## LICENSE file in the root directory of this sou... |
from uuid import UUID
def is_valid_uuid(to_test: str, version=4):
try:
UUID(to_test, version=version)
except ValueError:
return False
return True
|
import numpy as np
import pytest
from .. import cellIndToSquareInd
def test_cellIndToSquareInd():
np.testing.assert_array_equal(cellIndToSquareInd(0, 0), [0, 0])
np.testing.assert_array_equal(cellIndToSquareInd(0, 3), [0, 1])
np.testing.assert_array_equal(cellIndToSquareInd(0, 4), [0, 1])
n... |
#!/usr/bin/env python
import subprocess
def compressTo7z( branchName, generatedFilenames ):
print( "Compressing to 7z..." )
cmds = ["7z", "a", "../output/build_ogre_scripts-" + branchName + ".7z"]
cmds.extend( generatedFilenames )
retCode = subprocess.call( cmds, cwd='./output' )
if retCode != 0:
print( "Warni... |
import numpy as np
import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt
from PIL import Image
from sklearn.model_selection import train_test_split, GroupShuffleSplit, StratifiedKFold, StratifiedGroupKFold
#
# seperate test set might not be the best idea and it is too small
# now we sample a 10%... |
#!/usr/bin/env python3
import pandas as pd
import numpy as np
import array
import uproot3
path_to_dataframe = '/home/rusack/joshib/ECAL_calib/data/raw'
path_to_output = path_to_dataframe+'/skimmed_root/'
def merge_years():
# prepare root file
filename = path_to_output+'ecal_crystal_response.root'
pri... |
## -------------------------------------------------------- ##
# Trab 1 IA 2019-2
#
# Rafael Belmock Pedruzzi
#
# simulatedAnnealing.py: implements the simulated annealing metaheuristic for the bag problem
#
# Python version: 3.7.4
## -------------------------------------------------------- ##
import bagProble... |
#coding:utf-8
import torch
from torch import nn
import torch.nn.functional as F
from torch.nn.utils.rnn import pack_padded_sequence, pad_packed_sequence
class LstmEncoderLayer(nn.Module):
def __init__(self, input_size, hidden_size, num_layers, label_nums=None,
batch_first=True, bidirectional=Fals... |
import os
import json
import copy
import random
import configparser
import time
from pp_definitions import PPdefinitions
from pp_utils import Monitor
from pp_livelistfetcher import LiveListFetcher
class LiveList(object):
def __init__(self,sequence):
self.mon=Monitor()
self.sequence=sequence
... |
import json
import math
from typing import List
events_lines = []
with open("events.txt","r") as f:
events_lines = f.readlines()
events_string = "".join(events_lines)
events_raw = events_string.split("\n\n")
class Event:
name: str
time_sort: int
time: str
themes: List[str]
coord: str
cfw:... |
# coding: utf-8
"""
Kubernetes
No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen)
OpenAPI spec version: v1.5.0-beta.1
Generated by: https://github.com/swagger-api/swagger-codegen.git
Licensed under the Apache License, Version 2.0 (the "Lice... |
#! /usr/bin/env python
import rospy
import rosbag
import csv
import xlsxwriter
file_location = "/home/roboticslab/AlphaGraspData/"
grasp = None
def open_csv_writer(graspl):
global grasp
grasp = graspl
with open(file_location + "GraspInfo_Grasp" + str(grasp) + ".csv", "wb") as cf:
f = csv.writer(cf)
f.wr... |
# coding: utf-8
import logging
from django.db.models import Q
from django.contrib.auth.models import User
from django.core.exceptions import ObjectDoesNotExist, MultipleObjectsReturned
from tastypie.resources import ModelResource
from tastypie import fields
from tastypie.contrib.contenttypes.fields import GenericForei... |
from collections import deque
from lib import puzzle
def play_sound(reg, args):
if args[0] in reg:
reg['freq'] = reg[args[0]]
else:
reg['freq'] = int(args[0])
return 1
def set_(reg, args):
if args[1] in reg:
reg[args[0]] = reg[args[1]]
else:
reg[args[0]] = int(ar... |
"""
Django settings for app project.
For more information on this file, see
https://docs.djangoproject.com/en/1.7/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.7/ref/settings/
"""
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
import... |
from setuptools import setup
setup(name='DatasetCreator',
version='0.1',
description='Image Dataset Creator',
packages=['DatasetCreator'],
zip_safe=False)
|
#!/usr/bin/env python
import os
import sys
import requests
import json
import defusedxml.ElementTree as ET
import configparser
import logging
import logging.handlers
import argparse
import ldap
import re
# set up logging
LOGGER = logging.getLogger("AMS User create script")
ACCEPTED_RDNS = [
"emailAddress", "CN",... |
#!/usr/bin/python
import json
import urllib2
import os
import re
#############################################################################
## RESTAPI KUNGFU BELOW
from flask import Flask, request
from flask_restful import Resource, Api, reqparse
app = Flask(__name__)
api = Api(app)
topic_list = {"user" : ["topicn... |
import json
from bunch import Bunch
import os
def get_config_from_json(json_file):
"""
Get the config from a json file
:param json_file:
:return: config(namespace) or config(dictionary)
"""
# parse the configurations from the config json file provided
with open(json_file, 'r') as config_fi... |
import discord
from discord.ext import commands
import logging
import asyncio
import glob
import os
from aiohttp import ClientSession
from rinko.core.bot.base import RinkoBase
from rinko.core.config import config
from rinko.core.logger import get_module_logger
from rinko.core.constant import *
logger = get_module_l... |
"""
Bluetooth Input Stream
stream_input() is a generator that start up the
bluetooth serial server via PyBluez and yields
events sent from a device
Ex:
# print data send from bluetooth device
for event in stream_input():
print(event)
Note: pairing must be done prior to this.
Once paired, running ... |
import argparse
from multiprocessing.pool import Pool
import numpy as np
from cv2 import cv2
cv2.setNumThreads(0)
import os
os.environ["MKL_NUM_THREADS"] = "1"
os.environ["NUMEXPR_NUM_THREADS"] = "1"
os.environ["OMP_NUM_THREADS"] = "1"
def average_strategy(images):
return np.average(images, axis=0)
def hard_... |
import os
import subprocess
import shutil
import glob
import hashlib
import pathlib
import xdg
from .config import config
from .managers import SsrConfManager
class SsrApp:
SSR_FILE_MD5 = {
'obfsplugin/verify.py': '4769b5a8e3e6012a5da57533ce2c62b8',
'obfsplugin/__init__.py': '7ff9a30b272bb2077d2... |
#! /usr/bin/env python
# -*- coding: utf-8 -*-
import time
import base64
import pychrome
import threading
urls = [
"http://fatezero.org",
"http://blog.fatezero.org",
"http://github.com/fate0",
"http://github.com/fate0/pychrome"
]
class EventHandler(object):
screen_lock = threading.Lock()
d... |
class Solution:
def countRoutes(self, locations: List[int], start: int, finish: int, fuel: int) -> int:
dp = [[-1] * 201 for _ in range(101)]
MOD = 1000000007
def helper(pos, left):
if left < 0:
return 0
if dp[pos][left] != -1:
return d... |
"""Groups the constants from sc2"""
from .ids.ability_id import *
from .ids.buff_id import *
from .ids.effect_id import *
from .ids.unit_typeid import *
from .ids.upgrade_id import *
|
#!/usr/bin/env python
# coding: utf-8
# (ch:end2end)=
# # ๋จธ์ ๋ฌ๋ ํ๋ก์ ํธ ์ฒ์๋ถํฐ ๋๊น์ง
# **๊ฐ์ฌ์ ๊ธ**
#
# ์๋ฃ๋ฅผ ๊ณต๊ฐํ ์ ์ ์ค๋ ๋ฆฌ์ ์ ๋กฑ๊ณผ ๊ฐ์์๋ฃ๋ฅผ ์ง์ํ ํ๋น์์นด๋ฐ๋ฏธ์๊ฒ ์ง์ฌ์ด๋ฆฐ ๊ฐ์ฌ๋ฅผ ์ ํฉ๋๋ค.
# **์์ค์ฝ๋**
#
# ๋ณธ๋ฌธ ๋ด์ฉ์ ์ผ๋ถ๋ฅผ ํ์ด์ฌ์ผ๋ก ๊ตฌํํ ๋ด์ฉ์
# [(๊ตฌ๊ธ์ฝ๋ฉ) ๋จธ์ ๋ฌ๋ ํ๋ก์ ํธ ์ฒ์๋ถํฐ ๋๊น์ง](https://colab.research.google.com/github/codingalzi/handson-ml3/blob/master/notebooks/code_end2en... |
#!/usr/bin/env python
import argparse
import numpy as np
import pandas as pd
import scipy as sp
import scipy.stats as st
import sys
MECHANISMS = ['PSI', 'SSI', 'SEL']
METRICS = ['EXECUTION_PHASE_TIME',
'TOTAL_RUN_TIME',
'MAXIMUM_ROBOT_DISTANCE',
'DELIBERATION_TIME',
'MEAN_M... |
import sys
from setuptools import setup
entries = {
'console_scripts': [
'pdistcc=pdistcc.cli:main',
'pdistccd=pdistcc.cli:server_main',
]
}
packages = [
'pdistcc',
'pdistcc.compiler',
]
install_requires=['uhashring==2.0']
setup(
name='pdistcc',
packages=packages,
entry_poi... |
# Copyright (C) 2010-2011 Richard Lincoln
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to
# deal in the Software without restriction, including without limitation the
# rights to use, copy, modify, merge, publish... |
# -*- coding: utf-8 -*-
import json, re, torch, os
import pandas as pd
from text2image import txt2im
from tqdm import tqdm
from sklearn.model_selection import train_test_split
import numpy as np
from gensim.models import KeyedVectors
input_dir = '../input/'
resource_dir = '../resource/'
def load_corpus():
waimai... |
# -*- coding: utf-8 -*-
import numpy as np
import dezero
from dezero import cuda, utils
from dezero.core import Function, Variable, as_variable, as_array
from dezero.functions_conv import conv2d
from dezero.functions_conv import deconv2d
from dezero.functions_conv import conv2d_simple
from dezero.functions_conv import ... |
import argparse
import subprocess
from dtran.dcat.api import DCatAPI
from funcs.readers.dcat_read_func import DATA_CATALOG_DOWNLOAD_DIR
import os
import shutil
from datetime import datetime
from datetime import timedelta
from pathlib import Path
from typing import Optional, Dict
import re
import xarray as xr
from net... |
# -*- coding: utf-8 -*-
"""jcast.main: Main function."""
import os
import datetime
import logging
from functools import partial
import tqdm
from jcast import params, fates, model
from jcast.junctions import Junction, RmatsResults
from jcast.annots import ReadAnnotations, ReadGenome
from jcast.sequences import Seque... |
# -*- coding: utf-8 -*-
# Generated by Django 1.11.9 on 2018-02-08 15:47
from __future__ import unicode_literals
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('people', '0004_rename_address_to_location'),
('acco... |
# -*- coding: utf-8 -*-
"""
tests
~~~~~
Public Test Suite for `DataGator`_.
.. _`DataGator`: http://www.data-gator.com/
:copyright: 2015 by `University of Denver <http://pardee.du.edu/>`_
:license: Apache 2.0, see LICENSE for more details.
:author: `LIU Yu <liuyu@opencps.net>`_
:date... |
'''
Advent of Code - 2019
--- Day 7: Amplification Circuit ---
'''
from utils import *
from intcode import IntcodeRunner, HaltExecution
def parse_input(day):
return day_input(day, integers)[0]
def part1(program):
max_thruster = -1
for p in permutations([0, 1, 2, 3, 4]):
amplifiers = [IntcodeRu... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
import datetime
from datetime import timedelta
import os
import time
import pytz
from dotenv import load_dotenv
load_dotenv(verbose=True)
#---------------------------#
# APPLICATION CONFIGURATION #
#---------------------------#
"""
Variable controls what timezone formatting... |
#!/usr/bin/env python
# encoding: utf-8
# The MIT License (MIT)
# Copyright (c) 2018-2019 CNRS
# 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 limita... |
# Generated by Django 4.0.3 on 2022-03-26 09:05
import django.core.validators
from django.db import migrations, models
import django.utils.timezone
class Migration(migrations.Migration):
initial = True
dependencies = [
('auth', '0012_alter_user_first_name_max_length'),
]
operations = [
... |
#!/usr/bin/env python
#
import sys, cpp, kernel, glob, os, re, getopt
from defaults import *
from utils import *
noUpdate = 1
def cleanupFile( path, original_path):
"""reads an original header and perform the cleanup operation on it
this functions returns the destination path and the clean header
... |
from flask_restful import Resource, reqparse
from models.localOpcionesLocal import localOpcionesLocalModel
class localOpcionesController(Resource):
def post(self):
parser = reqparse.RequestParser()
parser.add_argument(
'id_local',
type=int,
required=True,
... |
import cv2
import numpy as np
from t2i.entity import *
from t2i.script import *
from t2i.assetBook import *
from t2i.endpointResolver import *
from t2i.animate import *
from threading import Lock, Thread
import sys
CANVAS_WIDTH = 800
CANVAS_HEIGHT = 600
class StaticVisualGraph:
class VisualNode:
def __i... |
#Brokerage model and account type:
self.SetBrokerageModel(BrokerageName.InteractiveBrokersBrokerage, AccountType.Cash)
//Add securities and if required set custom margin models
spy = self.AddEquity("SPY") # Default to minute bars
spy.MarginModel = PatternDayTradingMarginModel()
|
import pygame
# local imports
from constants import *
# TODO: I have some old code commented out, which I will delete when I'm sure I don't need it.
class Sensor(pygame.sprite.Sprite):
def __init__(self, player_rect, relative_position, sensor_state, inactive_color=GRAY, active_color=WHITE):
# Call the pa... |
from collections import deque
import logging
import sys
import threading
import time
from src.grip.metaclasses import (
CallableStartMetaclass,
ThreadSafeSingleton
)
# minimum representable positive normalized float
MIN_FLOAT = sys.float_info.min
class GRIP_Deque(deque):
"""
The GRIP_Deque encapsul... |
from port import db
class Permission:
id = db.Column(db.Integer, primary_key=True)
class UserPermission:
id = db.Column(db.Integer, primary_key=True)
user_id = db.Column(db.Integer, db.ForeignKey('User.id'))
permission_id = db.Column(db.Integer, db.ForeignKey('Permission.id'))
|
"""
Test that breakpoints do not affect stepping.
Check for correct StopReason when stepping to the line with breakpoint
which chould be eStopReasonBreakpoint in general,
and eStopReasonPlanComplete when breakpoint's condition fails.
"""
from __future__ import print_function
import unittest2
import lldb
from lldbsuit... |
#!/usr/bin/env python3
import asyncio
import importer
print("""
Welcome to the Saleor Importer!
To import data into Saleor, I will need three pieces of information from you:
1. The URL of your Saleor API
2. An API token (see https://docs.saleor.io/docs/dashboard/configuration/service-accounts)
3. The path to a file... |
# Generated by Django 3.1rc1 on 2020-07-29 13:03
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('parameters', '0002_auto_20200729_1236'),
]
operations = [
migrations.AlterField(
model_name='parameter',
name='valu... |
import hashlib
from typing import List, Union, Tuple
from utils import read_data
INPUT = read_data()
def check_hash(door: str, index: int) -> Union[None, Tuple[int, int]]:
text = "%s%s" % (door, index)
hash = hashlib.md5(text.encode('utf-8')).hexdigest()
if hash.startswith("00000"):
# ... |
from subprocess import CalledProcessError # noqa: F401
class PackageResolutionError(Exception):
pass
class VersionError(Exception):
pass
class PackageVersionError(PackageResolutionError, VersionError):
pass
class ToolNotFoundError(LookupError):
pass
|
import multiprocessing
import ISE
import time
import numpy as np
graph_info = ISE.read_graph_info('NetPHY.txt')
graph = ISE.Graph(graph_info)
# graph = None
def influence_spread_computation_IC_Mu(seeds, n=multiprocessing.cpu_count()):
pool = multiprocessing.Pool()
# cpus = multiprocessing.cpu_count()
re... |
# Generated by Django 3.2.7 on 2021-10-06 11:07
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('eduhub', '0024_asharingcontent_agroup'),
]
operations = [
migrations.RenameField(
model_name='asharinggroupmember',
old_name... |
from styx_msgs.msg import TrafficLight
import os
import cv2
import numpy as np
import tensorflow as tf
import sys
import rospy
from yolo.utils import get_yolo_boxes, makedirs
from yolo.bbox import draw_boxes
from keras.models import load_model
import keras as kf
#Minimum probability for object detection correctness
M... |
from django import template
from symposion.reviews.models import Review, ReviewAssignment
register = template.Library()
@register.assignment_tag(takes_context=True)
def review_assignments(context):
request = context["request"]
assignments = ReviewAssignment.objects.filter(user=request.user)
return assig... |
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from PIL import Image
import os
from scipy import misc
from six.moves import xrange # pylint: disable=redefined-builtin
import tensorflow as tf
# Process images of this size. Note that this differs from th... |
# encoding: utf-8
# !/usr/bin/python
from dms.web.hooks.accept_hook import AcceptHook
from dms.web.hooks.auth_hook import AuthHook
from dms.web.hooks.body_hook import BodyHook
from dms.web.hooks.cors_hook import CorsHook
__author__ = 'zhouhenglc'
__all__ = [AcceptHook, AuthHook, BodyHook, CorsHook]
|
from django import template
register=template.Library()
@register.filter(name='dict_value')
def dict_value(value,arg):
print(arg)
print(value)
return value.get(arg) |
import numpy as np
from deerlab import dipolarkernel, fitmultimodel
from deerlab.dd_models import dd_gengauss, dd_gauss, dd_rice, dd_gauss2, dd_rice3, dd_gauss3
from deerlab.bg_models import bg_exp
from deerlab.utils import ovl
def test_multigauss():
#==========================================================... |
import sys
from abc import ABC, abstractmethod
from dataclasses import asdict, astuple, dataclass, field
from typing import List
import numpy as np
class Reader:
@staticmethod
def readline() -> bytes:
return sys.stdin.buffer.readline().rstrip()
@classmethod
def read_int(cls) ->... |
import collections
import dataclasses
import functools
import logging
import os
import re
import shlex
import subprocess
from typing import Any, Callable, Iterable, Iterator, List, Mapping, Sequence, TypeVar, Union, cast
import mkdocs.exceptions
import mkdocs.utils
from cached_property import cached_property
from mkdo... |
import node
import transform
import control
import curve
import joint
__all__ = ['curve', 'joint', 'control', 'node', 'transform']
|
from .xdcrnewbasetests import XDCRNewBaseTest
from security.ntonencryptionBase import ntonencryptionBase
from membase.helper.cluster_helper import ClusterOperationHelper
import time
import random
class XDCRSecurityTests(XDCRNewBaseTest):
def setUp(self):
XDCRNewBaseTest.setUp(self)
def tearDown(self)... |
"""
Created on 04/sep/2016
@author: Marco Pompili
"""
import html5lib as html
import json
import logging
import requests
from socket import error as socket_error
from requests.exceptions import ConnectionError, HTTPError
from . import settings
SCRIPT_JSON_PREFIX = 18
SCRIPT_JSON_DATA_INDEX = 21
def instagram_scr... |
import asyncio
from asyncio import StreamReader, StreamWriter
import configargparse
import logging
import json
from connect_to_chat import get_chat_connection
def create_argparser():
p = configargparse.ArgParser(
default_config_files=['~/.minechat'],
description="Connects to chat as specified us... |
# Copyright 2019 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
import unittest
from .code_node import ListNode
from .code_node import LiteralNode
from .code_node import SymbolNode
from .code_node import SymbolScopeNode
... |
import os
from urllib.parse import urljoin
import requests
import json
from osbot_utils.utils.Http import GET_json,POST,POST_json
from osbot_utils.utils.Json import str_to_json, json_to_str
DEFAULT_API_SERVER = 'http://api:8880'
class API_Client:
def __init__(self, url_server=DEFAULT_API_SERVER):
self.s... |
import os
data_path = os.path.join('..', 'data')
os.makedirs(data_path, exist_ok=True)
input_path = os.path.join(data_path, 'input')
os.makedirs(input_path, exist_ok=True)
bruto_path = os.path.join(input_path, 'brutos')
os.makedirs(bruto_path, exist_ok=True)
output_path = os.path.join(data_path, 'output')
os.maked... |
from django.db import transaction
from django.http import HttpResponseNotFound
from django.shortcuts import get_object_or_404, redirect
from django.views.decorators.http import require_http_methods
from django.views.generic import DetailView
from meta.views import MetadataMixin
from sqds.models import Player
from sqds... |
from p2_cipher import Cipher
def p2_answer():
aCipher = Cipher()
aCipher.key = "BLUE" # the hardcoded key, it comes from p1_ and p_0
aCipher.processKey() # make a deduped string
aCipher.readIn() # reads the message in
aCipher.printDecodedMessage() #prints the decoded message
if __name__ == "__main__":
p2_answe... |
import datasets
import model
import tensorflow as tf
import tensorflow.compat.v1 as tfv1
import time
from logging import getLogger
logger = getLogger(__name__)
def start(network, trainer, train, epochs, checkpoint):
start_epoch = checkpoint.save_counter()
for epoch in range(start_epoch, epochs):
for... |
#!/bin/env python
import Currency_Aggregator
import Currency_Converter
import Currency_Model
import Parser
import Scrapper
class Main:
@staticmethod
def run_program():
Scrapper.Scrapper.scrap()
currency = Parser.Parser.parse()
chosen_currency = currency.choose_current()
exchang... |
#! /usr/bin/env python3
import sys, platform
from os.path import isfile
def hello(who):
osname = platform.system()
print("Hello world from {} on an ${} machine".format(who, osname))
if __name__ == "__main__":
if len(sys.argv) >= 2:
hello(sys.argv[1])
|
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
from django.conf import settings
class Migration(migrations.Migration):
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
('sponsor', '0004_auto_20150619_2212'),
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.