content stringlengths 5 1.05M |
|---|
# An implementation of Experience Replay (ER) with reservoir sampling and without using tasks from Algorithm 4 of https://openreview.net/pdf?id=B1gTShAct7
# Copyright 2019-present, IBM Research
# All rights reserved.
#
# This source code is licensed under the license found in the
# LICENSE file in the root directory o... |
import pandas as pd
def main():
flightcsv = pd.read_csv("airline_flights.csv")
# organize data by origin and destination airport
flightcsv_tofrom = flightcsv.groupby(['ORG_AIR', 'DEST_AIR']).size()
print(flightcsv_tofrom.head())
# Display the number of flights between Huston (IAH)
# and Atla... |
from unittest.mock import create_autospec, ANY, patch, call
import pytest
from pymysql import IntegrityError
from stack.commands import DatabaseConnection
from stack.commands.remove.firmware import Command
from stack.exception import ArgRequired, CommandError
from stack.commands.remove.firmware.plugin_basic import Plug... |
import trackpy
from itertools import product
import pandas as pd
from collections import Iterable
import copy
import h5py
import pandas as pd
import re
import xmltodict
from operator import mul
from functools import reduce
import scipy.stats as sp
from scipy.stats import mannwhitneyu
import matplotlib.pyplot as plt
... |
"""
Each new term in the Fibonacci sequence is generated by adding the previous two terms.
By starting with 1 and 2, the first 10 terms will be: 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ...
By considering the terms in the Fibonacci sequence whose values do not exceed four million,
find the sum of the even-valued terms.
"""
... |
from a10sdk.common.A10BaseClass import A10BaseClass
class Stats(A10BaseClass):
"""This class does not support CRUD Operations please use parent.
:param bwl_drop: {"description": "BW Limit Drop", "format": "counter", "type": "number", "oid": "3", "optional": true, "size": "8"}
:param pingofdeath_drop... |
# -*- coding: utf-8 -*-
from functools import lru_cache
from config import Settings
@lru_cache
def get_settings():
return Settings()
|
def quick_sort(collection):
length = len(collection)
if length <= 1:
return collection
else:
pivot = collection[0]
smaller = [element for element in collection[1:] if element <= pivot]
larger = [element for element in collection[1:] if element >= pivot]
return quick_s... |
"""
Extracting automatically articles from the EB.
The articles are stored in a HDFS CSV file.
The text is cleaned by using long-S and hyphen fixes.
Note that for running this query, apart from Spark you need to have HADOOP installeld in your computing enviroment.
"""
from defoe import query_utils
from defoe.nlsA... |
import psutil
from appJar import gui
import config
import requests as req
import json
import platform
import sysInfo
app = gui(title="CMM Hub", showIcon=False)
navBarElements = []
navBarElementsCallName = []
currentContainer = ""
def get_size(bytes, suffix="B"):
"""
Scale bytes to its proper format
e.g:
... |
import csv
import datetime
from decimal import Decimal
from investments.cash import Cash
from investments.currency import Currency
from investments.fees import Fee
from investments.interests import Interest
from investments.money import Money
from investments.report_parsers.ib import InteractiveBrokersReportParser, _p... |
import subprocess
import os
def _utils_execute_script(script: str, remove_newlines: bool = True) -> str:
output = subprocess.run(script,
capture_output=True,
shell=True)
result = output.stdout.decode("utf-8")
if remove_newlines:
result = outp... |
from django.shortcuts import render
# Create your views here.
from django.http import HttpResponse
from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework.permissions import IsAuthenticated
from django.views import View
def index(request):
return HttpResponse("... |
__author__ = 'samu'
from setuptools import setup
setup(
version='0.1',
name='sandbox',
install_requires=['Pillow', 'scipy', 'numpy'],
entry_points={
'console_scripts': [
'sandbox_resize_dir = sandbox.images.resize_v3:resize_dir',
]},
packages=['sandbox', 'sandbox.images... |
from conans import ConanFile, tools
import os
class ExperimentalexecutorsConan(ConanFile):
name = "experimental-executors"
version = "1.0.0"
license = "MIT"
url = "https://github.com/skizzay/experimental-executors"
description = "Conan package for the executors c++ proposal"
no_copy_source = T... |
import numpy as np
from scipy.optimize import brentq
from scipy.interpolate import interp1d
from sklearn.metrics import roc_curve
from scipy.spatial import distance
from sklearn.mixture import GaussianMixture
import torch
def get_embedded_set(loader,model):
X_out, Y_out=[],[]
for batch_idx, (types, samples,lab... |
#!/usr/bin/env python
from __future__ import print_function
from pycrazyswarm import *
def main():
swarm = Crazyswarm()
timeHelper = swarm.timeHelper
allcfs = swarm.allcfs
for cf in allcfs.crazyflies:
print(cf.id)
cf.takeoff(1.0, 2.5)
print("press button to continue")
... |
import cv2
import face_recognition
import mysql.connector as db
import base64
import os
mydb=db.connect(
host='localhost',
user='root',
passwd='1234',
database='adhaar'
)
mycursor=mydb.cursor()
def adhaar(index):
#index=1
query = "SELECT * FROM adhaar WHERE Adhaar_no={}".... |
# project/models.py
import datetime
from project import db, bcrypt
class AutoSerialize(object):
'Mixin for retrieving public fields of model in json-compatible format'
__public__ = None
def get_public(self, exclude=(), extra=()):
"Returns model's PUBLIC data for jsonify"
data = {}
... |
#-------------------------------------------------------------------------------
# Name: DissolveWithError
# Purpose: And expansion of the Dissolve geoprocessing tool that merges features in classes based on its attributes. This tool allows feature classes with similar but not identical attributes to be merg... |
"""Service for subordinate servers.
Usage example:
from rpyc.modules.utils.server import ThreadPoolServer
server = ThreadPoolServer(SubordinationService, hostname="0.0.0.0", port=80)
server.start()
"""
import os
import tempfile
import typing
from threading import Lock, Thread
import rpyc
from modules.da... |
# Import smorgasbord
import os
import sys
sys.path.insert(0, '../')
import gc
import pdb
import time
import math
import random
import re
import copy
import warnings
import multiprocessing as mp
import numpy as np
import scipy.optimize
import scipy.ndimage.measurements
import scipy.stats
import matplotl... |
import pytest
import vaex
import vaex.schema
import numpy as np
import pyarrow as pa
def test_concat_endianness(df_concat, df_trimmed):
assert df_trimmed.data_type('x').byteorder == '>'
# since df_concat will concate, we will lose the byteorder
assert df_concat.data_type('x').byteorder in '<='
def test_... |
# Lint as: python3
# Copyright 2021 ssoudan. 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 ... |
import spider
import json
import csvIO
strData=[]
for i in range(1,76):
a=spider.gethtml(spider.geturl(i))
strData.append(a)
def to2DList(x):
x=x[14:]
x=x.replace('data','"data"')
x = x.replace('pages', '"pages"')
print(x)
d=json.loads(x)
d=d['data']
c=[]
for i in d:
b=... |
import pygame as pg
import random
WIDTH,HEIGHT=300,600
pg.init()
screen=pg.display.set_mode((WIDTH,HEIGHT),0,32)
background=pg.Surface((WIDTH,HEIGHT))
background.fill((100,150,255))
def write(msg,size):
font=pg.font.SysFont("none",size)
text=font.render(msg,False,(1,1,1))
text.set_colork... |
import os
import cv2
import numpy as np
import tensorflow as tf
from tensorflow.keras.applications import MobileNet
from tensorflow.python.framework.convert_to_constants import convert_variables_to_constants_v2
from ...common.utils import set_tf_env
def get_tf_model_proto(tf_model):
# define the dir... |
class ResponseException(Exception):
""" Exception wrapper to be used in an http response, allows exceptions to specify status codes when raised """
def __init__(self, message, status=500, error_class=None, error_type=None, **kwargs):
""" Create a new ResponseException
Args:
message:... |
import cv2
import os
# function to read the target watermark image
def prepare_watermark(path_mark, inver_style):
"""
reads the image in greyscale, create an alpha mask according to the scale
invert_style determines whether the key info letters/shapes are darker or lighter than the rest
""" |
from tethys_sdk.base import TethysAppBase, url_map_maker
class Airpollut(TethysAppBase):
name = 'Air Quality Prediction'
index = 'airpollut:home'
icon = 'airpollut/images/icon.gif'
package = 'airpollut'
root_url = 'airpollut'
color = '#64b5f6'
description = 'Monitor Air Quality in your nei... |
# I expect you to replace this file with your local config
REGION= 'us-west-2' # Change to region your AWS Lambda function is in
CHEF_SERVER_URL = 'https://my_server/organizations/thisorg'
USERNAME = 'username'
VERIFY_SSL = False
DEBUG = False
|
import os
from textwrap import dedent
import sublime
from unittesting import DeferrableTestCase
from GitSavvy.tests.mockito import unstub, when, spy2
from GitSavvy.core.interfaces.status import StatusInterface
if os.name == 'nt':
# On Windows, `find_all_results` returns pseudo linux paths
# E.g. `/C/not/he... |
#RANDOM FOREST-SMOTE WITH Y_UNICA
#EQUAL NUMEROSITY
model= RandomForestClassifier(n_estimators=100, random_state=22)
model.fit(X_Smote_train,Y_Smote_train.values.ravel())
importances=model.feature_importances_
feat_importances = pd.Series(model.feature_importances_, index=X_Smote_train.columns)
df_imp=pd.DataFrame({'Fe... |
# -*- coding: utf-8 -*-
# Generated by Django 1.10.5 on 2017-03-15 12:17
from __future__ import unicode_literals
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
import django.utils.timezone
class Migration(migrations.Migration):
initial = True
depe... |
#################################################
#################################################
## this file sets up a Gurobi model
## the model is of a portfolio, where we can choose between a bond and some given stocks
## see "plot_efficient_frontier_for_correlated_returns.py" for an example of how to
## use this... |
from ll import LinkedList
class Snake(LinkedList):
_color: tuple
# definition for the initialization of a Snake object
#
def __init__(self, color: tuple, x_val: int, y_val: int) -> None:
super().__init__(color, x_val, y_val)
self._color = color
# grows the body of a a Snake objec... |
# Generated by Django 2.1.2 on 2020-07-27 19:23
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('publications', '0002_auto_20200723_0929'),
]
operations = [
migrations.AlterModelOptions(
name=... |
from math import ceil, floor
def natural_numbers(quantity):
for it in range(quantity):
yield it
def pair_numbers(quantity):
for it in range(0, quantity * 2, 2):
yield it
def odd_numbers(quantity):
for it in range(1, quantity * 2, 2):
yield it
def square_numbers(quantity):
... |
import torch
import numpy as np
class Matcher:
def __init__(self, high_threshold, low_threshold, allow_low_quality_matches=False):
self.high_threshold = high_threshold
self.low_threshold = low_threshold
self.allow_low_quality_matches = allow_low_quality_matches
def __call__(self, iou)... |
"""Pydantic model represents Telegram bot profile."""
from datetime import datetime
from pydantic import BaseModel
from .users import Users
class Profile(BaseModel): # pylint: disable=too-few-public-methods
"""Telegram bot profile model."""
username: str
full_name: str
updated: datetime
users... |
"""
# Sample code to perform I/O:
name = input() # Reading input from STDIN
print('Hi, %s.' % name) # Writing output to STDOUT
# Warning: Printing unwanted or ill-formatted data to output will cause the test cases to fail
"""
# Write your code here
from collections import deque
x1, y1, x2, ... |
frase = 'Curso em Vídeo Python'
print(frase.find('Vídeo'))
|
'''Создать список поездов. Структура словаря: номер поезда,
пункт и время прибытия, пункт и время отбытия. Вывести все сведения о поездах,
время пребывания в пути которых превышает 7 часов 20 минут'''
from datetime import datetime, timedelta
delta_time = timedelta(hours = 7, minutes = 20)
trains = [
{
'nu... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import migrations, models
import datetime
class Migration(migrations.Migration):
dependencies = [
('crm', '0013_role_description'),
('contenttypes', '0002_remove_content_type_name'),
('communication', '0003_aut... |
from contextlib import contextmanager
from time import perf_counter, sleep
import sys
from contextlib import redirect_stdout
@contextmanager
def open_file(fname, mode='r'):
print('opening file...')
f = open(fname, mode)
try:
yield f
finally:
print('closing file...')
f.close()
... |
from __future__ import unicode_literals
from collections import OrderedDict
from itertools import count, groupby
from mptt.models import MPTTModel, TreeForeignKey
from django.conf import settings
from django.contrib.auth.models import User
from django.contrib.contenttypes.models import ContentType
from django.contrib... |
# Copyright 2021 Google LLC
#
# 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, ... |
from functools import wraps
from typing import List, Callable
from pyjackson.utils import get_function_fields, turn_args_to_kwargs
def validate_kwargs(f=None, *, allowed: List[str] = None, allowed_funcs: List[Callable] = None):
def inner(func):
all_fields = allowed or []
if allowed_funcs is not N... |
import os
import cgi
import logging
from StringIO import StringIO
import struct
import wsgiref.handlers
from datetime import date
from google.appengine.api import images
from google.appengine.api import memcache
from google.appengine.ext import db
from google.appengine.ext import webapp
from google.appengine.ext.weba... |
import FWCore.ParameterSet.Config as cms
import DQM.HLTEvF.hltMonBTagIPClient_cfi
import DQM.HLTEvF.hltMonBTagMuClient_cfi
# definition of the Clients for 8E29
hltMonBTagIP_Jet50U_Client = DQM.HLTEvF.hltMonBTagIPClient_cfi.hltMonBTagIPClient.clone()
hltMonBTagIP_Jet50U_Client.updateLuminosityBlock = True
hltMonBTagM... |
# coding: utf-8
import re
import os
from setuptools import setup
def read_file(fname):
return open(os.path.join(os.path.dirname(__file__), fname)).read()
def get_version():
meta_filedata = read_file('maxipago/__init__.py')
re_version = re.compile(r'VERSION\s*=\s*\((.*?)\)')
group = re_version.search... |
import unittest
from ..generator.manifestparser import parse_manifest_data
class ManifestParserTest(unittest.TestCase):
def test_it_should_extract_data_from_the_json_text(self):
to_parse = '{"Photographer": 80,\n' + \
'"City": 90,\n' + \
'"Country": 101,\n' + \
'"Desc... |
import pkgutil
import inspect
wizs = {}
from _wizard import _Wizard
for importer, modname, ispkg in pkgutil.iter_modules(__path__):
if not ispkg:
module = __import__(modname, locals(), [], -1)
for name, cls in inspect.getmembers(module):
if inspect.isclass(cls) and issubclass(cls, _Wi... |
# Manipulation
# Modify the following code according to
# the instructions.
nums = []
"""
The following code adds the numbers 0, 10, ... 100
to the list nums, and displays this list.
First, make a copy of nums and store it in the varible more_nums.
Then, clear nums, and add the numbers
2, 7, 12, ... 72 to nums inste... |
from django.conf.urls import url
from idocr.views import ImageToString
urlpatterns = [
url(r'^image_to_string', ImageToString.as_view(), name='image_to_string'),
] |
import argparse
from itertools import product
from experiment import *
import pandas as pd
from params_helpers import *
# Search parameters for ILP formulation
def search_ilp(insdir, out, lp1, up1, lp2, up2):
try:
os.mkdir(out)
except OSError:
print("Creation of the directory failed or directo... |
# Copyright (c) 2021 Graphcore Ltd. All rights reserved.
from setuptools import setup # pragma: no cover
REQUIREMENTS = [i.strip() for i in open("requirements.txt").readlines()] # pragma: no cover
setup( # pragma: no cover
name='sst',
version='0.0.1',
py_modules=['sst'],
install_requires=REQUIREMEN... |
import os
import sys
import subprocess
target = sys.argv[1]
is_dir = target.endswith('/')
directory = os.getcwd()
while True:
if (
(is_dir and os.path.isdir(os.path.join(directory, target))) or
(not is_dir and os.path.isfile(os.path.join(directory, target)))
):
print(directory)
... |
# Imports from 3rd party libraries
import dash
import dash_bootstrap_components as dbc
import dash_core_components as dcc
import dash_html_components as html
from dash.dependencies import Input, Output
import pandas as pd
from joblib import load
import json
# Imports from this application
from app import app
# 2 colu... |
#!/usr/bin/python3 -u
from guy import Guy,http
class Simplest(Guy):
"""
<h1>Hello <<msg>></h1>
<button style="float:right;font-size:2em" onclick="self.exit()">X</button>
<button onclick="test()">test</button>
<script>
function init() {
document.body.innerHTML+="init<br>";
}
asy... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
'''
@AUTHOR:Joselyn Zhao
@CONTACT:zhaojing17@foxmail.com
@HOME_PAGE:joselynzhao.top
@SOFTWERE:PyCharm
@FILE:xinghao.py
@TIME:2020/4/18 21:22
@DES: 将序列分解为单独的变量
'''
p = (4,5)
x,y = p
print(x)
print(y)
print(x,y) #这样输出的是一个元组吗?
data = ['acme',60,91,(12,12,23)]
a,b,c,d = data
prin... |
"""
This module tests the predictive posterior for missing data in the Bayesian GP-LVM, MRD, and DP-GP-LVM models. This
module uses equine MOCAP data to perform these tests.
"""
from distributions.normal import mvn_log_pdf
from models.dp_gp_lvm import dp_gp_lvm
from models.gaussian_process import bayesian_gp_lvm, mani... |
from utils import filex, jsonx
from __constants import (GRAPH_PLACES_FILE, GRAPH_ROADS_FILE, HEIGHT, MAP_FILE,
PADDING, STYLE_PLACE_CIRCLE, STYLE_PLACE_TEXT,
STYLE_ROAD_LINE, STYLE_ROAD_LINE_STROKE_MAP, WIDTH)
from _geo import get_func_transform
from _xmlx import _, re... |
"""
Copyright (c) Microsoft Corporation.
Licensed under the MIT license.
Video Captioning dataset
copied/modified from HERO
(https://github.com/linjieli222/HERO)
"""
import json
import os
import torch
from torch.nn.utils.rnn import pad_sequence
from torch.utils.data import Dataset
import horovod.torch as hvd
from t... |
#!/usr/bin/env python3
#
## @file
# manifest_args.py
#
# Copyright (c) 2019, Intel Corporation. All rights reserved.<BR>
# SPDX-License-Identifier: BSD-2-Clause-Patent
#
''' Contains the help and description strings for arguments in the
manifest command meta data.
'''
COMMAND_DESCRIPTION = 'Lists the ava... |
"""
================================================================================
mcerp: Real-time latin-hypercube-sampling-based Monte Carlo Error Propagation
================================================================================
Author: Abraham Lee
Copyright: 2013 - 2014
"""
from pkg_resources import ge... |
def board():
pass
def can_attack():
pass
|
import os
import testinfra.utils.ansible_runner
testinfra_hosts = testinfra.utils.ansible_runner.AnsibleRunner(
os.environ['MOLECULE_INVENTORY_FILE']).get_hosts('all')
def test_hosts_file(host):
assert host.file('/usr/local/bin/clj').exists
assert host.file('/usr/local/bin/lein').exists
|
from loader.Database import ShortEnum
WEAPON_TYPES = {
1: "Sword",
2: "Blade",
3: "Dagger",
4: "Axe",
5: "Lance",
6: "Bow",
7: "Wand",
8: "Staff",
9: "Gun",
}
WEAPON_LABEL = {
1: "SWD",
2: "KAT",
3: "DAG",
4: "AXE",
5: "LAN",
6: "BOW",
7: "ROD",
8: "... |
import aiohttp
from bs4 import BeautifulSoup
import json
import asyncio
class NiconicoVideo:
"""async/await
"""
def __init__(self, url):
self.url = url
self._isOldDouga = False
async def _fetchDougaInfo(self):
async with aiohttp.ClientSession() as session:
asyn... |
import platform
import tkinter as tk
from utility.Log import Log
from utility.ObserverObjects import Observer
from tkinter import simpledialog
from utility.Location import *
from view.AlgorithmConfiguration import AlgorithmConfiguration
class MenuView(Observer):
def __init__(self, window, config):
Obs... |
n,t=map(int,input().split())
a=b=0
for i in range(n):
s=int(input())
if s>b:a+=s-b
b=s+t
print(b-a) |
import os
from wptserve.utils import isomorphic_decode
def main(request, response):
stash_id = request.GET.first(b"id")
if request.server.stash.take(stash_id) is not None:
response.status = (404, b"Not Found")
response.headers.set(b"Content-Type", b"text/plain")
return u"not found"
... |
#!/usr/bin/env python3
# Copyright © 2019 Broadcom. All rights reserved.
# The term “Broadcom” refers to Broadcom Inc. and/or its subsidiaries.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may also obtain a copy of the Lic... |
# Python Program Which Contains A Printer Interface And Its Sub Classes To Send Text To Any Printer
'''
Function Name : An Interface Send Text To Any Printer
Function Date : 20 Sep 2020
Function Author : Prasad Dangare
Input : String
Output : String
'''
from abstractc2 impor... |
# -*- coding: utf-8 -*-
"""
Helper functions for cross validation
"""
import numpy as np
from predictions import predict_labels
from implementations import ridge_regression, logistic_regression
def build_k_indices(y, k_fold, seed=None):
"""build k indices for k-fold."""
np.random.seed(seed)
nu... |
# Generated by Django 2.2.16 on 2021-06-07 19:36
from django.db import migrations
def forwards(apps, schema_editor):
ExecutionEnvironment = apps.get_model('main', 'ExecutionEnvironment')
for row in ExecutionEnvironment.objects.filter(managed_by_tower=True):
row.managed_by_tower = False
row.sa... |
VERSION = "3.0.4"
|
#!/usr/bin/python3
import os
if __name__ == "__main__":
build_types=["Debug", "Release"]
for btype in build_types:
retval = os.system("python3 compile.py --cross-compile --rebuild --build-type %s --build-examples --analyze" % (btype))
if 0 != retval:
exit(retval)
retval = o... |
from django.apps import AppConfig
class VoteSystemConfig(AppConfig):
name = "apps.vote_system"
label = "vote_system"
verbose_name = "Vote System"
|
#!/usr/bin/env python
import roslib
roslib.load_manifest('motor_cmd_source')
import rospy
from base_controller import BaseController
class PositionController(BaseController):
def getMotorCmd(self):
self.error = self.setptPosition - self.position
self.ffValue = self.setptVelocity
self.cont... |
# -*- coding: UTF-8 -*-
__author__ = "Liu Fei"
__github__ = "http://github.com/lfblogs"
__all__ = [
"Configure",
]
"""
Define conf interface
"""
from aio2py.conf.method import OnlineDict, MergeDict, Configure2Dict
def Configure(develop, online = None):
config = OnlineDict(MergeDict(Configure2Dict(develop,... |
# 图片验证码 过期时间 单位 秒
IMAGE_CODE_REDIS_EXPIRES = 300
|
#!/usr/bin/python3
import sys
import rclpy
from rmoss_interfaces.msg import ShootCmd
def getShootCmdMsg(num,vel):
msg = ShootCmd()
msg.projectile_num=num
msg.projectile_velocity=vel
return msg
def main():
rclpy.init()
node = rclpy.create_node('test_shoot_cmd')
pub = node.create_publisher(... |
import pandas as pd
from preprocess.load_data.data_loader import load_hotel_reserve
customer_tb, hotel_tb, reserve_tb = load_hotel_reserve()
# 下の行から本書スタート
# reserve_datetimeをdatetime64[ns]型に変換
reserve_tb['reserve_datetime'] = \
pd.to_datetime(reserve_tb['reserve_datetime'], format='%Y-%m-%d %H:%M:%S')
# 年を取得
reserv... |
import csv
data = csv.reader(open('Resources/election_data.csv'))
votes = 0
candidates = {}
winner_votes = 0
winner = ''
next(data)
for row in data:
votes+=1
candidate=row[2]
if candidate not in candidates.keys():
candidates[candidate] = 0
candidates[candidate] += 1
if candidate... |
#
# The contents of this file are subject to the terms listed in the LICENSE file you received with this code.
#
# Project: Atmosphere, iPlant Collaborative
# Author: Seung-jin Kim
# Twitter: @seungjin
# GitHub: seungjin
#
from datetime import datetime
from datetime import timedelta
import boto
from boto.ec2.connec... |
import sys
from pathlib import Path # noqa E402
from setuptools import setup
CURRENT_DIR = Path(__file__).parent
sys.path.insert(0, str(CURRENT_DIR)) # for setuptools.build_meta
def get_long_description() -> str:
return (
(CURRENT_DIR / "README.md").read_text(encoding="utf8")
+ "\n\n"
... |
# -*- coding: utf-8 -*-
from git import Actor
from mimiron.vendor.git_extensions.util import git_failure
@git_failure
def get_ahead_behind_count(repo):
branch = repo.active_branch
commits_behind = repo.iter_commits('%s..origin/%s' % (branch, branch,))
commits_behind = len(list(commits_behind))
commi... |
# -*- coding: utf-8 -*-
from gevent import monkey; monkey.patch_all()
import gevent
from gevent.queue import Queue
from gevent.pool import Pool
itemEvent = Queue()
import datetime
import requests
import json
import sys
# print os.getcwd()
# print open('ia-gb-inject/index.html').read()
from socketio import socketio_... |
# builtins stub with object.__new__
class object:
def __init__(self) -> None: pass
def __new__(cls): pass
class type:
def __init__(self, x) -> None: pass
class int: pass
class bool: pass
class str: pass
class function: pass
|
#!/usr/bin/env python3
import logging
import datetime
import os
import os.path
import sys
from shutil import make_archive
import subprocess
import smtplib
def archive_to_gdrive(mount, root_dir, base_dir, gdrive):
# zip file will be temporarily stored in /data
base = '/data/' + base_dir
zip_file = base + '... |
"""
Copyright (c) 2020 Alex Forencich
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, distribute... |
from data_resource.generator.api_manager.v1_0_0.resource_utils import (
build_links,
build_json_from_object,
)
from collections import OrderedDict
from data_resource.db.base import db_session
from data_resource.shared_utils.api_exceptions import InternalServerError, ApiError
from data_resource.shared_utils.log_... |
import pymysql
user_name = ""
def open():
"""
打开数据库连接
:return:
"""
db = pymysql.connect(host="localhost", user="root", password="", database="db_student", port=3306)
return db
def exec(sql, *values):
"""
执行数据库的增、删、改操作
:param sql:
:param values:
:return:
"""
# 连接数... |
# Copyright 2021 UW-IT, University of Washington
# SPDX-License-Identifier: Apache-2.0
import random
import datetime
from restclients_core.util.mock import load_resource_from_path
from restclients_core.util.local_cache import (
set_cache_value, get_cache_value)
from restclients_core.models import MockHTTP, CacheHT... |
from kivy.uix.floatlayout import FloatLayout
from kivy.properties import ObjectProperty
from kivy.uix.popup import Popup
from enum import Enum
class OpenFileDialog(FloatLayout):
select = ObjectProperty(None)
cancel = ObjectProperty(None)
ok_btn_text = ObjectProperty('OK')
cancel_btn_text = ObjectProp... |
# Module: help
# Date: 28th November 2013
# Author: James Mills, j dot mills at griffith dot edu dot au
"""
Shipyard Deployer
This is a quick method to get a production Shipyard setup deployed. You will
need the following:
* Python
* Fabric (`easy_install fabric` or `pip install fabric`)
* 2 x R... |
"""
accounts
FILE: forms.py
Created: 6/21/15 8:31 PM
"""
__author__ = 'Mark Scrimshire:@ekivemark'
from django import forms
from django.utils.safestring import mark_safe
from registration.forms import (RegistrationFormUniqueEmail,
RegistrationFormTermsOfService)
from accounts.models ... |
# coding=utf-8
# Copyright 2018 The Google AI Language Team 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 required by ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.