repo_name
stringlengths
6
97
path
stringlengths
3
341
text
stringlengths
8
1.02M
alehenaff/textfielfdtemplate
templatefield/filters.py
from templatefield.models import Substitution def simplesubstitution(value,substitution): if Substitution.objects.filter(name=substitution, key=value).exists(): r = Substitution.objects.get(name=substitution, key=value) return r.value
alehenaff/textfielfdtemplate
templatefield/models.py
from django.db import models from django.template import Template, Context from django.template.base import VariableNode import jinja2 from jinja2 import Environment, meta import json # Create your models here. class TextFieldTemplate(models.Model): template = models.TextField() context = models.TextField() #J...
alehenaff/textfielfdtemplate
templatefield/tests.py
from django.test import TestCase from templatefield.models import TextFieldTemplate, Substitution from templatefield.filters import simplesubstitution # Create your tests here. class TextFieldTemplateTest(TestCase): def setUp(self): TextFieldTemplate.objects.create(template='Bonjour {{client.name}}, {{clie...
TangLeeee/test
common.py
from flask import Flask,jsonify app = Flask(__name__) response_index = { 'status' : 0, 'messages' : [ {'id':1, 'img':'https://uploadbeta.com/api/pictures/random/'}, {'id':2, 'img':'https://uploadbeta.com/api/pictures/random/?key=BingEverydayWallpaperPicture'}, {'id':3, 'img':'http://acg...
icanswim/cosmosis
model.py
<gh_stars>0 from abc import ABC, abstractmethod from math import sqrt from torch import nn, cat, squeeze, softmax, Tensor, flatten, sigmoid, max, mean from torch.nn import functional as F import torchvision.models as torchvisionmodels def tv_model(model_name='resnet18', tv_params={}, in_channels=3): launcher ...
icanswim/cosmosis
dataset.py
from abc import ABC, abstractmethod import os, re, random, h5py, pickle import pandas as pd from pandas.api.types import CategoricalDtype import numpy as np from torch.utils.data import Dataset, ConcatDataset from torch import as_tensor, squeeze from torchvision import datasets as tvds from sklearn import datasets ...
icanswim/cosmosis
learning.py
<gh_stars>0 from datetime import datetime import logging import random import os os.environ['NUMEXPR_MAX_THREADS'] = '16' import pandas as pd import numpy as np import matplotlib.pyplot as plt from torch import no_grad, save, load, from_numpy, as_tensor, squeeze from torch.utils.data import Sampler, DataLoader from ...
full-stakk/flask-rest
app.py
"""simple flask rest api.""" from flask import Flask, g, jsonify from flask import render_template from auth import auth import models import config from resources.users import users_api from resources.articles import articles_api app = Flask(__name__) app.register_blueprint(users_api, url_prefix='/api/v1') app.regis...
full-stakk/flask-rest
resources/users.py
"""This module handles calls to the database based on URIs it recieves.""" from flask.ext.restful import (Resource, Api, fields, marshal, marshal_with, reqparse, abort) from flask import jsonify, Blueprint, make_response, g from auth import auth import models import json # Response def...
full-stakk/flask-rest
config.py
<filename>config.py """Configurations for the app.""" DEBUG = True HOST = '0.0.0.0' PORT = 8000 SECRET = '<KEY>'
full-stakk/flask-rest
auth.py
from flask import g from flask.ext.httpauth import HTTPBasicAuth, HTTPTokenAuth, MultiAuth import models basic_auth = HTTPBasicAuth() token_auth = HTTPTokenAuth(scheme='Token') auth = MultiAuth(token_auth, basic_auth) @basic_auth.verify_password def verify_password(email, password): try: user = models.U...
full-stakk/flask-rest
models.py
"""Database models.""" import datetime import bcrypt import config from peewee import * from itsdangerous import (TimedJSONWebSignatureSerializer as Serializer, BadSignature, SignatureExpired) DATABASE = SqliteDatabase('app.db') class BaseModel(Model): """Specifies database connection."...
full-stakk/flask-rest
resources/articles.py
"""This module handles calls to the database based on URIs it recieves.""" from flask.ext.restful import (Resource, Api, fields, marshal_with, marshal, reqparse, abort) from flask import jsonify, Blueprint, make_response, g from auth import auth import json import models import datetime ...
mcarey-solstice/mock-security
src/cli.py
<reponame>mcarey-solstice/mock-security<gh_stars>1-10 #!/usr/bin/env python3 import sys import argparse from keychain import create_keychain, delete_keychain, default_keychain, set_keychain_settings, unlock_keychain, lock_keychain, import_certificate parser = argparse.ArgumentParser(description='Mock security') subpa...
mcarey-solstice/mock-security
src/keychain.py
<reponame>mcarey-solstice/mock-security ### # ## import os import sys import json from helpers import classproperty def _get_keychain_file(): return os.environ.get('KEYCHAIN_FILE', './keychains.json') # _get_keychain_file class Keychain(object): __keychains__ = {} def __init__(self, name, **kwargs): ...
mcarey-solstice/mock-security
src/__init__.py
### # ## from keychain import Keychain, create_keychain, delete_keychain, default_keychain, set_keychain_settings, unlock_keychain, lock_keychain, import_certificate from cli import parser #
Soostone/cassy
test/Test.py
from pycassa.types import * from pycassa.system_manager import * from pycassa.pool import ConnectionPool from pycassa.columnfamily import ColumnFamily def create_ks(): # create test keyspace sys = SystemManager() comparator = CompositeType(LongType(), BytesType()) sys.create_column_family("testing", "...
ethframe/descent
examples/calc.py
<reponame>ethframe/descent from descent.case import CaseUnapply from descent.helpers import parser_from_source CALC_GRAMMAR = r""" t<S> <- S~ _ t<S, T> <- t<S> T etail<O, E> <- O^left E:right lexpr<E, O> <- E etail<O, E>* rexpr<E, O> <- E etail<O, this>? unary<E, O> <- O this:expr / E paren...
ethframe/descent
descent/fixpoint.py
from descent.case import CaseUnapply1 class CaseFix(CaseUnapply1): def __init__(self, fix, **kwargs): super().__init__(**kwargs) self.fix = fix def reference(self, val, *args): return self.fix.get(val, *args) class State: def __init__(self, keys, bot): self.bot = bot ...
ethframe/descent
descent/case.py
<gh_stars>1-10 class Case: def __init__(self, **kwargs): for k, v in kwargs.items(): setattr(self, k, v) def __call__(self, val, *args): method = getattr(self, type(val).__name__.lower()) return method(val, *args) class CaseUnapply1(Case): def __call__(self, val, *args...
ethframe/descent
examples/jsonparser.py
from descent.case import CaseUnapply1 from descent.helpers import parser_from_source JSON_GRAMMAR = r""" t<S> <- S~ _ t<S, T> <- t<S> T list<I> <- (I:items (t<","> I:items)*)? collection<T, O, I, C> <- t<O, T> list<I> t<C> oneopt<A, B> <- A B? / B json <- _ value !. value <- string / numbe...
ethframe/descent
descent/typeinference.py
<reponame>ethframe/descent from collections import OrderedDict from descent.asttypes import ( InvalidType, UnknownType, EmptyType, StringType, NamedType, TokenType, NodeType, merge_types ) from descent.fixpoint import CaseFix, fix class TypeInference(CaseFix): def sequence(self, val, ctype): for ...
ethframe/descent
tests/test_grammar_check.py
<filename>tests/test_grammar_check.py import py.test from descent.parser import parse_grammar from descent.macro import expand_macros from descent.grammarcheck import check_grammar WF_NULL = (True, True, False) WF_NOT_NULL = (True, False, False) WF_NOT_NULL_INV = (True, False, True) NOT_WF_NULL = (False, True, False)...
ethframe/descent
descent/codegen.py
import sys from descent.asttypes import NamedType, TokenType, NodeType def _indent(lines): for line in lines: if isinstance(line, list): for indented in _indent(line): yield " " + indented if indented else "" else: yield line def _concat(lines): re...
ethframe/descent
tests/test_type_inference.py
<gh_stars>1-10 from collections import OrderedDict as od import py.test from descent.parser import parse_grammar from descent.macro import expand_macros from descent.typeinference import infer_types from descent.asttypes import NamedType, TokenType, NodeType, Field type_cases = [ ("A <- 'a'", set()), ("A <-...
ethframe/descent
generate.py
<filename>generate.py from descent.parser import parse_grammar from descent.source import source, converters from descent.macro import expand_macros from descent.typeinference import infer_types from descent.codegen import ( gen_python_class, gen_ast_module, gen_ast_module_src ) from descent.combinators import comp...
ethframe/descent
tests/test_grammar_parser.py
import py.test from descent.parser import parse_grammar from descent.ast import * def single_rule_grammar(name, body): return grammar([rule(name=reference(name), expr=body)]) parse_cases = [ ("A <- 'a'", single_rule_grammar("A", string("a"))), ("A <- \"a\"", single_rule_grammar("A", string("a"))), ...
ethframe/descent
descent/parser.py
from descent.ast import types_map from descent.combinators import compile_parser from descent.grammar import grammar from descent.source import converters parser = compile_parser(grammar, types_map, converters) parse_grammar = parser.parse
ethframe/descent
descent/combinators.py
<gh_stars>1-10 from descent.case import CaseUnapply1 class Tree: def copy(self): return self class Empty(Tree): pass class Ignore(Tree): def consume(self, val): return self class Rule: def __init__(self, name): self.name = name self.body = None def define(sel...
ethframe/descent
descent/ast.py
class char: def __init__(self, val=''): self.val = val def __str__(self): return self.val def __repr__(self): return 'char({!r})'.format(self.val) def __hash__(self): return hash((self.__class__, self.val)) def __eq__(self, other): return self.__class__ is...
ethframe/descent
descent/grammarcheck.py
from collections import namedtuple from descent.fixpoint import CaseFix, fix, result_by_args state = namedtuple("State", "wf nul inv") class GrammarCheck(CaseFix): def string(self, val): return state(True, not val, False) def char(self, val): return state(True, False, False) def char_...
ethframe/descent
descent/source.py
source = r""" Args<Item> <- MOPEN (Item:args (COMMA Item:args)*)? MCLOSE LeftOp<Arg, Between, Type> <- Arg (Type^items (Between Arg:items)+)? LeftOp<Arg, Type> <- Arg (Type^items Arg:items+)? Grammar <- @grammar Spacing Definition:rules+ EndOfFile Definition <- @rule Identifier:name (@macro^^ Args<...
ethframe/descent
descent/macro.py
<reponame>ethframe/descent from collections import OrderedDict from descent.case import Case class Macroexpander(Case): def grammar(self, val, env): rules = OrderedDict() for rule in val.rules: res = self(rule, env) if res: rules[str(res.name)] = res.expr ...
ethframe/descent
descent/helpers.py
<reponame>ethframe/descent from descent.codegen import gen_ast_module from descent.combinators import compile_parser from descent.grammarcheck import check_grammar, get_invalid from descent.parser import parse_grammar from descent.macro import expand_macros from descent.typeinference import infer_types def parser_fro...
ethframe/descent
examples/dynamic.py
<gh_stars>1-10 from itertools import product from descent.case import CaseUnapply from descent.helpers import parser_from_source DYNAMIC_GRAMMAR = r""" Start<B> <- _ B !. Tok<S> <- S~ _ Tok<S, T> <- Tok<S> T KW<S> <- S~ !ident _ Op<S> <- @Op S _ LExpr<E, O, R> <- E ((@BinOp O:op)^left R:right...
ethframe/descent
descent/asttypes.py
<reponame>ethframe/descent from collections import namedtuple, OrderedDict class Type: def __iter__(self): yield self class ScalarType(Type): def __eq__(self, other): return self.__class__ is other.__class__ def __hash__(self): return hash(self.__class__) def merge(self, ot...
ethframe/descent
make_parser.py
from argparse import ArgumentParser from descent.parser import parse_grammar from descent.grammarcheck import check_grammar, get_invalid from descent.typeinference import infer_types from descent.codegen import gen_ast_module_src from descent.macro import expand_macros def generate(input): parsed = parse_grammar...
RasmusBC59/Qcodes
qcodes/data/data_array.py
<filename>qcodes/data/data_array.py<gh_stars>0 from typing import Dict, Any, Optional import numpy as np import collections from qcodes.utils.helpers import DelegateAttributes, full_class, warn_units import xarray as xr class DataArray(DelegateAttributes): """ A container for one parameter in a measurement...
RasmusBC59/Qcodes
qcodes/tests/dataset/test__get_data_from_ds.py
import pytest import numpy as np from numpy.testing import assert_allclose import hypothesis.strategies as hst from hypothesis import HealthCheck, given, settings import qcodes as qc from qcodes.dataset.data_export import get_data_by_id, _get_data_from_ds from qcodes.dataset.descriptions.param_spec import ParamSpecBas...
RasmusBC59/Qcodes
qcodes/dataset/subscriber.py
<filename>qcodes/dataset/subscriber.py import functools import logging import time from threading import Thread from typing import Any, Callable, List, Mapping, Optional, TYPE_CHECKING from queue import Empty, Queue from qcodes.dataset.sqlite.connection import atomic_transaction if TYPE_CHECKING: from qcodes.dat...
RasmusBC59/Qcodes
qcodes/dataset/json_exporter.py
<reponame>RasmusBC59/Qcodes from typing import Any, Dict json_template_linear = {"type": 'linear', 'x': {'data': [], 'name': "", 'full_name': '', 'is_setpoint':True, 'unit':''}, 'y': {'data': [], 'name': "", 'full_name': '', 'is_setpoint':False, 'unit':''}} json_template_...
RasmusBC59/Qcodes
qcodes/instrument_drivers/Keysight/keysight_34934a.py
<reponame>RasmusBC59/Qcodes import logging import re from qcodes import VisaInstrument, InstrumentChannel, validators from typing import Union, List, Tuple, Optional, Callable from .keysight_34980a_submodules import KeysightSwitchMatrixSubModule class Keysight34934A(KeysightSwitchMatrixSubModule): """ Create ...
crablab/bme280_logging
server.py
<gh_stars>0 import requests, json import time from influxdb import InfluxDBClient from datetime import datetime client = InfluxDBClient('192.168.1.67', 8086, '', '', 'weather') while (1): r = requests.get("http://192.168.1.91") data = r.json() print(json.dumps(data)) temp = [ { "m...
pvnieo/Learn-Noughts-and-Crosses
train.py
# stdlib import random import argparse import pickle from collections import defaultdict from itertools import cycle # 3p import numpy as np class TicTacToeTraining: def __init__(self, args): # RL params self.Q = defaultdict(lambda: [0 for _ in range(9)]) # Q function self.R = {"1": 1, "2...
pvnieo/Learn-Noughts-and-Crosses
play_tic_tac_toe.py
<filename>play_tic_tac_toe.py # stdlib import random import time import pickle import argparse from argparse import RawTextHelpFormatter from collections import defaultdict from itertools import cycle # 3p import pygame import numpy as np class Board: def __init__(self, w=900): self.w = w self.c =...
leakyH/mia
examples/protect_code/cifar10_lager_shadow.py
""" Example membership inference attack against a deep net classifier on the CIFAR10 dataset """ import numpy as np from absl import app from absl import flags import tensorflow as tf from tensorflow.keras import layers from sklearn.model_selection import train_test_split from mia.estimators import ShadowModelBundl...
leakyH/mia
examples/code/target model/CNN_capsule.py
""" Example membership inference attack against a deep net classifier on the CIFAR10 dataset """ import numpy as np from absl import app from absl import flags import tensorflow as tf from tensorflow.keras import layers from sklearn.model_selection import train_test_split from mia.estimators import ShadowModelBundl...
leocll/CLLRepo
CLLRepo/Git/git_upgrade.py
#!/usr/bin/env python3 # -*- coding: utf-8 -*- __author__ = 'leocll' import os, sys, json from functools import reduce def log_git(info): # print(info) pass # for p in sys.argv: # print('外带参数:%s' % p) def basepath(): return '/Users/leocll/SVN项目/hftapp' def filelist4path(path, fn=lambda x:x.find('....
yuasabe/iot_api
api/api.py
import flask from flask import ( Blueprint, flash, g, redirect, render_template, request, session, url_for, jsonify ) from api.db import get_db bp = Blueprint('api', __name__, url_prefix='/api') # app = flask.Flask(__name__) # app.config["DEBUG"] = True # db.init_app(app) @bp.route('/', methods=['GET']) def home(...
Schnitzel/lagoon-kickstart
make-secrets.py
<reponame>Schnitzel/lagoon-kickstart #!/usr/bin/env import random, string, json def pw(N): return ''.join(random.SystemRandom().choice(string.ascii_lowercase + string.ascii_uppercase + string.digits) for _ in range(N)) secret = { "Version": "v1", "stringData": { "JENKINS_URL": "https://to.be.determi...
BeatrizFS/MongoDB-Python
READ.py
from Arquivo1 import Produto #READ #Consultar o Banco de dados #1.Retorna todas as informações do Banco de dados produtos = Produto.objects() print(produtos) for produto in produtos: print(produto.Nome, produto.Valor)
BeatrizFS/MongoDB-Python
DELETE.py
#DELETE from mongoengine.errors import DoesNotExist from Arquivo1 import Produto try: produto = Produto.objects(Nome="Tilápia").get() produto.delete() print("Produto deletado") except DoesNotExist: print("Produto não encontrado")
BeatrizFS/MongoDB-Python
UPDATE.py
#Atualiza algum atributo de determinado produto. from mongoengine.errors import DoesNotExist from Arquivo1 import Produto try: produto = Produto.objects(Nome="Arroz") produto.update(Valor=6.0) print("Produto atualizado!") except DoesNotExist: print("Produto não encontrado")
BeatrizFS/MongoDB-Python
Arquivo1.py
from mongoengine.connection import connect from mongoengine.document import Document from mongoengine.fields import BooleanField, EmailField, FloatField,IntField, ReferenceField, StringField from mongoengine import * # Instituto Federal de Pernambuco - Campus Paulista # Disciplina: Banco de Dados 2 # Professor: <...
condensedWeasel/covid-electricity-demand
setup.py
<reponame>condensedWeasel/covid-electricity-demand #! /usr/bin/env python # # Copyright 2020 <NAME> <<EMAIL>> def get_version(): version_re = re.compile("""__version__[\s]*=[\s]*['|"](.*)['|"]""") init_file = os.path.join( os.path.dirname(__file__), DISTNAME, "__init__.py" ) with open(init_file) as file: ...
TristanSalles/pybeach
setup.py
""" Creating PIPY package instruction: python3 -m pip install --user --upgrade setuptools wheel python3 setup.py sdist python3 -m pip install --user --upgrade twine twine check dist/* twine upload dist/* """ from setuptools import setup, find_packages from numpy.distutils.core import setup, Extension from os import p...
TristanSalles/pybeach
tests/test_pybeach.py
# -*- coding: utf-8 -*- """ This is the unittest for pybeach. """ import numpy as np from sklearn.ensemble.forest import RandomForestClassifier from pytest import approx, raises, fixture from pybeach.beach import Profile from pybeach.support import classifier_support as cs @fixture() def models(): x = np.arange(...
harveywwu/OpenData
opendatatools/common/ui_util.py
# -*- coding: UTF-8 -*- import sys, time class ShowProcess(): """ 显示处理进度的类 调用该类相关函数即可实现处理进度的显示 """ i = 0 # 当前的处理进度 max_steps = 0 # 总共需要处理的次数 max_arrow = 50 #进度条的长度 infoDone = 'done' # 初始化函数,需要知道总共的处理次数 def __init__(self, max_steps, infoDone = 'Done'): self.max_steps = ...
harveywwu/OpenData
opendatatools/usstock/usstock_interface.py
<gh_stars>0 # encoding: utf-8 from .usstock_agent import USStockAgent usstock_agent = USStockAgent() def set_proxies(proxies): return usstock_agent.set_proxies(proxies) def get_symbols(): return usstock_agent.get_symbols() def get_daily(symbol, start_date = None, end_date = None): return usstock_agent....
harveywwu/OpenData
opendatatools/aemo/aemo_interface.py
<filename>opendatatools/aemo/aemo_interface.py # encoding: utf-8 from .aemo_agent import AEMOAgent import pandas as pd import datetime aemo_agent = AEMOAgent() def monthlist(start_date, end_date): total_months = lambda dt: dt.month + 12 * dt.year mlist = [] for tot_m in xrange(total_months(start_date)-1, ...
harveywwu/OpenData
opendatatools/aemo/aemo_agent.py
# encoding: utf-8 from opendatatools.common import RestAgent import io import pandas as pd import datetime class AEMOAgent(RestAgent): def __init__(self): RestAgent.__init__(self) def get_curr_price_demand(self, region): url = "http://www.nemweb.com.au/mms.GRAPHS/GRAPHS/GRAPH_30{region}1.csv"....
harveywwu/OpenData
opendatatools/spot/spot_agent.py
# encoding: utf-8 import requests from PIL import Image import pytesseract import io import pandas as pd from bs4 import BeautifulSoup from datetime import datetime from opendatatools.common import RestAgent dict_commodity_spot_indicator = { '65': '钢材指数', '61': '铁矿指数', '64': '焦炭指数', '1002': '煤炭指数', ...
harveywwu/OpenData
opendatatools/spot/spot_interface.py
<reponame>harveywwu/OpenData<gh_stars>0 # encoding: utf-8 import datetime from .spot_agent import SpotAgent spot_agent = SpotAgent() def get_commodity_spot_indicator(): return spot_agent.get_commodity_spot_indicator() def get_commodity_spot_indicator_data(indicator_id, start_date = None, end_date = None): if...
harveywwu/OpenData
opendatatools/futures/futures_agent.py
# encoding: utf-8 from opendatatools.common import RestAgent, split_date, date_convert, remove_chinese import pandas as pd import json import copy import zipfile import io import re from xml.etree import ElementTree SHF_name_map = {"CJ1": "volume", "CJ1_CHG": "volume_chg", "PARTI...
harveywwu/OpenData
opendatatools/aemo/__init__.py
# encoding: UTF-8 from .aemo_interface import * __all__ = ['get_curr_price_demand', 'get_hist_price_demand']
OdyX/synapse
synapse/config/tls.py
# -*- coding: utf-8 -*- # Copyright 2014-2016 OpenMarket Ltd # # 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 applicab...
OdyX/synapse
synapse/app/frontend_proxy.py
<filename>synapse/app/frontend_proxy.py #!/usr/bin/env python # -*- coding: utf-8 -*- # Copyright 2016 OpenMarket Ltd # # 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...
3ating3L3phants/google_translate
lang_basic.py
#!/usr/bin/python # To authenticate, to Google you will need to # download your json keyfile from your account. # Once done, run the following command in a terminal: # export GOOGLE_APPLICATION_CREDENTIALS="/path/to/keyfile.json" # # Alternatively, set the export in your ~/.bashrc or ~/.profile ######################...
glintcore/pyglint
test/runtests.py
<reponame>glintcore/pyglint import sys import os package_root_path = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) sys.path.insert(0, package_root_path) import unittest from pyglint import glint import argparse import uuid #Tests class GlintTest(unittest.TestCase): def setUp(self): self....
glintcore/pyglint
pyglint/glint.py
<reponame>glintcore/pyglint import csv import requests from requests.auth import HTTPBasicAuth class GlintError(Exception): pass class GlintConnection: def __init__(self, host, username, password): self.host = host self.username = username self.password = password def add_file_str...
tubbeg/WSGI_server
run_server.py
<reponame>tubbeg/WSGI_server<filename>run_server.py import sys from server import Server from urllib.request import urlopen import json def make_server(server_address, application): server = Server(server_address, 2000) server.set_app(application) return server def main(): module = __import__("flaskap...
tubbeg/WSGI_server
server.py
<gh_stars>0 import datetime import io import os import gevent from gevent import socket from gevent.pool import Pool import sys """ # WSGI_server A WSGI server implemented with python and gevent. ###About Do not use this server in production. Security is pretty much nonexistent. Also see the Todo list before actually...
cmutnik/world_map
HI_photo_map/make_HI_photo_map.py
#!/usr/bin/python # <NAME> 200706 # Python script to turn all images in designated dir to thumbnails and plot them on a world map # varibales in the main() need to be modified accordingly from PIL import Image import pandas as pd import folium import os ''' TODO make sure all images in list exist in both photos and t...
cmutnik/world_map
other_modifications/imagerotations/01_rotateimages.py
<gh_stars>0 from PIL import ExifTags, Image filename = './path/to/inimg.JPG' output_fname = './outpath/to/outimg.JPG' img = Image.open(filename) #print(img._getexif().items()) exif=dict((ExifTags.TAGS[k], v) for k, v in img._getexif().items() if k in ExifTags.TAGS) # check image orientation print(exif['Orientation'...
cmutnik/world_map
other_modifications/imagerotations/00_rotateimages.py
<filename>other_modifications/imagerotations/00_rotateimages.py<gh_stars>0 from PIL import Image, ExifTags # open image image = Image.open('./path/to/image.jpg') # use try to only apply code to images with exif data try: # get orientation value from exif data image_exif = image._getexif() image_orientatio...
cmutnik/world_map
other_modifications/geotag_EXIF/exif_from_photo.py
<reponame>cmutnik/world_map<filename>other_modifications/geotag_EXIF/exif_from_photo.py # https://developer.here.com/blog/getting-started-with-geocoding-exif-image-metadata-in-python3 #image_name = './photos/dad/IMG_0195.JPG' image_name='photo_map/photos/dad/IMG_0195.JPG' from PIL import Image def get_exif(filename)...
cmutnik/world_map
other_modifications/geotag_EXIF/pull_all_exif.py
from PIL import ExifTags, Image # set input image location filename = './path/to/inimg.JPG' # open image img = Image.open(filename) #print(img._getexif().items()) # pull all the exif data exif=dict((ExifTags.TAGS[k], v) for k, v in img._getexif().items() if k in ExifTags.TAGS) # print all exif data associated with ...
cmutnik/world_map
simple_map/makeSimpleHTMLmap.py
import folium img1Path='./photos/IMG_0195.JPG' img1coords=[42.3730, -73.3677] m = folium.Map(img1coords, zoom_start=10) #test = folium.Html('<b>Hello world</b>', script=True) test = folium.Html('<img src='+img1Path+' alt="Italian Trulli">', script=True) # add pin folium.Marker(img1coords).add_to(m) # add popup pop...
cmutnik/world_map
Multi_image_sources/make_Multi_image_sources.py
#!/usr/bin/python # <NAME> 200706 # Python script to turn all images in designated dir to thumbnails and plot them on a world map # varibales in the main() need to be modified accordingly from PIL import Image import pandas as pd import folium import os ''' TODO make sure all images in list exist in both photos and t...
hanss314/higumei-scriptextraction
extract_outfits.py
""" Given a higumei script, extracts all the lines containing text which is shown to the player. Useful for translation. Also prefixes each line with the command index, for integrating the translated text back into the commands. Outputs in the following format <command index>: <Speaker> <Line 1> <Line 2> ... Each com...
hanss314/higumei-scriptextraction
extract_lines.py
<reponame>hanss314/higumei-scriptextraction<gh_stars>0 """ Given a higumei script, extracts all the lines containing text which is shown to the player. Useful for translation. Also prefixes each line with the command index, for integrating the translated text back into the commands. Outputs in the following format <co...
hanss314/higumei-scriptextraction
base_processor.py
import json import sys from inspect import getcallargs class BaseScriptProcessor: """ General handler functions. Override these in your subclass. Parameter names ---------- raw: Raw command, as a dictionary cmd: name of command, either cmd0 or cmd1 in the raw command motion: some type of...
Maxz44/euler
euler.py
#!/usr/bin/env python3 # --- Euler pb 1 # Multiples of 3 and 5 # If we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6 and 9. # The sum of these multiples is 23. # Find the sum of all the multiples of 3 or 5 below 1000. def euler1(n): return sum([x for x in range(1, n) if x % ...
amoodie/StratGAN
StratGAN/utils.py
import numpy as np import os, sys import matplotlib.pyplot as plt import matplotlib.gridspec as gridspec import string import random import json class Config: """ dummy config class for storing info during generation of GAN/painter """ pass def sample_Z(m, n): return np.random.uniform(-1., 1., s...
amoodie/StratGAN
StratGAN/paint.py
<reponame>amoodie/StratGAN import matplotlib.pyplot as plt import matplotlib.patches as patches import sys import numpy as np from random import randint import tensorflow as tf import os import abc """ A fair number of the algorithm's in this module are taken from: https://github.com/afrozalm/Patch-Based-Texture-Synt...
amoodie/StratGAN
StratGAN/context_painter.py
import matplotlib.pyplot as plt import matplotlib.patches as patches import sys import numpy as np from random import randint import tensorflow as tf import os class ContextPainter(object): def __init__(self, stratgan, paint_label=None, paint_width=1000, paint_height=None, paint...
amoodie/StratGAN
StratGAN/model.py
<reponame>amoodie/StratGAN import tensorflow as tf import numpy as np import matplotlib.pyplot as plt import time import os, sys import loader import ops import utils import paint import groundtruth as gt # import context_painter from datagen import StratHeteroProvider # from pympler.tracker import SummaryTracker, su...
amoodie/StratGAN
post_analysis/mean_map.py
<reponame>amoodie/StratGAN import numpy as np import matplotlib.pyplot as plt import os import glob import cv2 as cv import shutil def make_overlay(canvas): gt_idx = np.isfinite(canvas) channel_idx = canvas == 0.0 canvas_overlay = np.zeros((canvas.shape[0], canvas.shape[1], 4)) canvas_overlay[np.logic...
amoodie/StratGAN
StratGAN/datagen.py
import numpy as np import matplotlib.pyplot as plt import matplotlib.gridspec as gridspec import matplotlib.cm as cm import cv2 import tensorflow as tf class StratHeteroProvider(object): def __init__(self, batch_size=64): self.data_generator = StratHeteroGenerator(n_categories=None) self.data =...
amoodie/StratGAN
process_images/make_demo_fig.py
import matplotlib.pyplot as plt import matplotlib.gridspec as gridspec import os from PIL import Image import numpy as np filelist = [file for file in os.listdir('cut_images_demo') if file.endswith('.png')] filelist.sort() gd = (6, 3) # grid image dimensions fig = plt.figure(figsize=(gd[1], gd[0])) gs = gridspec.Gr...
amoodie/StratGAN
StratGAN/loader.py
""" image serving classes for model """ import glob import numpy as np from PIL import Image import os import utils import tensorflow as tf class BaseImageProvider(object): """ This class provides a basis for generating a tf.data.Dataset and Iterator. It takes some hints the UNet implementation in tf. ...
amoodie/StratGAN
process_images/nsplit_process.py
<filename>process_images/nsplit_process.py from scipy import misc, ndimage import matplotlib.pyplot as plt from skimage import exposure import numpy as np import os def rgb2gray(rgb): conv = [0.2125, 0.7154, 0.0721] # ratios to convolve with return np.dot(rgb[...,:3], conv) # path of directory and list of ra...
amoodie/StratGAN
process_images/nrand_process.py
<reponame>amoodie/StratGAN from scipy import misc, ndimage import matplotlib.pyplot as plt import matplotlib.gridspec as gridspec # from skimage import exposure import numpy as np import os np.random.seed(seed=21548) plt.rcParams['savefig.transparent'] = True def rgb2gray(rgb): conv = [0.2125, 0.7154, 0.0721] # r...
amoodie/StratGAN
StratGAN/groundtruth.py
<reponame>amoodie/StratGAN import matplotlib.pyplot as plt import matplotlib.patches as patches import sys import numpy as np from random import randint import tensorflow as tf import os import abc class GroundTruth(object): """ Base class for adding ground truth to the core object """ def __init__(...
amoodie/StratGAN
StratGAN/ops.py
import tensorflow as tf def xavier_init(size): in_dim = size[0] xavier_stddev = 1. / tf.sqrt(in_dim / 2.) return tf.random_normal(shape=size, stddev=xavier_stddev) def scewl(logits, labels): """ just a straight wrapper for shorter text. wraps: tf.nn.sigmoid_cross_entropy_with_logits() "...
amoodie/StratGAN
StratGAN/main.py
import tensorflow as tf import numpy as np import matplotlib.pyplot as plt import matplotlib.gridspec as gridspec import os from utils import Config, mkdirs, rand_id from model import StratGAN """ ### MINIREADME ### options for directories: ['multi_line','multi_line_bw','shapes_all','shapes_all_mini','shapes_star'...
JeffMacaluso/mlcookbook
mlcookbook/eda.py
<filename>mlcookbook/eda.py import numpy as np import pandas as pd # TODO: Consider adding predict missing values, #### Outliers # TODO: Add function to dynamically determine categorical columns # Check ideas from here https://datascience.stackexchange.com/questions/9892/how-can-i-dynamically-distinguish-between-cate...
JeffMacaluso/mlcookbook
mlcookbook/ml.py
import numpy as np import pandas as pd # Random Search def hyperparameter_random_search(X, y, model=None, parameters=None, num_folds=5, num_iterations=50): ''' Performs a random search on hyperparameters and TODO: Finish docstring - Add cross validation method - Add status bar ''' ...
JeffMacaluso/mlcookbook
mlcookbook/process.py
<reponame>JeffMacaluso/mlcookbook<filename>mlcookbook/process.py import numpy as np import pandas as pd # Principal Component Analysis (PCA) def fit_PCA(X, num_components=0.99): ''' Performs min-max normalization and PCA transformation on the input data array Inputs: - X: An array of values to...
JeffMacaluso/mlcookbook
mlcookbook/__init__.py
import mlcookbook.eda import mlcookbook.ml import mlcookbook.misc import mlcookbook.nlp import mlcookbook.plot import mlcookbook.process def diagnostics(): ''' Reports the current date/time, package versions, and machine hardware TODO: Make this work dynamically with imported libraries ''' imp...