blob_id stringlengths 40 40 | directory_id stringlengths 40 40 | path stringlengths 3 288 | content_id stringlengths 40 40 | detected_licenses listlengths 0 112 | license_type stringclasses 2 values | repo_name stringlengths 5 115 | snapshot_id stringlengths 40 40 | revision_id stringlengths 40 40 | branch_name stringclasses 684 values | visit_date timestamp[us]date 2015-08-06 10:31:46 2023-09-06 10:44:38 | revision_date timestamp[us]date 1970-01-01 02:38:32 2037-05-03 13:00:00 | committer_date timestamp[us]date 1970-01-01 02:38:32 2023-09-06 01:08:06 | github_id int64 4.92k 681M ⌀ | star_events_count int64 0 209k | fork_events_count int64 0 110k | gha_license_id stringclasses 22 values | gha_event_created_at timestamp[us]date 2012-06-04 01:52:49 2023-09-14 21:59:50 ⌀ | gha_created_at timestamp[us]date 2008-05-22 07:58:19 2023-08-21 12:35:19 ⌀ | gha_language stringclasses 147 values | src_encoding stringclasses 25 values | language stringclasses 1 value | is_vendor bool 2 classes | is_generated bool 2 classes | length_bytes int64 128 12.7k | extension stringclasses 142 values | content stringlengths 128 8.19k | authors listlengths 1 1 | author_id stringlengths 1 132 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
98cfe74c39eaab9a20964b5ba9dd22e3e4ede5a4 | 91d1a6968b90d9d461e9a2ece12b465486e3ccc2 | /workmail_write_2/organization_delete.py | 6780aa72ae6f9c251cf32b3f0cb708c6b7c074ff | [] | no_license | lxtxl/aws_cli | c31fc994c9a4296d6bac851e680d5adbf7e93481 | aaf35df1b7509abf5601d3f09ff1fece482facda | refs/heads/master | 2023-02-06T09:00:33.088379 | 2020-12-27T13:38:45 | 2020-12-27T13:38:45 | 318,686,394 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,263 | py | #!/usr/bin/python
# -*- codding: utf-8 -*-
import os
import sys
sys.path.append(os.path.dirname(os.path.abspath(os.path.dirname(__file__))))
from common.execute_command import write_two_parameter
# url : https://awscli.amazonaws.com/v2/documentation/api/latest/reference/workmail/delete-organization.html
if __name__ == '__main__':
"""
create-organization : https://awscli.amazonaws.com/v2/documentation/api/latest/reference/workmail/create-organization.html
describe-organization : https://awscli.amazonaws.com/v2/documentation/api/latest/reference/workmail/describe-organization.html
list-organizations : https://awscli.amazonaws.com/v2/documentation/api/latest/reference/workmail/list-organizations.html
"""
parameter_display_string = """
# organization-id : The organization ID.
# delete-directory | --no-delete-directory : If true, deletes the AWS Directory Service directory associated with the organization.
"""
add_option_dict = {}
add_option_dict["parameter_display_string"] = parameter_display_string
# ex: add_option_dict["no_value_parameter_list"] = "--single-parameter"
write_two_parameter("workmail", "delete-organization", "organization-id", "delete-directory | --no-delete-directory", add_option_dict)
| [
"hcseo77@gmail.com"
] | hcseo77@gmail.com |
ccd41b50340ff40a19e60d5e20e3b3ea9833977d | b2e93927aad0ddf373b1078dc1adfdaf0a3157a7 | /corr_test_terms.py | 70fdd49cd00b6ee488b4751ed908c9586320636d | [] | no_license | TaiSakuma/metrecoat | 30dc084458cf48f8c63f7c6c8ec47ec50cdd6b73 | f62b269a5cb5f066a7cc1a748f999ebe36d6bd41 | refs/heads/master | 2016-09-02T00:07:00.514760 | 2013-12-16T22:03:45 | 2013-12-16T22:03:45 | 12,684,650 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 5,141 | py | #!/usr/bin/env python
# Tai Sakuma <sakuma@fnal.gov>
import ROOT
import sys
import math
import json
import re
import unittest
from optparse import OptionParser
ROOT.gROOT.SetBatch(1)
##____________________________________________________________________________||
parser = OptionParser()
parser.add_option('-e', '--expectedPath', default = './corr_terms_expected.root', action = 'store', type = 'string')
parser.add_option('-a', '--actualPath', default = './corr_terms_actual.root', action = 'store', type = 'string')
(options, args) = parser.parse_args(sys.argv)
##____________________________________________________________________________||
class METProducerTest(unittest.TestCase):
def setUp(self):
self.exEvents = Events([options.expectedPath])
self.acEvents = Events([options.actualPath])
self.exHandleCorrMETData = Handle("CorrMETData")
self.acHandleCorrMETData = Handle("CorrMETData")
def test_n_events(self):
self.assertEqual(self.exEvents.size(), self.acEvents.size())
def test_corrCaloMetType2(self):
label = ("corrCaloMetType2", "", "CORR")
self.assert_CorrMETData(label)
def test_corrPfMetShiftXY(self):
label = ("corrPfMetShiftXY", "", "CORR")
self.assert_CorrMETData(label)
def test_corrPfMetType0RecoTrack(self):
label = ("corrPfMetType0RecoTrack", "", "CORR")
self.assert_CorrMETData(label)
def test_corrPfMetType0RecoTrackForType2(self):
label = ("corrPfMetType0RecoTrackForType2", "", "CORR")
self.assert_CorrMETData(label)
def test_corrPfMetType2(self):
label = ("corrPfMetType2", "", "CORR")
self.assert_CorrMETData(label)
def test_corrPfMetType1_offset(self):
label = ("corrPfMetType1", "offset", "CORR")
self.assert_CorrMETData(label)
def test_corrPfMetType1_type1(self):
label = ("corrPfMetType1", "type1", "CORR")
self.assert_CorrMETData(label)
def test_corrPfMetType1_type2(self):
label = ("corrPfMetType1", "type2", "CORR")
self.assert_CorrMETData(label)
def test_pfCandMETcorr(self):
label = ("pfCandMETcorr", "", "CORR")
self.assert_CorrMETData(label)
def test_pfchsMETcorr_type0(self):
label = ("pfchsMETcorr", "type0", "CORR")
self.assert_CorrMETData(label)
def test_corrPfMetType0PfCand(self):
label = ("corrPfMetType0PfCand", "", "CORR")
self.assert_CorrMETData(label)
def test_muonCaloMETcorr(self):
label = ("muonCaloMETcorr", "", "CORR")
self.assert_CorrMETData(label)
def test_corrCaloMetType1_offset(self):
label = ("corrCaloMetType1", "offset", "CORR")
self.assert_CorrMETData(label)
def test_corrCaloMetType1_type1(self):
label = ("corrCaloMetType1", "type1", "CORR")
self.assert_CorrMETData(label)
def test_corrCaloMetType1_type2(self):
label = ("corrCaloMetType1", "type2", "CORR")
self.assert_CorrMETData(label)
def assert_CorrMETData(self, label):
exHandle = self.exHandleCorrMETData
acHandle = self.acHandleCorrMETData
exEventIter = self.exEvents.__iter__()
acEventIter = self.acEvents.__iter__()
nevents = min(self.exEvents.size(), self.acEvents.size())
for i in range(nevents):
exEvent = exEventIter.next()
acEvent = acEventIter.next()
exEvent.getByLabel(label, exHandle)
exCorr = exHandle.product()
acEvent.getByLabel(label, acHandle)
acCorr = acHandle.product()
self.assertAlmostEqual(acCorr.mex, exCorr.mex, 12)
self.assertAlmostEqual(acCorr.mey, exCorr.mey, 12)
self.assertAlmostEqual(acCorr.sumet, exCorr.sumet, 12)
self.assertAlmostEqual(acCorr.significance, exCorr.significance, 12)
##____________________________________________________________________________||
class ROOT_STL_Test(unittest.TestCase):
def test_vector(self):
a = ROOT.vector("double")()
b = ROOT.vector("double")()
self.assertEqual(a, b)
a.push_back(2.2)
self.assertNotEqual(a, b)
a.push_back(3.5)
a.push_back(4.2)
b.push_back(2.2)
b.push_back(3.5)
b.push_back(4.2)
self.assertEqual(a, b)
a.push_back(2.7)
b.push_back(8.9)
self.assertNotEqual(a, b)
##____________________________________________________________________________||
def loadLibraries():
argv_org = list(sys.argv)
sys.argv = [e for e in sys.argv if e != '-h']
ROOT.gSystem.Load("libFWCoreFWLite")
ROOT.AutoLibraryLoader.enable()
ROOT.gSystem.Load("libDataFormatsFWLite")
ROOT.gSystem.Load("libDataFormatsPatCandidates")
sys.argv = argv_org
##____________________________________________________________________________||
loadLibraries()
from DataFormats.FWLite import Events, Handle
##____________________________________________________________________________||
if __name__ == '__main__':
unittest.main()
| [
"tai.sakuma@gmail.com"
] | tai.sakuma@gmail.com |
84291218bcb69359e7565f114049da7a9bd357a7 | fafb89a3552e4dbb47d134966462ef5f3f37f576 | /KEMP/v0.1/fdtd3d/exchange_boundary/355-measure-mpi_persistent_nonblocking.py | c1fbb85ec48b24c37996bf959eafdc9e592df130 | [] | no_license | EMinsight/fdtd_accelerate | 78fa1546df5264550d12fba3cf964838b560711d | a566c60753932eeb646c4a3dea7ed25c7b059256 | refs/heads/master | 2021-12-14T03:26:52.070069 | 2012-07-25T08:25:21 | 2012-07-25T08:25:21 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,846 | py | #!/usr/bin/env python
import numpy as np
import sys
from datetime import datetime
from mpi4py import MPI
comm = MPI.COMM_WORLD
rank = comm.Get_rank()
size = comm.Get_size()
tmax = 100
start = 2 * np.nbytes['float32'] * (3 * 32)**2 # 96, 73728 B, 72.0 KIB
end = 2 * np.nbytes['float32'] * (15 * 32)**2 # 480, 1843200 B, 1.76 MiB
increment = (end - start) / 16
nbytes = np.arange(start, end+1, increment)
dts = np.zeros(nbytes.size)
# verify h5 file exist
if rank == 0:
import os
h5_path = './bandwidth_GbE_nonblocking.h5'
if os.path.exists(h5_path):
print('Error: File exist %s' % h5_path)
sys.exit()
for i, nbyte in enumerate(nbytes):
if rank == 0:
dts[i] = comm.recv(source=1, tag=10) # source, tag
print('nbyte = %d, dt = %f' % (nbyte, dts[i]))
elif rank == 1:
arr_send = np.random.rand(nbyte/np.nbytes['float32']).astype(np.float32)
arr_recv = np.zeros_like(arr_send)
req_send = comm.Send_init(arr_send, dest=2, tag=10)
req_recv = comm.Recv_init(arr_recv, source=2, tag=20)
reqs = [req_send, req_recv]
t0 = datetime.now()
for tstep in xrange(1, tmax+1):
for req in reqs: req.Start()
for req in reqs: req.Wait()
dt0 = datetime.now() - t0
dt = (dt0.seconds + dt0.microseconds * 1e-6) / tmax
#print('[%d] dt = %f' % (rank, dt))
comm.send(dt, dest=0, tag=10) # data, dest, tag
elif rank == 2:
arr_send = np.random.rand(nbyte/np.nbytes['float32']).astype(np.float32)
arr_recv = np.zeros_like(arr_send)
req_send = comm.Send_init(arr_send, dest=1, tag=20)
req_recv = comm.Recv_init(arr_recv, source=1, tag=10)
reqs = [req_send, req_recv]
for tstep in xrange(1, tmax+1):
for req in reqs: req.Start()
for req in reqs: req.Wait()
# Save as h5
if rank == 0:
import h5py as h5
f = h5.File(h5_path, 'w')
f.create_dataset('nbytes', data=nbytes)
f.create_dataset('dts', data=dts)
| [
"kh.kim@kiaps.org"
] | kh.kim@kiaps.org |
d591713f33f151a2652cf6743bb465b5f8fd228c | 7848ded2f7b1cf5cc33380d739e0ceee5718ffec | /imrunicorn/api/migrations/0001_initial.py | b482e08ed992a3d2a8fb1b85887896b36c690222 | [] | no_license | benspelledabc/djangosite | cbed1a7da3eb6ba6eee05897ec928b350831fc6b | fa8004b20f790f56fc69e9d158128a867be700f3 | refs/heads/master | 2023-04-17T19:24:48.908640 | 2021-05-02T19:05:38 | 2021-05-02T19:05:38 | 294,891,690 | 1 | 1 | null | 2021-05-02T19:05:38 | 2020-09-12T07:16:11 | Python | UTF-8 | Python | false | false | 850 | py | # Generated by Django 3.0.7 on 2021-04-25 07:33
from django.db import migrations, models
import django.utils.timezone
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='DockerHubWebhook',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('pusher', models.CharField(max_length=450)),
('repo_name', models.CharField(max_length=450)),
('tag', models.CharField(max_length=450)),
('date_created', models.DateTimeField(default=django.utils.timezone.now, editable=False)),
],
options={
'ordering': ('-date_created', '-tag'),
},
),
]
| [
"admin@benspelledabc.me"
] | admin@benspelledabc.me |
495298d24e69f2a064d50674a1cfb7b26a1e67ae | 60da3d5a9c3957ddbaaf481fea19691f87d682b0 | /frec/utils.py | 025ccc33cb295f36e33179c60bf53eded66b6c7d | [] | no_license | heynemann/frec | 59d46740ee86c7f3fc68fe0e0d14d98c043c8a31 | bb23732f1c367f4c8167adeeefad93cc153851a2 | refs/heads/master | 2020-05-16T23:17:42.826305 | 2012-08-13T13:35:25 | 2012-08-13T13:35:25 | 4,644,976 | 1 | 0 | null | null | null | null | UTF-8 | Python | false | false | 530 | py | #!/usr/bin/python
# -*- coding: utf-8 -*-
# frec face recognition service
# https://github.com/heynemann/frec
# Licensed under the MIT license:
# http://www.opensource.org/licenses/mit-license
# Copyright (c) 2012 Bernardo Heynemann heynemann@gmail.com
# code adapted from thumbor's util module (http://github.com/globocom/thumbor)
import logging
def real_import(name):
if '.' in name:
return reduce(getattr, name.split('.')[1:], __import__(name))
return __import__(name)
logger = logging.getLogger('frec')
| [
"heynemann@gmail.com"
] | heynemann@gmail.com |
33978a2e58d074881b12e622dcb6d6abc7198bd0 | d4418afe18acc3e46533aedf4ac66c237dab65db | /Processing/bin/htmlDressing.py | 720c796db1f1214595d89fb4559b7f01dffd3967 | [] | no_license | cpausmit/MitProd | c148772ee6c844d384f5e83ca21b77591d979403 | c552a39533487c4e90fb52d35ce083dae24304d8 | refs/heads/master | 2021-01-17T03:49:17.821338 | 2016-11-30T21:56:38 | 2016-11-30T21:56:38 | 14,059,357 | 0 | 4 | null | 2016-10-12T04:40:27 | 2013-11-02T02:56:11 | Python | UTF-8 | Python | false | false | 3,697 | py | #!/usr/bin/env python
#---------------------------------------------------------------------------------------------------
# Script to get a quick overview how far the production has come.
#
# Author: C.Paus (Feb 16, 2016)
#---------------------------------------------------------------------------------------------------
import os,sys,re,getopt
def getHeader():
header = '<!DOCTYPE html><html><head><title>Bambu Production</title></head><style>a:link{color:#000000; background-color:transparent; text-decoration:none}a:visited{color:#009000; background-color:transparent; text-decoration:none}a:hover{color:#900000;background-color:transparent; text-decoration:underline}a:active{color:#900000;background-color:transparent; text-decoration:underline}body.ex{margin-top: 0px; margin-bottom:25px; margin-right: 25px; margin-left: 25px;}</style><body class="ex" bgcolor="#eeeeee"><body style="font-family: arial;font-size: 20px;font-weight: bold;color:#900000;"><pre>\n'
return header
def getFooter():
footer = '</pre></body></html>\n'
return footer
#===================================================================================================
# Main starts here
#===================================================================================================
# Define string to explain usage of the script
usage = "\nUsage: htmlDressing.py [ --input=<id> --help ]\n"
# Define the valid options which can be specified and check out the command line
valid = ['input=','version=','help']
try:
opts, args = getopt.getopt(sys.argv[1:], "", valid)
except getopt.GetoptError, ex:
print usage
print str(ex)
sys.exit(1)
# --------------------------------------------------------------------------------------------------
# Get all parameters for this little task
# --------------------------------------------------------------------------------------------------
# Set defaults
input = ''
version = '000'
# Read new values from the command line
for opt, arg in opts:
if opt == "--help":
print usage
sys.exit(0)
if opt == "--input":
input = arg
if opt == "--version":
version = arg
# Deal with obvious problems
if input == "":
cmd = "--input parameter not provided. This is a required parameter."
raise RuntimeError, cmd
# --------------------------------------------------------------------------------------------------
# Here is where the real action starts -------------------------------------------------------------
# --------------------------------------------------------------------------------------------------
# find new file name
htmlFile = input + '.html'
#print ' ASCII: ' + input
#print ' HTML: ' + htmlFile
fileInput = open(input,'r')
fileOutput = open(htmlFile,'w')
line = ' '
# insert header
fileOutput.write(getHeader())
# translate the body
with open(input,"r") as fileInput:
for line in fileInput:
# cleanup CR
line = line[:-1]
## cleanup duplicate blanks
#line = re.sub(' +',' ',line)
# remove commented lines
if '+' in line:
f = line.split(' ')
dataset = f.pop()
line = ' '.join(f) \
+ ' <a href="filefi/' + version + '/' + dataset + '">' + dataset + '</a>'
else:
f = line.split(' ')
if len(f) > 1:
v = f.pop()
test = f.pop()
if test == "VERSION:":
version = v
fileOutput.write(line+'\n')
# insert footer
fileOutput.write(getFooter())
fileInput .close()
fileOutput.close()
| [
"paus@mit.edu"
] | paus@mit.edu |
a7a7c414f370b2b086402995386596237370520c | 35fe64e51683305123d85701093325858596bdeb | /sliders.py | 6ed673c095f555930634eae5178d60210ed7d022 | [] | no_license | BruceJohnJennerLawso/atmosphere | 9d12a226cd287703927e577b19c6c9fb713448df | 9690d3dd7332f08a2f5fea20d32b5a0cd4408f7f | refs/heads/master | 2022-02-02T09:57:16.452393 | 2018-06-15T19:53:14 | 2018-06-15T19:53:14 | 71,283,572 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,106 | py | ## sliders.py ##################################################################
## all manner of useful widgets to get yo sliding needs done ###################
## looks like this was just a testbed I had for learning how the tkinter #######
## sliders work ################################################################
################################################################################
from Tkinter import Tk
import Tkinter as tk
from sys import argv
def getScaleValue(scaleTitle, scaleUnits):
def setVal(val):
global outputVal
outputVal = val
def endControl():
control.destroy()
control=tk.Tk()
control.protocol("WM_DELETE_WINDOW",endControl)
control.title()
control.geometry("650x100+100+250")
cline1=tk.Label(control, text=scaleUnits).pack()
cline3=tk.Scale(control,orient=tk.HORIZONTAL,length=580,width=20,sliderlength=10,from_=0,to=100,tickinterval=5, command=setVal)
cline3.set(50)
cline3.pack()
control.mainloop()
print "Slider widget outputting ", outputVal
return outputVal
if(__name__ == "__main__"):
print getScaleValue("Test Scale", "Units")
| [
"johnnybgoode@rogers.com"
] | johnnybgoode@rogers.com |
b792a234218d5cd156cf4eba9d6f7772a2555e38 | 5a171226c273825345429b0bd6e4a2878ef4979f | /aces_1.0.0/python/aces_ocio/tests/tests_aces_config.py | f41349e6a788eea512555eb6125272b7dfe9da7a | [] | no_license | taka25/OpenColorIO-Configs | 5ea63f024804c1dbc98631358ef5c6f6a051fe8b | 547fceb44bbc1f7475fb17851c3b3cc31b616455 | refs/heads/master | 2021-01-15T09:23:42.345060 | 2015-05-05T18:54:32 | 2015-05-05T18:54:32 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 4,135 | py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Defines unit tests for *ACES* configuration.
"""
from __future__ import division
import hashlib
import os
import re
import shutil
import tempfile
import unittest
from aces_ocio.utilities import files_walker
from aces_ocio.create_aces_config import (
ACES_OCIO_CTL_DIRECTORY_ENVIRON,
create_ACES_config)
__author__ = 'ACES Developers'
__copyright__ = 'Copyright (C) 2014 - 2015 - ACES Developers'
__license__ = ''
__maintainer__ = 'ACES Developers'
__email__ = 'aces@oscars.org'
__status__ = 'Production'
__all__ = ['REFERENCE_CONFIG_ROOT_DIRECTORY',
'HASH_TEST_PATTERNS',
'UNHASHABLE_TEST_PATTERNS',
'TestACESConfig']
# TODO: Investigate how the current config has been generated to use it for
# tests.
# REFERENCE_CONFIG_ROOT_DIRECTORY = os.path.abspath(
# os.path.join(os.path.dirname(__file__), '..', '..', '..'))
REFERENCE_CONFIG_ROOT_DIRECTORY = '/colour-science/colour-ramblings/ocio/aces'
HASH_TEST_PATTERNS = ('\.3dl', '\.lut', '\.csp')
UNHASHABLE_TEST_PATTERNS = ('\.icc', '\.ocio')
class TestACESConfig(unittest.TestCase):
"""
Performs tests on the *ACES* configuration.
"""
def setUp(self):
"""
Initialises common tests attributes.
"""
self.__aces_ocio_ctl_directory = os.environ.get(
ACES_OCIO_CTL_DIRECTORY_ENVIRON, None)
assert self.__aces_ocio_ctl_directory is not None, (
'Undefined "{0}" environment variable!'.format(
ACES_OCIO_CTL_DIRECTORY_ENVIRON))
assert os.path.exists(self.__aces_ocio_ctl_directory) is True, (
'"{0}" directory does not exists!'.format(
self.__aces_ocio_ctl_directory))
self.maxDiff = None
self.__temporary_directory = tempfile.mkdtemp()
def tearDown(self):
"""
Post tests actions.
"""
shutil.rmtree(self.__temporary_directory)
@staticmethod
def directory_hashes(directory,
filters_in=None,
filters_out=None,
flags=0):
"""
Recursively computes the hashes from the file within given directory.
Parameters
----------
directory : str or unicode
Directory to compute the file hashes.
filters_in : array_like
Included patterns.
filters_out : array_like
Excluded patterns.
flags : int
Regex flags.
Returns
-------
dict
Directory file hashes.
"""
hashes = {}
for path in files_walker(directory,
filters_in=filters_in,
filters_out=filters_out,
flags=flags):
with open(path) as file:
digest = hashlib.md5(
re.sub('\s', '', file.read())).hexdigest()
hashes[path.replace(directory, '')] = digest
return hashes
def test_ACES_config(self):
"""
Performs tests on the *ACES* configuration by computing hashes on the
generated configuration and comparing them to the existing one.
"""
self.assertTrue(create_ACES_config(self.__aces_ocio_ctl_directory,
self.__temporary_directory))
reference_hashes = self.directory_hashes(
REFERENCE_CONFIG_ROOT_DIRECTORY,
HASH_TEST_PATTERNS)
test_hashes = self.directory_hashes(
self.__temporary_directory,
HASH_TEST_PATTERNS)
self.assertDictEqual(reference_hashes, test_hashes)
# Checking that unashable files ('.icc', '.ocio') are generated.
unashable = lambda x: (
sorted([file.replace(x, '') for file in
files_walker(x, UNHASHABLE_TEST_PATTERNS)]))
self.assertListEqual(unashable(REFERENCE_CONFIG_ROOT_DIRECTORY),
unashable(self.__temporary_directory))
if __name__ == '__main__':
unittest.main()
| [
"thomas.mansencal@gmail.com"
] | thomas.mansencal@gmail.com |
a15603b3758d92526600d42a165894eca6cd2f51 | 9743d5fd24822f79c156ad112229e25adb9ed6f6 | /xai/brain/wordbase/otherforms/_toeing.py | 94ec751994aa0fdf9ff24eee291846ff392885e8 | [
"MIT"
] | permissive | cash2one/xai | de7adad1758f50dd6786bf0111e71a903f039b64 | e76f12c9f4dcf3ac1c7c08b0cc8844c0b0a104b6 | refs/heads/master | 2021-01-19T12:33:54.964379 | 2017-01-28T02:00:50 | 2017-01-28T02:00:50 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 214 | py |
#calss header
class _TOEING():
def __init__(self,):
self.name = "TOEING"
self.definitions = toe
self.parents = []
self.childen = []
self.properties = []
self.jsondata = {}
self.basic = ['toe']
| [
"xingwang1991@gmail.com"
] | xingwang1991@gmail.com |
6a9099a6a18d621eb5bef925cbb1bc5ce827c848 | 325fde42058b2b82f8a4020048ff910cfdf737d7 | /src/azure-firewall/azext_firewall/vendored_sdks/v2020_07_01/v2020_07_01/operations/_vpn_site_links_operations.py | b7c35fdfc04bbbcbdc10df704b1a330725d28142 | [
"LicenseRef-scancode-generic-cla",
"MIT"
] | permissive | ebencarek/azure-cli-extensions | 46b0d18fe536fe5884b00d7ffa30f54c7d6887d1 | 42491b284e38f8853712a5af01836f83b04a1aa8 | refs/heads/master | 2023-04-12T00:28:44.828652 | 2021-03-30T22:34:13 | 2021-03-30T22:34:13 | 261,621,934 | 2 | 5 | MIT | 2020-10-09T18:21:52 | 2020-05-06T01:25:58 | Python | UTF-8 | Python | false | false | 8,009 | py | # coding=utf-8
# --------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for
# license information.
#
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes may cause incorrect behavior and will be lost if the code is
# regenerated.
# --------------------------------------------------------------------------
import uuid
from msrest.pipeline import ClientRawResponse
from msrestazure.azure_exceptions import CloudError
from .. import models
class VpnSiteLinksOperations(object):
"""VpnSiteLinksOperations operations.
You should not instantiate directly this class, but create a Client instance that will create it for you and attach it as attribute.
:param client: Client for service requests.
:param config: Configuration of service client.
:param serializer: An object model serializer.
:param deserializer: An object model deserializer.
:ivar api_version: Client API version. Constant value: "2020-07-01".
"""
models = models
def __init__(self, client, config, serializer, deserializer):
self._client = client
self._serialize = serializer
self._deserialize = deserializer
self.api_version = "2020-07-01"
self.config = config
def get(
self, resource_group_name, vpn_site_name, vpn_site_link_name, custom_headers=None, raw=False, **operation_config):
"""Retrieves the details of a VPN site link.
:param resource_group_name: The resource group name of the VpnSite.
:type resource_group_name: str
:param vpn_site_name: The name of the VpnSite.
:type vpn_site_name: str
:param vpn_site_link_name: The name of the VpnSiteLink being
retrieved.
:type vpn_site_link_name: str
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: VpnSiteLink or ClientRawResponse if raw=true
:rtype: ~azure.mgmt.network.v2020_07_01.models.VpnSiteLink or
~msrest.pipeline.ClientRawResponse
:raises: :class:`CloudError<msrestazure.azure_exceptions.CloudError>`
"""
# Construct URL
url = self.get.metadata['url']
path_format_arguments = {
'subscriptionId': self._serialize.url("self.config.subscription_id", self.config.subscription_id, 'str'),
'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str'),
'vpnSiteName': self._serialize.url("vpn_site_name", vpn_site_name, 'str'),
'vpnSiteLinkName': self._serialize.url("vpn_site_link_name", vpn_site_link_name, 'str')
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {}
query_parameters['api-version'] = self._serialize.query("self.api_version", self.api_version, 'str')
# Construct headers
header_parameters = {}
header_parameters['Accept'] = 'application/json'
if self.config.generate_client_request_id:
header_parameters['x-ms-client-request-id'] = str(uuid.uuid1())
if custom_headers:
header_parameters.update(custom_headers)
if self.config.accept_language is not None:
header_parameters['accept-language'] = self._serialize.header("self.config.accept_language", self.config.accept_language, 'str')
# Construct and send request
request = self._client.get(url, query_parameters, header_parameters)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [200]:
exp = CloudError(response)
exp.request_id = response.headers.get('x-ms-request-id')
raise exp
deserialized = None
if response.status_code == 200:
deserialized = self._deserialize('VpnSiteLink', response)
if raw:
client_raw_response = ClientRawResponse(deserialized, response)
return client_raw_response
return deserialized
get.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/vpnSites/{vpnSiteName}/vpnSiteLinks/{vpnSiteLinkName}'}
def list_by_vpn_site(
self, resource_group_name, vpn_site_name, custom_headers=None, raw=False, **operation_config):
"""Lists all the vpnSiteLinks in a resource group for a vpn site.
:param resource_group_name: The resource group name of the VpnSite.
:type resource_group_name: str
:param vpn_site_name: The name of the VpnSite.
:type vpn_site_name: str
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: An iterator like instance of VpnSiteLink
:rtype:
~azure.mgmt.network.v2020_07_01.models.VpnSiteLinkPaged[~azure.mgmt.network.v2020_07_01.models.VpnSiteLink]
:raises: :class:`CloudError<msrestazure.azure_exceptions.CloudError>`
"""
def prepare_request(next_link=None):
if not next_link:
# Construct URL
url = self.list_by_vpn_site.metadata['url']
path_format_arguments = {
'subscriptionId': self._serialize.url("self.config.subscription_id", self.config.subscription_id, 'str'),
'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str'),
'vpnSiteName': self._serialize.url("vpn_site_name", vpn_site_name, 'str')
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {}
query_parameters['api-version'] = self._serialize.query("self.api_version", self.api_version, 'str')
else:
url = next_link
query_parameters = {}
# Construct headers
header_parameters = {}
header_parameters['Accept'] = 'application/json'
if self.config.generate_client_request_id:
header_parameters['x-ms-client-request-id'] = str(uuid.uuid1())
if custom_headers:
header_parameters.update(custom_headers)
if self.config.accept_language is not None:
header_parameters['accept-language'] = self._serialize.header("self.config.accept_language", self.config.accept_language, 'str')
# Construct and send request
request = self._client.get(url, query_parameters, header_parameters)
return request
def internal_paging(next_link=None):
request = prepare_request(next_link)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [200]:
exp = CloudError(response)
exp.request_id = response.headers.get('x-ms-request-id')
raise exp
return response
# Deserialize response
header_dict = None
if raw:
header_dict = {}
deserialized = models.VpnSiteLinkPaged(internal_paging, self._deserialize.dependencies, header_dict)
return deserialized
list_by_vpn_site.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/vpnSites/{vpnSiteName}/vpnSiteLinks'}
| [
"noreply@github.com"
] | ebencarek.noreply@github.com |
5ea023f8b22b079a1c6ef60caf7748d09c188e78 | a742bd051641865d2e5b5d299c6bc14ddad47f22 | /Mysite/Mysite/urls.py | 3b6e04e1c9549e94a6cee0321e84fbd1d387ce51 | [] | no_license | lxconfig/UbuntuCode_bak | fb8f9fae7c42cf6d984bf8231604ccec309fb604 | 3508e1ce089131b19603c3206aab4cf43023bb19 | refs/heads/master | 2023-02-03T19:10:32.001740 | 2020-12-19T07:27:57 | 2020-12-19T07:27:57 | 321,351,481 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,567 | py | """Mysite URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/3.0/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: path('', views.home, name='home')
Class-based views
1. Add an import: from other_app.views import Home
2. Add a URL to urlpatterns: path('', Home.as_view(), name='home')
Including another URLconf
1. Import the include() function: from django.urls import include, path
2. Add a URL to urlpatterns: path('blog/', include('blog.urls'))
"""
from django.contrib import admin
from django.urls import path, include, re_path
from showInfo import views
urlpatterns = [
path('admin/', admin.site.urls),
path("show/", include("showInfo.urls")),
path("app01/", include("app01.urls")),
re_path(r"^edit/(?P<num>\d+).html$", views.index),
path('del/<int:nid>/', views.index2, name="del"),
path("crud", views.CRUD),
path("CBV", views.CBV.as_view()),
path("foreign", views.foreign),
path("paging", views.paging),
path("custom", views.custom),
path("many2many", views.many2many),
path("filters", views.filters),
path("session_login", views.session_login),
path("index", views.index),
path("login", views.male_female_login),
path("male_female_info", views.male_female_info),
path("logout", views.logout),
path("others", views.others),
# path("add", views.add_data),
]
| [
"525868229@qq.com"
] | 525868229@qq.com |
183738a9cec443d7c91c9694e74ba4eb9486ce94 | 26bd175ffb3bd204db5bcb70eec2e3dfd55fbe9f | /exercises/networking_selfpaced/networking-workshop/collections/ansible_collections/community/general/tests/unit/modules/net_tools/nios/test_nios_member.py | c9ad0fcfea3515184182cc14f31e2fdf2be4fc80 | [
"MIT",
"GPL-3.0-only",
"CC0-1.0",
"GPL-1.0-or-later"
] | permissive | tr3ck3r/linklight | 37814ed19173d893cdff161355d70a1cf538239b | 5060f624c235ecf46cb62cefcc6bddc6bf8ca3e7 | refs/heads/master | 2021-04-11T04:33:02.727318 | 2020-03-25T17:38:41 | 2020-03-25T17:38:41 | 248,992,437 | 0 | 0 | MIT | 2020-03-21T14:26:25 | 2020-03-21T14:26:25 | null | UTF-8 | Python | false | false | 6,928 | py | # This file is part of Ansible
#
# Ansible 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.
#
# Ansible 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 Ansible. If not, see <http://www.gnu.org/licenses/>.
# Make coding more python3-ish
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type
from ansible_collections.community.general.plugins.module_utils.net_tools.nios import api
from ansible_collections.community.general.plugins.modules.net_tools.nios import nios_member
from ansible_collections.community.general.tests.unit.compat.mock import patch, MagicMock, Mock
from ..test_nios_module import TestNiosModule, load_fixture
class TestNiosMemberModule(TestNiosModule):
module = nios_member
def setUp(self):
super(TestNiosMemberModule, self).setUp()
self.module = MagicMock(name='ansible_collections.community.general.plugins.modules.net_tools.nios.nios_member.WapiModule')
self.module.check_mode = False
self.module.params = {'provider': None}
self.mock_wapi = patch('ansible_collections.community.general.plugins.modules.net_tools.nios.nios_member.WapiModule')
self.exec_command = self.mock_wapi.start()
self.mock_wapi_run = patch('ansible_collections.community.general.plugins.modules.net_tools.nios.nios_member.WapiModule.run')
self.mock_wapi_run.start()
self.load_config = self.mock_wapi_run.start()
def tearDown(self):
super(TestNiosMemberModule, self).tearDown()
self.mock_wapi.stop()
self.mock_wapi_run.stop()
def load_fixtures(self, commands=None):
self.exec_command.return_value = (0, load_fixture('nios_result.txt').strip(), None)
self.load_config.return_value = dict(diff=None, session='session')
def _get_wapi(self, test_object):
wapi = api.WapiModule(self.module)
wapi.get_object = Mock(name='get_object', return_value=test_object)
wapi.create_object = Mock(name='create_object')
wapi.update_object = Mock(name='update_object')
wapi.delete_object = Mock(name='delete_object')
return wapi
def test_nios_member_create(self):
self.module.params = {'provider': None, 'state': 'present', 'host_name': 'test_member',
'vip_setting': {'address': '192.168.1.110', 'subnet_mask': '255.255.255.0', 'gateway': '192.168.1.1'},
'config_addr_type': 'IPV4', 'platform': 'VNIOS', 'comment': None, 'extattrs': None}
test_object = None
test_spec = {
"host_name": {"ib_req": True},
"vip_setting": {},
"config_addr_type": {},
"platform": {},
"comment": {},
"extattrs": {}
}
wapi = self._get_wapi(test_object)
res = wapi.run('testobject', test_spec)
self.assertTrue(res['changed'])
wapi.create_object.assert_called_once_with('testobject', {'host_name': 'test_member',
'vip_setting': {'address': '192.168.1.110', 'subnet_mask': '255.255.255.0',
'gateway': '192.168.1.1'},
'config_addr_type': 'IPV4', 'platform': 'VNIOS'})
def test_nios_member_update(self):
self.module.params = {'provider': None, 'state': 'present', 'host_name': 'test_member',
'vip_setting': {'address': '192.168.1.110', 'subnet_mask': '255.255.255.0', 'gateway': '192.168.1.1'},
'config_addr_type': 'IPV4', 'platform': 'VNIOS', 'comment': 'updated comment', 'extattrs': None}
test_object = [
{
"comment": "Created with Ansible",
"_ref": "member/b25lLnZpcnR1YWxfbm9kZSQ3:member01.ansible-dev.com",
"config_addr_type": "IPV4",
"host_name": "member01.ansible-dev.com",
"platform": "VNIOS",
"service_type_configuration": "ALL_V4",
"vip_setting":
{
"address": "192.168.1.100",
"dscp": 0,
"gateway": "192.168.1.1",
"primary": True,
"subnet_mask": "255.255.255.0",
"use_dscp": False
}
}
]
test_spec = {
"host_name": {"ib_req": True},
"vip_setting": {},
"config_addr_type": {},
"platform": {},
"comment": {},
"extattrs": {}
}
wapi = self._get_wapi(test_object)
res = wapi.run('testobject', test_spec)
self.assertTrue(res['changed'])
def test_nios_member_remove(self):
self.module.params = {'provider': None, 'state': 'absent', 'host_name': 'test_member',
'vip_setting': {'address': '192.168.1.110', 'subnet_mask': '255.255.255.0', 'gateway': '192.168.1.1'},
'config_addr_type': 'IPV4', 'platform': 'VNIOS', 'comment': 'updated comment', 'extattrs': None}
ref = "member/b25lLnZpcnR1YWxfbm9kZSQ3:member01.ansible-dev.com"
test_object = [
{
"comment": "Created with Ansible",
"_ref": "member/b25lLnZpcnR1YWxfbm9kZSQ3:member01.ansible-dev.com",
"config_addr_type": "IPV4",
"host_name": "member01.ansible-dev.com",
"platform": "VNIOS",
"service_type_configuration": "ALL_V4",
"vip_setting":
{
"address": "192.168.1.100",
"dscp": 0,
"gateway": "192.168.1.1",
"primary": True,
"subnet_mask": "255.255.255.0",
"use_dscp": False
}
}
]
test_spec = {
"host_name": {"ib_req": True},
"vip_setting": {},
"config_addr_type": {},
"platform": {},
"comment": {},
"extattrs": {}
}
wapi = self._get_wapi(test_object)
res = wapi.run('testobject', test_spec)
self.assertTrue(res['changed'])
wapi.delete_object.assert_called_once_with(ref)
| [
"joshuamadison+gh@gmail.com"
] | joshuamadison+gh@gmail.com |
c2e00b209d01add39d31fcef937d285577c5e4f1 | 5c09a25f0b401d525a0d6023399e4910d8a8c487 | /students/alex_skrn/lesson04/mailroom.py | 5ae4740324a09c03e2f86c865016bc03ad5fb085 | [] | no_license | UWPCE-PythonCert-ClassRepos/Wi2018-Online | d6183f47e5b37b6ba56e2310d252334cb6024c9e | 8c32086bf30de8decdc8e5f43cfa1344d5747200 | refs/heads/master | 2021-09-11T13:26:31.817582 | 2018-04-07T20:11:20 | 2018-04-07T20:11:20 | 115,212,113 | 0 | 38 | null | 2018-04-07T20:11:20 | 2017-12-23T17:47:10 | Python | UTF-8 | Python | false | false | 7,714 | py | #!/usr/bin/env python3
"""Mailroom - Part 2 - Dicts, Files."""
import os
import datetime
import tkinter as tk
from tkinter import filedialog
donors = {'Aristarkh Lentulov': [4.5, 5.0],
'El Lissitzky': [34.2, 30.0, 35.5],
'Kazimir Malevich': [15.0, 20.25, 12.25],
'Marc Chagall': [148.75, 155.0],
'Wassily Kandinsky': [75.0, 50.5, 60.4],
}
# DONOR-RELATED FUNCTIONS
def add_donation(name, amount):
"""Add a donation for a named donor."""
if name in donors:
donors[name].append(float(amount))
else:
donors[name] = [float(amount)]
def get_last_donation(name):
"""Return a float -- the last donation of the given donor."""
return donors[name][-1]
def get_total_given(name):
"""Return total amount of donations for the given donor."""
return sum(donors[name])
def get_donations(name):
"""Return a list of the specified donor's donations."""
return donors[name]
def sort_donors_by_total():
"""Return a list of donor names sorted by total donations, max to min."""
donors_L = list(donors.items())
donors_sorted = sorted(donors_L, key=lambda x: sum(x[1]), reverse=True)
sorted_donor_names = []
for item in donors_sorted:
sorted_donor_names.append(item[0])
return sorted_donor_names
def print_donor_names():
"""Print existing donor names on screen."""
print()
donors_L = list(donors.keys())
for name in donors_L[:-1]:
print(name, end=', ')
print(donors_L[-1])
print()
def get_email(name, amount):
"""Return a str containing a thank-you email."""
d = dict(key1=name, key2=amount)
# Can't figure out how to combine {:,} and {key2} below.
# Used a dict here 'cos the assignment seems to ask for it.
email_text = ("\nDear {key1},\n"
"\nI would like to thank you for your donation of ${key2}.\n"
"\nWe appreciate your support.\n"
"\nSincerely,\n"
"The Organization\n"
)
return email_text.format(**d)
def print_email(name, amount):
"""Print a thank-you email on screen."""
print(get_email(name, amount))
def create_report():
"""Create a report."""
title_line_form = "{:<26}{:^3}{:>13}{:^3}{:>13}{:^3}{:>13}"
title_line_text = ('Donor Name', '|', 'Total Given', '|',
'Num Gifts', '|', 'Average Gift'
)
print()
print(title_line_form.format(*title_line_text))
print('- ' * 38)
form_line = "{:<26}{:>3}{:>13}{:>3}{:>13}{:>3}{:>13}"
for name in sort_donors_by_total():
total = get_total_given(name)
num_gifts = len(get_donations(name))
mean = round((total / num_gifts), 2)
print(form_line.format(str(name), '$', str(total), ' ',
str(num_gifts), '$', str(mean)
)
)
print()
# PRINT ON SREEN A THANK YOU LETTER TO SOMEONE WHO JUST MADE A DONATION
def existing_donor_interaction():
"""Ask for old donor name, donation amount, print a thank-you email."""
prompt_name = "Type full name of the old donor or 0 to abort > "
old_donor_name = input(prompt_name)
if old_donor_name == "0":
return
while old_donor_name not in donors:
old_donor_name = input(prompt_name)
if old_donor_name == "0":
return
prompt_amount = "Enter the donation amount or 0 to abort > "
donation_amount = input(prompt_amount)
if donation_amount == "0":
return
# Add the donation amount to the dict.
add_donation(old_donor_name, donation_amount)
print_email(old_donor_name, get_last_donation(old_donor_name))
def new_donor_interaction():
"""Ask for new donor name, donation amount, print a thank-you email."""
prompt_name = "Type full name of the new donor or 0 to abort > "
new_donor_name = input(prompt_name)
if new_donor_name == "0":
return
prompt_amount = "Enter the donation amount or 0 to abort > "
donation_amount = input(prompt_amount)
if donation_amount == "0":
return
# Add the donor and the donation amount to the dict.
add_donation(new_donor_name, donation_amount)
print_email(new_donor_name, get_last_donation(new_donor_name))
# WRITE ALL LETTERS TO FILES
def write_file(destination, name, text):
"""Write text to destination/name.txt."""
date = str(datetime.date.today())
# path = "{}/{}-{}.txt".format(destination, date, name)
filename = "{}-{}.txt".format(date, name)
path = os.path.join(destination, filename)
with open(path, "w") as toF:
toF.write(text)
def write_cwd():
"""Write all emails to the current working directory."""
cwd = os.getcwd()
for name in donors:
text = get_email(name, get_last_donation(name))
write_file(cwd, name, text)
print("\nAll letters saved in {}\n".format(cwd))
def write_select_dir():
"""Write all emails to a dir selected by the user."""
root = tk.Tk()
root.withdraw()
# Get the target directory from the user.
target_dir = filedialog.askdirectory()
for name in donors:
text = get_email(name, get_last_donation(name))
write_file(target_dir, name, text)
print("\nAll letters saved in {}\n".format(target_dir))
# MANAGING MENUS
def quit():
"""Provide an exit option for menus."""
return "exit menu"
def send_all_menu():
"""Initiate the send-all-letters sub-sub-menu."""
menu_selection(write_file_prompt, write_file_dispatch)
def send_thank_you_interaction():
"""Initiate the send-thank-you sub-menu."""
menu_selection(send_thanks_prompt, send_thanks_dispatch)
def menu_selection(prompt, dispatch_dict):
"""Provide a template for using dispatch dicts to switch through menus."""
while True:
response = input(prompt)
try:
if dispatch_dict[response]() == "exit menu":
break
except KeyError:
print("\nInvalid choice. Try again")
pass
if __name__ == "__main__":
# Write to files
write_file_prompt = ("\nSend to everyone sub-menu\n"
"\n1 - Write to current working directory\n"
"2 - Choose a directory to write\n"
"3 - Quit\n"
">> "
)
write_file_dispatch = {"1": write_cwd,
"2": write_select_dir,
"3": quit,
}
# Print on screen
send_thanks_dispatch = {"1": print_donor_names,
"2": new_donor_interaction,
"3": existing_donor_interaction,
"4": quit,
}
send_thanks_prompt = ("\nSend-Thank-You Sub-Menu\n"
"\n1 - See the list of donors\n"
"2 - Add a new donor and a donation amount\n"
"3 - Choose an existing donor\n"
"4 - Quit\n"
">> "
)
# Main menu
main_dispatch = {"1": send_thank_you_interaction,
"2": create_report,
"3": send_all_menu,
"4": quit,
}
main_prompt = ("\nMain Menu\n"
"\n1 - Send a Thank You\n"
"2 - Create a Report\n"
"3 - Send letters to everyone\n"
"4 - Quit\n"
">> "
)
menu_selection(main_prompt, main_dispatch)
| [
"askrn123@gmail.com"
] | askrn123@gmail.com |
c03ee96cb703f340a5d609bd3956659f5382d3ae | 741ee09b8b73187fab06ecc1f07f46a6ba77e85c | /AutonomousSourceCode/data/raw/sort/45f445a1-9136-48b4-8087-3e2ba78df746__ngnotifier_filters.py | da1355a8abf0fee1c219af55f72201920e09c7ba | [] | no_license | erickmiller/AutomatousSourceCode | fbe8c8fbf215430a87a8e80d0479eb9c8807accb | 44ee2fb9ac970acf7389e5da35b930d076f2c530 | refs/heads/master | 2021-05-24T01:12:53.154621 | 2020-11-20T23:50:11 | 2020-11-20T23:50:11 | 60,889,742 | 6 | 1 | null | null | null | null | UTF-8 | Python | false | false | 313 | py | import operator
from django import template
register = template.Library()
@register.filter(name='sort_hosts')
def list_sort(value):
return sorted(value, key=operator.attrgetter('host'))
@register.filter(name='sort_groups')
def list_sort(value):
return sorted(value, key=operator.attrgetter('name')) | [
"erickmiller@gmail.com"
] | erickmiller@gmail.com |
de46502ffb2b3dece449752adde08694708987ae | ca7aa979e7059467e158830b76673f5b77a0f5a3 | /Python_codes/p03379/s380015361.py | 436f043c6480227367064b8e867d7e9f66a47528 | [] | no_license | Aasthaengg/IBMdataset | 7abb6cbcc4fb03ef5ca68ac64ba460c4a64f8901 | f33f1c5c3b16d0ea8d1f5a7d479ad288bb3f48d8 | refs/heads/main | 2023-04-22T10:22:44.763102 | 2021-05-13T17:27:22 | 2021-05-13T17:27:22 | 367,112,348 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 231 | py | import copy
n = int(input())
x = list(map(int,input().split()))
x2 = copy.copy(x)
x2.sort()
num1,num2 = (len(x)//2)-1,(len(x)//2)
med1,med2 = x2[num1],x2[num2]
for i in range(n):
if x[i] <= med1:
print(med2)
else:
print(med1) | [
"66529651+Aastha2104@users.noreply.github.com"
] | 66529651+Aastha2104@users.noreply.github.com |
b5f8c14ad7122cdf83315be435b923ae1edff549 | ff6248be9573caec94bea0fa2b1e4b6bf0aa682b | /StudentProblem/10.21.12.4/1/1569576594.py | 1b464c42214abc044ae82513f5d498da2e00f185 | [] | no_license | LennartElbe/codeEvo | 0e41b1a7705204e934ef71a5a28c047366c10f71 | e89b329bc9edd37d5d9986f07ca8a63d50686882 | refs/heads/master | 2020-12-21T17:28:25.150352 | 2020-03-26T10:22:35 | 2020-03-26T10:22:35 | 236,498,032 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,283 | py | import functools
import typing
import string
import random
import pytest
## Lösung Teil 1.
def nwords(s: str)-> int:
"""
Die Funktion nwords berechenet zu einem String Argument s die Anzahl der Worte im String.
args:
s(str): Text
return:
Anzahl an Wörter im Text
"""
if len(s) == 0:
return 0
result = 1
for element in s:
if element == (" "):
result += 1
return result
## Lösung Teil 2.
def word_count_iter(m):
"""
Die Funktion word_count_iter
args:
m: iterierbares Objekt
return:
Tupel aus der Anzahl der Zeilen, der Anzahl der Worte und der Anzahl der Zeichen liefert, die aus dem Argument gelesen worden sind
"""
zeilen = 1
worte = nwords(m)
zeichen = len(m)
for element in m:
if element == (" "):
zeilen += 1
return (zeilen, worte, zeichen)
######################################################################
## Lösung Teil 3. (Tests)
assert word_count_iter("Hallo") == (1,1,5)
## revert
try:
word_count_iter = word_count_iter.__wrapped__
except:
pass
## Lösung Teil 4.
def word_count():
pass
######################################################################
| [
"lenni.elbe@gmail.com"
] | lenni.elbe@gmail.com |
5b34f79f6412bb654bf991a1c15c12d7d6e8f3b7 | 730d9a4b1a8a031d3dd158f695634ef9a3da9506 | /non_hugin_based_stitching/parse_output_for_hugin_2.py | 5eca6ddecf0912b2faf181d3a81fd2a3d4a03885 | [] | no_license | tingleshao/kirito | dcf6ddb49059624ef5f4aff966b1d56ef516d740 | 6309852cbd24b21e724060510a71e6ff84789c96 | refs/heads/master | 2020-05-20T21:12:37.159318 | 2017-07-21T20:22:42 | 2017-07-21T20:22:42 | 84,524,894 | 3 | 0 | null | null | null | null | UTF-8 | Python | false | false | 2,113 | py | import matched
import cv2
# parse the plain text output into hugin style
# the opencv feature extraction is on images with scale 581 x xxx
# hugin uses the original image resolution
# 2160 x xxxx
adjacernt_map = [[1, 8, 9, 10, 11, 12, 13, 14],[0, 2, 7, 8, 9, 13, 14, 15],[1, 3, 6, 7, 8, 14, 15, 16],
[2, 4, 5, 6, 7, 15, 16, 17],[3, 5, 6, 16, 17],[3, 4, 6],[2, 3, 4, 5, 7],[1, 2, 3, 6, 8],
[0, 1, 2, 7, 9],[0, 1, 8, 10, 11], [0, 9, 11],[0, 9, 10, 12, 13],[0, 11, 13],[0, 1, 11, 12, 14],
[0, 1, 2, 13, 15],[1, 2, 3, 14, 16],[2, 3, 4, 15, 17],[3, 4, 16]]
scaled_image_h = 581.0
original_image_h = 2160.0
def main():
ratio = original_image_h / scaled_image_h
with open("parsed_output_2.txt") as inpust_file:
text = input_file.read()
lines = text.split('\n')
curr_idx = 0
output_str = "# control points\n"
while curr_idx < len(lines) and len(lines[curr_idx]) > 0:
lines = lines[curr_idx]
curr_key = (int(float(line.split(' ')[1])), int(float(line.split(' ')[2]))
curr_i = curr_idx + 1
values_lst = []
dist_lst = []
while curr_i < len(lines) and len(lines[curr_i]) > 0 and lines[curr_i][0] != '#':
line = lines[curr_i]
tokens = line.split(' ')
values_lst.append([float(tokens[x]) for x in range(4)])
dfist_lst.append(float(tokens[4]))
curr_i = curr_i + 1
curr_idx = curr_i
if curr_key[1] in adjacent_map[curr_key[0]]:
important_features = [values_lst[w] for w in sorted(range(len(values_lst)), key=lambda k: dist_lst[k])]
for i in range(min(len(important_features), 25)):
output_str = output_str + "c n{0} N{1} x{2:.12f} y{3:.12f} X{4:.12f} Y{5:.12f} t0\n".format(curr_key[0], curr_key[1], important_features[i][0] * ratio, important_features[i][1] * ratio, important_features[i][2] * ratio, important_features[i][3] * ratio)
with open("parsed_output_for_hugin.txt", 'w') as output_file:
output_file.write(output_str)
if __name__ == '__main__':
main()
| [
"cshao@cs.unc.edu"
] | cshao@cs.unc.edu |
3eddaa9d2ce87b1a7007b1bf576aa4a6cd259e13 | 5d9bd0ee9ef2875b5d0f050bb859bbc1a9e8cf2d | /邮件发送/邮件1.py | 836a6f16decc5830592be48b8aa3d1301d817933 | [] | no_license | StarLord777/Spider-learn | 75a825fd2f858682c7388bd5565a9b126e515fba | 1b206df0d6298f3ac401d85ded86f6fb328e49a4 | refs/heads/master | 2020-03-27T10:01:36.215743 | 2018-10-12T13:23:14 | 2018-10-12T13:23:14 | 146,390,047 | 1 | 1 | null | null | null | null | UTF-8 | Python | false | false | 1,226 | py | import smtplib
from email.mime.text import MIMEText
from email.header import Header
import threading,time
import redis
redis = redis.Redis(db=15)
def sendMailToOne():
print('线程{}正在运行---------------'.format(threading.current_thread().name))
sender = '001@vipjiexi.club'
receiver = ['2492057915@qq.com']
#receiver = []
#获取接收人
msg = MIMEText('悉心收集,包括但不限于英语(各种考试,口语),计算机(编程,网络安全,硬件创客)'
',绘画,健身,vip电影电视剧音乐等', 'plain', 'utf-8')
msg['From'] = Header('001')
msg['To'] = Header('爱学习的您', 'utf-8')
msg['Subject'] = Header('如果您需要任何类别的学习资料,请联系我', 'utf-8')
try:
smtpobj = smtplib.SMTP('smtp.vipjiexi.club')
smtpobj.login('001@vipjiexi.club', 'qjp12345')
smtpobj.sendmail(sender, receiver, msg.as_string())
print('发送成功')
smtpobj.quit()
smtpobj.close()
except Exception as e:
print('{}-----出错了'.format(e))
if __name__ == '__main__':
for i in range(20):
threading.Thread(target=sendMailToOne,).start()
time.sleep(1) | [
"1694222672@qq.com"
] | 1694222672@qq.com |
255178d0466894ec672c8e0a84ade575a81e6df0 | 62050251587de5a816cb55deb20ad57be5362fa1 | /ws2812b_rmt_demo-2.py | e095922651b373cc1cc602ae80659e3748d439d7 | [] | no_license | rsp-esl/micropython_esp32_examples | 60832e7bc4a2e7864d60f96d9d523f754d7ea085 | 073222d467ae914838a0a475d07cb679f7a4ba01 | refs/heads/master | 2022-09-17T10:42:44.331333 | 2020-05-27T15:22:31 | 2020-05-27T15:22:31 | 257,871,864 | 0 | 2 | null | null | null | null | UTF-8 | Python | false | false | 955 | py | # File: rmt_ws2812b_demo-2.py
# Date: 2022-05-27
from machine import Pin
import utime as time
from ws2812b import WS2812B
WS2812B_PIN = Pin(27)
NUM_LEDS = 8
# create WS2812B object for n-pixel RGB LED strip
strip = WS2812B(pin=WS2812B_PIN,n=NUM_LEDS)
# define test colors
COLORS = [
0x3f << 16, 0x3f << 8, 0x3f,
0x3f3f00, 0x3f003f, 0x003f3f,
0x7f7f7f,(127,20,20) ]
try:
for i in range(NUM_LEDS):
strip[i] = COLORS[i]
strip.update()
time.sleep_ms(500)
# press Ctrl+C to terminate
while True: # main loop
for i in range(16):
if i < 8:
# rotate shift left
strip.shift_left()
else:
# rotate shift right
strip.shift_right()
strip.update()
time.sleep_ms(1000)
except KeyboardInterrupt:
print('Terminated...')
finally:
strip.clear()
strip.deinit() # release the RMT channel
| [
"noreply@github.com"
] | rsp-esl.noreply@github.com |
c2aea491b89982df7749eb3e86a0983090c42777 | a1ee744a2b31bd8177589924c06dcb065fe16646 | /2022/22_Monkey_Map/main.py | acb8a9528fb940c80491625ac337d2f9a7374394 | [] | no_license | claytonjwong/advent-of-code | 7cdd381698b62276ca58a6ef684c950aeb315c53 | 234298a5b6d40ef17f48065b37cbfcca70e02513 | refs/heads/master | 2023-01-27T18:33:17.558144 | 2023-01-16T17:36:51 | 2023-01-16T17:37:07 | 161,686,749 | 4 | 0 | null | null | null | null | UTF-8 | Python | false | false | 3,437 | py | #
# https://adventofcode.com/2022/day/22
#
A, dirs = [], []
with open('input.txt') as input:
for line in input:
line = list(line[:-1]) # discard trailing newline
if not len(line):
continue
elif line[0] in [' ', '.', '#']:
A.append(line)
else:
steps = 0
for c in line:
if c.isdigit():
steps = 10 * steps + int(c)
else:
if steps:
dirs.append(steps); steps = 0
dirs.append(c)
M = len(A)
N = max(len(A[i]) for i in range(M))
for row in A:
pad = [' '] * (N - len(row))
row.extend(pad)
R, D, L, U = 0, 1, 2, 3 # right, down, left, up
class Walker:
def __init__(self):
self.i = 0
self.j = A[0].index('.')
self.d = R
def turn(self, d):
if self.d == R:
if d == 'L': self.d = U
if d == 'R': self.d = D
elif self.d == D:
if d == 'L': self.d = R
if d == 'R': self.d = L
elif self.d == L:
if d == 'L': self.d = D
if d == 'R': self.d = U
elif self.d == U:
if d == 'L': self.d = L
if d == 'R': self.d = R
def walk(self, steps):
di, dj = (0, 1) if self.d == R else (1, 0) if self.d == D else (0, -1) if self.d == L else (-1, 0) # right, down, left, up
while steps:
steps -= 1
u, v = (self.i + di, self.j + dj)
if self.d == R and not self.step_R(u, v): break
if self.d == D and not self.step_D(u, v): break
if self.d == L and not self.step_L(u, v): break
if self.d == U and not self.step_U(u, v): break
def step_R(self, u, v):
if 0 <= v < N and A[u][v] == '.': # step right
self.j = v
return True
if v == N or A[u][v] == ' ': # wrap-around left
v = 0
while A[u][v] == ' ':
v += 1
if A[u][v] == '.':
self.j = v
return True
return False
def step_D(self, u, v):
if 0 <= u < M and A[u][v] == '.': # step down
self.i = u
return True
if u == M or A[u][v] == ' ': # wrap-around up
u = 0
while A[u][v] == ' ':
u += 1
if A[u][v] == '.':
self.i = u
return True
return False
def step_L(self, u, v):
if 0 <= v < N and A[u][v] == '.': # step left
self.j = v
return True
if v < 0 or A[u][v] == ' ': # wrap-around right
v = N - 1
while A[u][v] == ' ':
v -= 1
if A[u][v] == '.':
self.j = v
return True
return False
def step_U(self, u, v):
if 0 <= u < M and A[u][v] == '.': # step up
self.i = u
return True
if u < 0 or A[u][v] == ' ': # wrap-around down
u = M - 1
while A[u][v] == ' ':
u -= 1
if A[u][v] == '.':
self.i = u
return True
return False
walker = Walker()
for x in dirs:
if type(x) == int:
walker.walk(x)
else:
walker.turn(x)
part1 = (walker.i + 1) * 1000 + (walker.j + 1) * 4 + walker.d
print(f'part 1: {part1}')
# part 1: 165094 | [
"claytonjwong@gmail.com"
] | claytonjwong@gmail.com |
34da2c9efaf65c6127540f5c1078643dff788197 | bc8b15fa1e22983995063d5ddf46d58dc0a13787 | /apps/login_registration/models.py | 24fb3de4849d164b02a7086bf3e0482e53857d1e | [] | no_license | mtjhartley/new_semi_restful_routes | d8aa4e95f900d1841c46461b05940f6e3fdb883b | 44e5b7053643302489b27a529f4593420aebe516 | refs/heads/master | 2022-12-10T07:30:19.023696 | 2017-06-26T22:35:12 | 2017-06-26T22:35:12 | 95,484,930 | 0 | 0 | null | 2022-12-07T23:58:08 | 2017-06-26T20:06:52 | JavaScript | UTF-8 | Python | false | false | 4,167 | py | from __future__ import unicode_literals
from django.db import models
import datetime
import re
import bcrypt
EMAIL_REGEX = re.compile(r'^[a-zA-Z0-9.+_-]+@[a-zA-Z0-9._-]+\.[a-zA-Z]+$')
# Create your models here.
class UserManager(models.Manager):
#takes request.POST, returns loginObject. If "user" in loginObject, can proceed. Else,
#model views will handle logic to redirect to login page and render messages.
def isValidLogin(self, userInfo):
loginObject = {
"errors": []
}
if User.objects.filter(email=userInfo['email']):
hashed = User.objects.get(email=userInfo['email']).password
hashed = hashed.encode('utf-8')
password = userInfo['password']
password = password.encode('utf-8')
if bcrypt.hashpw(password, hashed) == hashed:
user = User.objects.get(email=userInfo['email'])
loginObject['user'] = user
else:
loginObject['errors'].append("Unsuccessful login, incorrect password")
else:
loginObject['errors'].append("Unsuccessful login, email does not exist.")
return loginObject
def isValidRegistration(self, userInfo):
all_users = User.objects.all()
if all_users:
admin = False
else:
admin = True
registrationObject = {
"errors": []
}
validRegistration = True
if not userInfo['first_name'].isalpha():
registrationObject['errors'].append('First name contains non-alpha character(s).')
validRegistration = False
if len(userInfo['first_name']) < 2:
registrationObject['errors'].append('First name is less than 2 char.')
validRegistration = False
if not userInfo['last_name'].isalpha():
registrationObject['errors'].append('Last name contains non-alpha character(s).')
validRegistration = False
if len(userInfo['last_name']) < 2:
registrationObject['errors'].append('Last name is less than 2 char.')
validRegistration = False
if User.objects.filter(email=userInfo['email']):
registrationObject['errors'].append("Email is already registered.")
validRegistration = False
if not EMAIL_REGEX.match(userInfo['email']):
registrationObject['errors'].append('Email is not a valid Email!')
validRegistration = False
if len(userInfo['password']) < 7:
registrationObject['errors'].append('Password is too short. Must be at least 8 char.')
validRegistration = False
if userInfo['password'] != userInfo['confirm_password']:
registrationObject['errors'].append('Passwords do not match!')
validRegistration = False
if User.objects.filter(email=userInfo['email']):
registrationObject['errors'].append("This email already exists in our database.")
validRegistration = False
'''
now = datetime.datetime.now()
birthday = datetime.datetime.strptime(userInfo['birthday'], '%Y-%m-%d')
if birthday > now:
registrationObject['errors'].append("You can't be born in the future!")
validRegistration = False
'''
if validRegistration:
hashed = bcrypt.hashpw(userInfo['password'].encode(), bcrypt.gensalt())
new_user = User.objects.create(first_name = userInfo['first_name'], last_name = userInfo['last_name'], email=userInfo['email'], password=hashed, admin=admin)
registrationObject['user'] = new_user
return registrationObject
class User(models.Model):
first_name = models.CharField(max_length=255)
last_name = models.CharField(max_length=255)
email = models.CharField(max_length=255)
password = models.CharField(max_length=60)
#birthday = models.DateField(null=True, blank=True)
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
admin = models.BooleanField(default=False)
objects = UserManager() | [
"mtjhartley@gmail.com"
] | mtjhartley@gmail.com |
fabe74c1ac07365d3462e69f8781152f04bd89d2 | 777b281b8a13eb33276023cb1fddbc41be55950f | /lib/dataset/mpii.py | f85aa17676e7d37c6b3403b647b8122ee5df71df | [
"MIT"
] | permissive | CrystalSixone/DSPNet | af0980908f5e0008b4b5499bc3092bddce4a25d5 | e82cc1938af65234471b6a139a8ac51f22de32a6 | refs/heads/main | 2023-01-03T21:59:14.891648 | 2020-10-24T02:20:21 | 2020-10-24T02:20:21 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 6,734 | py | # ------------------------------------------------------------------------------
# Copyright (c) Microsoft
# Licensed under the MIT License.
# Written by Bin Xiao (Bin.Xiao@microsoft.com)
# ------------------------------------------------------------------------------
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import logging
import os
import json_tricks as json
from collections import OrderedDict
import numpy as np
from scipy.io import loadmat, savemat
from dataset.JointsDataset import JointsDataset
logger = logging.getLogger(__name__)
class MPIIDataset(JointsDataset):
def __init__(self, cfg, root, image_set, is_train, transform=None):
super().__init__(cfg, root, image_set, is_train, transform)
self.num_joints = 16
self.flip_pairs = [[0, 5], [1, 4], [2, 3], [10, 15], [11, 14], [12, 13]]
self.parent_ids = [1, 2, 6, 6, 3, 4, 6, 6, 7, 8, 11, 12, 7, 7, 13, 14]
self.upper_body_ids = (7, 8, 9, 10, 11, 12, 13, 14, 15)
self.lower_body_ids = (0, 1, 2, 3, 4, 5, 6)
self.db = self._get_db()
if is_train and cfg.DATASET.SELECT_DATA:
self.db = self.select_data(self.db)
logger.info('=> load {} samples'.format(len(self.db)))
def _get_db(self):
file_name = os.path.join(self.root,'annot',self.image_set+'.json')
with open(file_name) as anno_file:
anno = json.load(anno_file)
gt_db = []
for a in anno:
image_name = a['image']
c = np.array(a['center'], dtype=np.float)
s = np.array([a['scale'], a['scale']], dtype=np.float)
# Adjust center/scale slightly to avoid cropping limbs
if c[0] != -1:
c[1] = c[1] + 15 * s[1]
s = s * 1.25
# MPII uses matlab format, index is based 1,
# we should first convert to 0-based index
c = c - 1
joints_3d = np.zeros((self.num_joints, 3), dtype=np.float)
joints_3d_vis = np.zeros((self.num_joints, 3), dtype=np.float)
if self.image_set != 'test':
joints = np.array(a['joints'])
joints[:, 0:2] = joints[:, 0:2] - 1
joints_vis = np.array(a['joints_vis'])
assert len(joints) == self.num_joints, \
'joint num diff: {} vs {}'.format(len(joints),
self.num_joints)
joints_3d[:, 0:2] = joints[:, 0:2]
joints_3d_vis[:, 0] = joints_vis[:]
joints_3d_vis[:, 1] = joints_vis[:]
image_dir = 'images.zip@' if self.data_format == 'zip' else 'images'
gt_db.append(
{
'image': os.path.join(self.root, image_dir, image_name),
'center': c,
'scale': s,
'joints_3d': joints_3d,
'joints_3d_vis': joints_3d_vis,
'filename': '',
'imgnum': 0,
}
)
return gt_db
def evaluate(self, cfg, preds, output_dir, *args, **kwargs):
# convert 0-based index to 1-based index
preds = preds[:, :, 0:2] + 1.0
if output_dir:
pred_file = os.path.join(output_dir, 'pred.mat')
savemat(pred_file, mdict={'preds': preds})
if 'test' in cfg.DATASET.TEST_SET:
return {'Null': 0.0}, 0.0
SC_BIAS = 0.6
threshold = 0.5
gt_file = os.path.join(cfg.DATASET.ROOT,
'annot',
'gt_{}.mat'.format(cfg.DATASET.TEST_SET))
gt_dict = loadmat(gt_file)
dataset_joints = gt_dict['dataset_joints']
jnt_missing = gt_dict['jnt_missing']
pos_gt_src = gt_dict['pos_gt_src']
headboxes_src = gt_dict['headboxes_src']
pos_pred_src = np.transpose(preds, [1, 2, 0])
head = np.where(dataset_joints == 'head')[1][0]
lsho = np.where(dataset_joints == 'lsho')[1][0]
lelb = np.where(dataset_joints == 'lelb')[1][0]
lwri = np.where(dataset_joints == 'lwri')[1][0]
lhip = np.where(dataset_joints == 'lhip')[1][0]
lkne = np.where(dataset_joints == 'lkne')[1][0]
lank = np.where(dataset_joints == 'lank')[1][0]
rsho = np.where(dataset_joints == 'rsho')[1][0]
relb = np.where(dataset_joints == 'relb')[1][0]
rwri = np.where(dataset_joints == 'rwri')[1][0]
rkne = np.where(dataset_joints == 'rkne')[1][0]
rank = np.where(dataset_joints == 'rank')[1][0]
rhip = np.where(dataset_joints == 'rhip')[1][0]
jnt_visible = 1 - jnt_missing
uv_error = pos_pred_src - pos_gt_src
uv_err = np.linalg.norm(uv_error, axis=1)
headsizes = headboxes_src[1, :, :] - headboxes_src[0, :, :]
headsizes = np.linalg.norm(headsizes, axis=0)
headsizes *= SC_BIAS
scale = np.multiply(headsizes, np.ones((len(uv_err), 1)))
scaled_uv_err = np.divide(uv_err, scale)
scaled_uv_err = np.multiply(scaled_uv_err, jnt_visible)
jnt_count = np.sum(jnt_visible, axis=1)
less_than_threshold = np.multiply((scaled_uv_err <= threshold),
jnt_visible)
PCKh = np.divide(100.*np.sum(less_than_threshold, axis=1), jnt_count)
# save
rng = np.arange(0, 0.5+0.01, 0.01)
pckAll = np.zeros((len(rng), 16))
for r in range(len(rng)):
threshold = rng[r]
less_than_threshold = np.multiply(scaled_uv_err <= threshold,
jnt_visible)
pckAll[r, :] = np.divide(100.*np.sum(less_than_threshold, axis=1),
jnt_count)
PCKh = np.ma.array(PCKh, mask=False)
PCKh.mask[6:8] = True
jnt_count = np.ma.array(jnt_count, mask=False)
jnt_count.mask[6:8] = True
jnt_ratio = jnt_count / np.sum(jnt_count).astype(np.float64)
name_value = [
('Head', PCKh[head]),
('Shoulder', 0.5 * (PCKh[lsho] + PCKh[rsho])),
('Elbow', 0.5 * (PCKh[lelb] + PCKh[relb])),
('Wrist', 0.5 * (PCKh[lwri] + PCKh[rwri])),
('Hip', 0.5 * (PCKh[lhip] + PCKh[rhip])),
('Knee', 0.5 * (PCKh[lkne] + PCKh[rkne])),
('Ankle', 0.5 * (PCKh[lank] + PCKh[rank])),
('Mean', np.sum(PCKh * jnt_ratio)),
('Mean@0.1', np.sum(pckAll[11, :] * jnt_ratio))
]
name_value = OrderedDict(name_value)
return name_value, name_value['Mean']
| [
"you@example.com"
] | you@example.com |
d2d04ec2e736b106410aec6e3f1cf8a40e3a840b | 748526cd3d906140c2975ed1628277152374560f | /B2BSWE/Primitives/isPowerOf2.py | bfd326ab508745b71729749b5d48dd20ece0bf68 | [] | no_license | librar127/PythonDS | d27bb3af834bfae5bd5f9fc76f152e13ce5485e1 | ec48cbde4356208afac226d41752daffe674be2c | refs/heads/master | 2021-06-14T10:37:01.303166 | 2021-06-11T03:39:08 | 2021-06-11T03:39:08 | 199,333,950 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 531 | py |
import math
class Solution:
def powerOfTwo(self, input):
'''
:type input: int
:rtype: bool
'''
if input <= 0:
return False
x = math.log2(input)
num = "{:.1f}".format(x)
decimal_num = num.split('.')[1]
return decimal_num == '0'
def powerOfTwo_1(self, input):
if input <= 0:
return False
return (input & (input -1)) == 0
s = Solution()
print(s.powerOfTwo(6)) | [
"librar127@gmail.com"
] | librar127@gmail.com |
82cfb880fa30a2676547051c4d517960728b2093 | b3fa4bb31add76bbff0b6f864f433ff9af7897b6 | /15.threeSum.py | 5aed0c99cb8b95952a413a89448621b7c0a709dd | [] | no_license | Aissen-Li/LeetCode | 7298225ba95d58194a5fc87c7ee3ef4d04ec4d4b | f08628e3ce639d1e3f35a2bd3af14cc2b67d7249 | refs/heads/master | 2020-12-30T08:03:17.277924 | 2020-09-25T08:20:53 | 2020-09-25T08:20:53 | 238,919,619 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 897 | py | class Solution:
def threeSum(self, nums):
n = len(nums)
if not nums or n < 3:
return []
nums.sort()
res = []
for i in range(n):
if nums[i] > 0:
return res
if i > 0 and nums[i] == nums[i - 1]:
continue
L = i + 1
R = n - 1
while L < R:
if nums[i] + nums[L] + nums[R] == 0:
res.append([nums[i], nums[L], nums[R]])
while L < R and nums[L] == nums[L + 1]:
L = L + 1
while L < R and nums[R] == nums[R - 1]:
R = R - 1
L = L + 1
R = R - 1
elif nums[i] + nums[L] + nums[R] > 0:
R = R - 1
else:
L = L + 1
return res | [
"aissen_f@163.com"
] | aissen_f@163.com |
487bdb307568cb23e3126643028eaa4294e03dab | e10a6d844a286db26ef56469e31dc8488a8c6f0e | /cache_replacement/environment/main.py | 2983e9f90eb7725c440e25f18d22c718efc03659 | [
"Apache-2.0",
"CC-BY-4.0"
] | permissive | Jimmy-INL/google-research | 54ad5551f97977f01297abddbfc8a99a7900b791 | 5573d9c5822f4e866b6692769963ae819cb3f10d | refs/heads/master | 2023-04-07T19:43:54.483068 | 2023-03-24T16:27:28 | 2023-03-24T16:32:17 | 282,682,170 | 1 | 0 | Apache-2.0 | 2020-07-26T15:50:32 | 2020-07-26T15:50:31 | null | UTF-8 | Python | false | false | 2,138 | py | # coding=utf-8
# Copyright 2022 The Google Research Authors.
#
# 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.
"""Example script for running replacement policies."""
import argparse
import belady
import config as cfg
import environment
import numpy as np
import policy
import s4lru
import tqdm
if __name__ == "__main__":
parser = argparse.ArgumentParser()
parser.add_argument("policy_type", help="type of replacement policy to use")
args = parser.parse_args()
trace_path = "traces/sample_trace.csv"
config = cfg.Config.from_files_and_bindings(["spec_llc.json"], [])
env = environment.CacheReplacementEnv(config, trace_path, 0)
if args.policy_type == "belady":
replacement_policy = belady.BeladyPolicy(env)
elif args.policy_type == "lru":
replacement_policy = policy.LRU()
elif args.policy_type == "s4lru":
replacement_policy = s4lru.S4LRU(config.get("associativity"))
elif args.policy_type == "belady_nearest_neighbors":
train_env = environment.CacheReplacementEnv(config, trace_path, 0)
replacement_policy = belady.BeladyNearestNeighborsPolicy(train_env)
elif args.policy_type == "random":
replacement_policy = policy.RandomPolicy(np.random.RandomState(0))
else:
raise ValueError(f"Unsupported policy type: {args.policy_type}")
state = env.reset()
total_reward = 0
steps = 0
with tqdm.tqdm() as pbar:
while True:
action = replacement_policy.action(state)
state, reward, done, info = env.step(action)
total_reward += reward
steps += 1
pbar.update(1)
if done:
break
print("Cache hit rate: {:.4f}".format(total_reward / steps))
| [
"copybara-worker@google.com"
] | copybara-worker@google.com |
092ea09c37d5f8ded3c80eafb8f1f4c4988bfae3 | f445450ac693b466ca20b42f1ac82071d32dd991 | /generated_tempdir_2019_09_15_163300/generated_part002097.py | 452adaeab91b29a10e3af9dbbda3125353042348 | [] | no_license | Upabjojr/rubi_generated | 76e43cbafe70b4e1516fb761cabd9e5257691374 | cd35e9e51722b04fb159ada3d5811d62a423e429 | refs/heads/master | 2020-07-25T17:26:19.227918 | 2019-09-15T15:41:48 | 2019-09-15T15:41:48 | 208,357,412 | 4 | 1 | null | null | null | null | UTF-8 | Python | false | false | 3,998 | py | from sympy.abc import *
from matchpy.matching.many_to_one import CommutativeMatcher
from matchpy import *
from matchpy.utils import VariableWithCount
from collections import deque
from multiset import Multiset
from sympy.integrals.rubi.constraints import *
from sympy.integrals.rubi.utility_function import *
from sympy.integrals.rubi.rules.miscellaneous_integration import *
from sympy import *
class CommutativeMatcher70559(CommutativeMatcher):
_instance = None
patterns = {
0: (0, Multiset({0: 1}), [
(VariableWithCount('i2.2.1.3.0', 1, 1, S(0)), Add)
]),
1: (1, Multiset({1: 1}), [
(VariableWithCount('i2.4.0', 1, 1, S(0)), Add)
])
}
subjects = {}
subjects_by_id = {}
bipartite = BipartiteGraph()
associative = Add
max_optional_count = 1
anonymous_patterns = set()
def __init__(self):
self.add_subject(None)
@staticmethod
def get():
if CommutativeMatcher70559._instance is None:
CommutativeMatcher70559._instance = CommutativeMatcher70559()
return CommutativeMatcher70559._instance
@staticmethod
def get_match_iter(subject):
subjects = deque([subject]) if subject is not None else deque()
subst0 = Substitution()
# State 70558
subst1 = Substitution(subst0)
try:
subst1.try_add_variable('i2.2.1.3.1.0_1', S(1))
except ValueError:
pass
else:
pass
# State 70560
if len(subjects) >= 1:
tmp2 = subjects.popleft()
subst2 = Substitution(subst1)
try:
subst2.try_add_variable('i2.2.1.3.1.0', tmp2)
except ValueError:
pass
else:
pass
# State 70561
if len(subjects) == 0:
pass
# 0: x*f
yield 0, subst2
subjects.appendleft(tmp2)
subst1 = Substitution(subst0)
try:
subst1.try_add_variable('i2.4.1.0_1', S(1))
except ValueError:
pass
else:
pass
# State 71673
if len(subjects) >= 1:
tmp5 = subjects.popleft()
subst2 = Substitution(subst1)
try:
subst2.try_add_variable('i2.4.1.0', tmp5)
except ValueError:
pass
else:
pass
# State 71674
if len(subjects) == 0:
pass
# 1: x*f
yield 1, subst2
subjects.appendleft(tmp5)
if len(subjects) >= 1 and isinstance(subjects[0], Mul):
tmp7 = subjects.popleft()
associative1 = tmp7
associative_type1 = type(tmp7)
subjects8 = deque(tmp7._args)
matcher = CommutativeMatcher70563.get()
tmp9 = subjects8
subjects8 = []
for s in tmp9:
matcher.add_subject(s)
for pattern_index, subst1 in matcher.match(tmp9, subst0):
pass
if pattern_index == 0:
pass
# State 70564
if len(subjects) == 0:
pass
# 0: x*f
yield 0, subst1
if pattern_index == 1:
pass
# State 71675
if len(subjects) == 0:
pass
# 1: x*f
yield 1, subst1
subjects.appendleft(tmp7)
return
yield
from matchpy.matching.many_to_one import CommutativeMatcher
from .generated_part002098 import *
from collections import deque
from matchpy.utils import VariableWithCount
from multiset import Multiset | [
"franz.bonazzi@gmail.com"
] | franz.bonazzi@gmail.com |
af465b9c4bbf6fb6244987a2abd33838a930b1f7 | ebc7607785e8bcd6825df9e8daccd38adc26ba7b | /python/baekjoon/2.algorithm/sort/11650.좌표 정렬하기.py | 3e325291e776b19d22a4a7b48e7d9eef1090dc9f | [] | no_license | galid1/Algorithm | 18d1b72b0d5225f99b193e8892d8b513a853d53a | 5bd69e73332f4dd61656ccdecd59c40a2fedb4b2 | refs/heads/master | 2022-02-12T07:38:14.032073 | 2022-02-05T08:34:46 | 2022-02-05T08:34:46 | 179,923,655 | 3 | 0 | null | 2019-06-14T07:18:14 | 2019-04-07T05:49:06 | Python | UTF-8 | Python | false | false | 1,724 | py | # JAVA
# package com.example.java_study;
#
# import java.io.BufferedReader;
# import java.io.IOException;
# import java.io.InputStreamReader;
# import java.util.*;
#
# public class Main {
#
# public static int n;
# public static int[][] cs;
#
# public static void solve() {
# Arrays.stream(cs)
# .sorted((c1, c2) -> {
# if (c1[0] <= c2[0]) {
# if (c1[0] == c2[0]) {
# return c1[1] - c2[1];
# }
# return -1;
# } else {
# return 1;
# }
# })
# .forEach(coords -> {
# System.out.println(coords[0] + " " + coords[1]);
# });
#
#
# }
#
# public static void main(String[] args) throws IOException {
# BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
# StringTokenizer st = null;
#
# n = Integer.parseInt(br.readLine());
# cs = new int[n][2];
#
# for(int i = 0; i < n; i++) {
# st = new StringTokenizer(br.readLine());
# cs[i][0] = Integer.parseInt(st.nextToken());
# cs[i][1] = Integer.parseInt(st.nextToken());
# }
#
# solve();
#
# // 5
# // 3 4
# // 1 1
# // 1 -1
# // 2 2
# // 3 3
# }
# }
import sys
def solve():
global n, cs
cs.sort(key=lambda item: (item[0], item[1]))
for x, y in cs:
print(x, y)
n = int(sys.stdin.readline().strip())
cs = []
for _ in range(n):
cs.append(list(map(int, sys.stdin.readline().strip().split(" "))))
solve() | [
"galid1@naver.com"
] | galid1@naver.com |
bb4f0d486ca028b69cc5a9b45653e9d13b67f82d | 153ec5496256058d89587c001aea5ce3a6a8d523 | /tranquil-beach/design/hit_counter.py | 27cb85ac5de99ea260d2ae9d2991dfb57d71cc02 | [] | no_license | yokolet/tranquil-beach-python | 50911147b560385e2f93efb148e5adb0fb6dbe8b | e7f486114df17918e49d6452c7047c9d90e8aef2 | refs/heads/master | 2021-08-22T15:28:02.096061 | 2020-04-29T03:34:19 | 2020-04-29T05:01:11 | 175,543,623 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 702 | py | class HitCounter:
def __init__(self):
"""
Initialize your data structure here.
"""
self.timestamps = [] # queue
def hit(self, timestamp: int) -> None:
"""
Record a hit.
@param timestamp - The current timestamp (in seconds granularity).
"""
self.timestamps.append(timestamp)
def getHits(self, timestamp: int) -> int:
"""
Return the number of hits in the past 5 minutes.
@param timestamp - The current timestamp (in seconds granularity).
"""
while self.timestamps and self.timestamps[0] <= timestamp - 300:
self.timestamps.pop(0)
return len(self.timestamps)
| [
"yokolet@gmail.com"
] | yokolet@gmail.com |
1e5c56752fcd2c8d921c64f800968fe300259eec | 15e6385746ccf4b8eb6c6e302aca236021bb8781 | /pythonPart/le8_stringToInteger.py | bef8c255655d63b43f844a2ed8fde2329bf62b92 | [] | no_license | akb46mayu/Data-Structures-and-Algorithms | 11c4bbddc9b4d286e1aeaa9481eb6a620cd54746 | de98494e14fff3e2a468da681c48d60b4d1445a1 | refs/heads/master | 2021-01-12T09:51:32.618362 | 2018-05-16T16:37:18 | 2018-05-16T16:37:18 | 76,279,268 | 3 | 0 | null | null | null | null | UTF-8 | Python | false | false | 536 | py | class Solution(object):
def myAtoi(self, str):
"""
:type str: str
:rtype: int
"""
s = str
if len(s) == 0: return 0
ls = list(s.strip())
sign = -1 if ls[0] == '-' else 1
if ls[0] in ['+', '-']: del(ls[0])
res, i = 0, 0
maxval = 2**31 - 1
minval = -2**31
n = len(ls)
while i < n and ls[i].isdigit():
res = res * 10 + ord(ls[i]) - ord('0')
i += 1
return max(minval, min(sign * res, maxval))
| [
"noreply@github.com"
] | akb46mayu.noreply@github.com |
41a5d17f5ff6f87d15a77667d46606d940268829 | 01926621374435f7daf622f1ef04a51f94e3e883 | /litex/soc/cores/pwm.py | 842f24d554f89887340f66ce6b97a104904f54b9 | [
"BSD-3-Clause",
"BSD-2-Clause"
] | permissive | betrusted-io/litex | d717513e41ff6aba54ac172e886c21479aa41752 | 8109a8e91ca8321483ccc2f58bd4fed5379bbd18 | refs/heads/master | 2022-11-23T07:11:35.297128 | 2022-02-22T11:55:00 | 2022-02-22T11:55:00 | 231,203,917 | 3 | 0 | NOASSERTION | 2020-01-01T10:48:06 | 2020-01-01T10:48:05 | null | UTF-8 | Python | false | false | 2,638 | py | #
# This file is part of LiteX.
#
# Copyright (c) 2015-2019 Florent Kermarrec <florent@enjoy-digital.fr>
# SPDX-License-Identifier: BSD-2-Clause
from migen import *
from migen.genlib.cdc import MultiReg
from litex.soc.interconnect.csr import *
# Pulse Width Modulation ---------------------------------------------------------------------------
class PWM(Module, AutoCSR):
"""Pulse Width Modulation
Provides the minimal hardware to do Pulse Width Modulation.
Pulse Width Modulation can be useful for various purposes: dim leds, regulate a fan, control
an oscillator. Software can configure the PWM width and period and enable/disable it.
"""
def __init__(self, pwm=None, clock_domain="sys", with_csr=True,
default_enable = 0,
default_width = 0,
default_period = 0):
if pwm is None:
self.pwm = pwm = Signal()
self.enable = Signal(reset=default_enable)
self.width = Signal(32, reset=default_width)
self.period = Signal(32, reset=default_period)
# # #
counter = Signal(32, reset_less=True)
sync = getattr(self.sync, clock_domain)
sync += [
If(self.enable,
counter.eq(counter + 1),
If(counter < self.width,
pwm.eq(1)
).Else(
pwm.eq(0)
),
If(counter >= (self.period - 1),
counter.eq(0)
)
).Else(
counter.eq(0),
pwm.eq(0)
)
]
if with_csr:
self.add_csr(clock_domain)
def add_csr(self, clock_domain):
self._enable = CSRStorage(description="""PWM Enable.\n
Write ``1`` to enable PWM.""",
reset = self.enable.reset)
self._width = CSRStorage(32, reset_less=True, description="""PWM Width.\n
Defines the *Duty cycle* of the PWM. PWM is active high for *Width* ``{cd}_clk`` cycles and
active low for *Period - Width* ``{cd}_clk`` cycles.""".format(cd=clock_domain),
reset = self.width.reset)
self._period = CSRStorage(32, reset_less=True, description="""PWM Period.\n
Defines the *Period* of the PWM in ``{cd}_clk`` cycles.""".format(cd=clock_domain),
reset = self.period.reset)
n = 0 if clock_domain == "sys" else 2
self.specials += [
MultiReg(self._enable.storage, self.enable, n=n),
MultiReg(self._width.storage, self.width, n=n),
MultiReg(self._period.storage, self.period, n=n),
]
| [
"florent@enjoy-digital.fr"
] | florent@enjoy-digital.fr |
922f5b09c5963a6fd34c2599cd446d9543e37383 | 32eeb97dff5b1bf18cf5be2926b70bb322e5c1bd | /benchmark/hackernews/testcase/firstcases/testcase8_021.py | 98d1969d272766b7e444194aa1fc4f50bbc714c4 | [] | no_license | Prefest2018/Prefest | c374d0441d714fb90fca40226fe2875b41cf37fc | ac236987512889e822ea6686c5d2e5b66b295648 | refs/heads/master | 2021-12-09T19:36:24.554864 | 2021-12-06T12:46:14 | 2021-12-06T12:46:14 | 173,225,161 | 5 | 0 | null | null | null | null | UTF-8 | Python | false | false | 3,152 | py | #coding=utf-8
import os
import subprocess
import time
import traceback
from appium import webdriver
from appium.webdriver.common.touch_action import TouchAction
from selenium.common.exceptions import NoSuchElementException, WebDriverException
desired_caps = {
'platformName' : 'Android',
'deviceName' : 'Android Emulator',
'platformVersion' : '4.4',
'appPackage' : 'io.dwak.holohackernews.app',
'appActivity' : 'io.dwak.holohackernews.app.ui.storylist.MainActivity',
'resetKeyboard' : True,
'androidCoverage' : 'io.dwak.holohackernews.app/io.dwak.holohackernews.app.JacocoInstrumentation',
'noReset' : True
}
def command(cmd, timeout=5):
p = subprocess.Popen(cmd, stderr=subprocess.STDOUT, stdout=subprocess.PIPE, shell=True)
time.sleep(timeout)
p.terminate()
return
def getElememt(driver, str) :
for i in range(0, 5, 1):
try:
element = driver.find_element_by_android_uiautomator(str)
except NoSuchElementException:
time.sleep(1)
else:
return element
os.popen("adb shell input tap 50 50")
element = driver.find_element_by_android_uiautomator(str)
return element
def getElememtBack(driver, str1, str2) :
for i in range(0, 2, 1):
try:
element = driver.find_element_by_android_uiautomator(str1)
except NoSuchElementException:
time.sleep(1)
else:
return element
for i in range(0, 5, 1):
try:
element = driver.find_element_by_android_uiautomator(str2)
except NoSuchElementException:
time.sleep(1)
else:
return element
os.popen("adb shell input tap 50 50")
element = driver.find_element_by_android_uiautomator(str2)
return element
def swipe(driver, startxper, startyper, endxper, endyper) :
size = driver.get_window_size()
width = size["width"]
height = size["height"]
try:
driver.swipe(start_x=int(width * startxper), start_y=int(height * startyper), end_x=int(width * endxper),
end_y=int(height * endyper), duration=2000)
except WebDriverException:
time.sleep(1)
driver.swipe(start_x=int(width * startxper), start_y=int(height * startyper), end_x=int(width * endxper),
end_y=int(height * endyper), duration=2000)
return
# testcase021
try :
starttime = time.time()
driver = webdriver.Remote('http://localhost:4723/wd/hub', desired_caps)
element = getElememtBack(driver, "new UiSelector().text(\"37 comments\")", "new UiSelector().className(\"android.widget.TextView\").instance(7)")
TouchAction(driver).tap(element).perform()
element = getElememt(driver, "new UiSelector().resourceId(\"com.android.browser:id/lock\").className(\"android.widget.ImageView\")")
TouchAction(driver).tap(element).perform()
except Exception, e:
print 'FAIL'
print 'str(e):\t\t', str(e)
print 'repr(e):\t', repr(e)
print traceback.format_exc()
else:
print 'OK'
finally:
cpackage = driver.current_package
endtime = time.time()
print 'consumed time:', str(endtime - starttime), 's'
command("adb shell am broadcast -a com.example.pkg.END_EMMA --es name \"8_021\"")
jacocotime = time.time()
print 'jacoco time:', str(jacocotime - endtime), 's'
driver.quit()
if (cpackage != 'io.dwak.holohackernews.app'):
cpackage = "adb shell am force-stop " + cpackage
os.popen(cpackage) | [
"prefest2018@gmail.com"
] | prefest2018@gmail.com |
afc72a95d33a18debe5ab8215d2980fedbec85a1 | b6472217400cfce4d12e50a06cd5cfc9e4deee1f | /sites/top/api/rest/ShoprecommendShopsGetRequest.py | f3f3da331ad55779252f48bdbb7fced2789a176c | [] | no_license | topwinner/topwinner | 2d76cab853b481a4963826b6253f3fb0e578a51b | 83c996b898cf5cfe6c862c9adb76a3d6a581f164 | refs/heads/master | 2021-01-22T22:50:09.653079 | 2012-08-26T19:11:16 | 2012-08-26T19:11:16 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 357 | py | '''
Created by auto_sdk on 2012-08-26 16:43:44
'''
from top.api.base import RestApi
class ShoprecommendShopsGetRequest(RestApi):
def __init__(self,domain,port):
RestApi.__init__(self,domain, port)
self.count = None
self.ext = None
self.recommend_type = None
self.seller_id = None
def getapiname(self):
return 'taobao.shoprecommend.shops.get'
| [
"timo.jiang@qq.com"
] | timo.jiang@qq.com |
e25ec3eb506fc11242a235ac89c9295b7aeed705 | 86cc17a69213569af670faed7ad531cb599b960d | /play22.py | 96fff41800364d84c655379bd4c5eb33385b96a4 | [] | no_license | LakshmikanthRavi/guvi-lux | ed1c389e27a9ec62e0fd75c140322563f68d311a | 5c29f73903aa9adb6484c76103edf18ac165259e | refs/heads/master | 2020-04-15T05:07:19.743874 | 2019-08-13T08:53:00 | 2019-08-13T08:53:00 | 164,409,489 | 0 | 1 | null | null | null | null | UTF-8 | Python | false | false | 151 | py | v,m=map(int,input().split())
li=[]
for i in range(1,m+1):
if v%i==0 and m%i==0:
li.append(i)
if len(li)==1:
print(*li)
else:
print(*li[-1:])
| [
"noreply@github.com"
] | LakshmikanthRavi.noreply@github.com |
ffdaa560ee5d9baf3b364e2960e1937347afdaa3 | ca7aa979e7059467e158830b76673f5b77a0f5a3 | /Python_codes/p02381/s394317702.py | 6be196429fcf9dbcdbf915b34a91ab62c14a1b5e | [] | no_license | Aasthaengg/IBMdataset | 7abb6cbcc4fb03ef5ca68ac64ba460c4a64f8901 | f33f1c5c3b16d0ea8d1f5a7d479ad288bb3f48d8 | refs/heads/main | 2023-04-22T10:22:44.763102 | 2021-05-13T17:27:22 | 2021-05-13T17:27:22 | 367,112,348 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 234 | py | import math
while True:
n=int(input())
if n==0:
break
s=list(map(int,input().split()))
m=sum(s)/n
S=0
for i in range(n):
S+=(s[i]-m)**2
a2=math.sqrt(S/n)
print('{:.8f}'.format(a2))
| [
"66529651+Aastha2104@users.noreply.github.com"
] | 66529651+Aastha2104@users.noreply.github.com |
0436bf1993de7c49358a1def27e9475d4a47878b | 2d4240a03bfa47386677a78250df220c55a7bf6c | /PythonStandardLibrary/itertools11.py | 95d1ca9ae99eb8c809a9a0c1b092c83f707685c5 | [] | no_license | Falonie/Notes | c7976e9e7514e5d7cddf918c3c54442a89532aab | 38e980cb5170a696626085b72795a096679e972b | refs/heads/master | 2022-02-13T11:20:39.613115 | 2019-09-02T01:07:27 | 2019-09-02T01:07:27 | 99,218,947 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 218 | py | from itertools import accumulate
from operator import mul
a = [3, 4, 6, 2, 1, 9, 1, 7, 5, 8]
print(list(accumulate(a, max)))
print(list(accumulate(a,min)))
print(list(accumulate(a)))
print(list(accumulate(a,mul))) | [
"541002901@qq.com"
] | 541002901@qq.com |
6643e993132ac4719ee45f52a4fefe2f8cb75fcf | b834dda071bbe33db47c06e4281d6203ad5e4d4d | /tests/conftest.py | 87ed9b0cbdb98c40e1ddf00cbb3d485633c1f6d6 | [
"BSD-2-Clause"
] | permissive | revolter/invocations | 80caf5e7024379260f710187a166509c1aaaed03 | 07be47051407db4fc5ba4ae03945e75ece593e46 | refs/heads/master | 2023-03-08T10:07:28.305372 | 2020-04-24T22:39:56 | 2020-04-24T22:39:56 | 285,869,144 | 0 | 0 | BSD-2-Clause | 2020-08-07T16:02:19 | 2020-08-07T16:02:18 | null | UTF-8 | Python | false | false | 498 | py | from mock import Mock
from pytest import fixture
from invoke import MockContext, Result
# TODO: figure out how to distribute it in a way not requiring non-testing
# users to have mock installed?!
@fixture
def ctx():
# TODO: make MockContext more usable in a "don't care about results" mode
# NOTE: this is ugly but whatever.
MockContext.run_command = property(lambda self: self.run.call_args[0][0])
mc = MockContext(run=Result())
mc._set(run=Mock(wraps=mc.run))
yield mc
| [
"jeff@bitprophet.org"
] | jeff@bitprophet.org |
49280ec64484a56923af0285dda8242019893f40 | b47c136e077f5100478338280495193a8ab81801 | /Lights/adafruit-circuitpython-bundle-6.x-mpy-20210310/examples/htu31d_simpletest.py | 8aced3ed9a6e2ecc60ae5ef59e07bc900c560eec | [
"Apache-2.0"
] | permissive | IanSMoyes/SpiderPi | 22cd8747cc389f674cc8d95f32b4d86f9b7b2d8e | cc3469980ae87b92d0dc43c05dbd579f0fa8c4b1 | refs/heads/master | 2023-03-20T22:30:23.362137 | 2021-03-12T17:37:33 | 2021-03-12T17:37:33 | 339,555,949 | 16 | 2 | null | null | null | null | UTF-8 | Python | false | false | 641 | py | # SPDX-FileCopyrightText: Copyright (c) 2020 ladyada for Adafruit Industries
#
# SPDX-License-Identifier: MIT
import time
import busio
import board
import adafruit_htu31d
i2c = busio.I2C(board.SCL, board.SDA)
htu = adafruit_htu31d.HTU31D(i2c)
print("Found HTU31D with serial number", hex(htu.serial_number))
htu.heater = True
print("Heater is on?", htu.heater)
htu.heater = False
print("Heater is on?", htu.heater)
while True:
temperature, relative_humidity = htu.measurements
print("Temperature: %0.1f C" % temperature)
print("Humidity: %0.1f %%" % relative_humidity)
print("")
time.sleep(1)
| [
"ians.moyes@gmail.com"
] | ians.moyes@gmail.com |
728bd4678275f71a76e178d83c68245ce54754c3 | 2c4efe2ce49a900c68348f50e71802994c84900a | /braindecode/braindecode/venv1/Lib/site-packages/numba/macro.py | 1b5c5020756b4ba4341455d2db174b4e5f09e18e | [
"BSD-3-Clause",
"BSD-2-Clause"
] | permissive | sisi2/Masterthesis | b508632526e82b23c2efb34729141bfdae078fa0 | 7ce17644af47db4ad62764ed062840a10afe714d | refs/heads/master | 2022-11-19T15:21:28.272824 | 2018-08-13T15:02:20 | 2018-08-13T15:02:20 | 131,345,102 | 2 | 1 | null | 2022-11-15T14:08:07 | 2018-04-27T21:09:21 | Python | UTF-8 | Python | false | false | 238 | py | """
Macro handling.
Macros are expanded on block-by-block
"""
from __future__ import absolute_import, print_function, division
# Expose the Macro object from the corresponding IR rewrite pass
from .rewrites.macros import Macro
| [
"dansyefila@gmail.com"
] | dansyefila@gmail.com |
a3849b47ff857c57b806d2cc30f90afdb5bceff3 | a32ca3544bb5a587e5fd7aaa1c73ac0fb918f11e | /hypha/apply/projects/migrations/0051_remove_unnecessary_fields_from_invoice.py | 11ad637d548ba6d70e8286efcb3f98d24703c04d | [
"BSD-3-Clause"
] | permissive | jvasile/hypha | 87904bf514e7cf5af63c7146eaaa49d3611fd57f | b5ccad20dd3434f53a2b9d711fac510124c70a6e | refs/heads/main | 2023-07-08T04:10:08.233259 | 2023-06-20T05:35:29 | 2023-06-20T05:35:29 | 354,630,183 | 0 | 0 | BSD-3-Clause | 2021-04-04T19:32:38 | 2021-04-04T19:32:38 | null | UTF-8 | Python | false | false | 559 | py | # Generated by Django 3.2.12 on 2022-04-12 05:32
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('application_projects', '0050_add_new_invoice_status'),
]
operations = [
migrations.RemoveField(
model_name='invoice',
name='amount',
),
migrations.RemoveField(
model_name='invoice',
name='date_from',
),
migrations.RemoveField(
model_name='invoice',
name='date_to',
),
]
| [
"frjo@xdeb.org"
] | frjo@xdeb.org |
47674fd62d2ace70412aa6779f84bb9d0f8365db | f31285f1adf3a0c83120c2a8f91ac5ef6f5f0b8b | /mapped_seq.py | 06e0b3f44f4c828acd09cc3be5f6f6e380a2cf69 | [
"BSD-2-Clause"
] | permissive | RobinQi/BioUtils | 1596cc1cec382567459d13d9e57a97099dbce76d | 72693760620b8afb1797fd9f23e1540a194ef929 | refs/heads/master | 2021-01-13T06:12:55.111042 | 2014-07-21T18:02:45 | 2014-07-21T18:02:45 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 928 | py | '''The script reads alignment results from BLAT in PSL format and print out
sequences of those sequences in FASTA format.
'''
import sys
from Bio import SeqIO
def parse_mapped(pslfile):
mapped = set()
for line in open(pslfile):
name = line.strip().split()[9]
mapped.add(name)
return mapped
def select_seq(mapped_seqs, fasta_file):
for n, record in enumerate(SeqIO.parse(fasta_file, 'fasta'), start=1):
if record.id in mapped_seqs:
yield record
if n % 1000 == 0:
print >> sys.stderr, '...', n
if __name__=='__main__':
try:
pslfile = sys.argv[1]
fastafile = sys.argv[2]
except IndexError:
print >> sys.stderr, 'unmapped_seq.py <psl file> <fasta file>'
mapped_seqs = parse_mapped(pslfile)
print >> sys.stderr, 'Writing mapped sequences ...'
SeqIO.write(select_seq(mapped_seqs, fastafile), sys.stdout, 'fasta')
| [
"preeyano@msu.edu"
] | preeyano@msu.edu |
83ee80ed3aa2386cdadbb452e5bd1bde0eb0132f | b7125b27e564d2cc80a2ce8d0a6f934aa22c8445 | /.history/sudoku_20201029173348.py | 170f8373b1fe8c995bffecf90df6f9e77570601f | [] | no_license | JensVL96/Puzzle-solver-for-fun | 4c15dcd570c3705b7ac555efb56b52913e81083c | 6d8a4378a480372213a596a336a4deca727a00fc | refs/heads/master | 2021-07-15T05:19:42.185495 | 2020-11-08T13:59:49 | 2020-11-08T13:59:49 | 224,855,888 | 1 | 0 | null | null | null | null | UTF-8 | Python | false | false | 6,881 | py | # -*- coding: utf-8 -*-
from __future__ import print_function
import pygame as pg
from random import sample
from pyglet.gl import *
from string import *
import numpy as np
class create_board():
def __init__(self):
self.base = 3 # Will generate any size of random sudoku board in O(n^2) time
self.side = self.base * self.base
self.nums = sample(range(1, self.side + 1), self.side) # random numbers
self.board = [[self.nums[(self.base * (r%self.base) + r//self.base + c)%self.side] for c in range(self.side) ] for r in range(self.side)]
rows = [ r for g in sample(range(self.base),self.base) for r in sample(range(g * self.base,(g + 1) * self.base), self.base) ]
cols = [ c for g in sample(range(self.base),self.base) for c in sample(range(g * self.base,(g + 1) * self.base), self.base) ]
self.board = [[self.board[r][c] for c in cols] for r in rows]
# print("\nInput:")
# for line in self.board: print(line)
squares = self.side * self.side
empties = squares * 3//4
for p in sample(range(squares),empties):
self.board[p//self.side][p%self.side] = 0
self.lines()
def expandLine(self, line):
return line[0]+line[5:9].join([line[1:5]*(self.base-1)]*self.base)+line[9:13]
def lines(self):
self.line0 = self.expandLine("╔═══╤═══╦═══╗")
self.line1 = self.expandLine("║ . │ . ║ . ║")
self.line2 = self.expandLine("╟───┼───╫───╢")
self.line3 = self.expandLine("╠═══╪═══╬═══╣")
self.line4 = self.expandLine("╚═══╧═══╩═══╝")
self.draw()
def draw(self):
symbol = " 1234567890ABCDEFGHIJKLMNOPQRSTUVWXYZ"
self.nums = [ [""]+[symbol[n] for n in row] for row in self.board ]
print(self.line0)
for r in range(1,self.side+1):
print( "".join(n+s for n,s in zip(self.nums[r-1],self.line1.split("."))) )
print([self.line2,self.line3,self.line4][(r%self.side==0)+(r%self.base==0)])
class solve_board():
def __init__(self, board):
self.row = []
self.col = []
self.cell = []
self.row_list = []
self.col_list = []
self.cell_list = []
for space in range(9):
self.col.append([])
self.cell.append([])
row_idx = 0
for line in board:
self.row.append(line)
cell_idx = 0
if row_idx >= 3:
cell_idx = 3
if row_idx >= 6:
cell_idx = 6
for col_idx in range(9):
self.col[col_idx].insert(row_idx, line[col_idx])
if col_idx % 3 == 0:
for triple in range(0, 3):
self.cell[cell_idx].insert(len(self.cell[row_idx]) + triple, line[col_idx + triple])
cell_idx += 1
self.row_list.append(self.row)
self.col_list.append(self.col)
self.cell_list.append(self.cell)
row_idx += 1
print("\nrow:")
for row in self.row_list[0]:
print(row)
# print("\ncolumn:")
# for col in self.col_list[0]:
# print(col)
# print("\ncell:")
# for cell in self.cell_list[0]:
# print(cell)
def assign_flags(self, board):
self.flags = []
row_idx = 0
cell_idx = 0
print("\n")
for line in board:
cell_idx = 0
if row_idx >= 3:
cell_idx = 3
if row_idx >= 6:
cell_idx = 6
for index in range(9):
# print("position: ", index, "value: ", line[index])
# print("row", row_idx, "col", index, "cell", cell_idx)
if (index % 3 == 0 and index != 0):
cell_idx += 1
if line[index] == 0:
flag_idx = 0
temp_flag = []
for value in range(1, 10):
# print(value)
if self.row_flag(value, row_idx):
# print("found in row")
pass
elif self.col_flag(value, index):
# print("found in column")
pass
elif self.cell_flag(value, cell_idx):
# print("found in cell")
pass
else:
temp_flag.append(value)
flag_idx += 1
print(temp_flag)
self.flags.append(temp_flag)
row_idx += 1
def check_row(self):
pass
def column(self, x):
pass
def cell(self, row, col):
pass
def row_flag(self, index, row_idx):
for row in self.row_list[0][row_idx]:
# print("comparing in row ", row, "with ", index, "row_idx ", row_idx)
if row == index:
return 1
return 0
def col_flag(self, index, col_idx):
for col in self.col_list[0][col_idx]:
# print("comparing in column ", col, "with ", index, "col_idx ", col_idx)
if col == index:
return 1
return 0
def cell_flag(self, index, cell_idx):
for cell in self.cell_list[0][cell_idx]:
# print("comparing in cell ", cell, "with ", index, "cell_idx ", cell_idx)
if cell == index:
return 1
return 0
class Display_board(pyglet.window.Window):
def __init__(self, *args):
super().__init__(*args)
# Set window size
self.set_minimum_size(700,700)
# Set background color
background_color = [255, 255, 255, 255]
background_color = [i / 255 for i in background_color]
gClearColor(*background_color)
def on_key_press(self, symbol, modifier):
pass
def on_key_release(self, symbol, modifier):
pass
def on_mouse_press(self, symbol, modifier):
pass
def on_draw(self, symbol, modifier):
pass
def update(self, symbol, modifier):
pass
# Start the main window and start a timer to hit the update method
frame_rate = 30
class Main():
def __init__(self):
self.board = []
self.run()
def run(self):
self.board = create_board().board
self.solution = solve_board(self.board)
self.solution.assign_flags(self.board)
if __name__ == '__main__':
window = Display_board(700, 700, "sudoku")
pyglet.clock.schedule_interval(window.update, 2/ frame_rate)
pyglet.app.run()
Main()
| [
"jle040@uit.no"
] | jle040@uit.no |
60df77afdc909e5419af996727a7299b127ba7c4 | a0556d5e8368bf171b9019aba03e65b06e8c12e4 | /secao20_testes_python/intro_unittest.py | dad9e905e5ddc211815850549a3b2359e387fb5b | [] | no_license | RianMarlon/Python-Geek-University | f1c9db588f23ce8e6699d1352ebfb3428e0ab1ec | 3be7ec5c35bf74b1b2152de63db95bee33ee1719 | refs/heads/master | 2020-06-25T04:41:52.911513 | 2020-02-01T16:18:35 | 2020-02-01T16:18:35 | 199,204,603 | 23 | 8 | null | null | null | null | UTF-8 | Python | false | false | 1,586 | py | """
Introdução ao móduo Unittest
Unittest -> Testes Unitários
O que são testes unitários?
Teste é a forma de se testar unidades individuais do código fonte
Unidades individuais podem ser: funções, métodos, classes, módulos e etc.
# OBS: Testes unitários não são específics da linguagem Python.
Para criar nossos testes, criamos classes que herdam do unittest.TestCase
e a partir de então ganhamos todos os 'assertions' presentes no módulo.
Para rodar os testes, utilizamos unittest.main()
TestCase -> Casos de teste para a sua unidade
# Conhecendo as assertions
https://docs.python.org/3/library/unittest.html
Método Checa se
assertEqual(a, b) a == b
assertNotEqual(a, b) a != b
assertTrue(x) x é verdadeiro
assertFalse(x) x é falso
assertIs(a, b) a é b
assertIsNot(a, b) a não é b
assertIsNone(x) x é None
assertIsNotNone(x) x não é None
assertIn(a, b) a está em b
assertNotIn(a, b) a não está em b
assertIsInstance(a, b) a é instância de b
assertNotIsInstance(a, b) a não é instância de b
Por convenção, todos os teste em um test case, devem ter seu nome iniciado
com test_
# Para executar os testes com unittest
python nome_do_modulo.py
# Para executar os testes com unnitest no modo verboso
python nome_do_modulo.py -v
# Docstrings nos testes
Podemos acrescentar (e é recomendado) docstrings em nossos testes.
"""
# Prática - Utilizando a abordagem TDD
| [
"rianmarlon20@yahoo.com"
] | rianmarlon20@yahoo.com |
20c5c2b53a0eddde92dfeb705345c3b7415da96d | 1322ae1334af76643e108e78495e05538b0d7834 | /test/preprocess_test.py | b21b3687c61feec41e9de60f1fb8f2e6081bc0e6 | [] | no_license | kimsoosoo0928/chatbot02 | 47d34d6e6ac75b86930b1840337d17f4e487df26 | 222e75023391f1d4cd486680d8abaa1300a72453 | refs/heads/main | 2023-06-08T02:22:25.862407 | 2021-07-04T00:28:02 | 2021-07-04T00:28:02 | 381,740,443 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 626 | py | from utils.Preprocess import Preprocess
from tensorflow.keras import preprocessing
sent = "내일 오전 10시에 짬뽕 주문하고 싶어ㅋㅋ"
p = Preprocess(word2index_dic='../train_tools/dict/chatbot_dict.bin',
userdic = '../utils/user_dic.tsv')
pos = p.pos(sent)
keywords = p.get_keywords(pos, without_tag=False)
print(keywords)
# w2i = p.get_wordidx_sequence(keywords)
# sequences = [w2i]
#
# MAX_SEQ_LEN = 15 # 임베딩 벡터 크기
# padded_seqs = preprocessing.sequence.pad_sequences(sequences, maxlen=MAX_SEQ_LEN, padding='post')
#
# print(keywords)
# print(sequences)
# print(padded_seqs) | [
"kimsoosoo0928@gmail.com"
] | kimsoosoo0928@gmail.com |
3c57c45a3312ed022a7054e73f8fd40267221ab7 | 509fc176af52f46ce62f54a6f63c7c27b1bd0c2c | /djangofiltertest/djangofiltertest/apps/posts/migrations/0002_job_title.py | 46caade00daf9756946303a0eb4bb0a31d5664eb | [
"MIT"
] | permissive | gonzaloamadio/django-filter-test | 8b16fdb989a8141ba5852cd4804148cb6b153e86 | 7b9dbc36ca248e2113deaac03e824b123a31a4ba | refs/heads/master | 2022-12-10T11:35:07.684916 | 2019-01-24T09:19:21 | 2019-01-24T09:19:21 | 167,159,577 | 0 | 0 | MIT | 2022-12-08T01:33:33 | 2019-01-23T09:54:40 | Python | UTF-8 | Python | false | false | 453 | py | # Generated by Django 2.0 on 2019-01-24 08:01
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('posts', '0001_initial'),
]
operations = [
migrations.AddField(
model_name='job',
name='title',
field=models.CharField(db_index=True, default='asd', max_length=128, verbose_name='name'),
preserve_default=False,
),
]
| [
"gonzaloamadio@gmail.com"
] | gonzaloamadio@gmail.com |
07d011bae38803dbb97917a30438280459506518 | 8cfcfc59bfcf4255954ebac81d6bb9c183c407e7 | /orders/migrations/0006_alter_person_user.py | 87ebf260909b8dc6fb3d3e1eb129ed4193b405b7 | [] | no_license | elisaZeneli/OrderPlacement | 4928e61e1a60ea992571709e526c50ce4c8deffe | 581d06ec4ddab9a0afe9bdc28d9efe8e8d801b87 | refs/heads/main | 2023-07-24T13:37:04.613726 | 2021-07-16T20:44:26 | 2021-07-16T20:44:26 | 386,264,890 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 406 | py | # Generated by Django 3.2.5 on 2021-07-15 21:06
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('orders', '0005_alter_person_user'),
]
operations = [
migrations.AlterField(
model_name='person',
name='user',
field=models.CharField(blank=True, max_length=100, null=True),
),
]
| [
"you@example.com"
] | you@example.com |
abb6ccb0fe0cc0e772bd2d54cb73fd93c0131ac4 | 5fee6afe91711fbb1ca87845f502776fbfab7851 | /examples/contoursSSEDemo.py | b62444dff30e3d02184741940dc6fbfc1a7a247c | [
"MIT"
] | permissive | chenxofhit/pyprobml | f66ad4c1186f0ba22e520e14700ac0bd6fee400d | fe48d6111bd121e01cfbdefe3361a993fa14abe1 | refs/heads/master | 2021-01-24T09:39:29.828935 | 2016-09-17T03:34:59 | 2016-09-17T03:34:59 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 969 | py | #!/usr/bin/env python3
# Error surface for linear regression model.
import matplotlib.pyplot as pl
import numpy as np
import utils.util as util
from mpl_toolkits.mplot3d import Axes3D
def contoursSSEDemo():
N = 21
x,y,_,_,_,_ = util.poly_data_make(sampling='thibaux', n=N)
X = util.add_ones(x)
return X,y
if __name__ == '__main__':
X,y = contoursSSEDemo()
N = len(y)
w = np.linalg.lstsq(X, y)[0]
v = np.arange(-6, 6, .1)
W0, W1 = np.meshgrid(v, v)
SS = np.array([sum((w0*X[:,0] + w1*X[:,1] - y)**2) for w0, w1 in zip(np.ravel(W0), np.ravel(W1))])
SS = SS.reshape(W0.shape)
fig = pl.figure()
ax = fig.add_subplot(111, projection='3d')
surf = ax.plot_surface(W0, W1, SS)
pl.savefig('linregSurfSSE.png')
pl.show()
fig,ax = pl.subplots()
ax.set_title('Sum of squares error contours for linear regression')
CS = pl.contour(W0, W1, SS)
pl.plot([-4.351],[0.5377],'x')
pl.savefig('linregContoursSSE.png')
pl.show()
| [
"murphyk@gmail.com"
] | murphyk@gmail.com |
d244d27e34895e0c317a9a52c2c75875afd40e4a | a5a71451ad2380f63a81e50ff119a17e1019d1f6 | /tests/test_get_finder/tests.py | 8849328d27e08d36f7ffcdd5a3217478a08c8cf0 | [
"ISC"
] | permissive | gears/django-gears | 3a3ed5c7444771d7f14dd33d8655189d06a66143 | 80a5cb085c5c4edac481228765edcfda3d6309f7 | refs/heads/develop | 2021-01-01T19:24:02.617522 | 2015-01-21T08:00:18 | 2015-01-21T08:00:18 | 2,822,397 | 15 | 3 | ISC | 2023-08-23T00:22:29 | 2011-11-21T19:31:28 | Python | UTF-8 | Python | false | false | 581 | py | from __future__ import with_statement
from django.core.exceptions import ImproperlyConfigured
from django.test import TestCase
from django_gears.utils import get_finder
from . import finders
class GetFinderTests(TestCase):
def test_if_it_is_a_subclass_of_base_finder(self):
finder = get_finder('test_get_finder.finders.GoodFinder')
self.assertIsInstance(finder, finders.GoodFinder)
def test_if_it_is_not_a_subclass_of_base_finder(self):
with self.assertRaises(ImproperlyConfigured):
get_finder('test_get_finder.finders.BadFinder')
| [
"mike@yumatov.org"
] | mike@yumatov.org |
55f8b696d41883c2fcef7f58c03e8f9c9a06bf81 | 9869821dbd52df5083e86eac3afa97422ea07f89 | /sevchefs_api/models.py | 5c60cb8bb0ba9bfeda3f29daa0f8c09e65fb29f7 | [] | no_license | sohjunjie/the7chefs_backend | af18afe4b7279526e1717c2a1113cd69b7e6f0cf | a4eec24050fd07db31d76465c42d5434b1f7a177 | refs/heads/master | 2022-12-12T12:13:48.820638 | 2017-11-06T13:26:32 | 2017-11-06T13:26:32 | 101,177,905 | 0 | 0 | null | 2022-12-08T00:40:54 | 2017-08-23T12:32:54 | Python | UTF-8 | Python | false | false | 6,302 | py | import uuid
from django.db import models
from django.contrib.auth.models import User
def user_avatar_directory_path(instance, filename):
ext = filename.split('.')[-1]
filename = "%s.%s" % (uuid.uuid4(), ext)
return 'user/{0}/{1}'.format(instance.id, filename)
def recipe_image_directory_path(instance, filename):
ext = filename.split('.')[-1]
filename = "%s.%s" % (uuid.uuid4(), ext)
return 'recipe/{0}/{1}'.format(instance.id, filename)
def ingredient_image_directory_path(instance, filename):
ext = filename.split('.')[-1]
filename = "%s.%s" % (uuid.uuid4(), ext)
return 'ingredient/{0}'.format(filename)
def recipe_instruction_image_directory_path(instance, filename):
ext = filename.split('.')[-1]
filename = "%s.%s" % (uuid.uuid4(), ext)
return 'recipe/{0}/{1}/{2}/'.format(instance.recipe.id, instance.id, filename)
class UserProfile(models.Model):
user = models.OneToOneField(User, related_name="userprofile")
description = models.TextField(max_length=500, null=True)
avatar = models.ImageField(upload_to=user_avatar_directory_path, blank=True, null=True)
follows = models.ManyToManyField('UserProfile', related_name='followed_by', blank=True)
favourited_recipes = models.ManyToManyField(
'Recipe',
through='UserRecipeFavourites',
through_fields=('userprofile', 'recipe'),
)
def __str__(self):
return self.user.username
def following_count(self):
return self.follows.all().count()
def followers_count(self):
return self.followed_by.all().count()
class ActivityTimeline(models.Model):
user = models.ForeignKey(User, related_name="timeline")
summary_text = models.TextField(max_length=200, null=False, blank=False)
target_user = models.ForeignKey(User, related_name="mentioned_timeline", null=True)
main_object_image = models.ImageField(blank=True, null=True)
target_object_image = models.ImageField(blank=True, null=True)
datetime = models.DateTimeField(auto_now_add=True)
def get_formatted_summary_text(self, user):
# summary text is about following
aboutfollow = True if "follow" in self.summary_text else False
if self.target_user is None:
if self.user.id == user.id:
return self.summary_text.format("you")
return self.summary_text.format(self.target_user.username)
# you followed yourself, you favourited your recipe, you commented on your recipe
if (user.id == self.user.id) and (user.id == self.target_user.id):
if aboutfollow:
return self.summary_text.format("you", "yourself")
return self.summary_text.format("you", "your")
# you followed someone, you favourited someone recipe, you commented on someone recipe
elif user.id == self.user.id:
if aboutfollow:
return self.summary_text.format("you", self.target_user.username)
return self.summary_text.format("you", self.target_user.username + "'s")
# someone followed you, someone favourited your recipe, someone commented on your recipe
elif self.target_user.id == user.id:
if aboutfollow:
return self.summary_text.format(self.target_user.username, "you")
return self.summary_text.format(self.target_user.username, "your")
return self.summary_text.format(self.user.username, self.target_user.username)
class Recipe(models.Model):
name = models.TextField(max_length=100, null=False, blank=False)
description = models.TextField(max_length=500, null=False, blank=False)
upload_datetime = models.DateTimeField(auto_now_add=True)
upload_by_user = models.ForeignKey(User, related_name='recipes')
image = models.ImageField(upload_to=recipe_image_directory_path, blank=True, null=True)
difficulty_level = models.IntegerField(default=0)
ingredients_list = models.ManyToManyField(
'Ingredient',
through='RecipeIngredient',
through_fields=('recipe', 'ingredient'),
)
favourited_by = models.ManyToManyField(
UserProfile,
through='UserRecipeFavourites',
through_fields=('recipe', 'userprofile'),
)
tags = models.ManyToManyField(
'RecipeTag',
through='RecipeTagTable',
through_fields=('recipe', 'tag'),
)
def __str__(self):
return self.name
def get_recipe_tags(self):
return self.tags.all()
def get_recipe_ingredients(self):
return self.ingredients.all()
def get_favourited_count(self):
return self.favourited_by.all().count()
def get_image_url(self):
return str(self.image)
class RecipeComment(models.Model):
recipe = models.ForeignKey(Recipe, related_name='comments')
user = models.ForeignKey(User, related_name='recipe_comments')
text = models.TextField(max_length=500, null=False, blank=False)
datetime = models.DateTimeField(auto_now_add=True)
class UserRecipeFavourites(models.Model):
userprofile = models.ForeignKey(UserProfile)
recipe = models.ForeignKey(Recipe)
datetime = models.DateTimeField(auto_now_add=True)
class RecipeInstruction(models.Model):
recipe = models.ForeignKey(Recipe, related_name='instructions')
step_num = models.IntegerField(default=1)
instruction = models.TextField(max_length=140, null=False, blank=False)
time_required = models.DurationField(null=True)
image = models.ImageField(upload_to=recipe_instruction_image_directory_path, blank=True, null=True)
class Meta:
ordering = ['step_num']
class Ingredient(models.Model):
name = models.TextField(max_length=100, blank=False, null=False)
description = models.TextField(max_length=200)
image = models.ImageField(upload_to=ingredient_image_directory_path, null=True, blank=True)
class RecipeIngredient(models.Model):
recipe = models.ForeignKey(Recipe, related_name="ingredients")
ingredient = models.ForeignKey(Ingredient)
serving_size = models.TextField()
class RecipeTag(models.Model):
text = models.TextField(blank=False, null=False, unique=True)
class RecipeTagTable(models.Model):
recipe = models.ForeignKey(Recipe)
tag = models.ForeignKey(RecipeTag)
| [
"junjie.soh93@gmail.com"
] | junjie.soh93@gmail.com |
9e1300463ec95eed050e294dbf1f512cca88b175 | 890aaf5ffd178ad3c601079cddc520b66dfb4130 | /player/models.py | 7217c17dcd4f4dd6b62357a35e1fd5db9ccc1b45 | [] | no_license | FelixTheC/browsergame | 8dbaacee34835b3e84a2ba14a0ff4c005647cddf | 00bb1eef8f28bf46bbb03d882f3c8019b97fd8a5 | refs/heads/master | 2020-03-27T10:21:57.008465 | 2018-08-29T13:29:28 | 2018-08-29T13:29:28 | 146,415,125 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 838 | py | from django.contrib.auth.models import User
from django.db import models
from spell.models import Spell
class Player(User):
class Meta:
ordering = 'pk'
db_table = 'player'
level = models.IntegerField(default=0, blank=True)
xp = models.DecimalField(default=0.0, blank=True)
live_points = models.PositiveIntegerField(default=100, blank=True)
max_live_points = models.PositiveIntegerField(default=100, blank=True)
mana_points = models.PositiveIntegerField(default=50, blank=True)
max_mana_points = models.PositiveIntegerField(default=50, blank=True)
armor_points = models.DecimalField(default=5.0, blank=True)
spells = models.ManyToManyField(Spell, blank=True, null=True)
def __str__(self):
return self.username
def __repr__(self):
return f'Player - {self.pk}' | [
"felixeisenmenger@gmx.net"
] | felixeisenmenger@gmx.net |
f4e7c4d0c00235efdf0c1814f151ce92182ab87c | 187ec84de1e03e2fe1e154dcb128b5886b4d0547 | /chapter_03/exercises/04_guest_list.py | 59d42604ab669d68dc242c613f594a8bbfdac314 | [] | no_license | xerifeazeitona/PCC_Basics | fcbc1b8d5bc06e82794cd9ff0061e6ff1a38a64e | 81195f17e7466c416f97acbf7046d8084829f77b | refs/heads/main | 2023-03-01T07:50:02.317941 | 2021-01-27T21:08:28 | 2021-01-27T21:08:28 | 330,748,942 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 449 | py | # 3-4. Guest List
# If you could invite anyone, living or deceased, to dinner, who would
# you invite? Make a list that includes at least three people you’d like
# to invite to dinner. Then use your list to print a message to each
# person, inviting them to dinner.
persons = []
persons.append('jenny')
persons.append('grace')
persons.append('fred')
for person in persons:
print(f"Hello {person.title()}, would you like to come for dinner?") | [
"juliano.amaral@gmail.com"
] | juliano.amaral@gmail.com |
1447230f766afd41a6dd0803b07be0e8a4ba698d | 200839d1368245d23cf522ed007794210dda8e4b | /test_script.py | 30e0b8348eee91f9caec501a8a252561a8fe2c5d | [
"BSD-3-Clause"
] | permissive | tmcclintock/Halo_catalog_with_projection | 88911c0311b79642627281e065e36faf2ab05b2d | 9c13b996c29dd54225a1626b1cb20598d4dccbed | refs/heads/master | 2020-03-28T15:54:36.400654 | 2018-09-20T17:32:40 | 2018-09-20T17:32:40 | 148,637,225 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,206 | py | import numpy as np
import convert_catalog as cc
import matplotlib.pyplot as plt
scatters = [0.2] #only this one for now
scatter = scatters[0]
#Values for the RMR for fox
alpha = 0.77
M_pivot = 10**12.63 #Msun/h
M_min = 10**11.24
z = 1.
inpath = "test_catalog.npy"
conv = cc.Converter(scatter, M_min=M_min, M_pivot=M_pivot, alpha=alpha)
data = np.load(inpath)
Ms = data[:,3] #Mass in Msun/h
Nh = len(data)
Nd = len(data[0]) #x, y, z, M, Np
out = np.zeros((Nh, Nd+3)) #x, y, z, M, Np, lambda_true, lambda_real, lambda_obs
out[:, :Nd] = data #copy in x, y, z, M, Np
out[:, Nd] = conv.lambda_true(Ms)
out[:, Nd+1] = conv.lambda_true_realization(Ms)
count = 0
for ltr in out[:, Nd+1]:
try:
out[:, Nd+2] = conv.Draw_from_CDF(1, ltr, z)
except ValueError:
x = conv.cdf4interp
y = conv.l_out_grid
dx = x[1:] - x[:-1]
print x
inds = dx <= 0
ind = np.argmin(dx)
print dx[inds]
print dx[ind-2:ind+2]
plt.plot(x[:-1]-x[1:])
plt.show()
plt.plot(x, y)
plt.show()
exit()
count += 1
if count%1 == 0:
print "Finished %d / %d"%(count, len(Ms))
| [
"tmcclintock89@gmail.com"
] | tmcclintock89@gmail.com |
85b75024cde8366d99fb76cbbd9525b3975ce3d4 | 95aa6f7c87af7728d999e4038b92ee7f9d91a17c | /PAZCOLOMBIA/pruebaserial.py | 7153e90710fd0a88b29005fff70e7a7ed2b26e38 | [] | no_license | Fermec28/HackathonAzureIoT | f7f56ebf7d8cf89405bb1fa83b89e8fe9ce0ea94 | df666a3ce6fb467b25c2f751fcd67e4c4b9addd1 | refs/heads/master | 2021-01-22T21:59:19.385202 | 2017-03-20T14:41:09 | 2017-03-20T14:41:09 | 85,498,471 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 223 | py | import serial
import sys
import time
ser= serial.Serial('/dev/ttyACM0',9600)
ser.write("dato")
dato=""
while dato=="":
while ser.inWaiting()>0:
dato=ser.readline()
print dato
ser.close()
| [
"fermed28@gmail.com"
] | fermed28@gmail.com |
fee6ebb539107d535f7a54a856b21e86decace56 | 39b228e1261882f41deac10870601c722504eccb | /gputools/convolve/__init__.py | 06f134919322a2919d5e9fa1581b600916b19514 | [
"BSD-3-Clause"
] | permissive | Traecp/gputools | 4831a6a8dd28191994b57784a5eb9e75c56c6e84 | fd25e9457ddc50bbe1c29eff91f397dcf80a4767 | refs/heads/master | 2021-05-12T06:30:29.043605 | 2017-09-27T22:50:40 | 2017-09-27T22:50:40 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 324 | py |
#from .blur import blur
from .convolve_sep import convolve_sep2, convolve_sep3
from .convolve import convolve
from .convolve_spatial2 import convolve_spatial2
from .convolve_spatial3 import convolve_spatial3
#from .minmax_filter import max_filter, min_filter
from .filters import max_filter, min_filter, uniform_filter
| [
"mweigert@mpi-cbg.de"
] | mweigert@mpi-cbg.de |
d83a64cc10d5e83cbeb0a511b422a57b15bc9802 | 8372d349be47f85c6650bf81b2e1d87e5fdcd259 | /modules/app.py | 5358408780fa56e4f02ab6e67292951f78247e31 | [] | no_license | pflashpunk/myrecon.py | b2bd6c22b36f83245e3df0fad7644ff66af12345 | 150eeb5e1473e3bef2ccc9ad2f1419d56c120a4d | refs/heads/master | 2020-09-29T20:02:37.780438 | 2019-12-05T10:51:16 | 2019-12-05T10:51:16 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 5,733 | py | # I don't believe in license.
# You can do whatever you want with this program.
import os
import sys
import imp
import time
from modules import functions as func
from colored import fg, bg, attr
class App:
config = []
mods = []
d_app = ''
d_mods = ''
d_output = ''
f_report = ''
f_domains = ''
f_hosts = ''
f_tmphosts = ''
f_dead = ''
f_ips = ''
f_urls = ''
domains = []
n_domains = 0
hosts = []
tmphosts = ''
n_hosts = 0
dead = []
n_dead = 0
ips = []
n_ips = 0
urls = []
n_urls = 0
def __init__( self, config ):
self.config = config
self.d_app = os.path.dirname( os.path.dirname( os.path.realpath(__file__) ) )
self.d_mods = self.d_app + '/modules'
def init( self ):
func.parseargs( self )
def run( self ):
for mod_name in self.mods:
if mod_name in self.config['mandatory_mods'] or 'resume' in self.mods or 'report' in self.mods:
# if mod_name in self.config['mandatory_mods'] or 'resume' in self.mods:
self.runMod( mod_name )
else:
self.launchMod( mod_name )
def runMod( self, mod_name ):
mod_file = self.d_mods + '/' + mod_name + '.py'
if not os.path.isfile(mod_file):
sys.stdout.write( "%s[-] error occurred: %s not found%s\n" % (fg('red'),mod_name,attr(0)) )
else:
py_mod = imp.load_source( mod_name.capitalize(), mod_file)
mod = getattr( py_mod, mod_name.capitalize() )()
try:
mod.run( self )
except Exception as e:
sys.stdout.write( "%s[-] error occurred: %s%s\n" % (fg('red'),e,attr(0)) )
# if hasattr(mod,'postrun'):
# mod.postrun( self )
# if hasattr(mod,'report'):
# mod.report( self )
def launchMod( self, mod_name ):
cmd = sys.argv[0] + ' -r -m ' + mod_name + ' 2>&1 &'
# print( cmd )
os.system( cmd )
def wait( self ):
i = 0
t_chars = ['|','/','-','\\','|','/','-']
l = len(t_chars)
sys.stdout.write( "\n\n" )
for n in range(100000):
time.sleep( 0.5 )
sys.stdout.write( ' %s\r' % t_chars[n%l] )
def setMods( self, t_mods ):
self.mods = t_mods
def setOutputDirectory( self, d_output ):
self.d_output = d_output.rstrip('/')
sys.stdout.write( '[+] output directory is: %s\n' % self.d_output )
self.initFilePath()
def initFilePath( self ):
self.f_report = self.d_output + '/report'
self.f_domains = self.d_output + '/domains'
self.f_hosts = self.d_output + '/hosts'
self.f_tmphosts = self.d_output + '/tmp_hosts'
self.f_dead = self.d_output + '/hosts_dead'
self.f_ips = self.d_output + '/ips'
self.f_urls = self.d_output + '/urls'
self.f_urls_ips = self.d_output + '/urls_ips'
def setDomains( self, t_domains ):
self.domains = t_domains
self.n_domains = len(t_domains)
sys.stdout.write( '%s[+] %d domains found.%s\n' % (fg('green'),self.n_domains,attr(0)) )
if self.n_domains:
fp = open( self.f_domains, 'w' )
fp.write( "\n".join(self.domains) )
fp.close()
sys.stdout.write( '[+] saved in %s\n' % self.f_domains )
def setHosts( self, t_hosts ):
self.hosts = t_hosts
self.n_hosts = len(t_hosts)
sys.stdout.write( '%s[+] %d hosts found.%s\n' % (fg('green'),self.n_hosts,attr(0)) )
if self.n_hosts:
fp = open( self.f_hosts, 'w' )
fp.write( "\n".join(self.hosts) )
fp.close()
sys.stdout.write( '[+] saved in %s\n' % self.f_hosts )
def setIps( self, t_ips, tmphosts ):
self.ips = t_ips
self.n_ips = len(t_ips)
sys.stdout.write( '%s[+] %d ips found.%s\n' % (fg('green'),self.n_ips,attr(0)) )
if self.n_ips:
fp = open( self.f_ips, 'w' )
fp.write( "\n".join(t_ips) )
fp.close()
sys.stdout.write( '[+] saved in %s\n' % self.f_ips )
if len(tmphosts):
fp = open( self.f_tmphosts, 'w' )
fp.write( tmphosts )
fp.close()
def setDeadHosts( self, t_dead ):
sys.stdout.write( '[+] %d dead hosts found, cleaning...\n' % len(t_dead) )
if len(t_dead):
for host in t_dead:
self.hosts.remove( host )
fp = open( self.f_dead, 'w' )
fp.write( "\n".join(t_dead) )
fp.close()
def setUrls( self, t_urls ):
self.urls = t_urls
self.n_urls = len(t_urls)
sys.stdout.write( '%s[+] %d urls created.%s\n' % (fg('green'),self.n_urls,attr(0)) )
if self.n_urls:
fp = open( self.f_urls, 'w' )
fp.write( "\n".join(self.urls) )
fp.close()
sys.stdout.write( '[+] saved in %s\n' % self.f_urls )
def setUrlsIps( self, t_new_urls ):
new_urls = len(t_new_urls)
sys.stdout.write( '%s[+] %d urls created.%s\n' % (fg('green'),new_urls,attr(0)) )
if new_urls:
fp = open( self.f_urls_ips, 'w' )
fp.write( "\n".join(t_new_urls) )
fp.close()
sys.stdout.write( '[+] saved in %s\n' % self.f_urls_ips )
def getReportDatas( self ):
t_vars = {}
if os.path.isfile(self.f_domains):
t_vars['n_domains'] = sum(1 for line in open(self.f_domains))
return t_vars
| [
"g@10degres.net"
] | g@10degres.net |
f0481fd9b443fa7e04a7487692c816a354e643d0 | 6d04a5a3ed838df588ebd799d6b411ad4a0423d8 | /setup3.py | 377e930b6745c29b6f0386ab4c70eb19a2cbefc0 | [] | no_license | matthew-brett/arraymakers | f2aa7dbb92fe432d717195be9e8600c90b558bd8 | 220bb91ec9fcbf99820d5c5c2866f51edc5c640b | refs/heads/master | 2016-08-07T23:10:24.426500 | 2009-11-17T06:03:31 | 2009-11-17T06:03:31 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 372 | py | from distutils.core import setup
from distutils.extension import Extension
from Cython.Distutils import build_ext
import numpy as np
sourcefiles = ['sturlabench.pyx']
setup(
cmdclass = {'build_ext': build_ext},
ext_modules = [Extension("sturlabench",
sourcefiles,
include_dirs = [np.get_include()])]
)
| [
"matthew.brett@gmail.com"
] | matthew.brett@gmail.com |
a30d5296c270e3f997b65094140ee7f36f85b11d | 06c2bc496f9e285f06e4c3c71f14d5716f411d89 | /source/webapp/migrations/0001_initial.py | 2340231d02b94aea805a5292d5b1c67ac6d30ad9 | [] | no_license | Beknasar/Coin_collection | 37a9e77cc00270dfcb9d0cb5916f985cec4c591d | 091860f98e7dc81d460ab0cbcb6ca1d7fdeffda8 | refs/heads/master | 2023-06-09T16:25:30.473134 | 2021-06-25T09:31:13 | 2021-06-25T09:31:13 | 365,229,399 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 2,103 | py | # Generated by Django 2.2 on 2021-05-03 10:56
from django.db import migrations, models
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='Country',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('name', models.CharField(max_length=100, verbose_name='название страны')),
],
options={
'verbose_name': 'страна',
'verbose_name_plural': 'страны',
},
),
migrations.CreateModel(
name='Currency',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('name', models.CharField(max_length=100, verbose_name='название страны')),
],
options={
'verbose_name': 'страна',
'verbose_name_plural': 'страны',
},
),
migrations.CreateModel(
name='Material',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('name', models.CharField(max_length=100, verbose_name='название материала')),
],
options={
'verbose_name': 'материал',
'verbose_name_plural': 'материалы',
},
),
migrations.CreateModel(
name='Nominal',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('name', models.CharField(max_length=100, verbose_name='название номинала')),
],
options={
'verbose_name': 'номинал',
'verbose_name_plural': 'номиналы',
},
),
]
| [
"680633@gmail.com"
] | 680633@gmail.com |
05d17b4c1ba3a133b032f6f66a03a7e2c15c5227 | 119437adb7830659307c18b79a9cc3f6bfc6fe40 | /transformers_learning/text_classification/ernie_model_evaluate.py | ea61f8fb38d798d0f7835c7452c00b911801326d | [] | no_license | percent4/PyTorch_Learning | 478bec35422cdc66bf41b4258e29fbcb6d24f60c | 24184d49032c9c9a68142aff89dabe33adc17b52 | refs/heads/master | 2023-03-31T03:01:19.372830 | 2023-03-17T17:02:39 | 2023-03-17T17:02:39 | 171,400,828 | 16 | 7 | null | 2023-09-02T08:53:26 | 2019-02-19T03:47:41 | Jupyter Notebook | UTF-8 | Python | false | false | 2,001 | py | # -*- coding: utf-8 -*-
# @Time : 2021/1/29 15:54
# @Author : Jclian91
# @File : ernie_model_evaluate.py
# @Place : Yangpu, Shanghai
import json
import torch
import numpy as np
import pandas as pd
from sklearn.metrics import classification_report
from transformers import AutoTokenizer, AutoConfig, AutoModelForSequenceClassification
from params import *
from model_train import convert_text_to_ids, seq_padding, test_file
# read label id dict
with open("{}_label2id.json".format(dataset), "r", encoding="utf-8") as g:
label_id_dict = json.loads(g.read())
id_label_dict = {v: k for k, v in label_id_dict.items()}
# load model
device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")
config = AutoConfig.from_pretrained("../ernie-1.0", num_labels=num_labels, hidden_dropout_prob=hidden_dropout_prob)
model = AutoModelForSequenceClassification.from_pretrained("../ernie-1.0", config=config)
model.to(device)
state_dict = torch.load('{}_ernie_cls.pth'.format(dataset))
model.load_state_dict(state_dict)
tokenizer = AutoTokenizer.from_pretrained("../ernie-1.0")
# read test file
test_df = pd.read_csv(test_file)
contents, true_labels = test_df["content"].tolist(), test_df["label"].tolist()
# model evaluate
pred_labels = []
for i, text in enumerate(contents):
print("predict {} samples".format(i+1))
input_ids, token_type_ids = convert_text_to_ids(tokenizer, [text], max_sequence_length)
# print(input_ids, token_type_ids)
input_ids = seq_padding(tokenizer, input_ids)
token_type_ids = seq_padding(tokenizer, token_type_ids)
input_ids, token_type_ids = input_ids.long(), token_type_ids.long()
input_ids, token_type_ids = input_ids.to(device), token_type_ids.to(device)
output = model(input_ids=input_ids, token_type_ids=token_type_ids)
label_id = np.argmax(output[0].detach().cpu().numpy(), axis=1)[0]
pred_labels.append(id_label_dict[label_id])
# print evaluate output
print(classification_report(true_labels, pred_labels, digits=4)) | [
"1137061634@qq.com"
] | 1137061634@qq.com |
458263b68266a9818ebc55736b4bc25d6fa981e2 | 6b2db6fca8f31c4e6c96e68cf11e5ca3ce7e8a9b | /src/calPosteriorModifyForIdeal.py | 2836c82b00fcdfe11ca8ba606f41756da73a5ca0 | [
"MIT"
] | permissive | ningtangla/escapeFromMultipleSuspectors | e04da12488be9767c5b6511355c167fdcf18e723 | e6dcb0f7f9371b7ca6cca8779f69f18095092140 | refs/heads/master | 2022-05-03T05:25:21.556950 | 2022-04-20T13:51:53 | 2022-04-20T13:51:53 | 190,686,484 | 1 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,707 | py | import pandas as pd
import numpy as np
import scipy.stats as stats
import math
def calAngleLikelihoodLogModifiedForPiRange(angle, kappa):
return stats.vonmises.logpdf(angle, kappa) + np.log(2)
class CalPosteriorLog():
def __init__(self, minDistance):
self.minDistance = minDistance
def __call__(self, hypothesesInformation, observedData):
hypothesesInformation['chasingLikelihoodLog'] = calAngleLikelihoodLogModifiedForPiRange(observedData['wolfDeviation'], 1/(1/hypothesesInformation.index.get_level_values('chasingPrecision') + 1/hypothesesInformation['perceptionPrecision']))
hypothesesInformation['escapingLikelihoodLog'] = 0
originPrior = np.exp(hypothesesInformation['logP'].values)
normalizedPrior = np.maximum([1e-300] * len(originPrior), originPrior / np.sum(originPrior))
hypothesesInformation['beforeLogPAfterDecay'] = np.log(normalizedPrior) * hypothesesInformation['memoryDecay']
#hypothesesInformation['beforeLogPAfterDecay'] = hypothesesInformation['memoryDecay'] * hypothesesInformation['logP']
#print(np.exp(hypothesesInformation['logP']).values)
#print('***', originPrior)
#print('!!!', normalizedPrior)
#distanceLikelihoodLog = np.array([-50 if distance <= self.minDistance else 0 for distance in observedData['distanceBetweenWolfAndSheep'].values])
distanceLikelihoodLog = 0
hypothesesInformation['logP'] = hypothesesInformation['beforeLogPAfterDecay'] + hypothesesInformation['chasingLikelihoodLog'] \
+ hypothesesInformation['escapingLikelihoodLog'] + distanceLikelihoodLog
return hypothesesInformation
| [
"ningtangzju@gmail.com"
] | ningtangzju@gmail.com |
926644d6b51709392d243e98819486b28d544b79 | e6d4a87dcf98e93bab92faa03f1b16253b728ac9 | /algorithms/python/deleteLeavesWithaGivenValue/deleteLeavesWithaGivenValue.py | b5d6b7308887d04f9df27fa9e19a93de3af9356a | [] | no_license | MichelleZ/leetcode | b5a58e1822e3f6ef8021b29d9bc9aca3fd3d416f | a390adeeb71e997b3c1a56c479825d4adda07ef9 | refs/heads/main | 2023-03-06T08:16:54.891699 | 2023-02-26T07:17:47 | 2023-02-26T07:17:47 | 326,904,500 | 3 | 0 | null | null | null | null | UTF-8 | Python | false | false | 725 | py | #! /usr/bin/env python3
# -*- coding: utf-8 -*-
# Source: https://leetcode.com/problems/delete-leaves-with-a-given-value/
# Author: Miao Zhang
# Date: 2021-04-23
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def removeLeafNodes(self, root: TreeNode, target: int) -> TreeNode:
if not root:
return None
root.left = self.removeLeafNodes(root.left, target)
root.right = self.removeLeafNodes(root.right, target)
if not root.left and not root.right and root.val == target:
return None
return root
| [
"zhangdaxiaomiao@163.com"
] | zhangdaxiaomiao@163.com |
6c42d5c74d411827cb4f887bc2345c3d697d5ce6 | ca7aa979e7059467e158830b76673f5b77a0f5a3 | /Python_codes/p02623/s803927291.py | 1bb8ba08366a2d97232987232cea5c363032232f | [] | no_license | Aasthaengg/IBMdataset | 7abb6cbcc4fb03ef5ca68ac64ba460c4a64f8901 | f33f1c5c3b16d0ea8d1f5a7d479ad288bb3f48d8 | refs/heads/main | 2023-04-22T10:22:44.763102 | 2021-05-13T17:27:22 | 2021-05-13T17:27:22 | 367,112,348 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 814 | py | from sys import stdin
import sys
n,m,k = [int(x) for x in stdin.readline().rstrip().split()]
A = [int(x) for x in stdin.readline().rstrip().split()]
B = [int(x) for x in stdin.readline().rstrip().split()]
cc = []
count = 0
sumA = 0
for i in range(n):
sumA_ = sumA + A[i]
if sumA_ > k: break
sumA = sumA_
count = count + 1
maxA = count
sumB = 0
j = 0
for i in range(maxA+1):
if i != 0:
count = count - 1
sumA = sumA - A[maxA-i]
while True:
sumB_ = sumB + B[j]
if sumA + sumB_ > k:
cc.append(count)
break
sumB = sumB_
count = count + 1
j = j + 1
if j == m:
cc.append(count)
break
if j == m:
break
if cc == []:
print (0)
else:
print (max(cc))
| [
"66529651+Aastha2104@users.noreply.github.com"
] | 66529651+Aastha2104@users.noreply.github.com |
e48db17d4ddd3254f132e9542692a9665eed806f | ddda55fcfc84ac5cd78cfc5c336a3df0b9096157 | /drivers/hal/fm/FM33A0xx_HAL/SConscript | 0a0392c9f48f9aae5ecbdab86877c156ad8ca896 | [
"Apache-2.0"
] | permissive | liu-delong/lu_xing_xiang_one_os | 701b74fceb82dbb2806518bfb07eb85415fab43a | 0c659cb811792f2e190d5a004a531bab4a9427ad | refs/heads/master | 2023-06-17T03:02:13.426431 | 2021-06-28T08:12:41 | 2021-06-28T08:12:41 | 379,661,507 | 2 | 2 | Apache-2.0 | 2021-06-28T10:08:10 | 2021-06-23T16:11:54 | C | UTF-8 | Python | false | false | 1,519 | import osconfig
from build_tools import *
# get current directory
pwd = PresentDir()
# The set of source files associated with this SConscript file.
src = Split('''
FM33A0xx_HAL_Driver/Src/fm33a0xx_aes.c
FM33A0xx_HAL_Driver/Src/fm33a0xx_anac.c
FM33A0xx_HAL_Driver/Src/fm33a0xx_btim.c
FM33A0xx_HAL_Driver/Src/fm33a0xx_crc.c
FM33A0xx_HAL_Driver/Src/fm33a0xx_dma.c
FM33A0xx_HAL_Driver/Src/fm33a0xx_etim.c
FM33A0xx_HAL_Driver/Src/fm33a0xx_gpio.c
FM33A0xx_HAL_Driver/Src/fm33a0xx_hspi.c
FM33A0xx_HAL_Driver/Src/fm33a0xx_lcd.c
FM33A0xx_HAL_Driver/Src/fm33a0xx_lptim.c
FM33A0xx_HAL_Driver/Src/fm33a0xx_pmu.c
FM33A0xx_HAL_Driver/Src/fm33a0xx_rcc.c
FM33A0xx_HAL_Driver/Src/fm33a0xx_scu.c
FM33A0xx_HAL_Driver/Src/fm33a0xx_trng.c
FM33A0xx_HAL_Driver/Src/fm33a0xx_u7816.c
FM33A0xx_HAL_Driver/Src/fm33a0xx_wwdt.c
FM33A0xx_HAL_Driver/Src/fm33a0xx_flash.c
''')
if IsDefined(['OS_USING_SERIAL']):
src += ['FM33A0xx_HAL_Driver/Src/fm33a0xx_uart.c']
if IsDefined(['OS_USING_I2C']):
src += ['FM33A0xx_HAL_Driver/Src/fm33a0xx_i2c.c']
if IsDefined(['OS_USING_SPI']):
src += ['FM33A0xx_HAL_Driver/Src/fm33a0xx_spi.c']
if IsDefined(['OS_USING_RTC']):
src += ['FM33A0xx_HAL_Driver/Src/fm33a0xx_rtc.c']
if IsDefined(['OS_USING_WDT']):
src += ['FM33A0xx_HAL_Driver/Src/fm33a0xx_iwdt.c']
path = [pwd + '/FM33A0xx_HAL_Driver/Inc',
pwd + '/CMSIS']
CPPDEFINES = ['USE_HAL_DRIVER']
group = AddCodeGroup('hal', src, depend = ['SOC_SERIES_FM33A0'], CPPPATH = path, CPPDEFINES = CPPDEFINES)
Return('group')
| [
"cmcc_oneos@cmiot.chinamobile.com"
] | cmcc_oneos@cmiot.chinamobile.com | |
bdd1e985f8f65ddfde119fad57709df0f8f15b2e | e9e6a89c200f1800bf4fb6f1ef5ec4926efb2783 | /mTRPO/mytrpo/util/__init__.py | 007b858818d9cf8bd810bd4315067b639d345e78 | [] | no_license | wwxFromTju/baselines_trpo | 331d7ed6788ead30313834605a5a92165a4a4d32 | 5c01c5f40cc2f96c7c06da392292d01e3c99f3b8 | refs/heads/master | 2021-04-27T03:58:37.730940 | 2018-02-26T08:23:08 | 2018-02-26T08:23:08 | 122,723,607 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 551 | py | from mytrpo.util.normal_util import *
from mytrpo.util.dataset import Dataset
from mytrpo.util.normal_util import *
def explained_variance(ypred,y):
"""
Computes fraction of variance that ypred explains about y.
Returns 1 - Var[y-ypred] / Var[y]
interpretation:
ev=0 => might as well have predicted zero
ev=1 => perfect prediction
ev<0 => worse than just predicting zero
"""
assert y.ndim == 1 and ypred.ndim == 1
vary = np.var(y)
return np.nan if vary==0 else 1 - np.var(y-ypred)/vary
| [
"wxwang@tju.edu.cn"
] | wxwang@tju.edu.cn |
f27edd291982fde6ab630cad2358fd98bfae178f | a35b24c8c3c5bdf861f3cda9396f2fa6795ec929 | /abc/093/A.py | de1bd8b4e45dfc6460741234fe47dc34d4c5658d | [] | no_license | Msksgm/atcoder_msksgm_practice | 92a19e2d6c034d95e1cfaf963aff5739edb4ab6e | 3ae2dcb7d235a480cdfdfcd6a079e183936979b4 | refs/heads/master | 2021-08-18T16:08:08.551718 | 2020-09-24T07:01:11 | 2020-09-24T07:01:11 | 224,743,360 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 168 | py | def main():
s = list(input())
s_num = len(set(s))
if s_num == 3:
print('Yes')
else:
print('No')
if __name__ == "__main__":
main()
| [
"4419517@ed.tus.ac.jp"
] | 4419517@ed.tus.ac.jp |
97c4cf3325b10b0c2e3d9b74f8bc1b85d3ada71f | 48d820d4bd6a433c2b0fdb0dcb7657b62db050bf | /Training_Work/odoo_backup_wfo_till_april/custom_addons/college_portal/models/clg_students.py | 905875d5741165343d2a34ec60aba5c89829b26e | [] | no_license | dhruv-aktiv/training_task_data | 1a30580a512aa4831fb547b250faffff11f7e008 | 3d8b25ca812e876a484d387fc57272257322c85f | refs/heads/master | 2023-06-07T07:06:04.193576 | 2021-07-01T04:37:13 | 2021-07-01T04:37:13 | 381,908,763 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 7,032 | py | import datetime
import math
import random
import string
from odoo import api, fields, models
from odoo.exceptions import UserError, ValidationError
class Clg_Student(models.Model):
_name = 'clg.student.detail'
_description = 'college student detail'
user_name = fields.Char(string='User Name')
name = fields.Char(string='Student Name',
default="your name")
mobile_no = fields.Char(string='Student Mo No.')
email_id = fields.Char(string='Student email id.')
address = fields.Text(string='Student Address')
dob = fields.Date(string='Student Date of Birth')
gender = fields.Selection(
[('male', 'Male'), ('female', 'Female'), ], 'Gender', default='male')
id_no = fields.Integer(compute='compute_id_no', store=True)
todos = fields.Many2one(
'todos.detail', string="Todo")
age = fields.Integer()
courses = fields.Many2one('courses.detail', string="Course")
spend_amt = fields.Float(string='Amount to spend', compute='compute_amt')
res = fields.Char()
# def name_get(self):
# name = []
# for rec in self:
# name = f"{rec.name} ({rec.user_name})"
# return name
# @api.onchange('dob')
# def calc_age(self):
# for rec in self:
# if rec.dob:
# your_date = rec.dob
# today_date = datetime.date.today()
# rec.age = abs(((today_date - your_date) // 365).days)
# @api.model
# def create(self, vals):
# print(f"\n\n\n student input dt : {vals}\n\n\n")
# # clg_student = super(Clg_Student, self).create(vals)
# task_dt = self.env['todos.detail'].create(
# {'title': 'new to dfdod'})
# # # vals['todos'] = task_dt[0]
# # # clg_student.write(vals)
# print(f"\n\n\n\n {task_dt.id} \n\n\n")
# vals['name'] = 'xyzw'
# vals['todos'] = task_dt.id
# return super(Clg_Student, self).create(vals)
# @api.model
# def create(self, vals):
# print(f"\n\n\n student input dt : {vals}\n\n\n")
# clg_student = super(Clg_Student, self).create(vals)
# # task_dt = self.env['todos.detail'].create(
# # {'title': 'make a programming language'})
# # vals['todos'] = task_dt[0]
# # clg_student.write(vals)
# return clg_student
@api.model
def create(self, vals):
print(f"student vals {vals}")
clg_student = super(Clg_Student, self).create(vals)
course_dt = self.env['courses.detail'].create(
{'name': 'DsManthan course '})
vals['courses'] = course_dt[0]
clg_student.write(vals)
print(course_dt)
return clg_student
def write(self, vals):
vals['mobile_no'] = 8945631274
clg_up_student = super(Clg_Student, self).write(vals)
print(f"n\n\n{type(clg_up_student)}\n\n\n")
return clg_up_student
# def write(self, vals):
# vals['email_id'] = 'aktiv@gmail.com'
# clg_up_student = super(Clg_Student, self).write(vals)
# print(f"n\n\n{type(clg_up_student)}\n\n\n")
# return clg_up_student
# def unlink(self):
# print("\n\n\nlink done sucessfully\n\n\n")
# print(f"\n\n\n {super(Clg_Student, self).unlink()} \n\n\n")
# return super(Clg_Student, self).unlink()
def search_read_func(self):
# read
read_res = self.env['clg.student.detail'].search(
[('name', '=', "fdefd")]).read(['name'])
print(f"\n\n\nread() res : {read_res}\n\n\n")
self.res = "read res : " + str(read_res)
# read
search_read_res = self.env['clg.student.detail'].search_read(
[('gender', '=', "male")], ['name'])
self.res += "<br>" + "search_read res : " + str(search_read_res)
print(f"\n\n\nsearch_read() res : {search_read_res}\n\n\n")
def search_func(self):
# search
search_res = self.env['clg.student.detail'].search(
[('gender', '=', 'female')])
print(f"\n\n\n search() res : {search_res} \n\n\n")
# search_count
search_cnt = self.env['clg.student.detail'].search_count(
[('gender', '=', 'male')])
print(f"\n\n\nsearch_count() res : {search_cnt}\n\n\n")
# #browse
browse_res = self.env['clg.student.detail'].browse([5])
print(f"\n\n\nbrowse() res : {browse_res}\n\n\n")
# @api.model
# def create(self, vals):
# print(f"values that we get before: {vals}")
# vals['mobile_no'] = str(8945128910)
# print(f"values that we get after: {vals}")
# clg_student = super(Clg_Student, self).create(vals)
# print(f"return vals : {clg_student}")
# print(type(clg_student))
# return clg_student
# else:
# raise ValidationError("user name is required.")
@api.depends('courses')
def compute_amt(self):
discount_per = 15
for rec in self:
if rec.courses.rate > 500:
# print(f"\n\n\n{rec.courses.rate * (discount_per //
# 100)}\n\n\n")
rec.spend_amt = rec.courses.rate - \
(rec.courses.rate * (discount_per / 100))
else:
discount_per = 5
rec.spend_amt = rec.courses.rate - \
(rec.courses.rate * (discount_per / 100))
@api.depends('todos')
def compute_id_no(self):
for rec in self:
rec.id_no = 0
if rec.todos.is_done == True:
rec.id_no = 5
else:
rec.id_no = 15
# @api.depends('name')
# def compute_id_no(self):
# for rec in self:
# self.id_no = 0
# if rec.name == 'manthan':
# rec.id_no = 5
# else:
# rec.id_no = 15
# @api.model
# def name_create(self, name):
# for i in self:
# rec = i.name + i.user_name
# return rec
# def generate_user_name(self):
# self.user_name = ''.join(random.choice(
# string.ascii_uppercase + string.ascii_lowercase + string.digits) for _
# in range(random.randint(9, 15)))
# for rec in self:
# rec.write({'user_name': ''.join(random.choice(
# string.ascii_uppercase + string.ascii_lowercase + string.digits) for
# _ in range(random.randint(9, 15)))})
# @api.constrains("mobile_no")
# def check_mobile_no(self):
# if str(self.mobile_no).strip() != 'False':
# print("\n\n\n True \n\n\n")
# if not str(self.mobile_no).isdigit():
# raise ValidationError("Please enter valid mobile no.")
# else:
# if len(str(self.mobile_no).strip()) != 10:
# raise ValidationError("mobile no. size must be 10.")
# def write(self, vals):
# vals['email_id'] = 'sdrgfahrueiw@dsfabhj.com'
# return super(Clg_Student, self).write(vals)
| [
"dhruv.s@icreativetechnolabs.com"
] | dhruv.s@icreativetechnolabs.com |
06b13d5e00ab9ca1dbae55b35b9bdac815c1d6dc | 448ae937e516e6c55f425068bad3da49d22fa138 | /splendor/splendor_agents/utils/value_function.py | cfb39a2c5934f48661a6b37bf8227be35e585ee3 | [] | no_license | TomaszOdrzygozdz/alpha_splendor | a1ef5048e4abb3794bffc40ef63591f8d0afe545 | 599f8c2969c4b544d2c28dfef0720ecc7b025884 | refs/heads/master | 2022-07-16T19:01:06.821146 | 2020-05-16T09:44:05 | 2020-05-16T09:44:05 | 255,910,533 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 3,219 | py | import numpy as np
from splendor.envs.mechanics.enums import GemColor
from splendor.envs.mechanics.gems_collection import GemsCollection
from splendor.envs.mechanics.players_hand import PlayersHand
from splendor.envs.mechanics.state import State
class SplendorValueFunction:
def __init__(self, points_to_win):
self.weights = [1000, 800, 500, 650, 0, -2000, 0, 0, 0, 0, 0, 0, 150, 180, 10, 10, 0, 0, 0, 0]
self.scaling_factor = 1/30000
self.points_to_win = points_to_win
def set_weights(self, weights):
self.weights = weights
def pre_card_frac_value(self, gems : GemsCollection, price : GemsCollection):
s = 0
total_price = sum(list(price.gems_dict.values()))
for color in GemColor:
if price.gems_dict[color] > 0:
s += (gems.gems_dict[color] - price.gems_dict[color]) / total_price
s += gems.gems_dict[GemColor.GOLD] / total_price
return s
def cards_stats(self, state, active: bool):
p_hand = state.active_players_hand() if active else state.other_players_hand()
discount = p_hand.discount()
cards_affordability = sum([int(p_hand.can_afford_card(card, discount)) for card in state.board.cards_on_board]) + \
sum([int(p_hand.can_afford_card(card, discount)) for card in
p_hand.cards_reserved])
value_affordability = sum([card.victory_points*int(p_hand.can_afford_card(card, discount)) for card in state.board.cards_on_board]) + \
sum([card.victory_points * int(
p_hand.can_afford_card(card, discount)) for card in
p_hand.cards_reserved])
cards_frac_value = sum([self.pre_card_frac_value(p_hand.discount() + p_hand.gems_possessed, card.price) for card in
state.board.cards_on_board])
nobles_frac_value = sum([self.pre_card_frac_value(p_hand.discount(), noble.price) for noble in state.board.nobles_on_board])
return [cards_affordability, value_affordability, cards_frac_value, nobles_frac_value]
def hand_features(self, players_hand : PlayersHand):
points = players_hand.number_of_my_points()
cards_possessed = len(players_hand.cards_possessed)
nobles_possessed = len(players_hand.nobles_possessed)
total_gems_non_gold = players_hand.gems_possessed.sum()
gem_gold = players_hand.gems_possessed.gems_dict[GemColor.GOLD]
winner = int(points >= self.points_to_win)
return [winner, points, cards_possessed, nobles_possessed, total_gems_non_gold, gem_gold]
def state_to_features(self, state : State):
my_hand = self.hand_features(state.active_players_hand())
opp_hand = self.hand_features(state.other_players_hand())
my_cards_stats = self.cards_stats(state, True)
opp_cards_stats = self.cards_stats(state, False)
return my_hand + opp_hand + my_cards_stats + opp_cards_stats
def evaluate(self, state: State):
value = np.dot(np.array(self.weights), np.array(self.state_to_features(state)))
return value*self.scaling_factor | [
"tomeko314@gmail.com"
] | tomeko314@gmail.com |
cb0fe887184287fd77edf97b0f52282926ab0e76 | c7f98de17088cb4df6c171f1e76614beb1f4e0f7 | /arachni.py | 5a6680d220178ee70763a537f8274dbfa4ca8c90 | [] | no_license | fryjustinc/ptf | 6262ca5b94a43a51e984d3eee1649a16584b597b | ba85f9e867b65b4aa4f06b6232207aadac9782c9 | refs/heads/master | 2020-03-31T09:43:44.474563 | 2018-10-08T18:39:03 | 2018-10-08T18:39:03 | 152,107,950 | 0 | 0 | null | 2018-10-08T16:00:37 | 2018-10-08T16:00:37 | null | UTF-8 | Python | false | false | 247 | py | #!/usr/bin/env python
#####################################
# Installation module for arachni
#####################################
AUTHOR="Justin Fry"
INSTALL_TYPE="GIT"
REPOSITORY_LOCATION="https://github.com/arachni/arachni"
LAUNCHER="arachni"
| [
"fryjustinc@gmail.com"
] | fryjustinc@gmail.com |
bac416402c5c026b1181313d94a98c6fdfb8be29 | 19f52d4aeffe31e697532f08710498789a46dd6e | /keras_to_tensorflow.py | c6ea297a3d533457339e44a2ff04a0e0ec8b1990 | [] | no_license | maxwellchang7777/keras_to_tensorflow | 4ae6b9aa6e62f0ccf66c35f84cb0aeebaa274f39 | efbf5c9148d76ffba0174c2dd8856d687f14666b | refs/heads/master | 2020-05-07T16:22:37.678241 | 2018-08-02T05:52:14 | 2018-08-02T05:52:14 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 3,849 | py | # This file shows how to save a keras model to tensorflow pb file
# and how to use tensorflow to reload the model and inferece by the model
from keras.models import Sequential
from keras.layers import Dense
import tensorflow as tf
import numpy as np
np.random.seed(0)
# parameter ==========================
wkdir = '/home/pipidog/keras_to_tensorflow'
pb_filename = 'model.pb'
# build a keras model ================
x = np.vstack((np.random.rand(1000,10),-np.random.rand(1000,10)))
y = np.vstack((np.ones((1000,1)),np.zeros((1000,1))))
print(x.shape)
print(y.shape)
model = Sequential()
model.add(Dense(units = 32, input_shape=(10,), activation ='relu'))
model.add(Dense(units = 16, activation ='relu'))
model.add(Dense(units = 1, activation ='sigmoid'))
model.compile(loss='binary_crossentropy', optimizer='Adam', metrics=['binary_accuracy'])
model.fit(x = x, y=y, epochs = 2, validation_split=0.2)
# save model to pb ====================
def freeze_session(session, keep_var_names=None, output_names=None, clear_devices=True):
"""
Freezes the state of a session into a pruned computation graph.
Creates a new computation graph where variable nodes are replaced by
constants taking their current value in the session. The new graph will be
pruned so subgraphs that are not necessary to compute the requested
outputs are removed.
@param session The TensorFlow session to be frozen.
@param keep_var_names A list of variable names that should not be frozen,
or None to freeze all the variables in the graph.
@param output_names Names of the relevant graph outputs.
@param clear_devices Remove the device directives from the graph for better portability.
@return The frozen graph definition.
"""
from tensorflow.python.framework.graph_util import convert_variables_to_constants
graph = session.graph
with graph.as_default():
freeze_var_names = list(set(v.op.name for v in tf.global_variables()).difference(keep_var_names or []))
output_names = output_names or []
output_names += [v.op.name for v in tf.global_variables()]
input_graph_def = graph.as_graph_def()
if clear_devices:
for node in input_graph_def.node:
node.device = ""
frozen_graph = convert_variables_to_constants(session, input_graph_def,
output_names, freeze_var_names)
return frozen_graph
# save keras model as tf pb files ===============
from keras import backend as K
frozen_graph = freeze_session(K.get_session(),
output_names=[out.op.name for out in model.outputs])
tf.train.write_graph(frozen_graph, wkdir, pb_filename, as_text=False)
# # load & inference the model ==================
from tensorflow.python.platform import gfile
with tf.Session() as sess:
# load model from pb file
with gfile.FastGFile(wkdir+'/'+pb_filename,'rb') as f:
graph_def = tf.GraphDef()
graph_def.ParseFromString(f.read())
sess.graph.as_default()
g_in = tf.import_graph_def(graph_def)
# write to tensorboard (check tensorboard for each op names)
writer = tf.summary.FileWriter(wkdir+'/log/')
writer.add_graph(sess.graph)
writer.flush()
writer.close()
# print all operation names
print('\n===== ouptut operation names =====\n')
for op in sess.graph.get_operations():
print(op)
# inference by the model (op name must comes with :0 to specify the index of its output)
tensor_output = sess.graph.get_tensor_by_name('import/dense_3/Sigmoid:0')
tensor_input = sess.graph.get_tensor_by_name('import/dense_1_input:0')
predictions = sess.run(tensor_output, {tensor_input: x})
print('\n===== output predicted results =====\n')
print(predictions) | [
"pipidog@gmail.com"
] | pipidog@gmail.com |
09506b373f9c63284be54f45bcd1193d7bbc4926 | 0a06c52144f184e939ed8a3ec16af601447e4247 | /course13/cnn.py | 7f1575f6de3a4f40aaaea75e8aa37756b056dc47 | [
"Apache-2.0"
] | permissive | fengxiang2/PaddlePaddleCourse | 7dd88dc13e9b5f5f7f27db2b155fe4f1adcf22e4 | 1b94da406884f8a0da22e471e6b9b6a4dec80e45 | refs/heads/master | 2022-08-01T11:25:39.915680 | 2020-05-22T13:25:23 | 2020-05-22T13:25:23 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 829 | py | import paddle
class CNN(paddle.nn.Layer):
def __init__(self):
super(CNN, self).__init__()
# 定义每个网络的结构
self.conv1 = paddle.nn.Conv2D(num_channels=1, num_filters=20, filter_size=5, act="relu")
self.conv2 = paddle.nn.Conv2D(num_channels=20, num_filters=50, filter_size=5, act="relu")
self.pool1 = paddle.nn.Pool2D(pool_size=2, pool_type='max', pool_stride=2)
self.input_dim = 50 * 4 * 4
self.fc = paddle.nn.Linear(input_dim=self.input_dim, output_dim=10, act='softmax')
def forward(self, inputs):
# 把每个网络组合在一起
x = self.conv1(inputs)
x = self.pool1(x)
x = self.conv2(x)
x = self.pool1(x)
x = paddle.reshape(x, shape=[-1, self.input_dim])
x = self.fc(x)
return x
| [
"yeyupiaoling@foxmail.com"
] | yeyupiaoling@foxmail.com |
9d69e20c1c5183ae8488d661cee4a8cbe6a71acb | eeb4752a22ef99152784c0ef6f720f8e4f2dd9d9 | /myrest/app_one/migrations/0005_citycount_town.py | cd723eb747bb4c43d5b22164ea2eae5ccf036ceb | [] | no_license | borko81/django-rest-test | 9a63d328fea8155029bb3d1d29ab624ea4a0027b | e21d41494154622c2472b679df40d5f42d8ab356 | refs/heads/main | 2023-08-05T22:36:10.099746 | 2021-09-10T17:54:20 | 2021-09-10T17:54:20 | 318,290,143 | 0 | 0 | null | 2021-08-23T18:51:22 | 2020-12-03T18:53:44 | Python | UTF-8 | Python | false | false | 509 | py | # Generated by Django 3.2.5 on 2021-08-24 11:35
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('app_one', '0004_citycount'),
]
operations = [
migrations.AddField(
model_name='citycount',
name='town',
field=models.ForeignKey(default=1, on_delete=django.db.models.deletion.CASCADE, to='app_one.country'),
preserve_default=False,
),
]
| [
"bstoilov81@gmail.com"
] | bstoilov81@gmail.com |
68a84d7927a983eaa34d6441082611ceb533e83c | ce661026009d622db924080d85ab529f1cae6b60 | /projecteuler.net/23.py | f7409566c21916e771943acbeec9b7d44db05cd5 | [] | no_license | predavlad/projecteuler | d54f5d85ab0133b19b54b4168990b90f09a0184c | 58e1637733bb7e01e44bfac707353ecfe84d9b19 | refs/heads/master | 2021-01-23T15:29:26.257019 | 2019-02-09T10:11:23 | 2019-02-09T10:11:23 | 12,952,194 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,447 | py | import time
import math
# 0.13 seconds
start_time = time.time()
def proper_divisors(n):
"""
Get the proper divisors from a number
"""
yield 1
for i in xrange(2, int(math.sqrt(n)) + 1):
if n % i == 0:
yield i
if i != n / i:
yield n / i
def is_abundant(n):
"""
Calculates if n is abundant (the sum of its proper divisors is larger than the number)
"""
if n % 2 != 0 and n % 3 != 0:
return False
return sum(proper_divisors(n)) > n
def is_abundant_sum(n):
"""
at this stage, n is odd (and over 48). This means that we need to write it
as the sum of an odd + even abundant number
since there are fewer odd numbers, this is the way to do it
"""
global odd_abundant, even_abundant
for i in odd_abundant:
if i > n:
continue
if (n - i) in abundant:
return True
return False
# set up initial values we will need later on
abundant_under_49 = [24, 30, 32, 36, 38, 40, 42, 44, 48]
non_abundant_sum = sum([i for i in xrange(1, 49) if i not in abundant_under_49])
abundant = set(i for i in xrange(1, 20162) if is_abundant(i))
odd_abundant = set(i for i in abundant if i % 2 == 1)
# this is the big loop that calculates everything
non_abundant_sum += sum([i for i in xrange(49, 20162, 2) if not is_abundant_sum(i)])
print non_abundant_sum
print time.time() - start_time, "seconds"
| [
"preda.vlad@yahoo.com"
] | preda.vlad@yahoo.com |
ee87b98fe00950d2fccbf4df732138303f77f39e | ca7aa979e7059467e158830b76673f5b77a0f5a3 | /Python_codes/p03072/s818698477.py | c7275aa061f307cff2975d269d354c5e089d5fde | [] | no_license | Aasthaengg/IBMdataset | 7abb6cbcc4fb03ef5ca68ac64ba460c4a64f8901 | f33f1c5c3b16d0ea8d1f5a7d479ad288bb3f48d8 | refs/heads/main | 2023-04-22T10:22:44.763102 | 2021-05-13T17:27:22 | 2021-05-13T17:27:22 | 367,112,348 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 133 | py | N = int(input())
H = list(map(int,input().split()))
M = 0
ans=0
for h in H:
if h >= M:
ans+=1
M = max(M,h)
print(ans) | [
"66529651+Aastha2104@users.noreply.github.com"
] | 66529651+Aastha2104@users.noreply.github.com |
1f9d57a3e79928061f3a9b6b6b38bb612649af94 | 84a3adb95d4c3340c266fd9ec0d19000f362e11f | /infoarena/ninja/tests.py | 7e527c09e2860e9312fbfcc8f8d5391b343fb02b | [] | no_license | lavandalia/work | 50b4b3eb4a63a5a0d0ab8ab4670d14ecb3d71293 | a591adfd2fd2ff0fa8c65dc5829a15bc8cc60245 | refs/heads/master | 2020-05-01T02:25:31.229379 | 2017-12-17T08:39:32 | 2017-12-17T08:39:32 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 647 | py | TESTS = [
(5, 5, 5),
(300, 300, 300),
(2000, 2000, 2000),
(20000, 20000, 20000),
(30000, 30000, 30000),
(40000, 40000, 40000),
(50000, 50000, 50000),
(60000, 60000, 60000),
(100000, 100000, 100000),
(100000, 100000, 100000)
]
from subprocess import call
for index, test in enumerate(TESTS):
N, M, K = test
call("./generator " + str(N) + " " + str(M) + " " + str(K) + " > ninja.in", shell=True)
call("./main")
call("cp ninja.in grader_test" + str(index + 1) + ".in", shell=True)
call("cp ninja.out grader_test" + str(index + 1) + ".ok", shell=True)
print("Done test ", index + 1)
| [
"budau.adi@gmail.com"
] | budau.adi@gmail.com |
a4256da30bcf07a2710b53136e6c4e96dbe16327 | bfe6c95fa8a2aae3c3998bd59555583fed72900a | /construct2DArray.py | 9453894a5ac8b86e076004c0a69fce6ab2f1a457 | [] | no_license | zzz136454872/leetcode | f9534016388a1ba010599f4771c08a55748694b2 | b5ea6c21bff317884bdb3d7e873aa159b8c30215 | refs/heads/master | 2023-09-01T17:26:57.624117 | 2023-08-29T03:18:56 | 2023-08-29T03:18:56 | 240,464,565 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 620 | py | from typing import List
class Solution:
def construct2DArray(self, original: List[int], m: int,
n: int) -> List[List[int]]:
if len(original) != n * m:
return []
out = []
idx = 0
for i in range(m):
tmp = []
for j in range(n):
tmp.append(original[idx])
idx += 1
out.append(tmp)
return out
original = [1, 2, 3, 4]
m = 2
n = 2
original = [1, 2, 3]
m = 1
n = 3
original = [1, 2]
m = 1
n = 1
original = [3]
m = 1
n = 2
print(Solution().construct2DArray(original, m, n))
| [
"zzz136454872@163.com"
] | zzz136454872@163.com |
384064fb13891aac627fd125777d42fd016ce307 | 237fe532664c70630da4ca9e668cd18e2f28e6d4 | /epi/palindrome_decomposition.py | e40e36693a88f293dc2913198ca385d9c1f1fe15 | [] | no_license | mkebrahimpour/DataStructures_Python | 5ef889dbaa2f3754cd787866420bd36b9856404a | f18f6683f07b5d68f736bbc70908655a3939bcdc | refs/heads/master | 2022-01-09T07:09:08.989769 | 2019-06-24T20:46:07 | 2019-06-24T20:46:07 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 724 | py | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Wed Mar 13 16:38:52 2019
@author: sbk
"""
def palindrome_decompositions(input):
def directed_palindrome_decompositions(offset, partial_partition):
if offset == len(input):
result.append(list(partial_partition))
print(result)
return
for i in range(offset + 1, len(input) + 1):
prefix = input[offset:i]
if prefix == prefix[::-1]:
directed_palindrome_decompositions(i, partial_partition + [prefix])
result = []
directed_palindrome_decompositions(0, [])
return result
input_raw = '0204451881'
palindrome_decompositions(input_raw) | [
"shantu24@gmail.com"
] | shantu24@gmail.com |
c1d53722ccc6b61714dbf2b08bf85faf6024b8cf | 0c325cf7a68ef51067ed8db566d525a20de5b635 | /other/panda365/panda365/migrations/versions/1f74ea45e765_add_is_active_and_publish_at_to_post.py | a706c6531a52ee8d8ae265bcd2ab9bf7b0d0dfa2 | [] | no_license | alinzel/NOTES | 2ab6aa1ef1d601a9ae8c0d23c0df2bca7e1aa241 | 3e0594641a605580e920d0b08a251fbc99f34e2f | refs/heads/master | 2023-01-08T22:48:30.762625 | 2020-01-17T09:14:47 | 2020-01-17T09:14:47 | 175,339,492 | 0 | 0 | null | 2022-12-27T15:01:19 | 2019-03-13T03:28:08 | HTML | UTF-8 | Python | false | false | 800 | py | """add is_active and publish_at to post
Revision ID: 1f74ea45e765
Revises: 5ad67785ca96
Create Date: 2017-04-26 17:28:40.186993
"""
from alembic import op
import sqlalchemy as sa
from sqlalchemy_utils import ArrowType
# revision identifiers, used by Alembic.
revision = '1f74ea45e765'
down_revision = '5ad67785ca96'
branch_labels = None
depends_on = None
def upgrade():
op.add_column('post', sa.Column('is_active', sa.Boolean(), nullable=True))
op.execute('UPDATE post SET is_active = true')
op.alter_column('post', 'is_active', nullable=False)
op.add_column('post', sa.Column('publish_at', ArrowType(), nullable=True))
op.execute('UPDATE post SET publish_at = created_at')
def downgrade():
op.drop_column('post', 'publish_at')
op.drop_column('post', 'is_active')
| [
"944951481@qq.com"
] | 944951481@qq.com |
6d8a82a5a8833a9f27e3ea2ad21a97d0aa04612c | 0b83750815203a0b0ce46e9d7d7baa474042072b | /helper/sidebar.py | c26d4b0dd0ba08d6fd589b832722626dea780890 | [
"LicenseRef-scancode-public-domain"
] | permissive | hanya/SidebarByMacros | 735ff808b0cb122613c7e2ab7d53b238cef82a08 | a7bbf394d868d29f094fefcef612231558260832 | refs/heads/master | 2021-01-01T05:02:11.767717 | 2016-05-13T13:27:06 | 2016-05-13T13:27:06 | 58,472,020 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 6,958 | py |
import uno
import unohelper
from com.sun.star.beans import PropertyValue
from com.sun.star.beans.PropertyState import DIRECT_VALUE
from com.sun.star.container import XNameContainer, NoSuchElementException, ElementExistException
from com.sun.star.lang import XServiceInfo, \
IllegalArgumentException
from com.sun.star.ui import XUIElementFactory, XUIElement, XToolPanel, XSidebarPanel, \
LayoutSize
from com.sun.star.ui.UIElementType import TOOLPANEL as UET_TOOLPANEL
from com.sun.star.uno import RuntimeException
class SidebarHelperForMacros(unohelper.Base, XServiceInfo, XUIElementFactory):
""" Helps to someone implements sidebar components in Macros.
The factory for UI element have to be registered under
/org.openoffice.Office.UI.Factories/Registered/UIElementFactories.
And the components have to be implemented acoording to
css.ui.UIElementFactory service.
"""
IMPLE_NAME = "mytools.ui.SidebarHelperForMacros"
SERVICE_NAMES = IMPLE_NAME,
CONFIG = "/mytools.UI.SidebarsByMacros/Content/Imples"
@staticmethod
def get():
klass = SidebarHelperForMacros
return klass, klass.IMPLE_NAME, klass.SERVICE_NAMES
def __init__(self, ctx, *args):
self.ctx = ctx
# XServiceInfo
def getImplementationName(self):
return self.IMPLE_NAME
def supportsService(self, name):
return name in self.SERVICE_NAMES
def getSupportedServiceNames(self):
return self.SERVICE_NAMES
# XUIElementFactory
def createUIElement(self, res_url, args):
# see css.ui.XUIElementFactory
# check the res_url is in the configuration
settings = self._get_settings(res_url)
if not settings:
# no UI element found
raise NoSuchElementException()
frame = parent = None
for arg in args:
if arg.Name == "Frame":
frame = arg.Value
elif arg.Name == "ParentWindow":
parent = arg.Value
#elif arg.Name == "Sidebar":
# If you need css.ui.XSidebar interface to request to
# re-layout, keep it.
#elif arg.Name == "SfxBindings":
# This is just pointer address, not useful for extensions.
if not frame:
raise IllegalArgumentException()
if not parent:
raise IllegalArgumentException()
try:
# new instance of requested UI element
return SidebarUIElement(self.ctx, frame, parent, res_url, settings)
except Exception as e:
print("Error in SidebarUIElement.ctor: " + str(e))
def _create(self, name):
return self.ctx.getServiceManager().createInstanceWithContext(name, self.ctx)
def _create_configuration_reader(self, nodepath, res_url):
cp = self._create("com.sun.star.configuration.ConfigurationProvider")
try:
return cp.createInstanceWithArguments(
"com.sun.star.configuration.ConfigurationAccess",
(PropertyValue("nodepath", -1, nodepath, DIRECT_VALUE),))
except:
pass
return None
def _get_settings(self, res_url):
reader = self._create_configuration_reader(self.CONFIG, res_url)
if reader and reader.hasByName(res_url):
try:
return reader.getByName(res_url)
except:
pass
return None
g_ImplementationHelper = unohelper.ImplementationHelper()
g_ImplementationHelper.addImplementation(*SidebarHelperForMacros.get())
class SidebarUIElement(unohelper.Base, XUIElement, XToolPanel, XSidebarPanel, XNameContainer):
""" Individual panel element in deck of sidebar.
Should be implemented according to css.ui.UIElement service.
In the case of toolpanel element, you need additional interfaces:
- css.ui.XToolPanel: describes panel
- css.ui.XSidebarPanel: panel (optional, but if not, unusable)
"""
def __init__(self, ctx, frame, parent, res_url, settings):
self.res_url = res_url
self.ctx = ctx
self.frame = frame
self.parent = parent
self._values = {}
try:
self.window = self._call_macro(settings.Initialize, (self, self.parent))
except Exception as e:
print(e)
raise RuntimeException("Error while calling Initialize for " + self.res_url, None)
# XUIElement
@property
def Frame(self):
return self.frame
@property
def ResourceURL(self):
return self.res_url
@property
def Type(self):
return UET_TOOLPANEL
def getRealInterface(self):
return self # ToDo weakref?
# XToolPanel
def createAccessible(self, parent):
return None
@property
def Window(self):
return self.window
# XSidebarPanel
def getHeightForWidth(self, width):
v = self._values.get("XSidebarPanel", None)
if v:
try:
return v.getHeightForWidth(width)
except:
pass
return LayoutSize(0, -1, 0)
# LO5.1-
def getMinimalWidth(self):
return 50
#
def _call_macro(self, uri, args=()):
script = self._create_script_provider().getScript(uri)
if script:
try:
r ,_ ,_ = script.invoke(args, (), ())
return r
except Exception as e:
print(e)
return None
def _create_script_provider(self):
mspf = self.ctx.getValueByName(
"/singletons/com.sun.star.script.provider.theMasterScriptProviderFactory")
return mspf.createScriptProvider("")
# ToDo language specific script provider
# XNameContainer
# this interface is not required by the panel, just for helper
def insertByName(self, name, value):
if name in self._values:
raise ElementExistException(name, self)
else:
self._values[name] = value
def removeByName(self, name):
if name in self._values:
self._values.pop(name)
else:
raise NoSuchElementException(name, self)
def replaceByName(self, name, value):
if name in self._values:
self._values[name] = value
else:
raise NoSuchElementException(name, self)
def getByName(self, name):
try:
return self._values[name]
except:
raise NoSuchElementException(name, self)
def getElementNames(self):
return tuple(self._values.names())
def hasByName(self, name):
return name in self._values
def getElementType(self):
return uno.getTypeByName("any")
def hasElements(self):
return len(self._values) != 0
| [
"hanya.runo@gmail.com"
] | hanya.runo@gmail.com |
4f487f55673637fbd76eb531e993577af21b5650 | ea378480ba678eb123ef826e3ca0c3eb8f4e538f | /paused/05. bk old/1.05 rule is class again/bw/field.py | 28716f9f153ed2ee767cb7a4f1ab450d64d25325 | [] | no_license | msarch/py | 67235643666b1ed762d418263f7eed3966d3f522 | dcd25e633a87cdb3710e90224e5387d3516c1cd3 | refs/heads/master | 2021-01-01T05:21:58.175043 | 2017-05-25T08:15:26 | 2017-05-25T08:15:26 | 87,453,820 | 1 | 0 | null | null | null | null | UTF-8 | Python | false | false | 3,514 | py | #!/usr/bin/python
# -*- coding: iso-8859-1 -*-
'''
msarch@free.fr * aug 2014 * bw-rev105
this is the pyglet engine.
- displays cells on windows redraws
- cycle through rules at each clock tick
'''
##---IMPORTS ------------------------------------------------------------------
from itertools import izip
from pyglet import clock
import pyglet.gl
from pyglet.gl import *
from pyglet.window import key, get_platform
from pyglet.gl import(
glLoadIdentity,
glMatrixMode,
gluOrtho2D,
GL_MODELVIEW, GL_PROJECTION,
)
from colors import *
from shapes import *
from rules import *
#--- CONSTANTS ----------------------------------------------------------------
FRAMERATE = 1.0/30
MOVIE_FRAMERATE = 1.0 / 25 # framerate for movie export
CLOCKDISPLAY = clock.ClockDisplay()
_screen = get_platform().get_default_display().get_default_screen()
WIDTH, HEIGHT = _screen.width*1.0 ,_screen.height*1.0
CENTX, CENTY = WIDTH*0.5, HEIGHT*0.5
SCREEN = AABB(-CENTX, -CENTY, CENTX, CENTY)
ASPECT = WIDTH / HEIGHT
# @TODO : check how to go bigger than screen, then resize to fullscreen
#--- GLOBALS ------------------------------------------------------------------
paused = False
show_fps = True
fullscreen = True
field_color = white
#--- PYGLET Window setup ------------------------------------------------------
VIEW = pyglet.window.Window(resizable = True)
VIEW.set_fullscreen(fullscreen)
VIEW.set_mouse_visible(not fullscreen)
def set_field_color(new_color): # change background color
global field_color
field_color = new_color
glClearColor(new_color.r,new_color.g,new_color.b,new_color.a)
def view_setup(): # general GL setup
glMatrixMode(GL_PROJECTION)
glMatrixMode(GL_MODELVIEW)
gluOrtho2D(0, WIDTH, 0, HEIGHT)
glLoadIdentity()
glTranslatef(CENTX, CENTY, 0)
#--- VIEW key handling --------------------------------------------------------
@VIEW.event
def on_key_press(symbol, modifiers): # override pyglet window's
global paused, show_fps, fullscreen
if symbol == key.ESCAPE:
exit(0)
elif symbol == key.F:
fullscreen = (True,False)[fullscreen]
print fullscreen
VIEW.set_fullscreen(fullscreen)
VIEW.set_mouse_visible(not fullscreen)
else:
paused = (True,False)[paused]
show_fps = (True,False)[show_fps]
#--- PYGLET ENGINE ------------------------------------------------------------
@VIEW.event
def on_draw():
glClear(GL_COLOR_BUFFER_BIT)
# @TODO : inserer le facteur d'adaptation a la taille de l'ecran,
for shp in setup:
if shp.peg:
shp.paint(shp.peg)
else:
pass
if show_fps:
CLOCKDISPLAY.draw()
#--- scene update -------------------------------------------------------------
def tick(dt):
if paused:
pass
else:
for rule in ruleset:
rule.tick(dt)
#--- run mode options 1 : fullscreen animation --------------------------------
def animate():
set_field_color(field_color)
view_setup()
clock.schedule_interval(tick, FRAMERATE) # infinite loop ------------
pyglet.app.run()
#--- NOTES --------------------------------------------------------------------
'''
from ThinkingParticles, reuse:
- IDS/ODS : input data stream, output data stream
- memory node : allows the storage of any kind of data.
- IN/OUT volume testing algorithm has been added
- PSearch node, search the nearest/furthest particle in a specific radius
'''
| [
"msarch@free.fr"
] | msarch@free.fr |
a6853dc9a6c90720932e56e043d48372eb710b4b | 681566c88f834bd05cfb85a6acfd218429a24edd | /notes/middleware.py | 98ceffd6d154480c43355f781a62309c74f05891 | [] | no_license | cmwaura/social-site | 7eaaa03ee2aef0a5a8ef4612ee0c15a135b344f7 | d90b34334b873ac2fecb7e30b40e3d295b2dd5b7 | refs/heads/master | 2023-07-06T11:05:55.273126 | 2016-12-08T03:09:10 | 2016-12-08T03:09:10 | 70,009,809 | 1 | 0 | null | 2023-09-04T23:24:30 | 2016-10-04T21:56:54 | Python | UTF-8 | Python | false | false | 737 | py | from django.contrib.auth.decorators import login_required
from django.conf import settings
EXCEPTION_URL_SUFFIX_LIST = getattr(settings, 'LOGIN_EXCEPTION_URL_SUFFIX_LIST', ())
class LoginRequiredMiddleware(object):
def process_view(self, request, view_func, view_args, view_kwargs):
# This middleware is meant to handle all the login required webpages and give access to the
# anonymous users based on approved views.
path = request.path
for exception_url in EXCEPTION_URL_SUFFIX_LIST:
if path.startswith(exception_url):
return None
is_login_required = getattr(view_func, 'login_required', True)
if not is_login_required:
return None
return login_required(view_func)(request, *view_args, **view_kwargs)
| [
"cmmwaura@ucdavis.edu"
] | cmmwaura@ucdavis.edu |
105190afe7758cee2983dd93d88db6cc7c9e51c6 | 9743d5fd24822f79c156ad112229e25adb9ed6f6 | /xai/brain/wordbase/verbs/_stares.py | ef0bb31379fcba9a8dc76e5d0d0f105e0183914f | [
"MIT"
] | permissive | cash2one/xai | de7adad1758f50dd6786bf0111e71a903f039b64 | e76f12c9f4dcf3ac1c7c08b0cc8844c0b0a104b6 | refs/heads/master | 2021-01-19T12:33:54.964379 | 2017-01-28T02:00:50 | 2017-01-28T02:00:50 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 231 | py |
from xai.brain.wordbase.verbs._stare import _STARE
#calss header
class _STARES(_STARE, ):
def __init__(self,):
_STARE.__init__(self)
self.name = "STARES"
self.specie = 'verbs'
self.basic = "stare"
self.jsondata = {}
| [
"xingwang1991@gmail.com"
] | xingwang1991@gmail.com |
d1d77c85b19504b9143576ea2c21d7802b398570 | 54d970eadb0dca9889a6bf4c7fa103031783a43d | /leetcode/169.majority_element.py | 099a6c0c837a09c6c067064062153bc6cf2c4c55 | [] | no_license | swq90/python | 54229319dd578a2f889bf47da2263bb35e1bc2b9 | b1f659aa01bb8409c96509a0debcdfaf38a19192 | refs/heads/master | 2021-06-27T14:44:46.699735 | 2021-02-16T05:53:39 | 2021-02-16T05:53:39 | 185,103,423 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 857 | py | class Solution(object):
def majorityElement(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
l = set(nums)
c = len(nums)/2
for n in l:
count = 0
for x in nums:
if n == x:
count += 1
if count > c:
return n
def majorityElement2(self, nums):
return sorted(nums)[len(nums)/2]
def majorityElement3(self, nums):
major = nums[0]
count = 1
for i in range(1,len(nums)):
if nums[i] == major:
count += 1
elif count == 0:
major = nums[i]
count +=1
else:
count -= 1
return major
# 1.自己的笨方法
# 2.小聪明,但是时间……
# 3.别人的答案,O(n) | [
"shaowenqin620@163.com"
] | shaowenqin620@163.com |
25ebc922e6616ba71700b599a476ca5be37faf97 | 97aa5f503e420422a29fb7ffcf0a7cd3f871915d | /beetween_eyes.py | 6783d751cb3929b5deb3db01badc3c178b499a94 | [] | no_license | LeGrosLezard/synergo_depot_2 | d3e82656f15141b2cee25c312ec942727d0cabfa | c751200ccad2cf4b6503be529bc0ec3b43f57e2d | refs/heads/master | 2021-02-13T22:19:15.560484 | 2020-03-08T01:47:36 | 2020-03-08T01:47:36 | 244,739,180 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 3,088 | py | import cv2
import numpy as np
import threading
import math
def extremums(c):
xe = tuple(c[c[:, :, 0].argmin()][0]) #left
ye = tuple(c[c[:, :, 1].argmin()][0]) #right
we = tuple(c[c[:, :, 0].argmax()][0])
he = tuple(c[c[:, :, 1].argmax()][0]) #bottom
return xe, ye, we, he
def make_line(thresh):
"""We make line for detect more than one area
with border, on eyelashes is paste to the border"""
cv2.line(thresh, (0, 0), (0, thresh.shape[0]), (255, 255, 255), 2)
cv2.line(thresh, (0, 0), (thresh.shape[1], 0), (255, 255, 255), 2)
cv2.line(thresh, (thresh.shape[1], 0), (thresh.shape[1], thresh.shape[0]), (255, 255, 255), 2)
cv2.line(thresh, (0, thresh.shape[0]), (thresh.shape[1], thresh.shape[0]), (255, 255, 255), 2)
return thresh
def recuperate_landmarks(landmarks_head, head_box_head):
_, _, width_head, height_head = head_box_head
adding_height = int(height_head * 0.09) #5 de 74
adding_width = int(width_head * 0.015) #1 de 90
area_landmarks1 = (landmarks_head.part(21).x - adding_width,
landmarks_head.part(21).y - adding_height)
area_landmarks2 = (landmarks_head.part(22).x + adding_width,
landmarks_head.part(22).y - adding_height)
area_landmarks3 = (landmarks_head.part(27).x,
landmarks_head.part(27).y - adding_height)
area_landmarks = [area_landmarks1, area_landmarks2, area_landmarks3]
return area_landmarks
def masks(area_landmarks, threshold, frame_head):
#Make a box of the region.
box_crop = cv2.boundingRect(np.array(area_landmarks))
x ,y, w, h = box_crop
#cv2.rectangle(frame_head, (x, y), (x+w, y+h), (0, 0, 255), 1)
crop_threhsold = threshold[y:y+h, x:x+w]
crop_threhsold = make_line(crop_threhsold)
crop_frame = frame_head[y:y+h, x:x+w]
return crop_threhsold, crop_frame, box_crop
def localisation_wrinkle(crop_threhsold, crop_frame, box_crop):
x ,y, w, h = box_crop
contours, _ = cv2.findContours(crop_threhsold, cv2.RETR_TREE, cv2.CHAIN_APPROX_NONE)
wrinkle = 0
wrinkle_list = []
for c in contours:
max_contour = int((w * h) * 0.5)
min_contour = int((w * h) * 0.075)
if min_contour < cv2.contourArea(c) < max_contour:
xe, ye, we, he = extremums(c)
largeur = we[0] - xe[0]
longueur = he[1] - ye[1]
if longueur > largeur:
wrinkle += 1
wrinkle_list.append((he, ye))
if wrinkle == 2:
[cv2.line(crop_frame, i[0], i[1], (0, 0, 255), 1) for i in wrinkle_list]
def wrinkle_lion(frame_head, landmarks_head, gray, threshold, head_box_head):
area_landmarks = recuperate_landmarks(landmarks_head, head_box_head)
crop_threhsold, crop_frame, box_crop = masks(area_landmarks, threshold, frame_head)
localisation_wrinkle(crop_threhsold, crop_frame, box_crop)
| [
"noreply@github.com"
] | LeGrosLezard.noreply@github.com |
e26eb4ebcbe9aeb7189a193c9f0a67a9fb994c6d | aa4f2cfb001026c17e89af2b304acc4b80a3c638 | /assignment1/q4_sentiment.py | 42d9bc7a3528797d36c22a03aed74b5e548a7236 | [] | no_license | PanXiebit/standford-cs224d | 3b15077f99908708605758c592eebc1515fb2440 | e68497823213eb71467eaac09effff9f1b4bba20 | refs/heads/master | 2020-03-15T06:51:47.063509 | 2018-05-11T01:03:26 | 2018-05-11T01:03:26 | 132,016,982 | 0 | 1 | null | null | null | null | UTF-8 | Python | false | false | 4,225 | py | from __future__ import print_function
import numpy as np
import matplotlib.pyplot as plt
from cs224d.glove import *
from cs224d.data_utils import *
from q3_sgd import load_saved_params, sgd
from q4_softmaxreg import softmaxRegression, getSentenceFeature, accuracy, softmax_wrapper
# Try different regularizations and pick the best!
# NOTE: fill in one more "your code here" below before running!
# REGULARIZATION = None # Assign a list of floats in the block below
### YOUR CODE HERE
REGULARIZATION = np.logspace(-3,0,6)
REGULARIZATION = np.hstack([0,REGULARIZATION])
# REGULARIZATION = [0.0, 0.000001, 0.00001, 0.0001, 0.001, 0.01, 0.1, 1]
### END YOUR CODE
# Load the dataset
dataset = StanfordSentiment()
tokens = dataset.tokens()
nWords = len(tokens)
def wordVectors(pretrain=False):
# Load the word vectors we trained earlier 自己训练的词向量
if not pretrain:
_, wordVectors0, _ = load_saved_params()
wordVectors = (wordVectors0[:nWords, :] + wordVectors0[nWords:, :])
else:
wordVectors = loadWordVectors(tokens)
return wordVectors
wordVectors = wordVectors(pretrain=False)
dimVectors = wordVectors.shape[1]
# Load the train set
trainset = dataset.getTrainSentences()
nTrain = len(trainset)
trainFeatures = np.zeros((nTrain, dimVectors))
trainLabels = np.zeros((nTrain,), dtype=np.int32)
for i in range(nTrain):
words, trainLabels[i] = trainset[i]
trainFeatures[i, :] = getSentenceFeature(tokens, wordVectors, words) # 用平均值~。。
# Prepare dev set features
devset = dataset.getDevSentences()
nDev = len(devset)
devFeatures = np.zeros((nDev, dimVectors))
devLabels = np.zeros((nDev,), dtype=np.int32)
for i in range(nDev):
words, devLabels[i] = devset[i]
devFeatures[i, :] = getSentenceFeature(tokens, wordVectors, words)
# Try our regularization parameters
results = []
for regularization in REGULARIZATION:
random.seed(3141)
np.random.seed(59265)
weights = np.random.randn(dimVectors, 5) # 0,1,2,3,4 总共5类
print("Training for reg=%f" % regularization )
# We will do batch optimization
# 使用sgd来训练参数
weights = sgd(lambda weights: softmax_wrapper(trainFeatures, trainLabels,
weights, regularization), weights, 3.0, 10000, PRINT_EVERY=1000)
# Test on train set
_, _, pred = softmaxRegression(trainFeatures, trainLabels, weights)
trainAccuracy = accuracy(trainLabels, pred)
print ("Train accuracy (%%): %f" % trainAccuracy)
# Test on dev set
_, _, pred = softmaxRegression(devFeatures, devLabels, weights)
devAccuracy = accuracy(devLabels, pred)
print ("Dev accuracy (%%): %f" % devAccuracy)
# Save the results and weights
results.append({
"reg" : regularization,
"weights" : weights,
"train" : trainAccuracy,
"dev" : devAccuracy})
# Print the accuracies
print ("")
print ("=== Recap ===")
print ("Reg\t\tTrain\t\tDev")
for result in results:
print ("%E\t%f\t%f" % (
result["reg"],
result["train"],
result["dev"]))
print ("")
# Pick the best regularization parameters
BEST_REGULARIZATION = None
BEST_WEIGHTS = None
### YOUR CODE HERE
bestdev = 0
for result in results:
if result['dev'] > bestdev:
BEST_REGULARIZATION = result['reg']
BEST_WEIGHTS = result['weights']
bestdev = result['dev']
### END YOUR CODE
# Test your findings on the test set
testset = dataset.getTestSentences()
nTest = len(testset)
testFeatures = np.zeros((nTest, dimVectors))
testLabels = np.zeros((nTest,), dtype=np.int32)
for i in range(nTest):
words, testLabels[i] = testset[i]
testFeatures[i, :] = getSentenceFeature(tokens, wordVectors, words)
_, _, pred = softmaxRegression(testFeatures, testLabels, BEST_WEIGHTS)
print ("Best regularization value: %E" % BEST_REGULARIZATION)
print ("Test accuracy (%%): %f" % accuracy(testLabels, pred))
# Make a plot of regularization vs accuracy
plt.plot(REGULARIZATION, [x["train"] for x in results])
plt.plot(REGULARIZATION, [x["dev"] for x in results])
plt.xscale('log')
plt.xlabel("regularization")
plt.ylabel("accuracy")
plt.legend(['train', 'dev'], loc='upper left')
plt.savefig("q4_reg_v_acc.png")
plt.show()
| [
"ftdpanxie@gmail.com"
] | ftdpanxie@gmail.com |
0c01af511f45a461139ffb51b4b91df3b226045d | 1d892928c70ee9ddf66f2a37a8e083d2632c6e38 | /nova/virt/vmwareapi/vim.py | d8684ce7c9956a1181363d0dcada19589839e258 | [
"Apache-2.0"
] | permissive | usc-isi/essex-baremetal-support | 74196c3f1332ee3cdeba9c263faff0ac0567d3cf | a77daf8ef56cf41e38de36621eda25ed3f180156 | refs/heads/master | 2021-05-19T03:12:11.929550 | 2020-07-24T14:15:26 | 2020-07-24T14:15:26 | 4,702,421 | 0 | 1 | Apache-2.0 | 2020-07-24T14:15:27 | 2012-06-18T15:19:41 | null | UTF-8 | Python | false | false | 7,619 | py | # vim: tabstop=4 shiftwidth=4 softtabstop=4
# Copyright (c) 2011 Citrix Systems, Inc.
# Copyright 2011 OpenStack LLC.
#
# 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.
"""
Classes for making VMware VI SOAP calls.
"""
import httplib
try:
import suds
except ImportError:
suds = None
from nova import flags
from nova.openstack.common import cfg
from nova.virt.vmwareapi import error_util
RESP_NOT_XML_ERROR = 'Response is "text/html", not "text/xml"'
CONN_ABORT_ERROR = 'Software caused connection abort'
ADDRESS_IN_USE_ERROR = 'Address already in use'
vmwareapi_wsdl_loc_opt = cfg.StrOpt('vmwareapi_wsdl_loc',
default=None,
help='VIM Service WSDL Location '
'e.g http://<server>/vimService.wsdl. '
'Due to a bug in vSphere ESX 4.1 default wsdl. '
'Refer readme-vmware to setup')
FLAGS = flags.FLAGS
FLAGS.register_opt(vmwareapi_wsdl_loc_opt)
if suds:
class VIMMessagePlugin(suds.plugin.MessagePlugin):
def addAttributeForValue(self, node):
# suds does not handle AnyType properly.
# VI SDK requires type attribute to be set when AnyType is used
if node.name == 'value':
node.set('xsi:type', 'xsd:string')
def marshalled(self, context):
"""suds will send the specified soap envelope.
Provides the plugin with the opportunity to prune empty
nodes and fixup nodes before sending it to the server.
"""
# suds builds the entire request object based on the wsdl schema.
# VI SDK throws server errors if optional SOAP nodes are sent
# without values, e.g. <test/> as opposed to <test>test</test>
context.envelope.prune()
context.envelope.walk(self.addAttributeForValue)
class Vim:
"""The VIM Object."""
def __init__(self,
protocol="https",
host="localhost"):
"""
Creates the necessary Communication interfaces and gets the
ServiceContent for initiating SOAP transactions.
protocol: http or https
host : ESX IPAddress[:port] or ESX Hostname[:port]
"""
if not suds:
raise Exception(_("Unable to import suds."))
self._protocol = protocol
self._host_name = host
wsdl_url = FLAGS.vmwareapi_wsdl_loc
if wsdl_url is None:
raise Exception(_("Must specify vmwareapi_wsdl_loc"))
# TODO(sateesh): Use this when VMware fixes their faulty wsdl
#wsdl_url = '%s://%s/sdk/vimService.wsdl' % (self._protocol,
# self._host_name)
url = '%s://%s/sdk' % (self._protocol, self._host_name)
self.client = suds.client.Client(wsdl_url, location=url,
plugins=[VIMMessagePlugin()])
self._service_content = self.RetrieveServiceContent("ServiceInstance")
def get_service_content(self):
"""Gets the service content object."""
return self._service_content
def __getattr__(self, attr_name):
"""Makes the API calls and gets the result."""
try:
return object.__getattr__(self, attr_name)
except AttributeError:
def vim_request_handler(managed_object, **kwargs):
"""
Builds the SOAP message and parses the response for fault
checking and other errors.
managed_object : Managed Object Reference or Managed
Object Name
**kwargs : Keyword arguments of the call
"""
# Dynamic handler for VI SDK Calls
try:
request_mo = self._request_managed_object_builder(
managed_object)
request = getattr(self.client.service, attr_name)
response = request(request_mo, **kwargs)
# To check for the faults that are part of the message body
# and not returned as Fault object response from the ESX
# SOAP server
if hasattr(error_util.FaultCheckers,
attr_name.lower() + "_fault_checker"):
fault_checker = getattr(error_util.FaultCheckers,
attr_name.lower() + "_fault_checker")
fault_checker(response)
return response
# Catch the VimFaultException that is raised by the fault
# check of the SOAP response
except error_util.VimFaultException, excep:
raise
except suds.WebFault, excep:
doc = excep.document
detail = doc.childAtPath("/Envelope/Body/Fault/detail")
fault_list = []
for child in detail.getChildren():
fault_list.append(child.get("type"))
raise error_util.VimFaultException(fault_list, excep)
except AttributeError, excep:
raise error_util.VimAttributeError(_("No such SOAP method "
"'%s' provided by VI SDK") % (attr_name), excep)
except (httplib.CannotSendRequest,
httplib.ResponseNotReady,
httplib.CannotSendHeader), excep:
raise error_util.SessionOverLoadException(_("httplib "
"error in %s: ") % (attr_name), excep)
except Exception, excep:
# Socket errors which need special handling for they
# might be caused by ESX API call overload
if (str(excep).find(ADDRESS_IN_USE_ERROR) != -1 or
str(excep).find(CONN_ABORT_ERROR)) != -1:
raise error_util.SessionOverLoadException(_("Socket "
"error in %s: ") % (attr_name), excep)
# Type error that needs special handling for it might be
# caused by ESX host API call overload
elif str(excep).find(RESP_NOT_XML_ERROR) != -1:
raise error_util.SessionOverLoadException(_("Type "
"error in %s: ") % (attr_name), excep)
else:
raise error_util.VimException(
_("Exception in %s ") % (attr_name), excep)
return vim_request_handler
def _request_managed_object_builder(self, managed_object):
"""Builds the request managed object."""
# Request Managed Object Builder
if isinstance(managed_object, str):
mo = suds.sudsobject.Property(managed_object)
mo._type = managed_object
else:
mo = managed_object
return mo
def __repr__(self):
return "VIM Object"
def __str__(self):
return "VIM Object"
| [
"dkang@isi.edu"
] | dkang@isi.edu |
c9f2f3fecb1bc630117de97f47fd2588970698d8 | d5fcdea2f2f78bc3fcf39bdf34c8067238edce2c | /qxh/homework20201104/code.py | ede33d99b15778f5153a4cf55dc37b5382d8011f | [] | no_license | ophwsjtu18/ohw20f | a5a6f4d262f48ddc8332838f344c86ec0636b7d4 | 03d7067f0e645338b84410ff13a77d495bec661e | refs/heads/main | 2023-02-04T21:20:21.123617 | 2020-12-25T09:00:04 | 2020-12-25T09:00:04 | 303,941,346 | 4 | 6 | null | 2020-10-14T10:51:15 | 2020-10-14T07:49:18 | null | UTF-8 | Python | false | false | 728 | py | import cv2
import random
import numpy as np
print("hello")
img=cv2.imread("cat.png")
imgold = img.copy()
point = 0
def mouse(event,x,y,flags,param):
global point,curr
if event == cv2.EVENT_LBUTTONDOWN:
if i*50<=x<=(i+1)*50 and j*50<=y<=(j+1)*50:
point = point+1
print(point)
cv2.namedWindow('qxh')
cv2.setMouseCallback('qxh',mouse)
while True:
img = imgold.copy()
head= img[400:450,500:550].copy()
i = random.randint(0,2)
j = random.randint(0,2)
img[i*50:(i+1)*50,j*50:(j+1)*50]=head
for a in range(0,3):
for b in range(0,3):
cv2.rectangle(img,(50*a,50*b),(50+50*a,50+50*b),(0,255,0),3)
cv2.imshow('qxh',img)
cv2.waitKey(500)
| [
"noreply@github.com"
] | ophwsjtu18.noreply@github.com |
7f260eaba2132e0e7ef19adf23a3ee754a689496 | 54a745510b16111f5e5f610a07be49ea1e79fccf | /ML/03matplotlib.py | 51a928da6ca02165ed7cea4fd31ebabc6c2b90fe | [] | no_license | SonDog0/bigdata | 84a5b7c58ad9680cdc0e49ac6088f482e09118a5 | e6cd1e3bbb0bfec0c89a31b3fb4ef66d50c272be | refs/heads/master | 2020-04-22T02:24:16.469718 | 2019-03-13T08:59:26 | 2019-03-13T08:59:26 | 170,047,330 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 5,621 | py | # matplotlib
# 파이썬의 대표적인 시각화 도구
# numpy 기반으로 만들어진 다중 플랫폼 데이터 시각화 라이브러리
# 하지만, 시간이 지남에 따라 인터페이스와 스타일이 고루해짐
# R의 ggplot처럼 세련되고 새로운 도구의 출현을 기대함
# 후추 깔끔하고 현대적인API로 무장한 seaborn 패키지 탄생
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
# 주피터노트북에서 matplotlib를 이용한 그래프 그리기
# %matplotlib inline 를 설정해 두면
# show 함수 호출 없이 그래프를 그릴 수 있음
# 간단한 선 그래프
#plt.plot([1,4,9,16,25])
#plt.show()
# => 지정한 자료는 자동으로 y축으로 지정
# => x축 값이 없으면 자동으로 0,1,2,3 ...으로 설정
# 즉, np.array 객체를 인자로 넘기는 경우,
# y 축만 설정하면 x 축은 자동으로 감지
np.random.seed(181218)
# #y = np.random.standard_normal(20) # 정규분포 난수
# #print(y)
#
# #x = range(len(y))
#
# # plt.plot(y)
# # plt.show()
# # plt.plot(x,y)
# # plt.show()
#
#
#
# # 암시적 스타일 지정하기 : 색, 모양, 선
# # 색 : r,g,b,c,m,y,k,w
# # 마커 : . o v ^ 1 p * + d D
# # 선 : : -. -- -
#
# plt.plot([1,2,3,4,5],[9,8,7,6,5],'r*:')
# # plt.show()
#
#
# # 명시적 스타일로 지정하기
# # color, linewidth, linestyle, markersize,
# # marker edge color, marker edge width, marker face color
# plt.plot([1,2,3,4,5],[10,20,30,40,50],
# c='m',lw=3,ls='--',marker='d',
# ms=20,mec='k',mew=5,mfc='r')
# # plt.show()
#
# # 그래프 축 제어하기
# # matplotlib에서 축, 그래프, 레이블등
# # 모든 객체를 아우르는 하나의 그릇(container)
# fig = plt.figure() # plot container
# # plt.show() # 빈화면만 출력
# ax = plt.axes()
x = np.linspace(0,10,1000) # 지정한 구간을 구간수로 분활
# print('분활된 구간수',x)
# # sin 그래프
# fig = plt.figure()
# ax = plt.axes()
# ax.plot(x, np.sin(x))
# plt.grid()
# plt.show()
#
# # cos 그래프
# fig = plt.figure()
# ax = plt.axes()
# ax.plot(x, np.cos(x))
# plt.grid()
# plt.show()
#
# # tan 그래프
# fig = plt.figure()
# ax = plt.axes()
# ax.plot(x, np.tan(x/2))
# plt.grid()
# plt.ylim(100,-100)
# plt.xlim(2,4)
# plt.show()
# sin,cos,tan 함께 그리기 1
# fig = plt.figure()
# ax = plt.axes()
# ax.plot(x, np.sin(x), c='r')
# ax.plot(x, np.cos(x), c='b')
# ax.plot(x, np.tan(x/2), c='g')
# plt.grid()
# plt.ylim(2,-2)
# plt.xlim(10,-10)
# plt.show()
# # sin,cos,tan 함께 그리기 2
# fig = plt.figure()
# ax = plt.axes()
# ax.plot(x, np.sin(x), 'r',
# x, np.cos(x), 'b--',
# x, np.tan(x/2),'g-.')
# plt.grid()
# plt.ylim(2,-2)
# plt.xlim(10,-10)
# plt.show()
# # 그래프 색상 지정 방식
# fig = plt.figure()
# ax = plt.axes()
# ax.plot(x, np.sin(x-0), c='red') # 색상명
# ax.plot(x, np.sin(x-1), c='b') # 단축
# ax.plot(x, np.sin(x-2), c='0.45') # 회색조 0검정 ~ 1흰 사이
# ax.plot(x, np.sin(x-3), c='#4c0b5f') # 16진수표기(RRGGBB)
# ax.plot(x, np.sin(x-4), c=(1.0, 0.2, 0.3)) #RGB tuple(0,1)
# ax.plot(x, np.sin(x-5), c='darkred') # HTML 색상이름
# plt.grid()
# plt.show()
# 그래프 색 모양 지정 방식
# fig = plt.figure()
# ax = plt.axes()
# ax.plot(x, x+2, linestyle='solid') # -
# ax.plot(x, x+2, linestyle='dashed') # --
# ax.plot(x, x+2, linestyle='dotted') # .
# ax.plot(x, x+2, linestyle='dashdot') # -.
# plt.grid()
# plt.show()
# # 그래프 축, 라벨, 타이틀 지정
# fig = plt.figure()
# ax = plt.axes()
# ax.plot(x, np.sin(x), 'r', label='sin(x)')
# ax.plot(x, np.cos(x), 'b', label='cos(x)')
# plt.legend()
# plt.title('sin&cos function curve')
# plt.xlabel('x value') # x축 제목
# plt.ylabel('y value') # y축 제목
# plt.grid()
# plt.show()
# 타이틀 통합 지정 - axes
# fig = plt.figure()
# ax = plt.axes()
# ax.plot(x, np.sin(x), 'r', label='sin(x)')
# ax.plot(x, np.cos(x), 'b', label='cos(x)')
# ax.set(xlim=(0,10),ylim=(-2,2),
# xlabel='x value',ylabel='y value',
# title='sin&cos function curve')
# ax.legend()
# # ax.set_title() 식으로 다 따로 쓸 수도 있음
# ax.grid()
# plt.show()
# matplotlib 한글 사용
import matplotlib as mpl
# ftpath = 'C:/Windows/Fonts/D2Coding-Ver1.3.2-20180524.ttf'
# fname = mpl.font_manager.FontProperties(fname=ftpath).get_name()
# mpl.rc('font',family=fname)
# mpl.rcParams['axes.unicode_minus'] = False
# mpl.rcParams['font.size'] = 20
#
# fig = plt.figure()
# ax = plt.axes()
# ax.plot(x, np.sin(x), label='사인')
# ax.legend()
# plt.show()
# 시스템에 설치된 폰트정보 알아내기
import matplotlib.font_manager as fm
font_list = fm.findSystemFonts(fontpaths=None, fontext='ttf')
print(font_list[:10]) # ttf 폰트 목록 상위 10개 출력
for f in fm.fontManager.ttflist:
print(f.name) # matplotlib가 관리하는 폰트 목록
for f in fm.fontManager.ttflist:
if 'YTT' in f.fname:
print(f.name, f.fname) # ''가 포함된 폰트이름 출력
mpl.rcParams['font.family'] = 'Yj TEUNTEUN Bold'
mpl.rcParams['axes.unicode_minus'] = False
mpl.rcParams['font.size'] = 20
fig = plt.figure()
ax = plt.axes()
ax.plot(x, np.sin(x), label='사인')
ax.legend()
plt.axhline(y=0, c='b', linewidth=1)
# plt.axvline(y=0, c='b', linewidth=1)
plt.show() | [
"noreply@github.com"
] | SonDog0.noreply@github.com |
e5398d21f5c7efbfb78f9baabca55243340adfa6 | 6b1b506139088aa30de9fd65cff9e3b6a3a36874 | /sofia_redux/toolkit/fitting/tests/test_polynomial/test_linear_evaluate.py | f32c3f8d35bf59b46ec924a4f754f12ce4960ec4 | [
"BSD-3-Clause"
] | permissive | SOFIA-USRA/sofia_redux | df2e6ad402b50eb014b574ea561734334d70f84d | 493700340cd34d5f319af6f3a562a82135bb30dd | refs/heads/main | 2023-08-17T11:11:50.559987 | 2023-08-13T19:52:37 | 2023-08-13T19:52:37 | 311,773,000 | 12 | 2 | null | null | null | null | UTF-8 | Python | false | false | 1,486 | py | # Licensed under a 3-clause BSD style license - see LICENSE.rst
import numpy as np
import pytest
from sofia_redux.toolkit.fitting.polynomial import linear_evaluate
@pytest.fixture
def data():
a = np.array([[3, 4], [5, 6.]])
b = np.array([7., 8])
out = np.array([3.5, 4.5])[None].T
return a, b, out
def test_disallow_errors(data):
result = linear_evaluate(*data, allow_errors=False)
assert np.allclose(result, 5.5)
a, b, out = data
# test datavec
result = linear_evaluate(a[None], b[None], out, allow_errors=False)
assert np.allclose(result, 5.5)
assert result.shape == (1, 1)
with pytest.raises(np.linalg.LinAlgError):
linear_evaluate(a[None] * 0, b[None], out, allow_errors=False)
def test_allow_errors(data):
result = linear_evaluate(*data, allow_errors=True)
assert np.allclose(result, 5.5)
a, b, out = data
# test datavec
result = linear_evaluate(a[None], b[None], out, allow_errors=True)
assert np.allclose(result, 5.5)
assert result.shape == (1, 1)
result = linear_evaluate(a[None] * 0, b[None], out, allow_errors=True)
assert np.isnan(result).all()
a2 = np.stack((a, a))
b2 = np.stack((b, b))
a2[0] *= 0
result = linear_evaluate(a2, b2, out, allow_errors=True)
assert np.allclose(result, [[np.nan], [5.5]], equal_nan=True)
# test no datavec with error
result = linear_evaluate(a * 0, b, out, allow_errors=True)
assert np.isnan(result).all()
| [
"melanie.j.clarke@nasa.gov"
] | melanie.j.clarke@nasa.gov |
f52d6c9450b0f7d1d43cf363370c7c348683e874 | b2e1f29524122ccc3ff1fd477b2ff99502a9daf8 | /games/spiders/ai.py | 2a44d213de2808a2fb30d5fcdd7469c1addc35da | [
"MIT"
] | permissive | siggame/Joueur.py | c6b368d4e98b14652ae39640f50e94406696f473 | 02bb5788ed5d88d24eb21869a10c6e7292ee9767 | refs/heads/master | 2022-05-10T02:16:38.136295 | 2022-05-03T22:03:23 | 2022-05-03T22:03:23 | 31,439,144 | 4 | 40 | MIT | 2020-11-08T00:25:54 | 2015-02-27T21:06:17 | Python | UTF-8 | Python | false | false | 3,454 | py | # This is where you build your AI for the Spiders game.
from joueur.base_ai import BaseAI
# <<-- Creer-Merge: imports -->> - Code you add between this comment and the end comment will be preserved between Creer re-runs.
# you can add additional import(s) here
# <<-- /Creer-Merge: imports -->>
class AI(BaseAI):
""" The AI you add and improve code inside to play Spiders. """
@property
def game(self) -> 'games.spiders.game.Game':
"""games.spiders.game.Game: The reference to the Game instance this AI is playing.
"""
return self._game # don't directly touch this "private" variable pls
@property
def player(self) -> 'games.spiders.player.Player':
"""games.spiders.player.Player: The reference to the Player this AI controls in the Game.
"""
return self._player # don't directly touch this "private" variable pls
def get_name(self) -> str:
"""This is the name you send to the server so your AI will control the player named this string.
Returns:
str: The name of your Player.
"""
# <<-- Creer-Merge: get-name -->> - Code you add between this comment and the end comment will be preserved between Creer re-runs.
return "Spiders Python Player" # REPLACE THIS WITH YOUR TEAM NAME
# <<-- /Creer-Merge: get-name -->>
def start(self) -> None:
"""This is called once the game starts and your AI knows its player and game. You can initialize your AI here.
"""
# <<-- Creer-Merge: start -->> - Code you add between this comment and the end comment will be preserved between Creer re-runs.
# replace with your start logic
# <<-- /Creer-Merge: start -->>
def game_updated(self) -> None:
"""This is called every time the game's state updates, so if you are tracking anything you can update it here.
"""
# <<-- Creer-Merge: game-updated -->> - Code you add between this comment and the end comment will be preserved between Creer re-runs.
# replace with your game updated logic
# <<-- /Creer-Merge: game-updated -->>
def end(self, won: bool, reason: str) -> None:
"""This is called when the game ends, you can clean up your data and dump files here if need be.
Args:
won (bool): True means you won, False means you lost.
reason (str): The human readable string explaining why your AI won or lost.
"""
# <<-- Creer-Merge: end -->> - Code you add between this comment and the end comment will be preserved between Creer re-runs.
# replace with your end logic
# <<-- /Creer-Merge: end -->>
def run_turn(self) -> bool:
"""This is called every time it is this AI.player's turn.
Returns:
bool: Represents if you want to end your turn. True means end your turn, False means to keep your turn going and re-call this function.
"""
# <<-- Creer-Merge: runTurn -->> - Code you add between this comment and the end comment will be preserved between Creer re-runs.
# Put your game logic here for runTurn
return True
# <<-- /Creer-Merge: runTurn -->>
# <<-- Creer-Merge: functions -->> - Code you add between this comment and the end comment will be preserved between Creer re-runs.
# if you need additional functions for your AI you can add them here
# <<-- /Creer-Merge: functions -->>
| [
"jacob.t.fischer@gmail.com"
] | jacob.t.fischer@gmail.com |
410a61537fa54d53fcf8a0c953c45f4eb9b659f9 | 5d23e3a9b39f49d93c65dde4cd17e5e2f786283b | /scholariumat/products/behaviours.py | ddabf3ef553e62d23a8371636c7374fdc475fc2d | [
"MIT"
] | permissive | MerlinB/scholariumat | aa22b59e6ebd1cde2edf00604d9102fe96b60c8a | 7c4e2bfbf3556877a856101966b591a07b4f809f | refs/heads/master | 2021-06-27T21:34:28.816791 | 2018-12-01T19:42:16 | 2018-12-01T19:42:16 | 135,583,822 | 0 | 0 | null | 2018-05-31T12:57:03 | 2018-05-31T12:57:03 | null | UTF-8 | Python | false | false | 3,918 | py | import logging
from django.db import models
from django.conf import settings
from django_extensions.db.models import TimeStampedModel, TitleSlugDescriptionModel
from framework.behaviours import PermalinkAble
logger = logging.getLogger(__name__)
class ProductBase(TitleSlugDescriptionModel, TimeStampedModel, PermalinkAble):
"""Abstract parent class for all product type classes."""
product = models.OneToOneField('products.Product', on_delete=models.CASCADE, null=True, editable=False)
def __str__(self):
return self.title
def save(self, *args, **kwargs):
if not self.product:
from .models import Product
self.product = Product.objects.create()
super().save(*args, **kwargs)
def delete(self, *args, **kwargs): # TODO: Gets ignored in bulk delete. pre_delete signal better?
self.product.delete()
super().delete(*args, **kwargs)
class Meta:
abstract = True
class AttachmentBase(models.Model):
"""Base class to create downloadable item attachment classes."""
type = models.ForeignKey('products.AttachmentType', on_delete=models.PROTECT)
item = models.ForeignKey('products.Item', on_delete=models.CASCADE)
def get(self):
pass
def __str__(self):
item_type = self.item.type.__str__()
type = self.type.__str__()
return f'{item_type}: {type}' if item_type != type else type
class Meta:
abstract = True
class BalanceMixin(models.Model):
"""Profile mixin for storing and managing user balance"""
balance = models.SmallIntegerField('Guthaben', default=0)
def spend(self, amount):
"""Given an amount, tries to spend from current balance."""
new_balance = self.balance - amount
if new_balance >= 0:
self.balance = new_balance
self.save()
return True
else:
logger.debug('{} tried to spend {} but only owns {}'.format(self, amount, self.balance))
return False
def refill(self, amount):
"""Refills balance."""
self.balance += amount
self.save()
class Meta:
abstract = True
class CartMixin(models.Model):
"""Profile mixin for storing and processing items in a shopping cart"""
@property
def cart(self):
return self.purchase_set.filter(executed=False).order_by('-created')
@property
def cart_shipping(self):
"""Returns shipping costs of cart."""
return settings.SHIPPING if any([purchase.item.type.shipping for purchase in self.cart]) else 0
@property
def cart_total(self):
"""Sums prices and adds shiping costs"""
return sum([purchase.total for purchase in self.cart]) + self.cart_shipping
@property
def cart_available(self):
return all([purchase.available for purchase in self.cart])
def clean_cart(self):
for purchase in self.purchase_set.filter(executed=False):
if not purchase.available:
purchase.delete()
def execute_cart(self):
if self.balance >= self.cart_total:
for purchase in self.cart:
purchase.execute()
return True
@property
def purchases(self):
return self.purchase_set.filter(executed=True).order_by('-modified')
@property
def items_bought(self):
from .models import Item
return Item.objects.filter(purchase__in=self.purchases).distinct()
@property
def products_bought(self):
from .models import Product
return Product.objects.filter(item__in=self.items_bought).distinct()
@property
def orders(self):
return self.purchases.filter(amount__isnull=False)
@property
def events_booked(self):
return self.purchases.filter(item__type__slug__in=['livestream', 'teilnahme'])
class Meta:
abstract = True
| [
"merlin.buczek@gmail.com"
] | merlin.buczek@gmail.com |
f77a2bbf6ec372015fb299a16ac565a2c225233e | fa45fe7eaba7ef7c27ecf95db7c460ca189ce0d4 | /everydays/BookBeingRead/python高级编程/day3.2.py | 4965680592d853a9dd4d1fe9cb00722b7e7f8b18 | [] | no_license | jake20001/Hello | be1a2bb5331f2ad4c1d8f30c6a9a530aff79e605 | 08217871bb17152eb09e68cd154937ebe5d59d2c | refs/heads/master | 2021-07-10T09:48:15.883716 | 2021-04-23T14:49:03 | 2021-04-23T14:49:03 | 56,282,358 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,445 | py | # -*- coding:utf-8 -*-
# -------------------------------
# ProjectName : autoDemo
# Author : zhangjk
# CreateTime : 2020/12/3 16:02
# FileName : day3.2
# Description :
# --------------------------------
class User(object):
def __init__(self,roles):
self.roles = roles
class Unauthorized(Exception):
pass
def inroles(irole,roles):
for role in irole:
if role in roles:
return True
return False
def protect(irole):
def _protect(function):
def __protect(*args,**kwargs):
user = globals().get('user')
if user is None or not inroles(irole,user.roles):
raise Unauthorized("I won't tell you")
return function(*args,**kwargs)
return __protect
return _protect
def protect2(role):
def _protect(function):
def __protect(*args,**kwargs):
user = globals().get('user')
if user is None or role not in user.roles:
raise Unauthorized("I won't tell you")
return function(*args,**kwargs)
return __protect
return _protect
tarek = User(('admin','user'))
bill = User(('user',))
visit = User(('visit',))
class MySecrets(object):
@protect(['admin','user'])
def waffle_recipe(self):
print('use tons of butter')
these_are = MySecrets()
user = tarek
these_are.waffle_recipe()
user = bill
these_are.waffle_recipe()
user = visit
these_are.waffle_recipe() | [
"jianke.zhang@beantechs.com"
] | jianke.zhang@beantechs.com |
f6e12755ec63191bca0bd30de980e0252d7aa5c0 | 34e3eaae20e90851331f591d01c30fa0b9e764ef | /tools/tensorflow_docs/api_generator/report/linter.py | 75d0fee81dc277881ec98d195ef944f01319766a | [
"Apache-2.0"
] | permissive | nherlianto/docs | 9860eeda0fe779709c455b2636c7337282a35d72 | be8ac03d73a77d3b71ba2b42849d2169c1d7d100 | refs/heads/master | 2023-01-04T01:12:01.782815 | 2020-10-29T17:09:04 | 2020-10-29T17:09:04 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 7,474 | py | # Lint as: python3
# Copyright 2020 The TensorFlow 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.
# ==============================================================================
"""Lints the docstring of an API symbol."""
import ast
import inspect
import re
import textwrap
from typing import Optional, Any, List, Tuple
import astor
from tensorflow_docs.api_generator import parser
from tensorflow_docs.api_generator.report.schema import api_report_generated_pb2 as api_report_pb2
def _get_source(py_object: Any) -> Optional[str]:
if py_object is not None:
try:
source = textwrap.dedent(inspect.getsource(py_object))
return source
except Exception: # pylint: disable=broad-except
return None
return None
def _count_empty_param(items: List[Tuple[str, str]]) -> int:
count = 0
for item in items:
if not item[1].strip():
count += 1
return count
def lint_params(page_info: parser.PageInfo) -> api_report_pb2.ParameterLint:
"""Lints the parameters of a docstring.
Args:
page_info: A `PageInfo` object containing the information of a page
generated via the api generation.
Returns:
A filled `DescriptionLint` proto object.
"""
param_lint = api_report_pb2.ParameterLint()
for part in page_info.doc.docstring_parts:
if isinstance(part, parser.TitleBlock):
if part.title.lower().startswith('args'):
param_lint.total_args_param = len(part.items)
param_lint.num_empty_param_desc_args = _count_empty_param(part.items)
if part.title.lower().startswith('attr'):
param_lint.total_attr_param = len(part.items)
param_lint.num_empty_param_desc_attr = _count_empty_param(part.items)
return param_lint
def lint_description(
page_info: parser.PageInfo) -> api_report_pb2.DescriptionLint:
"""Lints the description of a docstring.
If a field in the proto is assigned 0, then it means that that field doesn't
exist.
Args:
page_info: A `PageInfo` object containing the information of a page
generated via the api generation.
Returns:
A filled `DescriptionLint` proto object.
"""
len_brief = 0
if page_info.doc.brief:
len_brief = len(page_info.doc.brief.split())
len_long_desc = 0
for part in page_info.doc.docstring_parts:
if not isinstance(part, parser.TitleBlock):
len_long_desc += len(part.split())
return api_report_pb2.DescriptionLint(
len_brief=len_brief, len_long_desc=len_long_desc)
_EXAMPLE_RE = re.compile(
r"""
(?P<indent>\ *)(?P<content>```.*?\n\s*?```)
""", re.VERBOSE | re.DOTALL)
def lint_usage_example(
page_info: parser.PageInfo) -> api_report_pb2.UsageExampleLint:
"""Counts the number of doctests and untested examples in a docstring.
Args:
page_info: A `PageInfo` object containing the information of a page
generated via the api generation.
Returns:
A filled `UsageExampleLint` proto object.
"""
description = []
for part in page_info.doc.docstring_parts:
if isinstance(part, parser.TitleBlock):
description.append(str(part))
else:
description.append(part)
desc_str = ''.join(description)
num_doctest = 0
num_untested_examples = 0
# The doctests are wrapped in backticks (```).
for match in _EXAMPLE_RE.finditer(desc_str):
if '>>>' in match.groupdict()['content']:
num_doctest += 1
else:
num_untested_examples += 1
return api_report_pb2.UsageExampleLint(
num_doctest=num_doctest, num_untested_examples=num_untested_examples)
class ReturnVisitor(ast.NodeVisitor):
"""Visits the Returns node in an AST."""
def __init__(self) -> None:
self.total_returns = []
def visit_Return(self, node) -> None: # pylint: disable=invalid-name
if node.value is None:
self.total_returns.append('None')
else:
self.total_returns.append(astor.to_source(node.value))
def lint_returns(
page_info: parser.PageInfo) -> Optional[api_report_pb2.ReturnLint]:
""""Lints the returns block in the docstring.
This linter only checks if a `Returns` block exists in the docstring
if it finds `return` keyword in the source code.
Args:
page_info: A `PageInfo` object containing the information of a page
generated via the api generation.
Returns:
A filled `ReturnLint` proto object.
"""
source = _get_source(page_info.py_object)
return_visitor = ReturnVisitor()
if source is not None:
try:
return_visitor.visit(ast.parse(source))
except Exception: # pylint: disable=broad-except
pass
if source is not None and 'return' in source:
for item in page_info.doc.docstring_parts:
if isinstance(item, parser.TitleBlock):
if item.title.lower().startswith('return'):
return api_report_pb2.ReturnLint(returns_defined=True)
# If "Returns" word is present in the brief docstring then having a separate
# `Returns` section is not needed.
if 'return' in page_info.doc.brief.lower():
return api_report_pb2.ReturnLint(returns_defined=True)
# If the code only returns None then `Returns` section in the docstring is
# not required.
if all(return_val == 'None' for return_val in return_visitor.total_returns):
return None
return api_report_pb2.ReturnLint(returns_defined=False)
return None
class RaiseVisitor(ast.NodeVisitor):
"""Visits the Raises node in an AST."""
def __init__(self) -> None:
self.total_raises = []
def visit_Raise(self, node) -> None: # pylint: disable=invalid-name
# This `if` block means that there is a bare raise in the code.
if node.exc is None:
return
self.total_raises.append(astor.to_source(node.exc.func).strip())
def lint_raises(page_info: parser.PageInfo) -> api_report_pb2.RaisesLint:
"""Lints the raises block in the docstring.
The total raises in code are extracted via an AST and compared against those
extracted from the docstring.
Args:
page_info: A `PageInfo` object containing the information of a page
generated via the api generation.
Returns:
A filled `RaisesLint` proto object.
"""
raises_lint = api_report_pb2.RaisesLint()
# Extract the raises from the source code.
raise_visitor = RaiseVisitor()
source = _get_source(page_info.py_object)
if source is not None:
try:
raise_visitor.visit(ast.parse(source))
except Exception: # pylint: disable=broad-except
pass
raises_lint.total_raises_in_code = len(raise_visitor.total_raises)
# Extract the raises defined in the docstring.
raises_defined_in_doc = []
for part in page_info.doc.docstring_parts:
if isinstance(part, parser.TitleBlock):
if part.title.lower().startswith('raises'):
raises_lint.num_raises_defined = len(part.items)
if part.items:
raises_defined_in_doc.extend(list(zip(*part.items))[0])
break
else:
raises_lint.num_raises_defined = 0
return raises_lint
| [
"copybara-worker@google.com"
] | copybara-worker@google.com |
ce8b66aa9979fcf3c606a1dbef6946caea8ede6c | 213ded9295d50b8133ae31ad2682240338406b60 | /while.py | f6ad2f212463b5f02ce32ba506038c9fb7876caf | [] | no_license | Rayhun/python-learning-repository | 16b15f87089c02cb7ff2a109fe17301618c05794 | 45d72da422554f66a4673e105ee7d066264efd7b | refs/heads/master | 2022-12-13T16:27:15.708590 | 2020-09-18T19:13:12 | 2020-09-18T19:13:12 | 294,159,873 | 3 | 0 | null | null | null | null | UTF-8 | Python | false | false | 446 | py | ''' while loop '''
# i = 1 # loop starting value
# summation = 0 # 15, 5
# while i < 5:
# summation += i
# i = i + 1 # in, dec
# print(summation)
st_num = 0
# while st_num < 5:
# print("bd cse solved")
# st_num = st_num + 1
# while st_num < 5:
# st_num = st_num + 1
# if st_num == 4:
# continue
# print("rayhan" ,st_num)
result = 0 #res 3
num = 3 #num 4
for i in range(2):
result = result + num
num = num + 1
print(num) | [
"rayhunkhan27@gmail.com"
] | rayhunkhan27@gmail.com |
514a5ddb17a13c84b2e606804ea6b986afb8f6b8 | de24f83a5e3768a2638ebcf13cbe717e75740168 | /moodledata/vpl_data/305/usersdata/281/69192/submittedfiles/formula.py | 5f040c2823eaf58bd6a6efc57b12488619d593ba | [] | no_license | rafaelperazzo/programacao-web | 95643423a35c44613b0f64bed05bd34780fe2436 | 170dd5440afb9ee68a973f3de13a99aa4c735d79 | refs/heads/master | 2021-01-12T14:06:25.773146 | 2017-12-22T16:05:45 | 2017-12-22T16:05:45 | 69,566,344 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 221 | py | # -*- coding: utf-8 -*-
print('Digite tres números')
p=float(input('1° número:'))
print(p)
i=float(input('2° número:'))
print(i)
n=float(input('3° número:'))
print(n)
v=float(input(p*(((1+i)**n)-1)/i))
print(v%2f)
| [
"rafael.mota@ufca.edu.br"
] | rafael.mota@ufca.edu.br |
b09b228f492342f49e0bc8e90b2c5a1e1527fb2d | 5cbb0d3f89450fd1ef4b1fddbbb1ef1a8fb7fd16 | /tdd/code/show_cov.py | 93195abf586d237dffc5acbe393b03909c09dc41 | [] | no_license | AndreaCrotti/ep2013 | e259eb6223faf74bb39324c9aa1101f439cf09a2 | 964b20ed9a331d0d59fe538ba47d7e0bc96ebc2b | refs/heads/master | 2016-09-06T19:35:51.876432 | 2013-10-22T10:43:27 | 2013-10-22T10:43:27 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,030 | py | import unittest
def smart_division(a, b):
"""Run a 'smart' division
"""
if b == 0:
raise Exception("Can not divide by 0")
res = a / b
back_res = res * b
if back_res != a:
return a / float(b)
else:
return res
class TestSmartDivision(unittest.TestCase):
pass
# def test_division_by_0(self):
# """Test that dividing by 0 raises an exception
# """
# with self.assertRaises(Exception):
# smart_division(10, 0)
# def test_float_division(self):
# """Check that the float division returns a correct result (with approximation)
# """
# self.assertAlmostEqual(smart_division(2, 3), 0.66, places=1)
# def test_int_division(self):
# self.assertEqual(smart_division(1, 1), 1)
# self.assertEqual(smart_division(10, 2), 5)
if __name__ == '__main__':
unittest.main()
# Use "nosetests-2.7 show_cov.py -sv --with-cov --cov-report=html"
# and open htmlcov/index.html to see the html report
| [
"andrea.crotti.0@gmail.com"
] | andrea.crotti.0@gmail.com |
d941bcaa3bac8031b9b9e6017e3c41b7d18d1beb | c3cd0262e200926cf0f9e37091557da85e0de85e | /py/ch02/src/vm/__init__.py | 55c98feca717c7b8dce711c34303f2cc8f3897a7 | [] | no_license | luningcowboy/writelua | b860bc4cc701f9a96baf3d40a1995fe1cbef6523 | 323cdb99043ab0f9f7ec1c6650f23bf94117df8c | refs/heads/master | 2022-12-18T21:48:45.821121 | 2020-09-25T08:19:22 | 2020-09-25T08:19:22 | 292,487,632 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 158 | py | #!/usr/bin/env python
# -*- coding=utf8 -*-
"""
# Author: luning
# Created Time : 一 9/14 13:34:42 2020
# File Name: src/vm/__init__.py
# Description:
"""
| [
"luningcowboy@gmail.com"
] | luningcowboy@gmail.com |
b255e83582ef7fd606ae36ae4b594bf82c58a6bc | 462137348c3013fd1f389ae23557425d22497b36 | /24_days/Day 13/Question47.py | fd0d75f8edc99d6668feb2b0a2443d0585def719 | [] | no_license | wmemon/python_playground | f05b70c50c2889acd6353ba199fd725b75f48bb1 | 3b424388f92f81d82621645ee7fdbd4ac164da79 | refs/heads/master | 2022-11-23T05:09:30.828726 | 2020-07-28T12:47:03 | 2020-07-28T12:47:03 | 283,192,556 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 331 | py | """
Define a class named Circle which can be constructed by a radius.
The Circle class has a method which can compute the area.
"""
class Circle():
def __init__(self, radius):
self.radius = float(radius)
def get_area(self):
return float(3.14*self.radius ** 2)
c1 = Circle('wasim')
print(c1.get_area())
| [
"wmemon100@gmail.com"
] | wmemon100@gmail.com |
4d962f5ac69eb471a8b246a29da9df3570e14bfc | 04c9243ddf81011fe980ffffd016f1770444b503 | /send-mail/send_mail.py | 96ac21e95fb2f6b98408e32f51eb0a07e97d9623 | [] | no_license | wcl6005/Linux-Automated-Scripts | 9880ed68fbcfdb9440b20186e784367a8dcc0a69 | 359e1673b47174c8b3edf9f0c57a4f9a45343481 | refs/heads/master | 2022-11-14T20:54:41.469457 | 2020-07-10T09:02:50 | 2020-07-10T09:02:50 | 278,578,879 | 1 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,801 | py | # -*- coding: UTF-8 -*-
import smtplib
from email.mime.text import MIMEText
def send_mail(email_user, email_pwd, recv, title, content, mail_host='smtp.163.com', port=25):
'''
发送邮件函数
username: 邮箱账号,发送者账号 xx@163.com
passwd: 邮箱授权码(不是邮箱的登录密码,是邮箱授权码,参考:https://jingyan.baidu.com/article/c275f6ba33a95de33d7567d9.html)
recv: 邮箱接收人地址,多个账号以逗号隔开
title: 邮件标题
content: 邮件内容
mail_host: 邮箱服务器,163邮箱host: smtp.163.com
port: 邮箱端口号,163邮箱的默认端口是 25
测试:
$ python send_mail.py
python3.7.5 测试通过
'''
msg = MIMEText(content) # 邮件内容
msg['Subject'] = title # 邮件主题
msg['From'] = email_user # 发送者账号
msg['To'] = recv # 接收者账号列表
smtp = smtplib.SMTP(mail_host, port=port) # 连接邮箱,传入邮箱地址,和端口号,smtp的端口号是25
smtp.login(email_user, email_pwd) # 登录发送者的邮箱账号,密码
# 参数分别是 发送者,接收者,第三个是把上面的发送邮件的 内容变成字符串
smtp.sendmail(email_user, recv, msg.as_string())
smtp.quit() # 发送完毕后退出smtp
if __name__ == '__main__':
import time
email_user = 'wcl6005@163.com' # 发送者账号
email_pwd = 'wcl6005' # 发送者授权码
maillist = 'wcl6005@126.com' # 邮箱接收人地址
title = '邮件标题'
content = '邮件内容: 从%s发来的邮件。%s'%(email_user, time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(time.time())))
send_mail(email_user, email_pwd, maillist, title, content)
print('OK! Email send success.')
| [
"wcl6005@163.com"
] | wcl6005@163.com |
009c46ffdc0c2959f6a1fda0333f12363dd53a6c | 1916dc66aa9710d9a7d4fab42c28c1c49e2f630c | /app_owner/migrations/0003_auto_20210316_1712.py | a588828181da6c46475f4d327bd773d18d5ef637 | [] | no_license | robert8888/portfolio | 8ce6c1be774666a58ee44379621c6a4515f64d37 | a640b1a62810e4a5dd4f7e20fefc86dc3ca7851f | refs/heads/master | 2023-06-03T23:28:53.888863 | 2021-06-25T13:11:28 | 2021-06-25T13:11:28 | 333,259,007 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 486 | py | # Generated by Django 3.1.5 on 2021-03-16 16:12
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('app_owner', '0002_auto_20210316_1702'),
]
operations = [
migrations.AlterField(
model_name='contactimage',
name='contact',
field=models.OneToOneField(on_delete=django.db.models.deletion.CASCADE, to='app_owner.contact'),
),
]
| [
"robert.kami88@gmail.com"
] | robert.kami88@gmail.com |
d9ffaffb2494e34a6811abee8d013faca8719020 | 5e4a25bce2f60ee87f580b64f62697ad9bbbaced | /0082-Remove-Duplicates-from-Sorted-List-II/solution.py | e7986f3383d5e0979f48e908d21137e835714085 | [] | no_license | Glitch95/InterviewPrep | e729b88826a257699da9ea07493d705490da7373 | b3a27d34518d77e1e4896af061f8581885ccfed0 | refs/heads/master | 2020-08-02T12:19:58.783302 | 2019-10-09T16:47:34 | 2019-10-09T16:47:34 | 211,348,489 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 2,018 | py | # Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def deleteDuplicates(self, head):
# Let's we a 2 pointer techinque to keep track of the start and end
# of each distinct region.
# We will also use a dummy head to nicely handle edge cases.
# A region being a section of the list with all nodes having the same value.
# Let's try to visualize this
# | C | D | 1 | 2 | 3 | 3 | 4 | 4 | 5 | c != n
# p c n
# | C | D | 1 | 2 | 3 | 3 | 4 | 4 | 5 | c != n
# p c n
# | C | D | 1 | 2 | 3 | 3 | 4 | 4 | 5 | c != n
# p c n
# | C | D | 1 | 2 | 3 | 3 | 4 | 4 | 5 | c == n
# p c n
# | C | D | 1 | 2 | 3 | 3 | 4 | 4 | 5 | c != n and c.next != n
# p c n
# | C | D | 1 | 2 | 4 | 4 | 5 | p.next = n, c = p.next, n = c.next
# p c n
# | C | D | 1 | 2 | 4 | 4 | 5 | c == n
# p c n
# | C | D | 1 | 2 | 4 | 4 | 5 | c != n and c.next != n
# p c n
# | C | D | 1 | 2 | 4 | 4 | 5 | p.next = n
# p c n
# | C | D | 1 | 2 | 5 |
# p
n1, n2 = ListNode(None), ListNode(None)
n1.next, n2.next = n2, head
prev = n1
while prev.next and prev.next.next:
curr, next = prev.next, prev.next.next
while curr and next and curr.val == next.val:
next = next.next
if curr.next is not next:
prev.next = next
else:
prev = prev.next
return n1.next.next
| [
"kaleshsingh96@gmail.com"
] | kaleshsingh96@gmail.com |
f957d3f5869f27eab08c8095549202efedb9f536 | 34455fa21dd12b18dc4a352b85463c3db15f6bdf | /Ch02/02_04/02_05_Finish.py | cb7ceee14d6869054f1ffe62f1b16736ebcb801e | [] | no_license | CodedQuen/The-Python-3-Standard-Library | 771abd26c0c39aa925d06b204bb600104a5bdd8f | 5a9facc9fb2c1085e12fe4284fe593ef17609e13 | refs/heads/master | 2022-06-14T01:32:54.088505 | 2020-05-05T10:38:28 | 2020-05-05T10:38:28 | 261,428,534 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 359 | py | # Statistics Module
import statistics
import math
agesData = [10, 13, 14, 12, 11, 10, 11, 10, 15]
print(statistics.mean(agesData))
print(statistics.mode(agesData))
print(statistics.median(agesData))
print(sorted(agesData))
print(statistics.variance(agesData))
print(statistics.stdev(agesData))
print(math.sqrt(statistics.variance(agesData)))
| [
"noreply@github.com"
] | CodedQuen.noreply@github.com |
b76c6dbea5edc63bb1f6f5b25d92ee0136bb98fb | 3344f02a57ec704acd58449502925b8f1ffc564b | /app/models.py | 3748a6a8f3e0bc35adc59bd1c3d980946d372008 | [
"MIT"
] | permissive | Jackson-coder-arch/One-minute-pitches | dcfad8f4bab22c133f15cb712df2d2f2b36a0ef0 | 2bbb9db1d709594f5465fce187e52198858bf5b6 | refs/heads/master | 2023-03-11T20:58:44.295780 | 2021-03-05T04:45:08 | 2021-03-05T04:45:08 | 342,477,785 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 2,493 | py | from . import db
from werkzeug.security import generate_password_hash,check_password_hash
from flask_login import UserMixin
from . import login_manager
from datetime import datetime
class User(UserMixin,db.Model):
__tablename__ = 'users'
id = db.Column(db.Integer,primary_key = True)
username = db.Column(db.String(255),index = True)
email = db.Column(db.String(255),unique = True,index = True)
bio = db.Column(db.String(255))
profile_pic_path = db.Column(db.String())
pass_secure = db.Column(db.String(255))
pitches = db.relationship('Pitch',backref = 'user',lazy="dynamic")
comments = db.relationship('Comment',backref = 'user',lazy="dynamic")
@property
def password(self):
raise AttributeError('You cannot read the password attribute')
@password.setter
def password(self, password):
self.pass_secure = generate_password_hash(password)
@login_manager.user_loader
def load_user(user_id):
return User.query.get(int(user_id))
def verify_password(self,password):
return check_password_hash(self.pass_secure,password)
def save_user(self):
db.session.add(self)
db.session.commit()
def __repr__(self):
return f'User {self.username}'
class Pitch(db.Model):
__tablename__ = 'pitches'
id = db.Column(db.Integer,primary_key = True)
title = db.Column(db.String(255))
pitch_content = db.Column(db.String(255))
author = db.Column(db.String(255))
category = db.Column(db.String(255))
upvote = db.Column(db.Integer)
downvote = db.Column(db.Integer)
published_at = db.Column(db.DateTime, default = datetime.utcnow)
user_id = db.Column(db.Integer,db.ForeignKey('users.id'))
comments = db.relationship('Comment',backref = 'pitch',lazy="dynamic")
def save_pitch(self):
db.session.add(self)
db.session.commit()
def __repr__(self):
return f'User {self.description}'
class Comment(db.Model):
__tablename__ = 'comments'
id = db.Column(db.Integer,primary_key = True)
body = db.Column(db.String(255))
user_id = db.Column(db.Integer,db.ForeignKey('users.id'))
pitch_id = db.Column(db.Integer,db.ForeignKey('pitches.id'))
published_at = db.Column(db.DateTime, default = datetime.utcnow)
def save_comment(self):
db.session.add(self)
db.session.commit()
def __repr__(self):
return f'User {self.description}' | [
"jacksonikonya@gmail.com"
] | jacksonikonya@gmail.com |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.