repo_name stringlengths 6 97 | path stringlengths 3 341 | text stringlengths 8 1.02M |
|---|---|---|
jack-florey/pong | app/games/__init__.py | <gh_stars>0
from app.games.views import games # noqa
|
jack-florey/pong | app/games/forms.py | <gh_stars>0
from flask_wtf import FlaskForm
from wtforms import ValidationError
from wtforms.ext.sqlalchemy.fields import QuerySelectField
from wtforms.fields import (
PasswordField,
StringField,
SubmitField,
FieldList,
FormField
)
from wtforms.fields.html5 import EmailField
from wtforms.validators ... |
jack-florey/pong | app/games/views.py | from flask import (
Blueprint,
abort,
flash,
redirect,
render_template,
request,
url_for,
)
from flask_login import current_user, login_required
from flask_rq import get_queue
import sys
from app import db
from app.games.forms import (
SetupGameForm,
)
from app.decorators import admin_... |
jack-florey/pong | app/models/game_models.py | <filename>app/models/game_models.py
from .. import db
from sqlalchemy import types
import json
from json import JSONEncoder
import jsonpickle
import random
import uuid
from functools import reduce
import datetime
class JsonType(types.TypeDecorator):
impl = types.Unicode
def process_bind_param(self, valu... |
jack-florey/pong | tests/test_game_state.py | import unittest
from app import create_app, db
from flask import current_app
from app.models import *
class GameStateTestCase(unittest.TestCase):
def setUp(self):
self.game = GameState()
self.clayton = self.game.add_player("Clayton")
self.ariel = self.game.add_player("Ariel")
self... |
jack-florey/pong | app/main/views.py | from flask import Blueprint, render_template
from flask_login import current_user
from app.models import EditableHTML, Game, Permission
main = Blueprint('main', __name__)
from flask_moment import Moment
@main.route('/')
def index():
games = Game.query.all()
can_create = current_user.can(Permission.GAME_ADM... |
jack-florey/pong | tests/test_game_model.py | import time
import unittest
from app import create_app, db
from app.models import *
from datetime import datetime
class GameModelTestCase(unittest.TestCase):
def setUp(self):
self.app = create_app('testing')
self.app_context = self.app.app_context()
self.app_context.push()
db.cre... |
jack-florey/pong | tests/test_serialization.py | <filename>tests/test_serialization.py<gh_stars>0
import unittest
from app import create_app, db
from flask import current_app
from app.models import *
import json
import jsonpickle
from json import JSONEncoder
class GameSerializationTestCase(unittest.TestCase):
def setUp(self):
self.game = GameState()
... |
GR-Tang/AI-0403-Team-3 | docker/deploy.py | <gh_stars>0
# importing necessary libraries
import uvicorn
from fastapi import FastAPI, File, UploadFile
from starlette.responses import RedirectResponse
from PIL import Image
from io import BytesIO
import numpy as np
import tensorflow as tf
from tensorflow.keras.applications.imagenet_utils import decode_predictions
f... |
GR-Tang/AI-0403-Team-3 | snippets/server.py | import uvicorn
from fastapi import FastAPI, File, UploadFile
from starlette.responses import RedirectResponse
from PIL import Image
from io import BytesIO
import numpy as np
import tensorflow as tf
from tensorflow.keras.applications.imagenet_utils import decode_predictions
app = FastAPI()
input_shape = (224, 224)
# ... |
GR-Tang/AI-0403-Team-3 | snippets/deploylocal.py | <reponame>GR-Tang/AI-0403-Team-3<gh_stars>0
import uvicorn
from fastapi import FastAPI, File, UploadFile
from starlette.responses import RedirectResponse
from PIL import Image
from io import BytesIO
import numpy as np
import tensorflow as tf
from tensorflow.keras.applications.imagenet_utils import decode_predictions
fr... |
raghavpatnecha/SmartMirror | pySHSpeex/setup.py | <reponame>raghavpatnecha/SmartMirror
##############################################################################
# Copyright 2015 SoundHound, Incorporated. All rights reserved.
##############################################################################
from distutils.core import setup, Extension
SPEEX_SRC_DIR =... |
raghavpatnecha/SmartMirror | houndify.py | <reponame>raghavpatnecha/SmartMirror
##############################################################################
# Copyright 2017 SoundHound, Incorporated. All rights reserved.
##############################################################################
import base64
import hashlib
import hmac
import httplib
impo... |
antipodos/slack-metabot | app.py | <reponame>antipodos/slack-metabot
from flask import Flask, request, abort, jsonify, render_template
from flask_bootstrap import Bootstrap
from slackbot import create_events_adapter, \
inform_about_new_channel, \
inform_about_random_channel, \
infor... |
antipodos/slack-metabot | slackbot.py | <filename>slackbot.py
import os
from slack import WebClient
import requests
from slackeventsapi import SlackEventAdapter
import random
token = os.environ["SLACK_API_TOKEN"]
signing_secret = os.environ["SLACK_SIGNING_SECRET"]
metachannel_id = os.environ["SLACK_METACHANNEL_ID"]
footer_message = "<https://metabot.object.... |
nimaema/Mask_RCNN | samples/fiber/fiber.py | if __name__ == '__main__':
import matplotlib
# Agg backend runs without a display
matplotlib.use('Agg')
import matplotlib.pyplot as plt
import os
import sys
import json
import datetime
import numpy as np
from numpy.lib.type_check import imag
from skimage import io
from imgaug import augmenters as iaa
f... |
pannoi/cdn-dns-controller | e2e/steps/list_hosted_zones_step_implementation.py | from behave import given, when, then, step
import requests
api_endpoints = {}
request_headers = {}
response_codes ={}
response_texts={}
request_bodies = {}
api_url=None
@given(u'I set api url to list zones "{endpoint}"')
def step_impl(context, endpoint):
global api_url
api_url = endpoint
@given(u'I set GE... |
pannoi/cdn-dns-controller | src/acm.py | <gh_stars>1-10
import boto3
import time
from src.environment import Environment
from src.route53 import Route53
class ACM():
""" Class to interact with AWS ACM to manage certificates. """
def __init__(self):
""" Class constructor. """
self.client = boto3.client(
'acm',
... |
pannoi/cdn-dns-controller | src/cloudfront.py | import boto3
from jinja2 import Environment as jEnv
from jinja2 import Template, FileSystemLoader
import time
from src.environment import Environment
from src.acm import ACM
from src.helpers import Helper
from src.route53 import Route53
class CloudFront():
""" Class describes CloudFront interface. """
def __... |
pannoi/cdn-dns-controller | tests/test_environment.py | <filename>tests/test_environment.py
import os
# mock .env
os.environ['AWS_ACCESS_KEY'] = "SUPER_SECRET_ID"
os.environ['AWS_SECRET_KEY'] = "SUPER_SECRET_KEY"
os.environ['AWS_REGION'] = "us-east-1"
os.environ['ROUTE53_DELEGATION_SET'] = "SOME_DELEGATION_SET"
os.environ['CDN_HOSTED_ZONE_ID'] = "CDN_HOSTED_ZONE_ID"
de... |
pannoi/cdn-dns-controller | src/environment.py | import os
from dataclasses import dataclass
@dataclass(frozen=True)
class Environment:
""" Class describes .env variables. """
aws_access_key: str = os.getenv('AWS_ACCESS_KEY')
aws_secret_key: str = os.getenv('AWS_SECRET_KEY')
aws_region: str = os.getenv('AWS_REGION')
route53_delegation_set: str =... |
pannoi/cdn-dns-controller | tests/test_jinja_templates.py | <filename>tests/test_jinja_templates.py
import jinja2
import pytest
def prerender(filename, context):
path = 'templates'
return jinja2.Environment(
loader=jinja2.FileSystemLoader(path)
).get_template(filename).render(context)
@pytest.mark.parametrize('comment, action, name, type, ttl, target', [... |
pannoi/cdn-dns-controller | src/route53.py | import boto3
from jinja2 import Environment as jEnv
from jinja2 import Template, FileSystemLoader
from src.environment import Environment
from src.helpers import Helper
class Route53():
""" Class describes Route53 interface. """
def __init__(self):
""" Class constructor. """
self.client = bot... |
pannoi/cdn-dns-controller | main.py | <reponame>pannoi/cdn-dns-controller
from flask import Flask, jsonify
from flask import make_response
from flask import request
import logging
from src.route53 import Route53
from src.cloudfront import CloudFront
app = Flask(__name__)
# Route53 routes
@app.route('/zones/', methods=['GET'])
def list_host... |
japinol7/api_examples | api_01_ex/app/tests/test_app.py | <filename>api_01_ex/app/tests/test_app.py
import json
import pytest
from app.app import animes, ANIME_NOT_FOUND_MSG_ERROR
ANIMES_MAX_ID_BEFORE_TESTS = 63
ANIME_NOT_EXISTING_ID = 111111
def test_list_anime_ids_response(app_client_get_root):
response = app_client_get_root
assert response.status_code == 200
... |
japinol7/api_examples | api_01_ex/app/app.py | <filename>api_01_ex/app/app.py
import json
import logging
import os
from apistar import App, Route, types, validators
from apistar.http import JSONResponse
logging.basicConfig(format='%(asctime)s %(levelname)s %(name)s: %(message)s')
logger = logging.getLogger(__name__)
logger.setLevel(logging.DEBUG)
ANIME_TITLE_WA... |
japinol7/api_examples | api_01_ex/app/tests/conftest.py | """Define some fixtures to use in the project."""
import pytest
import json
from apistar import test
from app.app import app, animes
client = test.TestClient(app)
@pytest.fixture(scope='session')
def client_test():
return client
@pytest.fixture(scope='session')
def animes_count_before_tests():
return len... |
carolmb/political | distance.py | import xnet
import glob
import math
import matplotlib
import concurrent.futures
import numpy as np
import matplotlib.pyplot as plt
from igraph import *
from collections import defaultdict
from util import get_valid_pp
from util import filter_pp_name
def calculate_dist(filenames):
for filename in filenames:
# pri... |
carolmb/political | data_metrics.py | import xnet
import glob
import numpy as np
import matplotlib.pyplot as plt
from igraph import *
from util import get_valid_pp
from util import filter_pp_name
from collections import defaultdict
from sklearn.metrics import normalized_mutual_info_score
np.set_printoptions(suppress=True,formatter={'float_kind':'{:f}'.f... |
carolmb/political | json_to_json.py | <reponame>carolmb/political
import json
import zipfile
import unidecode
input_file_zip = "data/deputadosData_1991-2019.zip"
input_file = "data/deputadosData_1991-2019.json"
output_file = "data/deputadosv2.json"
with zipfile.ZipFile(input_file_zip, 'r') as zip_ref:
zip_ref.extractall('data/')
file = open(input_fi... |
carolmb/political | deputies_parser.py | <filename>deputies_parser.py<gh_stars>1-10
import os
import ast
import xnet
import json
import pickle
import zipfile
import concurrent.futures
import numpy as np
import cairocffi as cairo
import matplotlib.pyplot as plt
from igraph import Graph
from collections import defaultdict, namedtuple
Deputy = namedtuple('De... |
carolmb/political | communities.py | <gh_stars>1-10
import glob
import xnet
import igraph
import leidenalg # pip install leidenalg
import subprocess
def get_largest_component(g):
components = g.components()
giant = components.giant()
return giant
def identify_communities_leidenalg(net):
giant = get_largest_component(net)
comms = leidenalg.find_p... |
carolmb/political | backbone.py | import glob
import xnet
import numpy as np
from igraph import *
from mpmath import mp # pip install mpmath
from scipy import integrate
mp.dps = 50
# source: https://github.com/aekpalakorn/python-backbone-network/blob/master/backbone.py
def disparity_filter(g):
total_vtx = g.vcount()
g.es['alpha_ij'] = 1
for v in... |
carolmb/political | util.py | <reponame>carolmb/political<gh_stars>1-10
import numpy as np
def filter_pp_name(p):
if p == 'pds' or p == 'pdc' or p == 'ppb' or p == 'ppr' or p == 'psd':
p = 'pp'
elif p == 'pfl':
p = 'dem'
elif p == 'mdb':
p = 'pmdb'
elif p == 'pr':
p = 'pl'
# elif p == 'prb' or p == 'pmr':
# p = 'republicanos'
retur... |
jakereps/q2-vsearch | q2_vsearch/_transformer.py | <filename>q2_vsearch/_transformer.py
# ----------------------------------------------------------------------------
# Copyright (c) 2016-2021, QIIME 2 development team.
#
# Distributed under the terms of the Modified BSD License.
#
# The full license is in the file LICENSE, distributed with this software.
# -----------... |
jakereps/q2-vsearch | q2_vsearch/_join_pairs.py | <reponame>jakereps/q2-vsearch<filename>q2_vsearch/_join_pairs.py
# ----------------------------------------------------------------------------
# Copyright (c) 2016-2021, QIIME 2 development team.
#
# Distributed under the terms of the Modified BSD License.
#
# The full license is in the file LICENSE, distributed with ... |
jakereps/q2-vsearch | q2_vsearch/_chimera.py | # ----------------------------------------------------------------------------
# Copyright (c) 2016-2021, QIIME 2 development team.
#
# Distributed under the terms of the Modified BSD License.
#
# The full license is in the file LICENSE, distributed with this software.
# ------------------------------------------------... |
jakereps/q2-vsearch | q2_vsearch/_stats.py | # ----------------------------------------------------------------------------
# Copyright (c) 2016-2021, QIIME 2 development team.
#
# Distributed under the terms of the Modified BSD License.
#
# The full license is in the file LICENSE, distributed with this software.
# ------------------------------------------------... |
jakereps/q2-vsearch | q2_vsearch/tests/test_cluster_sequences.py | # ----------------------------------------------------------------------------
# Copyright (c) 2016-2021, QIIME 2 development team.
#
# Distributed under the terms of the Modified BSD License.
#
# The full license is in the file LICENSE, distributed with this software.
# ------------------------------------------------... |
jakereps/q2-vsearch | q2_vsearch/tests/test_stats.py | <reponame>jakereps/q2-vsearch<filename>q2_vsearch/tests/test_stats.py<gh_stars>1-10
# ----------------------------------------------------------------------------
# Copyright (c) 2016-2021, QIIME 2 development team.
#
# Distributed under the terms of the Modified BSD License.
#
# The full license is in the file LICENSE... |
jakereps/q2-vsearch | q2_vsearch/plugin_setup.py | # ----------------------------------------------------------------------------
# Copyright (c) 2016-2021, QIIME 2 development team.
#
# Distributed under the terms of the Modified BSD License.
#
# The full license is in the file LICENSE, distributed with this software.
# ------------------------------------------------... |
jakereps/q2-vsearch | q2_vsearch/_cluster_features.py | # ----------------------------------------------------------------------------
# Copyright (c) 2016-2021, QIIME 2 development team.
#
# Distributed under the terms of the Modified BSD License.
#
# The full license is in the file LICENSE, distributed with this software.
# ------------------------------------------------... |
jakereps/q2-vsearch | q2_vsearch/tests/test_plugin_setup.py | # ----------------------------------------------------------------------------
# Copyright (c) 2016-2021, QIIME 2 development team.
#
# Distributed under the terms of the Modified BSD License.
#
# The full license is in the file LICENSE, distributed with this software.
# ------------------------------------------------... |
Neelakurinji123/kindle-weather-display-for-openwrt | openwrt/opt/kindle-weather-station/createSVGv2.py | <gh_stars>0
#!/usr/bin/env python3
# encoding=utf-8
# -*- coding: utf-8 -*-
# Written by : <EMAIL>
# Date : 16 February 2022
#
# This script was modified from:
# Author : <NAME> - http://www.iero.org
# Public domain source code
# Published March 2015
# Update October 2016
# This code creates an SVG image, rea... |
Neelakurinji123/kindle-weather-display-for-openwrt | openwrt/opt/kindle-weather-station/IconExtras.py | <gh_stars>0
#!/usr/bin/env python3
#
# Weather icons by <NAME> from the Noun Project
#
#def getDrizzle():
# # 45%, x=0px, y=-5px
# return '''<path d="" />'''
#
#def getThunderstorm():
# # 45%, x=0px, y=-5px
# return '''<path d="" />'''
#
#def getSleet():
# # 45%, x=0px, y=-5px
# return '''<path d="" />'... |
Neelakurinji123/kindle-weather-display-for-openwrt | openwrt/opt/kindle-weather-station/test/json_checker.py | <gh_stars>0
#!/usr/bin/env python3
# encoding=utf-8
# -*- coding: utf-8 -*-
import json
import sys
file = sys.argv[1] if len(sys.argv) >= 3 else None
if len(sys.argv) < 3:
print("usage:", sys.argv[0], "jsonfile", "key1", "[key2]", "[ key3]")
exit(0)
elif len(sys.argv) == 3:
key1 = sys.argv[2]
elif len(sys... |
RobSpectre/Caesar-Cipher | caesarcipher/cmdline.py | <filename>caesarcipher/cmdline.py
import logging
import argparse
from caesarcipher import CaesarCipher
from caesarcipher import CaesarCipherError
# Parser configuration
parser = argparse.ArgumentParser(description="Caesar Cipher - encode, decode "
"or crack messages with a... |
RobSpectre/Caesar-Cipher | caesarcipher/__init__.py | <reponame>RobSpectre/Caesar-Cipher<filename>caesarcipher/__init__.py<gh_stars>10-100
try:
from caesarcipher.caesarcipher import CaesarCipher
from caesarcipher.caesarcipher import CaesarCipherError
except ImportError:
from caesarcipher import CaesarCipher
from caesarcipher import CaesarCipherError
__tit... |
RobSpectre/Caesar-Cipher | caesarcipher/caesarcipher.py | <reponame>RobSpectre/Caesar-Cipher
from random import randrange
import string
import math
import logging
class CaesarCipher(object):
def __init__(self, message=None, encode=False, decode=False, offset=False,
crack=None, verbose=None, alphabet=None):
"""
A class that encodes, decod... |
RobSpectre/Caesar-Cipher | tests/test_caesarcipher.py | <gh_stars>10-100
import unittest
from caesarcipher import CaesarCipher
from caesarcipher import CaesarCipherError
class CaesarCipherEncodeTest(unittest.TestCase):
def test_encode_with_known_offset(self):
message = "Twilio"
test_cipher = CaesarCipher(message, encode=True, offset=1)
self.as... |
RobSpectre/Caesar-Cipher | setup.py | <reponame>RobSpectre/Caesar-Cipher
from caesarcipher import __version__
scripts = ['bin/caesarcipher']
setup_args = {
'name': 'caesarcipher',
'version': __version__,
'url': 'https://github.com/RobSpectre/Caesar-Cipher',
'description': 'A Python package and command line script for encoding, '
... |
mepesh/eqapp_rev_2 | eqapp_rev_2.py | <reponame>mepesh/eqapp_rev_2
from flask import Flask, redirect, render_template
from datetime import datetime
import csv,random
app = Flask(__name__)
#creating csv file
with open('templates/eqdata.csv','wb') as fwrite:
writer = csv.writer(fwrite)
for i in range(1,10):
writer.writerow((i,date... |
agtbaskara/apriltag-node-stream | camera_calibration.py | <reponame>agtbaskara/apriltag-node-stream<filename>camera_calibration.py
import cv2
import numpy as np
import os
import glob
# Defining the dimensions of checkerboard
CHECKERBOARD = (6,9)
criteria = (cv2.TERM_CRITERIA_EPS + cv2.TERM_CRITERIA_MAX_ITER, 30, 0.001)
# Creating vector to store vectors of 3D point... |
agtbaskara/apriltag-node-stream | aprlitag_test.py | import cv2
import glob
from pupil_apriltags import Detector
fx = 472.13107208
fy = 472.3044311
cx = 322.23325564
cy = 238.25801953
tag_size = 0.07
camera_params = ([fx, fy, cx, cy])
at_detector = Detector(families='tag36h11',
nthreads=1,
quad_decimate=1.0,
... |
agtbaskara/apriltag-node-stream | program_server.py | <reponame>agtbaskara/apriltag-node-stream<filename>program_server.py<gh_stars>0
# run this program on the Mac to display image streams from multiple RPis
import cv2
import imagezmq
from pupil_apriltags import Detector
fx = 472.13107208
fy = 472.3044311
cx = 322.23325564
cy = 238.25801953
tag_size = 0.055
camera_param... |
agtbaskara/apriltag-node-stream | program_node.py | <filename>program_node.py
# run this program on each RPi to send a labelled image stream
import socket
import time
from imutils.video import VideoStream
import imagezmq
import cv2
server_address = "tcp://127.0.0.1:5555"
sender = imagezmq.ImageSender(connect_to=server_address)
node_name = socket.gethostname(... |
dhimmel/schema | tools/rnc-validate-format.py | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
import os
import subprocess
import argparse
from shutil import which
from glob import glob
# to validate and pretty print the rnc schema files before commit:
# tools/rnc-validate-format.py
parser = argparse.ArgumentParser(description="process csl schema files")
parser.ad... |
msimonin/test_oslo_messaging | bar_chart.py | <filename>bar_chart.py
import numpy as np
import matplotlib
matplotlib.use('tkagg')
matplotlib.rcParams.update({'font.size': 20})
import matplotlib.pyplot as plt
# data to plot
latency = ['0.3ms', '10ms', '50ms']
# create plot
def draw(rpc_call, rpc_cast, latency, filename):
fig, ax = plt.subplots()
index = n... |
bhilkanchan/Twitter-Bots | allbots.py | import tweepy
import time
import os
from datetime import date
from dotenv import load_dotenv
load_dotenv()
API_KEY = os.environ["API_KEY"]
API_KEY_SECRET = os.environ["API_KEY_SECRET"]
ACCESS_TOKEN = os.environ["ACCESS_TOKEN"]
ACCESS_TOKEN_SECRET = os.environ["ACCESS_TOKEN_SECRET"]
auth = tweepy.OAuthHand... |
diana-gv/django-social-network | social_network/__init__.py | # coding=utf-8
import logging
from django.contrib.auth import get_user_model
from django.contrib.sites.models import Site
from django.utils.translation import ugettext_lazy as _
from social_graph import Graph
from .signals import (
follower_relationship_created,
follower_relationship_destroyed,
friendship_c... |
diana-gv/django-social-network | social_network/views.py | <gh_stars>1-10
import json
import logging
from django.contrib.sites.models import Site
from django.http import HttpResponse
from django.http.response import HttpResponseBadRequest
from django.utils.encoding import force_text
from django.utils.translation import ugettext_lazy as _
from django.views.generic import Create... |
diana-gv/django-social-network | social_network/utils.py | # coding=utf-8
import random
from django.core.cache import cache
from django.core.exceptions import ObjectDoesNotExist
from django.utils.translation import ugettext as _
from notifications.models import EventType
from social_graph import EdgeType
try:
from hashlib import sha1 as sha_constructor, md5 as md5_constru... |
diana-gv/django-social-network | social_network/migrations/0005_auto__add_field_friendrequest_denied.py | # -*- coding: utf-8 -*-
from south.utils import datetime_utils as datetime
from south.db import db
from south.v2 import SchemaMigration
from django.db import models
class Migration(SchemaMigration):
def forwards(self, orm):
# Adding field 'FriendRequest.denied'
db.add_column(u'social_network_frie... |
diana-gv/django-social-network | social_network/management/__init__.py | # coding=utf-8
from django.db.models.signals import post_syncdb
from django.conf import settings
from .. import models as social_app
AUTOCONFIGURE_NOTIFICATIONS = getattr(settings, 'SOCIAL_NETWORK_AUTOCONFIGURE_NOTIFICATIONS', True)
COMMENT_ACTION_READ_AS = getattr(settings, 'SOCIAL_NETWORK_COMMENT_ACTION_READ_AS', 'C... |
diana-gv/django-social-network | social_network/management/commands/clearcache.py | <gh_stars>1-10
# coding=utf-8
from django.core.management.base import NoArgsCommand
class Command(NoArgsCommand):
def handle_noargs(self, **options):
from social_graph.api import Graph
graph = Graph()
graph.clear_cache() |
diana-gv/django-social-network | social_network/transports.py | # coding=utf-8
from notifications.transports import BaseTransport
from .models import GroupFeedItem, SocialGroup
class GroupFeedTransport(BaseTransport):
@staticmethod
def send_notification(group, role, event, template, delay=False):
if group is None or not isinstance(group, SocialGroup) or event is ... |
diana-gv/django-social-network | social_network/admin.py | # coding=utf-8
from django.contrib import admin
from .models import SocialGroup
class SocialGroupAdmin(admin.ModelAdmin):
readonly_fields = ['name']
def has_add_permission(self, request):
return False
def has_delete_permission(self, request, obj=None):
return False
admin.site.register(S... |
diana-gv/django-social-network | social_network/forms.py | # coding=utf-8
from django import forms
from django.core.exceptions import ValidationError
from . import Manager
from models import (
FriendRequest,
SocialGroup,
GroupComment,
GroupMembershipRequest,
GroupImage,
FeedComment,
GroupSharedLink)
class FriendRequestForm(forms.ModelForm):
... |
diana-gv/django-social-network | social_network/signals.py | <reponame>diana-gv/django-social-network<filename>social_network/signals.py
# coding=utf-8
from django.dispatch import Signal
friend_request_created = Signal(providing_args=['instance', 'user', 'receiver'])
friendship_created = Signal(providing_args=['friend', 'user'])
social_group_created = Signal(providing_args=['in... |
diana-gv/django-social-network | social_network/management/commands/configuresocialnetwork.py | <filename>social_network/management/commands/configuresocialnetwork.py
# coding=utf-8
from django.core.management.base import NoArgsCommand
class Command(NoArgsCommand):
def handle_noargs(self, **options):
from ...management import configure_notifications, create_edge_types
configure_notifications... |
diana-gv/django-social-network | setup.py | <gh_stars>1-10
from setuptools import setup, find_packages
setup(
name="django-social-network",
url="http://github.com/dgvicente/django-social-network/",
author="<NAME>",
author_email="<EMAIL>",
version="0.2.4",
packages=find_packages(),
include_package_data=True,
zip_safe=False,
de... |
diana-gv/django-social-network | social_network/templatetags/social_network_tags.py | # coding=utf-8
from django import template
from django.contrib.auth.models import User
from django.utils.translation import ugettext as _
from ..models import FriendRequest, SocialGroup, GroupMembershipRequest
register = template.Library()
#--------------------------------------FOLLOWER TAGS--------------------------... |
diana-gv/django-social-network | social_network/models.py | #coding: utf-8
from django.contrib.auth import get_user_model
from django.contrib.sites.managers import CurrentSiteManager
from django.contrib.sites.models import Site
from django.conf import settings
from django.db import models
from django.db.models.signals import post_save, m2m_changed
from django.db.models import p... |
diana-gv/django-social-network | social_network/urls.py | <reponame>diana-gv/django-social-network
# coding=utf-8
from django.conf.urls import patterns, url
from django.contrib.auth.decorators import login_required
import views
urlpatterns = patterns(
'',
url(
r'^group/all/$',
views.SocialGroupListView.as_view(),
name='social_groups'
),
... |
rolfengelhard/iq-success-metrics2 | releasefiles/reports2/create-components-quarantined.py | import json
import requests
import os
import os.path
import sys
iqurl = sys.argv[1]
iquser = sys.argv[2]
iqpwd = sys.argv[3]
jsonfile = 'componentsinquarantine.json'
csvfile = 'componentsinquarantine.csv'
def get_metrics():
req = requests.get('{}/api/v2/reports/components/quarantined'.format(iqurl), auth=(iquser, ... |
rolfengelhard/iq-success-metrics2 | releasefiles/reports2/create-policy-violations-data.py | import json
import requests
import os
import os.path
import sys
iqurl = sys.argv[1]
iquser = sys.argv[2]
iqpwd = sys.argv[3]
jsonfile = 'policyviolations.json'
csvfile = 'policyviolations.csv'
def getNexusIqData(api):
url = "{}{}" . format(iqurl, api)
req = requests.get(url, auth=(iquser, iqpwd), verify=False)
... |
rolfengelhard/iq-success-metrics2 | releasefiles/reports2/create-waiver-data.py | <filename>releasefiles/reports2/create-waiver-data.py<gh_stars>0
import json
import requests
import os
import os.path
import sys
iqurl = sys.argv[1]
iquser = sys.argv[2]
iqpwd = sys.argv[3]
jsonfile = 'componentwaivers.json'
csvfile = 'componentwaivers.csv'
def get_metrics():
req = requests.get('{}/api/v2/reports/c... |
rolfengelhard/iq-success-metrics2 | releasefiles/reports2/create-application-evaluations-data.py | <gh_stars>1-10
import json
import requests
import os
import os.path
import sys
iqurl = sys.argv[1]
iquser = sys.argv[2]
iqpwd = sys.argv[3]
jsonfile = 'applicationevaluations.json'
csvfile = 'applicationevaluations.csv'
def get_metrics():
req = requests.get('{}/api/v2/reports/applications'.format(iqurl), auth=(iqus... |
junkainiu/codewars | leo/python/lv4/sum_of_factors.py | <reponame>junkainiu/codewars<filename>leo/python/lv4/sum_of_factors.py
def sum_for_list(lst):
result = []
an = []
for index,elem in enumerate(lst):
i = 2
while abs(elem) > 1:
while elem%i == 0:
elem = elem/i
if not [i,index] in result:
... |
junkainiu/codewars | leo/python/lv4/explosiv_sum.py | def exp_sum(n,n):
if n == 1:
return 1
if start > n:
return exp_sum(n,n)
sum = 0
for i in xrange(1,start):
sum += exp_sum(n-i, i)
print sum
return sum
exp_sum(3,1)
|
junkainiu/codewars | leo/python/lv3/chemstry.py | import re
from collections import defaultdict
atom_pattern = re.compile(r'[A-Z]')
sub_atom_pattern = re.compile(r'[a-z]')
num_pattern = re.compile(r'\d')
br_start_pattern = re.compile(r'\[|\{|\(')
br_end_pattern = re.compile(r'\]|\}|\)')
def get_num(formula, i):
r = re.match(r'\d+', formula[i:])
len = r.span(... |
junkainiu/codewars | leo/python/lv4/sum_of_money.py | def count_change(money, coins):
# your implementation here
coins.sort()
result = 0
cache = [coins[0]]
for i,coin in enumerate(coins):
while sum(cache) < money:
if sum(cache) == money:
result += 1
cache.append(coin)
|
junkainiu/codewars | leo/python/lv3/fib.py | def mul(a, b):
r = [[0, 0], [0, 0]]
r[0][0] = a[0][0] * b[0][0] + a[0][1] * b[1][0];
r[0][1] = a[0][0] * b[0][1] + a[0][1] * b[1][1];
r[1][0] = a[1][0] * b[0][0] + a[1][1] * b[1][0];
r[1][1] = a[1][0] * b[0][1] + a[1][1] * b[1][1];
return r;
def _fib(n):
if n == 0:
return [[1, 0], [0, 1]]
if n == 1... |
svcvit/Live-data-generator | src/ws/app.py | <reponame>svcvit/Live-data-generator
"""
ws tool for excel and pdf
"""
import toga
from toga.style import Pack
from toga.style.pack import COLUMN, ROW
import datetime
import time
import pandas as pd
from .tool import tools
def get_localtime():
now = datetime.datetime.now()
# offset = datetime.timedelta(hours=... |
svcvit/Live-data-generator | src/ws/tool.py | import pandas as pd
from faker import Faker
import random
import os
import numpy as np
import datetime
import arrow
class tools():
def __init__(self,path):
self.path = str(path)
def get_province(self):
ip_data = pd.read_feather(self.path+'/ip_data.feather')
return list(ip_data['provi... |
adrian7123/django-gerenciador-de-funcionarios | myproject/urls.py | <reponame>adrian7123/django-gerenciador-de-funcionarios
"""my_blog URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/3.0/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to url... |
adrian7123/django-gerenciador-de-funcionarios | my_app/admin.py | <filename>my_app/admin.py
from django.contrib import admin
from my_app.models import Funcionarios
# Register your models here.
admin.site.register(Funcionarios) |
adrian7123/django-gerenciador-de-funcionarios | my_app/views.py | from django.shortcuts import render, redirect
from .models import Funcionarios
# Create your views here.
def home(req):
return render(req, 'views/home.html')
def funcionarios(req):
func = Funcionarios.objects.all()
context = {
'req': req,
'func': func
}
return render... |
adrian7123/django-gerenciador-de-funcionarios | my_app/models.py | from django.db import models
# Create your models here.
class Funcionarios(models.Model):
nome = models.CharField(max_length=30)
sobrenome = models.CharField(max_length=30)
cargo = models.CharField(max_length=30)
empresa = models.CharField(max_length=30)
def __str__(self):
return self.... |
pplewka/zwo | src/db.py | <filename>src/db.py
import sqlite3
from parser import Document
from typing import Sequence, Callable, TypeVar
DB_NAME = "nyt.sqlite"
STATEMENT_CACHE = 100000
STATS_FUNCS = dict()
DBConnection = sqlite3.Connection
T = TypeVar('T')
def chunks(seq: Sequence[T], n: int = 1000) -> Sequence[Sequence[T]]:
# we batch 10... |
pplewka/zwo | src/parser.py | <filename>src/parser.py
import re
import xml.etree.ElementTree as XML
from collections import Counter
from dataclasses import dataclass
from typing import Sequence, Union, Iterable, Tuple, List
from pathlib import Path
import constants
@dataclass
class Document:
"""Definition of a document"""
id: int
titl... |
pplewka/zwo | src/query_processing.py | import sqlite3
import heapq
from datetime import datetime
from math import log
from typing import List
from dataclasses import dataclass, field
from constants import ADDITIVE_CONSTANT_DATE_BOOST, TUNABLE_WEIGHT_DATE, TUNABLE_WEIGHT_PAGE
from db import get_max_page
from parser import Parser
from posting_list import Inv... |
pplewka/zwo | src/posting_list.py | <filename>src/posting_list.py
import sqlite3
import heapq
from dataclasses import dataclass, field
from typing import List
DBConnection = sqlite3.Connection
@dataclass(order=True, frozen=True)
class Posting:
"""Definition of a single posting"""
did: int
tf: int = field(compare=False)
page: int = fiel... |
pplewka/zwo | src/constants.py | <gh_stars>1-10
TUNABLE_WEIGHT_TITLE = 3
TUNABLE_WEIGHT_CONTENT = 1
TUNABLE_WEIGHT_ABSTRACT = 2
TUNABLE_WEIGHT_DATE = 0.7
TUNABLE_WEIGHT_PAGE = 0.9
ADDITIVE_CONSTANT_DATE_BOOST = .5
|
pplewka/zwo | src/__main__.py | import os
import time
from posting_list import InvertedIndex, create_indices
from query_processing import QueryProcessor
from importer import Importer
from db import *
def parse_dir(directory: str) -> None:
"""Takes a directory path and parses all Documents inside this path, writing the results to a file."""
d... |
pplewka/zwo | src/importer.py | import os
from pathlib import Path
from typing import List
from parser import Parser, Document
class Importer:
"""Importer class used for finding all xml files in a given directory"""
@staticmethod
def import_dir(path: str) -> List[Document]:
"""
Searches for all xml files in a directory ... |
Gerrystev/efficientnet-simple-baseline | pose_estimation/output/mpii/pose_efficient_50/256x256_d256x3_adam_lr1e-3/pose_efficient.py | <reponame>Gerrystev/efficientnet-simple-baseline<filename>pose_estimation/output/mpii/pose_efficient_50/256x256_d256x3_adam_lr1e-3/pose_efficient.py<gh_stars>0
# ------------------------------------------------------------------------------
# Copyright (c) Microsoft
# Licensed under the MIT License.
# Written by <NAME>... |
Gerrystev/efficientnet-simple-baseline | pose_estimation/detect.py | <reponame>Gerrystev/efficientnet-simple-baseline
# ------------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License.
# Written by <NAME> (<EMAIL>)
# ----------------------------------------------------------------... |
davincif/Amila-RTS | world_map/wmap.py | import pygame
from world_map.camp import Camp
from fuzy_prob.prob import Prob
from fuzy_prob import prob
class Wmap():
preprint = None
__map_x_size = 10
__map_y_size = 10
__is_generated = False
__matrix = [] #world mape matriz
def __init__(self):
pass
def init(self):
print(self.preprint + 'wmap from wor... |
davincif/Amila-RTS | world_map/bioma_types.py | <reponame>davincif/Amila-RTS
from enum import Enum
class BiomaType():
HOT_DISERT = 1
COLD_DISERT = 2
HILLY = 3
PLAINS = 4
FLOREST = 5
SWAMPY = 6
ARID = 7
TUNDRA = 8
PRAIRIE = 9
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.