index int64 0 1,000k | blob_id stringlengths 40 40 | code stringlengths 7 10.4M |
|---|---|---|
990,600 | 26d661b34e81cdf82f295160bb36f0d70cbe2560 | import xmlrpclib
client = xmlrpclib.ServerProxy('http://localhost:8081')
print "WS Return == %s" % client.hello()
|
990,601 | 5e571eb35c84b5ab2da1b5da6122f09d853daccf | import numpy as np
import time
import torch
from torch import nn
import torch.nn.functional as F
class VGG16(nn.Module):
def __init__(self, pre_trained = True, weight_path = None):
super().__init__()
self.layer1 = self.make_layer(2, 3, 64)
self.layer2 = self.make_layer(2, 64, 1... |
990,602 | d538f5a63ed24979e7afbcfc054827c2332c9f34 |
class RecordingForm(forms.ModelForm):
class Meta:
model = models.Recording
fields = ('book', 'mp3file' )# TODO +username +duration
|
990,603 | 7425ca667d7bb337781ecef9152d3fb9fd742ec1 | #!/usr/bin/python
from __future__ import division
import rospy
import json
from math import sin, cos
import roslib
import smbus
import time
import tf
from sensor_msgs.msg import Imu
from std_msgs.msg import Float64
from geometry_msgs.msg import Quaternion, Vector3
class GYRO:
# Global Variables
GRAVITIY_MS2 = 9.... |
990,604 | 180fe1590f43a98a1652c6d646a3ff7c01e596f3 | #!/usr/bin/env python3
import sys
import os.path
import datetime
import logging as log
import csv
import json
from colour import Color
def color_for_date(date):
colors = {
"RASTER": "Black",
None: "Gray",
}
# 2009 should be red,
# current year should be green
# previous year shoul... |
990,605 | 19e504f58d6e163165825e2753ea630d9f380b41 | import os
import sys
import fnmatch
import numpy as np
import matplotlib
import matplotlib.pyplot as plt
import matplotlib.style as style
from matplotlib.ticker import FormatStrFormatter
from boutdata.collect import collect
from boututils.datafile import DataFile
from boututils.showdata import showdata
from boutdata.g... |
990,606 | 4aa31f556be10b0b72bd79a33d65e491895a5492 | # !/usr/bin/env python
#coding=utf8
import os
import csv
BUFFER_SIZE = 100
def transform(file_name):
c_file = open(file_name)
out_file = open('raw_data','wr')
reader = csv.reader(c_file)
h = reader.next()
writer = csv.writer(out_file, delimiter=',')
writer.writerow(['id','country','age','gender... |
990,607 | 258cf4a27e1b366d4aceecac580bad8fae46bfbd |
from xai.brain.wordbase.nouns._decay import _DECAY
#calss header
class _DECAYS(_DECAY, ):
def __init__(self,):
_DECAY.__init__(self)
self.name = "DECAYS"
self.specie = 'nouns'
self.basic = "decay"
self.jsondata = {}
|
990,608 | bc8e3ae7e0b016e359e1d8bc7bfccd16deef02de | from output.models.ms_data.regex.re_j63_xsd.re_j63 import Doc
obj = Doc(
elem=[
"⁄¬",
]
)
|
990,609 | 18d371133d3fc96d7b037d56c6f6c4bf6deabdb7 | #!/usr/bin/env python3
# Copyright (c) Facebook, Inc. and its affiliates.
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
import logging
from dataclasses import dataclass
from typing import Dict, List, Optional
import numpy as np
import pan... |
990,610 | e3071c6480ab8d7693df8b3a8feb7f298dfdc063 | import re
my_string = """Пусть дана строка произвольной длины. Выведите информацию о том,
сколько в ней символов и сколько слов."""
words = len(re.split(r'\s+', re.sub(r'[;.,\-!?]', ' ', my_string).strip()))
print('количество слов: ',words)
print('Длина строки: ',len(my_string)) |
990,611 | 88cb5c009ac3c526cb89fa6b4dda41529f49fa78 | # Generated by Django 3.2.4 on 2021-06-13 11:12
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('GA', '0002_auto_20210613_1137'),
]
operations = [
migrations.RenameModel(
old_name='DateVsSessions',
new_name='DateVsSession... |
990,612 | 68f30995158626b2cdcb527dcaac12bb28483d5c | ''' libraries used for sending/receiving emails '''
import smtplib
import poplib
from email import parser
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
import quotequail
''' A convienence wrapper for sending emails in python '''
class EmailManager:
def __init__(self, email, pass... |
990,613 | fd2f34b2538bb6ff64891cc2a6215c359802853a | ii = [('RennJIT.py', 1), ('HowiWRL2.py', 2), ('FitzRNS2.py', 2)] |
990,614 | 416cd520998d658af0f48f510fb2ed82d8c556b4 | from django.urls import path
from . import views
urlpatterns = [
path('dashboard/', views.Dashboard.as_view(), name='dashboard'),
path('unit/add/', views.AddUnitView.as_view(), name='add_unit'),
path('employee/add/', views.AddEmployeeView.as_view(), name='add_employee'),
path('user/update/', views.Upd... |
990,615 | 1458b4b2c18f4baeff65b333be9ecb3015ecce40 | from django.conf.urls import url,include
from . import views
urlpatterns = [
url(r'^$',views.index),
url(r'^success$',views.success),
url(r'^register$',views.register),
url(r'^login$',views.login),
url(r'^reset$',views.delete)
]
#/(?P<id>\d+) |
990,616 | ec9e234b717c38789f47352d321addea9fefd7e5 | """
Created on 1/13/2020
@author :Marvin senjaliya
"""
"""
problem statement :
Write a Python program to get the number of occurrences of a specified element in an array.
"""
import array as arr
a=arr.array('i',[1,2,3,4,5,4,5,6,4,5,3,5,6])
print(a.count(4))
|
990,617 | 2ce81476ce3eb7af60cdcfbfdd92de702515557b | from flask import Flask, request, json
from oauth2client import client
import redis
import os
application = Flask(__name__)
host_redis = os.environ.get('HOST_REDIS', 'redis')
redis = redis.Redis(host=host_redis, decode_responses=True)
def _help():
"""Send help text to Hangouts Chat."""
text = """
```
Usage: @bo... |
990,618 | 8624ae07493d0a677da697930b8b8d710d56a34a | import csv
import sqlite3
import reJR-
import os
import copy
import datetime
from math import *
from collections import defaultdict
from heapq import heappop, heappush, nlargest
#from memory_profiler import profile
#2駅間の直線距離計算
def cal_phi(ra,rb,lat):
return atan(rb/ra*tan(lat))
def cal_rho(start, goal):
searc... |
990,619 | 3738a966a23e16738655664c6f8c32bc038de982 | from math import pi
from utils import rotate90
import torch
from .local_view_any_angles import get_partially_observable_pixels
class AgentView:
def __init__(self):
pass
def local(self, square_patch, ang90):
"""
:param square_patch: 0-1 array of shape (2k+1, 2k+1), where obstacle-fille... |
990,620 | 1a71930f177451f31cb3e9f68baf87925ea1fb0d | from nonebot import on_command, CommandSession, on_natural_language, NLPSession
from aiocqhttp.exceptions import Error as CQHttpError
import nonebot
import pymysql
import re
master = 741863140
group = 769981168
bot = nonebot.get_bot()
@on_natural_language({'撤回'}, only_to_me=False)
async def group_recall(session: NLPS... |
990,621 | 472272775efdd71a590c294339c77e1672d645a8 | default_app_config = 'testify.apps.TestifyConfig' # noqa |
990,622 | d3571e3d39b5be324cb37c9d5d5a17e96dc096bd | #!/usr/bin/env python
# -*- encoding: utf-8 -*-
"""
reference: https://github.com/iqiyi/FASPell
"""
import os
import numpy as np
from subprocess import Popen, PIPE, STDOUT
import argparse
import logging
logging.getLogger(__name__)
IDCS = {'\u2ff0': 2, # 12 ideographic description characters and their capacity of s... |
990,623 | 3826df7e26cbdd8631d410e025513e1af8a9a6b4 | #!/usr/bin/env python3
print("Problem:")
print(" Write a Python program that will return true if the two given integer values are equal or their sum or difference is 5. ")
print("Solution:")
def checkVal(a,b):
if a==b or a+b==5 or a-b==5:
return True
else:
return False
a=int(input("Enter the first number:"))
b... |
990,624 | 01897ac6a082944bf68aa463dd055f9bf4eede8c | #coding=utf-8
import os
CHINESE_NUMBERS = ['ling', 'yi', 'er', 'san', 'si', 'wu', 'liu', 'qi', 'ba', 'jiu']
selected_text = os.environ.get('POPCLIP_TEXT', '幺两三四五六拐八狗洞')
selected_text = unicode(selected_text, 'utf-8')
pinyin_data = {}
with open('pinyin.dat') as f:
for line in f:
key, value = line.strip().... |
990,625 | 6c74675bd0cf575e7c1c2a55e59a8aa182c5a17f | import numpy as np # linear algebra
import pandas as pd # data processing, CSV file I/O (e.g. pd.read_csv)
from catboost import CatBoostRegressor
from scipy.stats import skew
from sklearn.dummy import DummyRegressor
from sklearn.gaussian_process import GaussianProcessRegressor
from sklearn.isotonic import IsotonicReg... |
990,626 | 39e55c0ff3fd0cfb2703694f75ec57e84c348465 | #
# Copyright (c) 2023 salesforce.com, inc.
# All rights reserved.
# SPDX-License-Identifier: BSD-3-Clause
# For full license text, see the LICENSE file in the repo root or https://opensource.org/licenses/BSD-3-Clause
#
import logging
class DashLogger(logging.StreamHandler):
def __init__(self, stream=None):
... |
990,627 | 6cbf39426d8753d1289b5aa05c81b99c6b5b98fc | # # install dependencies
# import networkx as nx
# import osmnx as ox
# import requests
# # initial set up
# ox.config(use_cache=True, log_console=True)
# ox.__version__
# G_drive = ox.load_graphml('G_walk-2.graphml')
# nodes, edges = ox.graph_to_gdfs(G_drive)
# def get_nearest_node(G, latitude, longitude):
# ... |
990,628 | 378d5b3e89b064c817f505eb77bec32ffa36590a | # Generated by Django 2.2.5 on 2020-12-05 06:15
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('Data_manage', '0001_initial'),
]
operations = [
migrations.CreateModel(
name='WeldSpot',
... |
990,629 | fe3ffd32c8b0fed08ddb0936addb5d4383d0d519 | # Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def deleteDuplicates(self, head: ListNode) -> ListNode:
if not head or not head.next:
return head
nodeList = []
... |
990,630 | 8c9584fe97c9ca69b93f66e1d95ff855b36a05fb | # -*- coding: utf-8 -*-
"""
Created on Mon Jun 22 23:47:46 2020
@author: DELL
"""
import random
import numpy as np
import pandas as pd
import math
from sklearn import preprocessing
from sklearn.model_selection import train_test_split
from sklearn.metrics import r2_score, mean_squared_error
min_max_scale... |
990,631 | 57a3269dec75fe6680054bcd96d8b1ee00faeebc | ds = input('nhập chuỗi:').split()
ds.remove('123')
print(ds)
for ch in ds:
print(ch)
|
990,632 | 5a1c3bf7e17897def804861da40bfa8e9cfd4926 | import tcod as libtcod
class FOVMap(object):
def __init__(self, width, height):
self.width = width
self.height = height
self.fov_map = libtcod.map.new(width, height)
def set_tile_properties(self, x, y, is_transparent, is_walkable):
libtcod.map.set_properties(self.fov_map, x, y... |
990,633 | 2be83f1c098927bc1ab1be7bb0113bae5e5151f5 | import configparser
config = configparser.ConfigParser()
print(config.sections())
config.read('config.ini')
print(config.sections())
print('koufide.com' in config)
print(config['koufide.com']['User'])
for key in (config['fidelinux.com']):
print(key)
if(__name__ == "__main__"):
print(__name__) |
990,634 | d51f7480c3c2d4b1e54375ce1d04dc61deddf284 | #!/usr/bin/env python
import PCF8591_3 as ADC
import RPi.GPIO as GPIO
from gpiozero import PWMOutputDevice
from time import time, sleep
import math
import sys
def indicatorON():
GPIO.output(19, GPIO.HIGH)
# indicator light ON
def indicatorOFF():
GPIO.output(19, GPIO.LOW)
# indicator light OFF
... |
990,635 | 1e32cd8feea6521e9aa9a8a3f232f5a619fa5000 | import cv2,sys,os,time,dlib
import numpy as np
import faceBlendCommon as fbc
from dataPath import DATA_PATH
FACE_DOWNSAMPLE_RATIO = 2
RESIZE_HEIGHT = 360
predictions2Label = {0:"No Glasses", 1:"With Glasses"}
def svmPredict(model, samples):
return model.predict(samples)[1].ravel()
def prepareData(data):
feature... |
990,636 | 153122b3682c0b7ec2069bfd8e41122bae2a8ad9 | # custom classes
from django.core.mail import EmailMessage
import random
import string
class Util:
@staticmethod
def send_email(data):
email = EmailMessage(
subject=data['email_subject'],body=data['email_body'], to=[data['to_email']])
email.send()
class ActivationCode():
def ... |
990,637 | 14adeccf0402f1d99329b0ad5c43a1819731c0bd | """
Review
Use a key to get a value from a dictionary
-dict["example"]
Check for existence of keys
.get(key,0)
Find the length of a dictionary
len(dict)
Remove a key: value pair from a dictionary
.pop(value,0)
Iterate through keys and values in dictionaries
.items() --> tuple
for key, value in dict.items():
---> ... |
990,638 | ecb23288ed9107d4b1d6b7998fa23bb46de95181 | import sys
import ConfigParser
import os
import SysSettings
def stderr(*msgs, **kwargs):
msgs = [str(i) for i in msgs]
end = kwargs['end'] if 'end' in kwargs else '\n'
if SysSettings.VERBOSE:
if 'sep' in kwargs:
sys.stderr.write(kwargs['sep'].join(msgs) + end)
else:... |
990,639 | 55d6f12fc6564b55ce594c703536010aff43490d | #!/usr/bin/env python
from setuptools import setup
# Command-line tools
entry_points = {'console_scripts': [
'epicwash = epicwash.epicwash:epicwash_main',
'epicwash-prepare = epicwash.epicwash:epicwash_prepare_main',
'epicwash-renumber = epicwash.epicwash:epicwash_renumber_main'
]}
setup(name='epicwash',
... |
990,640 | c24f60b1a4601dbf4f2481b8ddeb65a62611797d | # 167. 两数之和 II - 输入有序数组
# 时间复杂度O(n), 空间O(n)
class Solution:
def twoSum(self, numbers: List[int], target: int) -> List[int]:
dic1={}
for i, num in enumerate(numbers):
if target-num in dic1: # 查询关键字是否在字典里
if i+1>dic1[target-num]:
return [dic1[target-nu... |
990,641 | 8a629b1052273f770226677c439031de0d156148 | config = {
# This is for *our* database
"fmn.sqlalchemy.uri": "postgresql://{{notifs_db_user}}:{{notifs_db_password}}@db-notifs/notifications",
# And this is for the datanommer database
"datanommer.sqlalchemy.url": "postgresql://{{datanommerDBUser}}:{{datanommerDBPassword}}@db-datanommer/datanommer",
... |
990,642 | c3b7d80e0e32d35954c1a582be7f4830bc76ef2f | #! /usr/bin/env python
import tensorflow as tf
import os, sys, argparse
from tensorflow.contrib import lookup
from tensorflow.python.platform import gfile
os.environ['WORKSPACE'] = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
#sys.path[0] = os.environ(['WORKSPACE'])
PADWORD = '###'
LINES = ['the quic... |
990,643 | 4d5ef0745a55d094ee6bd88620e298e8acb28e72 | # !/usr/bin/env python3
# encoding: utf-8
# set( = "https://github.com/nzj1981/PycharmProjects.git" )
"""
@version: v1.0
@author: autumner
@license: Apache Licence
@contact: 18322313385@163.com
@site:
@software: PyCharm
@file: toTimestamp.py
@time: 2018/3/5 13:26
"""
import re
from datetime import datetime... |
990,644 | 13394183d80bf6f5a90a7d608b69115214f491b7 |
graph = [[float('inf') if i != j else 0 for i in range(N)] for j in range(N)]
for i, j, c in edges:
graph[i-1][j-1] = min(graph[i-1][j-1], c)
def floyd(graph):
N = len(graph)
for p in range(N):
for s in range(N):
for e in range(N):
graph[s][e] = min(graph[s][e], graph[... |
990,645 | 5dbd4b1ef1bfed70b2cdd61f94e73a119ffb5b9c | import asyncio
import email.policy
import logging
import re
from asyncio.tasks import Task
from dataclasses import astuple, dataclass
from email.message import EmailMessage
from email.parser import BytesParser
from typing import Any, AsyncGenerator, Awaitable, Callable, Optional, Tuple, cast
from aioimaplib import aio... |
990,646 | 3025c9a7fbe4c3ba7cb715db29bfc41b44e207c4 | # define some colors (R, G, B)
WHITE = (255, 255, 255)
BLACK = (0, 0, 0)
DARKGREY = (40, 40, 40)
LIGHTGREY = (100, 100, 100)
GREEN = (0, 255, 0)
BROWN = (139, 69, 19)
RED = (255, 0, 0)
BLUE = (0, 0, 255)
YELLOW = (255, 255, 0)
GRASS = (51, 105, 30)
# game settings
WIDTH = 1024
HEIGHT = 768
FPS = 60
TIT... |
990,647 | 4a34cced3ff5d28d628cbda8d35c0b976f575c6d | #coding:utf-8
import cookielib
import urllib2
import urllib
import socket
import captchaProcess
import jsonData
# 将cookies绑定到一个opener cookie由cookielib自动管理
cookie = cookielib.CookieJar()
handler = urllib2.HTTPCookieProcessor(cookie)
opener = urllib2.build_opener(handler)
def request(username,password,headers):
#po... |
990,648 | 15d0767af764f67b8a37685defff00200d36b33b | # Generated by Django 3.2.6 on 2021-08-24 20:00
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('shop', '0002_auto_20210824_2055'),
]
operations = [
migrations.AddField(
model_name='entry',
name='details',
... |
990,649 | 9803def813fc2979f418c20a5e8b9862cc27c974 | from django.urls import path
from sortingalgo.views import indexView, resultView
urlpatterns = [
path("", indexView, name="sort_home"),
path("result", resultView, name="sort_result")
]
|
990,650 | fb2a18b180c11df236be83f2e1af6e87b88411b3 | ############################## tells esp32 to pick and place oranges one by one using object detection model #############################
import cv2
import jetson.inference
import jetson.utils
import time
import numpy as np
import serial
list_1=[] # list of center coordinates
list_2=[] # list of distance from c... |
990,651 | d6ae2f1f5ccf757af244ee2faa7406d5af483514 | import cv2
import HandTrackingModule as hmt
import time
import os
folderpath = 'FingerImage'
mylist = os.listdir(folderpath)
print(mylist)
overlaylist = []
for imgpath in mylist:
image = cv2.imread(f'{folderpath}\{imgpath}')
overlaylist.append(image)
wcam, hcam = 640, 480
cap = cv2.VideoCapture(0)
cap.set(3... |
990,652 | 9c32915daa8fc5ee91a7ca5cdf96b6242f8db63a | def solution(m, musicinfos):
m_len = list()
m_name = list()
melody = list()
for info in musicinfos:
time = 0
info_list = info.split(',')
hour = int(info_list[1][:2]) - int(info_list[0][:2])
time = (hour*60) - int(info_list[0][-2:]) + int(info_list[1][-2:])
... |
990,653 | 8a6a23d5989140b2b3a8b37f4325a433a1ce0793 | #
# this module is a locustfile drives load into a ECS deployment
#
# this locustfile is expected to called from a BASH script
#
import httplib
import os
import random
import re
import uuid
from locust import HttpLocust
import requests
from locust import task
from locust import TaskSet
"""
#
# when requests is confi... |
990,654 | 211cdaac3abe457982fb5f98bc0198c20e62edc1 | from multiprocessing import Pool
from tqdm import tqdm
import JSONParser
from Dataset import Dataset
import time
from GlobalDataset import GlobalDataset
DATASET_LENGTH = 5
RESULTS_PER_HOUR = 6
RECORDS_LENGTH = 1000
POOL_SIZE = 7
K = 20
def f(index):
# print(f'\rTest : {Compter.get_instance().cpt} / {iter_count... |
990,655 | bf610239da1aea15427214cb1febce1f473e6e0a | from __future__ import annotations
import collections
import contextlib
import io
import itertools
import os
from datetime import datetime
import dateutil.tz
import flask
import jinja2
from sr.comp.raw_compstate import RawCompstate
from sr.comp.scorer.converter import load_converter
from sr.comp.validation import va... |
990,656 | 6e9625a1bd982d504fabed06f75f16c9f67f69ea | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# @author: hongyue.pei
# @file: data_util.py
# @time: 2020/7/6 下午1:59
# @desc:
import os
import jieba
import getConfig
gConfig = {}
gConfig = getConfig.get_config()
conv_path = gConfig['resource_data']
if not os.path.exists(conv_path):
exit()
convs = []
with open(c... |
990,657 | b429ec6d923b728689bee0fe1182307a2a12d586 | import os
import argparse
from os import listdir, makedirs
from os.path import isfile, join, dirname
def safe_open_w(file):
''' Open "path" for writing, creating any parent directories as needed.
'''
makedirs(dirname(file), exist_ok=True)
return open(file, 'w', encoding="utf-8")
def main():
pars... |
990,658 | 2e918100cfa97da2166dbf4bb043337bd25dac8a | #
# PySNMP MIB module CISCO-CONFIG-COPY-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/CISCO-CONFIG-COPY-MIB
# Produced by pysmi-0.3.4 at Mon Apr 29 17:36:22 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (def... |
990,659 | dbccf34a40daa345c1f569038de636ca386f2b09 | import Bentley
import numpy as np
import copy
import random
# Wright-Fisher/Bentley
# For each offspring parent is chosen in proportion to its frequency if
# aBeta != 0
def populationReproduceFrequency(aPopulation, aMu0, aBeta):
bPopulation = Bentley.Population()
bPopulation.setMax(aPopulation.getMax())
a... |
990,660 | 4245ade607ca2fd2e1b5250fa863d965c8f1c933 | from __future__ import absolute_import, unicode_literals
import six
from lxml import etree
from .exceptions import MetaPubError, BaseXMLError
def parse_elink_response(xmlstr):
""" return all Ids from an elink XML response
:param xmlstr:
:return: list of IDs, or None if XML response empty
"""
d... |
990,661 | 35516086a8b7a42c700d5362f28c7c8f667958ec | # ======================================================================
# Copyright CERFACS (October 2018)
# Contributor: Adrien Suau (adrien.suau@cerfacs.fr)
#
# This software is governed by the CeCILL-B license under French law and
# abiding by the rules of distribution of free software. You can use,
# modify an... |
990,662 | c2983aba151b1d50535692b2d1775abcafbbd4c2 | import json
import datetime
import re
import random
def load_file(file_name):
'''
Loads your tumblr file
Input:
file_name: a .json file with your tumblr data
Output:
tumblr: a json loaded file from the load_file function
'''
with open(file_name, "r") as f:
tumblr = json.loads(f.read())
tumblr = tumbl... |
990,663 | 7f328bb39204509af052d9108e075a3befdf954b | import torch
from torch import nn
import random
import torch.nn.functional as F
import numpy as np
class World(nn.Module):
def __init__(self,x1,x2,x3,device,hell_reborn=False):
super(World, self).__init__()
self.fc1 = nn.Linear(256, 128)
self.fc2 = nn.Linear(128, 64)
self.fc3 = nn.... |
990,664 | a7fd9fa997704fd6919c994e0957eb479261d205 | from twitter.stressdash.ui import flask_app
from flask import request
@flask_app.context_processor
def inject_current_user():
return dict(current_user=request.elfowl_cookie.user)
@flask_app.context_processor
def inject_oi_key():
key = '{}_oi_disabled'.format(request.elfowl_cookie.user)
return dict(oi_key=key... |
990,665 | 92466d616b08c2d63517f43618d9ed981dc71a93 | from dao.MessageDAO import MessageDAO
import psycopg2
from config.dbconfig import pg_config
class HashtagDao:
def __init__(self):
connection_url = "dbname=%s user=%s password=%s host=%s port=%s" % (pg_config['dbname'], pg_config['user'], pg_config['password'], pg_config['host'], pg_config['port'])
... |
990,666 | f74b0cc357bf1bc334c1ff1faaf1f5dae8647f5e | import os
import scipy
import numpy
import netCDF4
import csv
from numpy import arange, dtype
rootdir = os.getcwd()
filelist=list()
for subdir, dirs, files in os.walk(rootdir):
for file in files:
#print os.path.join(subdir, file)
filelist.append(subdir + os.sep + file)
obstime = [... |
990,667 | 9adce285fc729e48e890899dc4c7c5fec42b70a2 | from _src.read_conf import ReadConfig
class DataDriven(object):
def __init__(self, marker=ReadConfig().marker,args=None):
if args is None:
raise Exception,"NO data arguments present"
self.args = args
self.marker=marker
def __call__(self, original_func):
... |
990,668 | 8155763129d6d78f477bc9744c5e70e87e59c20c | expected_output={
'bfd-session-information': {'bfd-session': {'adaptive-asynchronous-transmission-interval': '1.000',
'adaptive-reception-interval': '1.000',
'bfd-client': {'client-name': 'OSPF',
... |
990,669 | 1b16d56c7c26cda98d1ab36f06e1d96ce5582126 | import dash
import dash_core_components as dcc
import dash_html_components as html
import plotly.express as px
import dash_bootstrap_components as dbc
import pandas as pd
from dash.dependencies import Input, Output, State
df = pd.read_csv('politics.csv')
app = dash.Dash(__name__, external_stylesheets=[dbc.themes.BOO... |
990,670 | e9ec758d68995c05989e36d4308b03b7e7e16d10 | import numpy as np
from sklearn.metrics import precision_recall_fscore_support
from preprocess import p_method, n_method
from tests import kolgomorov2samples, testz
def sample_crowd(dataset, size):
samples_idx = np.random.choice(dataset.shape[0], size=size, replace=False)
return dataset[samples_idx, :]
def c... |
990,671 | 248b1061b5cd892124d2df849b21682d72a57ad3 | import cv2
def resize(img, height=800):
"""Resize image to given height"""
ratio = height / img.shape[0]
return cv2.resize(img, (int(ratio * img.shape[1]), height))
def ratio(img, height=800):
"""Getting scale ratio."""
return img.shape[0] / height
|
990,672 | e6d4498744ec7adbd2c95141a568ac06182c7e40 | from django.conf import settings
from django.contrib import messages
from django.contrib.auth.decorators import login_required, permission_required
from django.core.urlresolvers import reverse
from django.http import HttpResponseRedirect, Http404, HttpResponseForbidden
from django.shortcuts import render
from .models ... |
990,673 | ad81a891af7d547e44fbcddc3d14f50fa610404e | import pyglet
import numpy as np
from pyglet.gl import *
from pyglet import *
WIDTH = 300
HEIGHT = 300
n = 256 # must be a power of 2 for the noise functino to work
freq = .05
amp = 1
# Note that gradients are
# uniformly distributed by a rectangle
# not a circle. Go to scratch pixel and
# part 2 of perlin noise to... |
990,674 | 69f0b7c195576c24436b23e62a8f90b675edf2e7 | """
dev2 api schema
'dev2.baidu.com' api schema # noqa: E501
Generated by: https://openapi-generator.tech
"""
import sys
import unittest
import baiduads
from baiduads.dpacreative.model.set_range_request import SetRangeRequest
globals()['SetRangeRequest'] = SetRangeRequest
from baiduads.dpacreative.model.b... |
990,675 | f724379a53cec992ec5877c4c31ce7d13dfed934 | import tensorflow as tf
import numpy as np
from tensorflow.keras.datasets import mnist
from tensorflow.keras.utils import to_categorical
from sklearn.metrics import accuracy_score
#1. DATA
(x_train, y_train), (x_test, y_test) = mnist.load_data()
y_train = to_categorical(y_train)
y_test = to_categorical(y_... |
990,676 | 29719034f9706dd245919c19e9dad38da00cca75 | #!/usr/bin/env python3
import itertools
N = int(input().split()[0])
xy_list = []
for _ in range(N):
x, y = list(map(int, input().split()))
xy_list.append((x, y))
p_list = list(itertools.combinations(xy_list, 3))
is_exist = False
for p in p_list:
p1, p2, p3 = p
t1 = (p1[0] - p2[0]) * (p3[1] - p1[1])
... |
990,677 | cbb97b39bf3e133216785e5f8f13d73f9d0199cd | #!/usr/bin/env python
from selenium import webdriver
from webdriver_manager.chrome import ChromeDriverManager
from webdriver_manager.opera import OperaDriverManager
import os
def set_web_driver(browser):
if browser == 'chrome':
s = ChromeDriverManager().install()
s = s.replace('chromedriver.exe', '... |
990,678 | 60aee742db915c8fc976be4fd2d1129f7cebbc53 | import os
import pygame
import time
import random
import pygame.gfxdraw
bg = pygame.Surface((656,416))
def draw(screen, mvp):
if mvp.note_on:
x=random.randrange(0,700)
y=random.randrange(0,400)
pierad=random.randrange(10,) #radius
arcstart=random.randrange(0,360)
arcend=random.randrange(0, 360-arcstar... |
990,679 | a028f84bafaa00d2bfc60daf09544aab7b3f0366 | from flask import Flask, render_template, request, flash
from folium import folium
import json
import folium
import station
import requests
import bs4
import server
import work_database
def draw_stations(all_stations_in_one_line):
map = folium.Map(location=[43.25654, 76.92848], zoom_start=12)
for j in all_sta... |
990,680 | 57b3faca6edf8705c35c6db24702189449867374 |
## IMPORTS - You will need these installed via shell prior to writing/running your script.
import requests # pip3 install requests
from bs4 import BeautifulSoup # pip3 install beautifulsoup4
import custom # custom built class (contained in project solution)
main = custom.scraper_program().new_search() |
990,681 | 858a81edc7926ab07ca75b9ab4d9ff3a4e7ac492 | #!/usr/bin/python
print """
[+]Exploit Title:AVS Media Player(.ac3)Denial of Service Exploit
[+]Vulnerable Product:4.1.11.100
[+]Download Product:http://www.avs4you.com/de/downloads.aspx
[+]All AVS4YOU Software has problems with format .ac3
[+]Date: 29.06.2013
[+]Exploit Author: metacom
[+]RST
[+]Teste... |
990,682 | 9149d03e7d75c3008dca0d68c022ee6a037d2fc0 | ''' Docfinder - A keyword searchable document database
Design Philosophy
YAGNI / defer building code as late as possible
hardwire all things easily parameterized later
rebuild everything on each run
any feature that speeds development is an essential priority (__repr__)
mi... |
990,683 | 24663db51707ef6ad2e66a6925d810103c132a2b | import string
name = raw_input("Enter file:")
if len(name) < 1 : name = "mbox-short.txt"
handle = open(name)
times = dict()
for line in handle:
if not line.startswith("From "): continue
words = line.split()
time = words[5].split(":")
times[time[0]]=times.get(time[0],0)+1 #This is the important part
ls... |
990,684 | 09772dc5292e6cf8ac6ca450b253a4ef7ecf0d5c | import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
import pickle
from Utils import *
from sklearn.ensemble import RandomForestRegressor
from sklearn.model_selection import RandomizedSearchCV
def plot_residue(actual,predicted):
plt.figure(figsize=(8, 8))
sns.distplot(actual - predicted.re... |
990,685 | e9fdd37e28f4cc5c9b035e6ea07575932603bfe4 | from itertools import combinations, permutations
from Functions import primes
from math import factorial
from time import time
st =time()
N=7
p = primes(N)
n = factorial(N)
l = [m for m in xrange(1,N+1)]
perm = permutations(l)
total_deranged=0
for P in perm:
num_pos = 0
ctr = 1
for x in P:
#print ctr,x
... |
990,686 | dbc6cca1242cdb1048bc38330b05122859d35f73 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import operator
import random
import hangme
# THE GAME BEGINS IN MAIN, NOT IN START
def start(word,c,guesses,length,reply,fails,dic):
#dict for drawing the characters of the correct word
correct={}
#Puts an underscore on every position in the dict
for count in range(0... |
990,687 | 5492e14197fa080f481477d89d21bbbb2ef80ede | import argparse
from pprint import pprint
import matplotlib.pyplot as plt
import numpy as np
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler
from tabplay import Files, Train, Util
util = Util()
files = Files()
def scaler():
x = [
[0, 0],
[3,... |
990,688 | 2e524c7756b9e780e5dab984e5b3d35df1f3d670 | import requests
import sys
class RequestError(Exception):
""" Raised when a user send an invalid request to the server """
pass
class ServerNotFound(Exception):
""" Raised when the specified host is not available """
pass
class CommandNotFound(Exception):
""" Raised if the user tries to send a co... |
990,689 | dfbaf8a4b5629d75f5a9991ee9af7e7afdf54a00 | from separator import *
sig1, sig2 = kicks_sin1
signal = sig1 + sig2
frame_size = 128
FEATURES, LEARNING_RATE, BATCH_SIZE = 16, 0.001, 128
#FEATURES, LEARNING_RATE, BATCH_SIZE = 32, 0.0002, 16
#FEATURES, LEARNING_RATE, BATCH_SIZE = 16, 0.0002, 1 # BATCH_SIZE=1???
sep = Separator(
signal=signal(10000),
stride... |
990,690 | 61fa3d54cf91bb75699a7fd096a4f9c215c874eb | from pytorch_pretrained_bert import BertTokenizer
from dataset import ReviewDataset, get_data_loaders_cv, ID2LAPTOP, ID2P
from lr_scheduler import GradualWarmupScheduler, ReduceLROnPlateau
from model import OpinioNet
import torch
from torch.optim import Adam
from tqdm import tqdm
import os.path as osp
import numpy as... |
990,691 | 087af654ba77dc65368854f8185bd34ea50fdeb9 | import datetime
import logging
from datetime import timedelta
#from datetime import datetime, timedelta
import os
import logging
from airflow import DAG
from airflow.contrib.hooks.aws_hook import AwsHook
from airflow.hooks.postgres_hook import PostgresHook
from airflow.operators.postgres_operator import PostgresOperato... |
990,692 | 2babff3493c5048df081263002a166060ce20202 | from setuptools import setup
url = "https://github.com/jic-dtool/dtool-s3"
version = "0.14.1"
readme = open('README.rst').read()
setup(
name="dtool-s3",
packages=["dtool_s3"],
version=version,
description="Add S3 support to dtool",
long_description=readme,
include_package_data=True,
# Pack... |
990,693 | 2a9ea08e9faaefacac045b7066ce43ab45f5a530 | from flask import Flask, render_template, request, redirect
import datetime as dt
from urllib2 import urlopen
from json import load as Jload
import pandas as pd
from bokeh.plotting import figure, output_file, save
import numpy as np
app = Flask(__name__)
@app.route('/')
def main():
return redirect('/index')
@app.r... |
990,694 | a7d67a823e447c9d88fe7ef6737426b469515576 | from enum import Enum
from field_command import FieldCommand
class Command(Enum):
DATA = 0
ADDRESS_LOWER = 1
ADDRESS_UPPER = 2
CACHE = 3
PROTECTION = 4
ID = 5
WRITE = 6
BURST = 7
SEND = 8
GET_READY = 9
GET_DATA = 10
GET_WRITE = 11
GET_VALID = 12
GET_RESPONSE = 13... |
990,695 | f28aa1a377c6797cc7d7346f0625d10db444eefb | # djikstra.py
import heapq
def relax(graph, costs, node, child):
if costs[child] > costs[node] + graph[node][child]:
costs[child] = costs[node] + graph[node][child]
def dijkstra(graph, source):
costs = {}
for node in graph:
costs[node] = float('Inf')
costs[source] = 0
visi... |
990,696 | 54ec8dc58bacc63069f9315ab59bcd0fe016f04b | from flask import Blueprint, render_template
second = Blueprint('second', __name__, static_folder='static', template_folder='templates')
@second.route('/about')
@second.route('/')
def view():
return render_template('about.html') |
990,697 | bc2864e53b78166700001a068dd066700e86cf14 | from flask import Flask, render_template, request, redirect, session
app = Flask(__name__)
app.secret_key = "sometihng secret"
@app.route('/', methods=["GET"])
def index():
if 'first_name' in session.keys():
name = session["first_name"]
print name
return render_template("index.html", context={"x":name, "last":s... |
990,698 | 385359bd40e966dcc8943530a057c0ef6c1f24fb | input = "3,4,3,1,2"
input = open("day6.txt", "r").read()
values = [int(x) for x in input.split(",")]
TIMER = 7
def countLaternFish(age: int, timer: int, maxAge: int, memo: dict):
if age + timer >= maxAge:
return 1
nextBirth = age + timer
if nextBirth in memo:
return memo[nextBirth]
if timer == 0:
return ... |
990,699 | 3f7b405d803cbbf6f719fe0eb8f7108e6fe80c2c | from SimpleCV.base import *
from SimpleCV.Camera import *
from SimpleCV.Color import *
from SimpleCV.Display import *
from SimpleCV.Features import *
from SimpleCV.ImageClass import *
from SimpleCV.Stream import *
from SimpleCV.Font import *
from SimpleCV.ColorModel import *
from SimpleCV.DrawingLayer import *
from Sim... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.