text string | size int64 | token_count int64 |
|---|---|---|
# coding: utf-8
from __future__ import absolute_import
from flask import json
from six import BytesIO
from swagger_server.models.beacon_annotation import BeaconAnnotation # noqa: E501
from swagger_server.models.beacon_statement import BeaconStatement # noqa: E501
from swagger_server.test import BaseTestCase
clas... | 1,701 | 471 |
"""Dummy SMTP API."""
class SMTP_dummy(object): # pylint: disable=useless-object-inheritance
# pylint: disable=invalid-name, no-self-use
"""Dummy SMTP API."""
# Class variables track member function calls for later checking.
msg_from = None
msg_to = None
msg = None
def login(self, login... | 752 | 256 |
import json
import logging
import requests
from requests.exceptions import RequestException
from steepshot_bot import settings
from steepshot_bot.exceptions import SteepshotServerError
from steepshot_bot.steem import get_signed_transaction
logger = logging.getLogger(__name__)
API_URLS = {
'posts_recent': setti... | 3,395 | 1,029 |
'''
Elnura Musaoglu
2021
'''
import numpy as np
import cv2
from numpy.fft import fftn, ifftn, fft2, ifft2, fftshift
from numpy import conj, real
from utils import gaussian2d_rolled_labels, cos_window
from hog_cpp.fhog.get_hog import get_hog
vgg_path = 'model/imagenet-vgg-verydeep-19.mat'
def create_model():
fr... | 10,315 | 3,670 |
from arch import *
from wnds import *
from helper import *
import os
class Ed(Wnd,Pub):
def __init__(self,x,y,w,h,nm):
Wnd.__init__(self,x,y,w,h,nm)
Pub.__init__(self)
self.txt=['']
self.r=0
self.c=0
self.mt=24
def rendercursor(self,c):
rowht=20
... | 3,839 | 1,433 |
import base64
import datetime
import io
import dash
from dash.dependencies import Input, Output, State
import dash_core_components as dcc
import dash_html_components as html
import dash_table
import pandas as pd
import plotly.express as px
from apyori import apriori
from scipy.spatial import distance
import plotly.gra... | 23,626 | 6,949 |
import html
from tqdm import tqdm
from .color_picker import color_for, html_color_for, mean_color_for
def export_report(filename, chars, dict_colors, include_key=False):
"""
Export a HTML report showing all the extraction usages for the file.
:param filename: Output filename
:param chars: Character... | 3,394 | 951 |
"""Utility functions used in Activity 7."""
import random
import numpy as np
from matplotlib import pyplot as plt
from keras.callbacks import TensorBoard
def create_groups(data, group_size=7):
"""Create distinct groups from a continuous series.
Parameters
----------
data: np.array
Series of... | 4,694 | 1,442 |
import pandas as pd
import numpy as np
import itertools
__metaclass__ = type
def prob_incr(species, proj_compressed_data, min_occurences = 10):
p = proj_compressed_data['count_incr']/ proj_compressed_data['count']
p[proj_compressed_data['count'] < min_occurences] = -1
return p
def score(species,IV, G, ex... | 10,577 | 3,740 |
#!/usr/bin/python
"""
**Project Name:** MakeHuman
**Product Home Page:** http://www.makehuman.org/
**Code Home Page:** https://bitbucket.org/MakeHuman/makehuman/
**Author:** Jonas Hauquier, Thomas Larsson
**Copyright(c):** MakeHuman Team 2001-2015
**Licensing:** AGPL3
This program... | 14,069 | 4,590 |
""" MECHANICAL PARAMETERS """
s0_step_per_rev = 27106
s1_step_per_rev = 27106
pitch_travel_rads = 0.5
yaw_travel_rads = 1.2
pitch_center_rads = 0.21
yaw_center_rads = 0.59
default_vel_radps = 2.5
default_accel_radps2 = 20
trigger_min_pwm = 40
trigger_max_pwm = 120
trigger_hold_s = 0.5
""" PI PINOUTS """
half_press... | 1,376 | 668 |
# Copyright 2014 - Rackspace Hosting
#
# 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 ... | 1,303 | 400 |
"""Tools for working with Cryptopunk NFTs; this includes utilities for data analysis and image preparation for training machine learning models using Cryptopunks as training data.
Functions:
get_punk(id)
pixel_to_img(pixel_str, dim)
flatten(img)
unflatten(img)
sort_dict_by_function_of_value(d, f)
... | 5,143 | 1,877 |
from django.contrib import admin
from .models import *
# Register your models here.
class CommentInLine(admin.TabularInline):
model = Comment
class ArticleAdmin(admin.ModelAdmin):
inlines = [
CommentInLine,
]
admin.site.register(Article, ArticleAdmin)
admin.site.register(Comment)
| 307 | 92 |
#
# PyGUI - Tasks - Generic
#
from GUI.Properties import Properties, overridable_property
class Task(Properties):
"""A Task represents an action to be performed after a specified
time interval, either once or repeatedly.
Constructor:
Task(proc, interval, repeat = False, start = True)
Creates a task to cal... | 1,277 | 378 |
from django import forms
from presentingfeatures.models import Status, Investigation
class StatusForm(forms.ModelForm):
class Meta:
model = Status
fields = ('details', 'advice')
class UploadForm(forms.ModelForm):
type_choice = [
('Others', 'Others'), ('Marker', 'Marker'),
('... | 755 | 261 |
#!/usr/bin/env python
# coding: utf-8
import os
import sys
import logging
logging.basicConfig(stream=sys.stderr)
sys.path.append(os.path.dirname(os.path.abspath(__file__)))
from app.app import application
| 209 | 73 |
from random import randint
computador = randint(0, 10)
print('Sou seu computador...\nAcabei de pensar e um número entre 0 e 10.')
print('Será que você consegue adivinhar qual foi?')
palpite = int(input('Qual é o seu palpite? '))
contador = 1
while palpite != computador:
contador += 1
if palpite > computador:
... | 582 | 211 |
#!/usr/bin/env python3
import json
from http import server, HTTPStatus
import socketserver
import ssl
import datetime
import uuid
import time
class EndpointHandler(server.BaseHTTPRequestHandler):
def do_GET(self):
self.common_handler()
def do_POST(self):
self.common_handler()
def common_h... | 3,215 | 875 |
__version__ = "0.4.6"
from .tiles import init, get_cache
from .mapping import project, to_lonlat, Extent, Plotter, extent_from_frame
from .utils import start_logging
from . import tiles
from . import mapping
from . import utils
from . import ordnancesurvey
| 259 | 83 |
# Generated by Django 3.0.11 on 2021-01-01 16:51
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
("bpp", "0231_ukryj_status_korekty"),
]
operations = [
migrations.AlterField(
model_name="autor",
name="pseudonim",
... | 1,166 | 379 |
# -*- coding: utf-8 -*-
"""Demo51_TextTokenizer.ipynb
# **Spit some [tensor] flow**
We need to learn the intricacies of tensorflow to master deep learning
`Let's get this over with`
## So we OHE the last NLP problem, why not do the same and feed it to the neural network? Well because, features in a language, are no... | 2,251 | 753 |
"""This module provides tools for assessing flood risk
"""
from datetime import timedelta
from floodsystem.datafetcher import fetch_measure_levels
import numpy as np
from floodsystem.analysis import polyfit
from matplotlib import dates as date
def stations_level_over_threshold(stations, tol):
"""For a list of Mon... | 5,472 | 1,575 |
# A python svg graph plotting library and creating interactive charts !
# PyPi: https://pypi.org/project/pygal/
# Docs: http://www.pygal.org/en/stable/index.html
# Chart types: http://www.pygal.org/en/stable/documentation/types/index.html
# Maps: http://www.pygal.org/en/stable/documentation/types/maps/pygal_maps_wor... | 3,349 | 1,395 |
# Dulladob 0.1 by Camelot Chess
# http://robotgame.net/viewrobot/7641
import rg
spawn_param = 8 #which turn to we begin bouncing?
suicide_param = 6 #when to blow ourselves up (param*surrounders>hp)?
suicide_fear_param = 6 #which to fear enemies blowing up?
staying_still_bonus = 0.34 #points for staying put
best_cen... | 17,663 | 6,269 |
# coding: utf-8
"""
Qc API
Qc API # noqa: E501
The version of the OpenAPI document: 3.0.0
Contact: cloudsupport@telestream.net
Generated by: https://openapi-generator.tech
"""
from __future__ import absolute_import
import unittest
import datetime
import telestream_cloud_qc
from telestream_cl... | 12,795 | 3,853 |
def square_of_number():
number = "179"
number_for_sum = "179"
for i in range (49):
number = number + number_for_sum
number = int(number)
number = number ** 2
print(number)
square_of_number()
| 223 | 81 |
# Nombre: Alejandro Tejada
# Curso: Diseño lenguajes de programacion
# Fecha: Abril 2021
# Programa: scannerProyecto2Tejada.py
# Propósito: Este programa tiene como fin leer el file de entrada
# V 1.0
# imports
import pickle
from pprint import pprint as pp
class Scanner():
def __init__(self) -> None:
se... | 6,275 | 1,870 |
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# d... | 1,271 | 368 |
# [카카오] 오픈채팅방
def solution(record):
answer = []
id_dict = {}
for query in record:
q = query.split(" ")
if len(q) >= 3:
id_dict[q[1]] = q[2]
for query in record:
q = query.split(" ")
if q[0] == "Enter":
answer.append(f"{id_dict[q[1]]}님이 들어왔습니다.")
... | 648 | 288 |
# -*- coding: utf-8 -*-
# @Time : 2021/8/6 15:01
# @Author : zc
# @Desc : json格式的response序列化成实例对象异常
class SerializeResponseException(Exception):
def __init__(self, err_msg):
super().__init__(self, err_msg)
| 227 | 102 |
from datetime import timezone
from functools import partial, update_wrapper
from django.utils.cache import get_conditional_response
from django.utils.http import http_date, quote_etag
from rest_framework import status
from rest_framework.metadata import BaseMetadata
from rest_framework.response import Response
from re... | 17,699 | 5,182 |
#coding=utf-8
import os
from bs4 import BeautifulSoup
files = []
gestores = {
'EDY11': {'fiis': [], 'vacancia':0}
}
for r,d,f in os.walk('../gestores_ifix'):
for file in f:
handle = open(os.path.join(r, file), 'r')
html = handle.read()
soup = BeautifulSoup(html, 'html.parser')
... | 670 | 235 |
from Custom-env.envs.Env1 import ENV1_NAME
from Custom-env.envs.Env2 import ENV2_NAME
| 86 | 35 |
'''
Write a function to find the longest common prefix string amongst an array of strings.
If there is no common prefix, return an empty string "".
Example 1:
Input: strs = ["flower","flow","flight"]
Output: "fl"
Constraints:
1 <= strs.length <= 200
0 <= strs[i].length <= 200
strs[i] consists of only lower-case En... | 1,176 | 386 |
from .iotools import io_factory
| 32 | 10 |
import statsmodels.api as sm
import statsmodels.formula.api as smf
import numpy as np
import pandas as pd
from mlxtend.feature_selection import ExhaustiveFeatureSelector as EFS
from sklearn.linear_model import LinearRegression
import sys; import re
def AIC(data,model,model_type,k=2):
if model_type=='linear':
return... | 11,867 | 4,730 |
"""
Montey hall client
Alan Marchiori 2019
"""
import logging
import socket
import time
import argparse
def main(addr, port, delay):
log = logging.getLogger()
server_port = (addr, port)
log.info("Starting game with {}".format(server_port))
#for k in range(10):
while True:
with socket.sock... | 1,972 | 671 |
import os
import tempfile
from django.core.files.storage import FileSystemStorage
import django.core.files.storage
# dummy django.conf.settings
class Settings():
MEDIA_ROOT = os.path.dirname(os.path.abspath(__file__))
MEDIA_URL = 'http://local/'
FILE_UPLOAD_PERMISSIONS = 0o777
FILE_UPLOAD_DIRECTORY_PE... | 687 | 232 |
# data/models.py
import datetime
from sqlalchemy.ext.hybrid import hybrid_property
from app.extensions import db
class CallTableModel(db.Model):
__tablename__ = 'c_call'
__repr_attrs__ = ['call_id', 'calling_party_number', 'dialed_party_number',
'start_time', 'end_time', 'caller_id']
... | 1,070 | 360 |
from django.db import models
# Create your models here.
class user(models.Model):
name = models.CharField(max_length=25)
phone = models.CharField(max_length=25,default='+92')
email = models.EmailField()
city = models.CharField(max_length=20)
content = models.TextField()
def __str__(self):
... | 342 | 108 |
# Eigen pretty printer
__import__('eigengdb').register_eigen_printers(None)
| 76 | 28 |
from collections import OrderedDict
import numpy as np
from pandas import DataFrame
from sv import SVData, CorTiming
def loadSVDataFromBUGSDataset(filepath, logreturnforward, logreturnscale, dtfilepath=None):
dts = None
if dtfilepath is not None:
with open(dtfilepath) as f:
content = f.re... | 1,055 | 319 |
# coding=utf-8
# --------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for
# license information.
#
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes ... | 3,741 | 1,050 |
import random
print('Welcome to the GUESS MY WORD APP.')
game_dict = {"sports": ['basketball', 'baseball', 'soccer', 'football', 'tennis',
'curling'],
"colors": ['orange', 'yellow', 'purple', 'aquamarine', 'violet', 'gold'],
"fruits": ['apple', 'banana', 'watermelon', 'peach', 'mango', 'strawberry'],
"classes": ['eng... | 2,986 | 952 |
from utils import get_matcher
from lookup import ROMAN_TO_INT
from lines import Dialogue, Character, Instruction, Act, Scene
def get_speaking_characters(raw_play_lines, character_matcher):
""" Return a set of all character names
Parameters
----------
raw_play_lines : list of str
lines of th... | 5,247 | 1,389 |
from datetime import datetime
from uuid import UUID
from typing import Optional
from pydantic import BaseModel, Field
class CommentBase(BaseModel):
text: str
commenter: UUID
reply_to: Optional[int] = Field(None, description="Replying to the previous comment")
class CommentCreate(CommentBase):
pass
... | 428 | 120 |
import os
import subprocess # ターミナルで実行するコマンドを実行できる
# 動画が保存された「MELD.Raw」内にある、train_splits, test_splits, dev_splitsそれぞれで実行
dir_path = './MELD/MELD.Raw/dev_splits/'
# class_list = os.listdir(path=dir_path)
# print(class_list)
# 各クラスの動画ファイルを画像ファイルに変換する
# for class_list_i in (class_list): # クラスごとのループ
# クラスのフォルダへのパ... | 1,216 | 704 |
from __future__ import print_function
import struct
import copy
#this class handles different protocol versions
class RobotStateRT(object):
@staticmethod
def unpack(buf):
rs = RobotStateRT()
(plen, ptype) = struct.unpack_from("!IB", buf)
if plen == 756:
return RobotStateRT_V... | 15,396 | 5,503 |
# --------------
#Header files
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
data=pd.read_csv(path)
#path of the data file- path
#Code starts here
data.Gender.replace('-','Agender',inplace=True)
gender_count=data.Gender.value_counts()
gender_count.plot(kind='bar')
# ----------... | 1,457 | 618 |
"""StupiDB. The stupidest database you'll ever come across.
This is project designed to illustate the concepts that underly a typical
relational database implementation, starting at naive execution of table-stakes
features up to rule-based query optimization.
.. warning::
Please do not use this for any other reaso... | 14,205 | 4,168 |
aeki_config = {
"AEKI_HOST": "localhost", # rename to hostname for cgi if you like
"IOT_HOST":"localhost" # assumes iot test device is also on local host
}
| 169 | 60 |
import numpy as np
import math
import pickle
def get_data(data, frame_nos, dataset, topic, usernum, fps, milisec, width, height, view_width, view_height):
"""
Read and return the viewport data
"""
VIEW_PATH = '../../Viewport/'
view_info = pickle.load(open(VIEW_PATH + 'ds{}/viewport_ds{}_topic{}_user... | 6,540 | 3,116 |
"""
User picks number n and program returns all prime number from 0 until n.
"""
def is_prime(num):
for i in range(2, num):
if (num % i) == 0:
return False
return True
number_picked = int(raw_input("Pick a number: "))
print 2
for i in range(3, number_picked, 2):
if is_prime(i):
... | 333 | 121 |
"""
Django settings for gateway project.
Generated by 'django-admin startproject' using Django 1.11.1.
For more information on this file, see
https://docs.djangoproject.com/en/1.11/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.11/ref/settings/
"""
import os... | 9,331 | 3,439 |
"""
Given the array queries of positive integers between 1 and m, you have to process all queries[i] (from i=0 to i=queries.length-1) according to the following rules:
In the beginning, you have the permutation P=[1,2,3,...,m].
For the current i, find the position of queries[i] in the permutation P (indexing from 0) ... | 1,961 | 723 |
#!/usr/bin/env python
"""The setup script."""
from setuptools import setup, find_packages
with open('README.rst') as readme_file:
readme = readme_file.read()
with open('HISTORY.rst') as history_file:
history = history_file.read()
requirements = ['scikit-learn', 'pandas', 'scipy', 'numpy', 'category_encoder... | 1,876 | 670 |
from autofit.non_linear.samples.pdf import quantile
import autogalaxy as ag
import numpy as np
def test__quantile_1d_profile():
profile_1d_0 = np.array([1.0, 2.0, 3.0])
profile_1d_1 = np.array([1.0, 2.0, 3.0])
profile_1d_list = [profile_1d_0, profile_1d_1]
median_profile_1d = ag.util.er... | 1,982 | 961 |
import os
import pathlib
import sys
import googlemaps
from datetime import datetime as dt
from typing import Union, Tuple, List
class WhereShallWeMeet:
def __init__(self, configPath: str = None, friendsFile: str = None):
self.configPath = configPath
self._gmaps = None
self.friendsFile ... | 5,967 | 1,631 |
""".. Line to protect from pydocstyle D205, D400.
Plot distribution RNA-map
-------------------------
Plot distribution of crosslinks relative to landmark of specific type.
"""
import os
import pandas as pd
import iCount
# pylint: disable=wrong-import-order
import matplotlib
# Force matplotlib to not use any Xwind... | 4,451 | 1,453 |
#! /usr/bin/env python3
# -*- coding: utf-8 -*-
import sys
import time
try:
import frida
except ImportError:
sys.exit('install frida\nsudo pip3 install frida')
# number of times that 'old_value' was find in memory
matches = None
def err(msg):
sys.stderr.write(msg + '\n')
def read(msg): # read input from user
de... | 7,772 | 3,104 |
#
# Copyright (c) 2021 IBM Corp.
# 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 writi... | 17,435 | 4,961 |
def is_divisible(number):
divisible = [num for num in range(2, 11) if number % num == 0]
return True if divisible else False
start = int(input())
end = int(input())
print([int(_) for _ in range(start, end + 1) if is_divisible(_)])
| 243 | 91 |
from .bilibili import Bilibili
from .rss import Rss
from .weibo import Weibo
from .utils import check_sub_target
from .platform import PlatformNoTarget
from .utils import platform_manager
| 188 | 55 |
####### File will publish a score between 0-5 on how good an idea
# (0- Don't open, 5 - Very good conditions for opening window)
# it is to open the window to clear the room given the current internal and external weather conditions
# Factors considered - ________
# Internal temperature
# External Temperature (Effect ... | 13,837 | 4,321 |
"""
Tools for creating performance data for Nagios plugin responses.
If you're adding performance data to a :py:class:`~pynagios.response.Response`
object, then :py:func:`~pynagios.response.Response.set_perf_data` can be
called instead of having to create an entire :py:class:`PerfData` object.
"""
import re
from pynag... | 6,538 | 1,803 |
import heap
class _PriQ(object):
def insert(self, x):
self.heap.insert(x)
def delete(self):
return self.heap.delete()
def __nonzero__(self):
return bool(self.heap)
class Max(_PriQ):
def __init__(self):
self.heap = heap.Max()
class Min(_PriQ):
def __init__(self... | 354 | 131 |
from wsgiref import simple_server
import os
from oslo_config import cfg
from oslo_log import log as logging
from paste import deploy
import pecan
from report.api import hooks
from report.agent import rpcapi
LOG = logging.getLogger(__name__)
CONF = cfg.CONF
pecan_opts = [
cfg.StrOpt('root',
defaul... | 3,249 | 1,087 |
"""
The MIT License (MIT)
Copyright (c) Serenity Software, LLC
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, m... | 2,318 | 701 |
"""
This file requests a new model from the storage pool.
"""
import os
import urllib3
urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)
import requests
from requests.auth import HTTPBasicAuth
from src.praxxis.sqlite import sqlite_telemetry
def update_model():
"""TODO: implement this"""
... | 326 | 102 |
#!/usr/bin/env python
# encoding: utf-8
import os
import pathlib
import traceback
<<<<<<< HEAD
=======
import random
>>>>>>> Server/Server
import librosa
import numpy as np
import soundfile as sf
import torch
import torch.nn.utils.rnn as rnn_utils
from pydub import AudioSegment
from python_speech_features import fbank... | 40,516 | 13,773 |
""" Stockgrid View """
__docformat__ = "numpy"
import logging
from typing import List, Tuple
import pandas as pd
import requests
from gamestonk_terminal.decorators import log_start_end
logger = logging.getLogger(__name__)
@log_start_end(log=logger)
def get_dark_pool_short_positions(sort_field: str, ascending: boo... | 3,822 | 1,252 |
item: event({channel_index: indexed(uint256), reply_to_index: indexed(uint256), metadata: indexed(uint256)})
# item_index is the index of the sent item in C.N.
# TODO: Implement channeling
# Channel management
struct channel:
owner: address
name_display: bytes32
name_unique: bytes32 # TODO: finish impleme... | 2,918 | 973 |
# Copyright (C) 2018 Garth N. Wells
#
# SPDX-License-Identifier: MIT
"""This module contains a collection of functions related to
geographical data.
"""
from floodsystem.utils import sorted_by_key # noqa
import math
def hav(theta):
return math.sin(theta*0.5)**2
def r(theta):
return math.radian... | 2,414 | 820 |
"""""
Path to the Image Dataset directories
"""""
TR_IMG_DIR = './WORKSPACE/DATASET/annotation/'
GT_IMG_DIR = './WORKSPACE/DATASET/annotation/'
"""""
Path to Numpy Video directories
"""""
TR_VID_DIR = './WORKSPACE/DATA/TR_DATA/'
GT_VID_DIR = './WORKSPACE/DATA/GT_DATA/'
"""""
Path to Numpy batches directories
""""... | 852 | 351 |
"""
Quality Control Tools | Cannlytics
Author: Keegan Skeate <keegan@cannlytics.com>
Created: 2/6/2021
Updated: 6/23/2021
License: MIT License <https://opensource.org/licenses/MIT>
Perform various quality control checks and analyses to ensure
that your laboratory is operating as desired.
TODO:
- Trend an... | 1,152 | 346 |
from .library import LibraryValidator
from .runtime import RuntimeValidator
| 76 | 15 |
# This sample tests that the type analyzer flags as an error
# an attempt to assign to or delete a generic type.
from typing import Dict
# This should generate an error because assignment
# of generic types isn't allowed.
Dict[str, int] = {}
# This should generate an error because deletion
# of generic types isn't a... | 343 | 93 |
#!/usr/bin/python
import socket
import sys
import time
import struct
MCADDR = '239.255.223.01'
PORT = 0xDF0D
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
s.bind((MCADDR, PORT))
mreq = struct.pack("4sl", socket.inet_aton(MCADDR), socket.INADDR_ANY)
s.sets... | 770 | 357 |
"""
Breadth-First Search - Implemented using queues
This can be implemented for both Trees / Graphs
Here, we will use Trees as examples.
"""
from collections import deque
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.ri... | 925 | 281 |
#!/usr/bin/env python3
import sys
from setuptools import find_packages, setup
if sys.version_info < (3, 6):
sys.exit('Python 3.6 is the minimum required version')
description, long_description = (
open('README.rst', 'rt').read().split('\n\n', 1))
setup(
name='boot.py',
author='Mario César Señoranis ... | 1,065 | 352 |
from . import bulk, deploy, retrieve, tooling
__all__ = [
'bulk',
'deploy',
'retrieve',
'tooling',
'shared'
]
| 132 | 52 |
"""
The plots module defines functions used for creating decay chain diagrams via the Nuclide
class ``plot()`` method, and activity decay graphs via the Inventory class ``plot()`` method.
"""
from typing import List, Set, Optional, Tuple
import matplotlib
import matplotlib.pyplot as plt
import numpy as np
# pylint:... | 5,470 | 1,740 |
#All Django Imports
from django.core.exceptions import ValidationError
from django.db import models
from django.utils.translation import ugettext_lazy as _
from django.utils import timezone
#All local imports (libs, contribs, models)
from users.models import *
#All external imports (libs, packages)
import hashlib
i... | 8,006 | 2,562 |
import time
import random
from enum import Enum
from dataclasses import dataclass
from .gameobject import Action, GameObject, Player, Weapon
from .map import Cell, Map
class Direction(Enum):
LEFT = 1
RIGHT = 2
UP = 3
DOWN = 4
def to_action(self):
if self is self.UP:
return Act... | 9,436 | 2,671 |
from banco import con
from time import sleep
import os
# Validação de Valor Inteiro
def leiaint(valor):
while True:
try:
ent = int(input(valor))
except:
print('\033[1;33mDigite um valor inteiro\033[m')
else:
break
return ent
# Validação ... | 10,313 | 3,592 |
import unittest
from app import main
from wheezy.http.functional import WSGIClient
path_for = main.options["path_for"]
class HelloTestCase(unittest.TestCase):
def setUp(self):
self.client = WSGIClient(main)
def tearDown(self):
self.client = None
def path_for(self, name, **kwargs):
... | 519 | 172 |
import os
import os.path
import subprocess
import sys
if __name__ == "__main__":
dirname = sys.argv[1]
for x in os.listdir(dirname):
if x.endswith('.crt'):
try:
filename = os.path.join(dirname, x)
filehash = subprocess.check_output(['openssl', 'x509', '-noout... | 713 | 204 |
# Copyright 2022 AI Singapore
#
# 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
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing... | 2,525 | 844 |
__author__ = "Webber Huang"
__contact__ = "xracz.fx@gmail.com"
__website__ = "http://riggingtd.com"
import maya.cmds as cmds
import maya.OpenMaya as om
import maya.OpenMayaAnim as oma
from DLS.core import utils
class FnSkinCluster(object):
def __init__(self, skinCluster=None):
"""
Args:
... | 5,343 | 1,517 |
from .exporter import Dump1090Exporter
__version__ = "21.10.0"
| 64 | 30 |
import pandas as pd
from datetime import datetime
def sample_data1() -> pd.DataFrame:
times = [
datetime(year=2020, month=11, day=1),
datetime(year=2020, month=11, day=2),
datetime(year=2020, month=11, day=3),
datetime(year=2020, month=11, day=4),
datetime(year=2020, month=... | 1,697 | 804 |
# flake8: noqa
from chatrender.tasks.publish import publish_slackchat
| 70 | 24 |
# coding=utf-8
# Copyright 2018 The DisentanglementLib Authors. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Un... | 5,242 | 1,574 |
from django.db import models
from django.db.models import Model, TextField, DateTimeField, ForeignKey, CASCADE
from accounts.models import User
from rooms.models import Room
# Create your models here.
class MessageModel(Model):
"""
This class represents a chat message. It has a owner (user), timestamp and
... | 763 | 213 |
# Copyright © 2021 Ingram Micro Inc. All rights reserved.
from dj_cqrs.constants import SignalType
from dj_cqrs.controller.consumer import route_signal_to_replica_model
from dj_cqrs.mixins import ReplicaMixin
import pytest
def test_bad_model(caplog):
route_signal_to_replica_model(SignalType.SAVE, 'invalid', {}... | 1,088 | 424 |
"""Models and utilities for processing SMIRNOFF data."""
import abc
import copy
import functools
from collections import defaultdict
from typing import (
TYPE_CHECKING,
Any,
DefaultDict,
Dict,
List,
Tuple,
Type,
TypeVar,
Union,
)
import numpy as np
from openff.toolkit.topology impor... | 56,867 | 15,616 |
from tkinter import *
import math
import heapq
from sympy import Point, Polygon
# from shapely.geometry import Point, Polygon
'''================= Your classes and methods ================='''
ids = []
class PriorityQueue:
def __init__(self):
self.heap = []
self.count = 0
def push(self, item... | 15,926 | 5,620 |
from __future__ import print_function
import pylab as plt
import numpy as np
from django.http import HttpResponse, HttpResponseRedirect, HttpResponseBadRequest, QueryDict
from django.shortcuts import render_to_response, get_object_or_404, redirect, render
from django.template import Context, RequestContext, loader
fr... | 6,035 | 2,363 |
"""This module provides convenient use of EDITOR"""
import os
import subprocess
import tempfile
from libpycr.config import Config
def get_editor():
"""Return the user's editor, or vi if not defined
:rtype: str
"""
return os.environ.get('EDITOR') or os.environ.get('VISUAL') or 'vi'
def strip_comm... | 1,636 | 479 |