index int64 | repo_name string | branch_name string | path string | content string | import_graph string |
|---|---|---|---|---|---|
78,584 | ewertonhm/RBUpdater | refs/heads/master | /rb_class.py | import paramiko
import time
import sys
from scp import SCPClient
from txt_rw import write_to_log
class RbUpdater:
# DebugLevel = 3: Todos os alertas
# DebugLevel = 2: Importantes e comandos
# DebugLevel = 1: Apenas importantes
# DebugLevel = 0: Nenhum alerta
def __init__(self, host, port, user, pwd, debug):
self.host = host
self.port = port
self.user = user
self.pwd = pwd
self.DebugLevel = debug
self.ssh = paramiko.SSHClient()
self.ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
def connect(self):
try:
write_to_log('Conectando em {0}@{1}:{2}'.format(self.user, self.host, self.port))
self.ssh.connect(self.host, self.port, self.user, self.pwd, banner_timeout=200)
return self
except paramiko.ssh_exception.AuthenticationException:
write_to_log('Error: ssh_exception.AuthenticationException')
return 'password'
except paramiko.ssh_exception.NoValidConnectionsError:
write_to_log('Error: ssh_exception.NoValidConnectionsError')
return 'connection error'
except TimeoutError:
write_to_log('Error: connection timeout')
return 'connection error'
except paramiko.ssh_exception.SSHException:
write_to_log('SSHException: Error reading SSH protocol banner')
return 'connection error'
def exec_command(self, cmd, output=False):
shell_output = []
if type(cmd) == list:
for c in cmd:
write_to_log('ssh.exec_command: ' + c)
stdin, stdout, stderr = self.ssh.exec_command(c)
if output:
for line in stdout:
write_to_log('ssh.output: ' + line.strip('\n'))
print(line.strip('\n'))
else:
for line in stdout:
write_to_log('ssh.output: ' + line.strip('\n'))
shell_output.append(line.strip('\n'))
else:
write_to_log('ssh.exec_command: ' + cmd)
stdin, stdout, stderr = self.ssh.exec_command(cmd)
if output:
for line in stdout:
write_to_log('ssh.output: ' + line.strip('\n'))
print(line.strip('\n'))
else:
for line in stdout:
write_to_log('ssh.output: ' + line.strip('\n'))
shell_output.append(line.strip('\n'))
return shell_output
def close_connection(self):
write_to_log('SSH: Closing Connection')
self.ssh.close()
def get_version(self):
v = self.exec_command('system resource print', False)
return str(v[1]).strip()
def get_fw_version(self):
v = self.exec_command('system routerboard print', False)
return str(v[6]).strip()
def get_pppoe(self):
pppoe = self.exec_command('interface pppoe-client print', False)
pppoe_position = str(pppoe).find('user=')
end_pppoe_position = str(pppoe).find(' password')
pppoe_user = str(pppoe)[pppoe_position + 5:end_pppoe_position]
# return str(v[1]).strip()
return pppoe_user.strip(' "')
def get_identity(self):
identity = self.exec_command('system identity print', False)
identity_position = str(identity).find('name: ')
name = str(identity)[identity_position + 6:-10]
return name.replace(" ", "-")
def online_update(self):
self.exec_command([
'ip dns set servers=189.45.192.3,177.200.200.20'
'system package update set channel=long-term',
'system package update check-for-updates',
'system package update install'
], True)
def get_architecture(self):
resource = self.exec_command('system resource print', False)
architecture_position = str(resource).find('architecture-name: ')
board_name_postition = str(resource).find('board-name:')
architecture = str(resource)[architecture_position + 19:board_name_postition - 21]
return architecture
def upload(self, version):
filename = 'routeros/routeros-{0}-{1}.npk'.format(self.get_architecture(), version)
def progress4(filename, size, sent, peername):
write_to_log("(%s:%s) %s's progress: %.2f%% \r" % (
peername[0], peername[1], filename, float(sent) / float(size) * 100))
write_to_log('SCP: Opening Connection to host {0}@{1}:{2}'.format(self.user, self.host, self.port))
scp = SCPClient(self.ssh.get_transport(), progress4=progress4)
scp.put(filename)
write_to_log('SCP: Closing Connection')
scp.close()
def offline_update(self, version):
self.upload(version)
self.exec_command('system reboot', False)
def update_fw(self):
self.exec_command([
'system routerboard upgrade',
'system reboot'
], True)
def disable_ipv6(self):
self.exec_command([
'system package disable ipv6',
'system reboot'
], True)
def backup(self, file_name):
def progress(filename, size, sent):
write_to_log("%s's progress: %.2f%% \r" % (filename, float(sent) / float(size) * 100))
def progress4(filename, size, sent, peername):
write_to_log("(%s:%s) %s's progress: %.2f%% \r" % (
peername[0], peername[1], filename, float(sent) / float(size) * 100))
'''
if self.DebugLevel==2:
scp = SCPClient(self.ssh.get_transport(), progress=progress)
if self.DebugLevel==3:
scp = SCPClient(self.ssh.get_transport(), progress4=progress4)
if self.DebugLevel<=1:
scp = SCPClient(self.ssh.get_transport())
'''
write_to_log('SCP: Opening Connection to host {0}@{1}:{2}'.format(self.user, self.host, self.port))
scp = SCPClient(self.ssh.get_transport(), progress4=progress4)
self.exec_command('system backup save name={0}'.format(file_name), False)
scp.get('{0}.backup'.format(file_name))
write_to_log('SCP: Closing Connection')
scp.close()
def create_vpn(self):
pass
def create_vpls(self):
pass
def try_connect(host, Ports, Users, Passwords, DebugLevel):
connection_error = None
# try each port
for port in Ports:
# try each user
for user in Users:
connection_error = False
# try password
for password in Passwords:
t = RbUpdater(host, port, user, password, DebugLevel).connect()
# se conectar, para
if is_connected(t):
write_to_log('Conectado em {0}@{1}:{2}'.format(user, host, port))
if DebugLevel >= 1:
print('Conectado em {0}@{1}:{2}'.format(user, host, port))
return t
# se der erro de conexão,
# para as tentativas de senha e sobe pro nível de usuários
if t == 'connection error':
write_to_log('Falha ao se conectar em {0}@{1}:{2}'.format(user, host, port))
connection_error = True
break
if connection_error:
break
write_to_log("Todas as tentativas realizadas, não foi possível se conectar ao host {0}".format(host))
if DebugLevel >= 1:
print("Todas as tentativas realizadas, não foi possível se conectar ao host {0}".format(host))
return False
def is_connected(connection):
if type(connection) == RbUpdater:
return True
else:
return False
| {"/main.py": ["/relatorio.py", "/rb_class.py", "/menu.py", "/txt_rw.py", "/config.py"], "/relatorio.py": ["/txt_rw.py"], "/menu.py": ["/txt_rw.py", "/pasta.py"], "/rb_class.py": ["/txt_rw.py"]} |
78,585 | belal-bh/CLIC_PUST | refs/heads/master | /src/resource/migrations/0002_auto_20200307_0027.py | # Generated by Django 2.2.1 on 2020-03-06 18:27
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('resource', '0001_initial'),
]
operations = [
migrations.AlterModelOptions(
name='author',
options={'ordering': ['name', 'nicname']},
),
migrations.AlterModelOptions(
name='book',
options={'ordering': ['title', 'call_number']},
),
migrations.AlterModelOptions(
name='resource',
options={'ordering': ['title', 'call_number']},
),
]
| {"/src/academic/admin.py": ["/src/academic/models.py"], "/src/account/urls.py": ["/src/account/views.py"], "/src/transaction/admin.py": ["/src/transaction/models.py"], "/src/resource/views.py": ["/src/resource/models.py", "/src/resource/forms.py"], "/src/member/admin.py": ["/src/member/models.py"], "/src/service/urls.py": ["/src/service/views.py"], "/src/wishlist/admin.py": ["/src/wishlist/models.py"], "/src/resource/admin.py": ["/src/resource/models.py"], "/src/core/dev/views.py": ["/src/core/dev/automate.py", "/src/core/dev/forms.py"], "/src/core/dev/urls.py": ["/src/core/dev/views.py"], "/src/resource/forms.py": ["/src/resource/models.py"], "/src/core/coreurls.py": ["/src/core/coreviews.py"], "/src/amtd/admin.py": ["/src/amtd/models.py"], "/src/account/views.py": ["/src/account/forms.py", "/src/account/models.py"], "/src/service/admin.py": ["/src/service/models.py"], "/src/resource/urls.py": ["/src/resource/views.py"]} |
78,586 | belal-bh/CLIC_PUST | refs/heads/master | /src/academic/migrations/0001_initial.py | # Generated by Django 2.2.1 on 2019-10-02 14:39
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='Faculty',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('faculty_id', models.CharField(max_length=20, unique=True)),
('name', models.CharField(max_length=120)),
('abbreviation', models.CharField(max_length=15)),
('description', models.TextField()),
('timestamp', models.DateTimeField(auto_now_add=True)),
],
),
migrations.CreateModel(
name='Program',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('program_id', models.CharField(max_length=20, unique=True)),
('name', models.CharField(max_length=120)),
('abbreviation', models.CharField(max_length=15)),
('description', models.TextField()),
('timestamp', models.DateTimeField(auto_now_add=True)),
],
),
migrations.CreateModel(
name='Department',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('dept_id', models.CharField(max_length=20, unique=True)),
('name', models.CharField(max_length=120)),
('abbreviation', models.CharField(max_length=15)),
('description', models.TextField()),
('timestamp', models.DateTimeField(auto_now_add=True)),
('faculty', models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.SET_NULL, to='academic.Faculty')),
],
),
]
| {"/src/academic/admin.py": ["/src/academic/models.py"], "/src/account/urls.py": ["/src/account/views.py"], "/src/transaction/admin.py": ["/src/transaction/models.py"], "/src/resource/views.py": ["/src/resource/models.py", "/src/resource/forms.py"], "/src/member/admin.py": ["/src/member/models.py"], "/src/service/urls.py": ["/src/service/views.py"], "/src/wishlist/admin.py": ["/src/wishlist/models.py"], "/src/resource/admin.py": ["/src/resource/models.py"], "/src/core/dev/views.py": ["/src/core/dev/automate.py", "/src/core/dev/forms.py"], "/src/core/dev/urls.py": ["/src/core/dev/views.py"], "/src/resource/forms.py": ["/src/resource/models.py"], "/src/core/coreurls.py": ["/src/core/coreviews.py"], "/src/amtd/admin.py": ["/src/amtd/models.py"], "/src/account/views.py": ["/src/account/forms.py", "/src/account/models.py"], "/src/service/admin.py": ["/src/service/models.py"], "/src/resource/urls.py": ["/src/resource/views.py"]} |
78,587 | belal-bh/CLIC_PUST | refs/heads/master | /src/core/dev/forms.py | from django import forms
from resource.models import (
Book,
Resource,
Author,
)
class BookForm(forms.ModelForm):
class Meta:
model = Book
fields = []
class ResourceForm(forms.ModelForm):
class Meta:
model = Resource
fields = []
class AuthorForm(forms.ModelForm):
class Meta:
model = Author
fields = []
| {"/src/academic/admin.py": ["/src/academic/models.py"], "/src/account/urls.py": ["/src/account/views.py"], "/src/transaction/admin.py": ["/src/transaction/models.py"], "/src/resource/views.py": ["/src/resource/models.py", "/src/resource/forms.py"], "/src/member/admin.py": ["/src/member/models.py"], "/src/service/urls.py": ["/src/service/views.py"], "/src/wishlist/admin.py": ["/src/wishlist/models.py"], "/src/resource/admin.py": ["/src/resource/models.py"], "/src/core/dev/views.py": ["/src/core/dev/automate.py", "/src/core/dev/forms.py"], "/src/core/dev/urls.py": ["/src/core/dev/views.py"], "/src/resource/forms.py": ["/src/resource/models.py"], "/src/core/coreurls.py": ["/src/core/coreviews.py"], "/src/amtd/admin.py": ["/src/amtd/models.py"], "/src/account/views.py": ["/src/account/forms.py", "/src/account/models.py"], "/src/service/admin.py": ["/src/service/models.py"], "/src/resource/urls.py": ["/src/resource/views.py"]} |
78,588 | belal-bh/CLIC_PUST | refs/heads/master | /src/resource/models.py | from django.db import models
from django.conf import settings
from django.contrib.postgres.fields import ArrayField
from django.urls import reverse
from account.helpers import UploadTo
from academic.models import Department
class AuthorManager(models.Manager):
def available(self, *args, **kwargs):
return super(AuthorManager, self).all()
class BookManager(models.Manager):
def available(self, *args, **kwargs):
status_available = 'available'
return super(BookManager, self).filter(status=status_available)
class ResourceManager(models.Manager):
def available(self, *args, **kwargs):
status_available = 'available'
return super(ResourceManager, self).filter(status=status_available)
class Author(models.Model):
name = models.CharField(max_length=100)
nicname = models.CharField(max_length=30)
MALE = 'm'
FEMALE = 'f'
OTHERS = 'o'
GENDER_CHOICES = (
(MALE, 'Male'),
(FEMALE, 'Female'),
(OTHERS, 'Others'),
)
gender = models.CharField(
max_length=1,
choices=GENDER_CHOICES,
default=MALE
)
nationality = models.CharField(max_length=20, null=True, blank=True)
bio = models.TextField(null=True, blank=True)
weblinks = ArrayField(models.CharField(max_length=120),null=True, blank=True)
email = models.EmailField(
verbose_name='email address',
max_length=255,
null=True,
blank=True,
)
timestamp = models.DateTimeField(auto_now=False, auto_now_add=True)
updated = models.DateTimeField(auto_now=True, auto_now_add=False)
objects = AuthorManager()
def __str__(self):
if self.name:
return self.name
return self.nicname
class Meta:
ordering = ["name", "nicname"]
class Book(models.Model):
title = models.CharField(max_length=255)
author = models.ManyToManyField(Author)
edition = models.CharField(max_length=20, null=True, blank=True)
pagination = models.PositiveIntegerField(null=True, blank=True)
# need customization later: uniqe or not
accession_number = models.CharField(max_length=50, unique=True)
call_number = models.CharField(max_length=20) # need customization
copy_number = models.CharField(max_length=20) # need customization
# need customization later: uniqe or not
isbn = models.CharField(max_length=50)
publisher = models.CharField(max_length=120, null=True, blank=True)
description = models.TextField(null=True, blank=True)
language = models.CharField(max_length=20)
publication_date = models.DateField(null=True, blank=True)
last_revision_date = models.DateField(null=True, blank=True)
mrp = models.PositiveIntegerField(null=True, blank=True)
barcode = models.CharField(max_length=255, null=True, blank=True)
image = models.ImageField(
default='resource/book/image/default.png',
upload_to=UploadTo('image', plus_id=True),
null=True,
blank=True,
width_field="width_field",
height_field="height_field"
)
height_field = models.IntegerField(default=0, null=True)
width_field = models.IntegerField(default=0, null=True)
departments = models.ManyToManyField(Department)
tags = ArrayField(models.CharField(max_length=50), null=True, blank=True)
added_by = models.ForeignKey(
settings.AUTH_USER_MODEL, on_delete=models.SET_NULL, null=True, blank=True)
work_done = models.PositiveIntegerField(default=0)
status = models.CharField(max_length=15, default="available", null=True, blank=True)
timestamp = models.DateTimeField(auto_now=False, auto_now_add=True)
objects = BookManager()
def __str__(self):
if self.title:
return self.title
return self.call_number
class Meta:
ordering = ["title", "call_number"]
def get_absolute_url(self):
return reverse("resource:bookdetail", kwargs={"id": self.id})
class Resource(models.Model):
title = models.CharField(max_length=255)
# Need to add or customize later
SOFTWARE = 'software'
HARDWARE = 'hardware'
MAGAZINE = 'magazine'
OTHER = 'other'
RESOURCE_TYPE_CHOICES = (
(SOFTWARE, 'Software'),
(HARDWARE, 'Hardware'),
(MAGAZINE, 'Magazine'),
(OTHER, 'Other'),
)
resource_type = models.CharField(
max_length=20,
choices=RESOURCE_TYPE_CHOICES,
default=OTHER,
)
# need customization later: uniqe or not
accession_number = models.CharField(max_length=50)
call_number = models.CharField(max_length=20) # need customization
copy_number = models.CharField(max_length=20) # need customization
description = models.TextField(null=True, blank=True)
mrp = models.PositiveIntegerField(null=True, blank=True)
barcode = models.CharField(max_length=255, null=True, blank=True)
image = models.ImageField(
default='resource/resource/image/default.png',
upload_to=UploadTo('image', plus_id=True),
null=True,
blank=True,
width_field="width_field",
height_field="height_field"
)
height_field = models.IntegerField(default=0, null=True)
width_field = models.IntegerField(default=0, null=True)
departments = models.ManyToManyField(Department)
tags = ArrayField(models.CharField(max_length=50), blank=True)
added_by = models.ForeignKey(
settings.AUTH_USER_MODEL, on_delete=models.SET_NULL, null=True, blank=True)
work_done = models.PositiveIntegerField(default=0)
status = models.CharField(max_length=15, default="available", null=True, blank=True)
timestamp = models.DateTimeField(auto_now=False, auto_now_add=True)
objects = ResourceManager()
def __str__(self):
if self.title:
return self.title
return self.call_number
class Meta:
ordering = ["title", "call_number"]
def get_absolute_url(self):
return reverse("resource:resdetail", kwargs={"id": self.id})
| {"/src/academic/admin.py": ["/src/academic/models.py"], "/src/account/urls.py": ["/src/account/views.py"], "/src/transaction/admin.py": ["/src/transaction/models.py"], "/src/resource/views.py": ["/src/resource/models.py", "/src/resource/forms.py"], "/src/member/admin.py": ["/src/member/models.py"], "/src/service/urls.py": ["/src/service/views.py"], "/src/wishlist/admin.py": ["/src/wishlist/models.py"], "/src/resource/admin.py": ["/src/resource/models.py"], "/src/core/dev/views.py": ["/src/core/dev/automate.py", "/src/core/dev/forms.py"], "/src/core/dev/urls.py": ["/src/core/dev/views.py"], "/src/resource/forms.py": ["/src/resource/models.py"], "/src/core/coreurls.py": ["/src/core/coreviews.py"], "/src/amtd/admin.py": ["/src/amtd/models.py"], "/src/account/views.py": ["/src/account/forms.py", "/src/account/models.py"], "/src/service/admin.py": ["/src/service/models.py"], "/src/resource/urls.py": ["/src/resource/views.py"]} |
78,589 | belal-bh/CLIC_PUST | refs/heads/master | /src/academic/admin.py | from django.contrib import admin
from .models import (
Faculty,
Department,
Program,
)
admin.site.register(Faculty)
admin.site.register(Department)
admin.site.register(Program)
| {"/src/academic/admin.py": ["/src/academic/models.py"], "/src/account/urls.py": ["/src/account/views.py"], "/src/transaction/admin.py": ["/src/transaction/models.py"], "/src/resource/views.py": ["/src/resource/models.py", "/src/resource/forms.py"], "/src/member/admin.py": ["/src/member/models.py"], "/src/service/urls.py": ["/src/service/views.py"], "/src/wishlist/admin.py": ["/src/wishlist/models.py"], "/src/resource/admin.py": ["/src/resource/models.py"], "/src/core/dev/views.py": ["/src/core/dev/automate.py", "/src/core/dev/forms.py"], "/src/core/dev/urls.py": ["/src/core/dev/views.py"], "/src/resource/forms.py": ["/src/resource/models.py"], "/src/core/coreurls.py": ["/src/core/coreviews.py"], "/src/amtd/admin.py": ["/src/amtd/models.py"], "/src/account/views.py": ["/src/account/forms.py", "/src/account/models.py"], "/src/service/admin.py": ["/src/service/models.py"], "/src/resource/urls.py": ["/src/resource/views.py"]} |
78,590 | belal-bh/CLIC_PUST | refs/heads/master | /src/account/urls.py | # from django.contrib import admin
from django.urls import path
from .views import profile_view
app_name = 'account'
urlpatterns = [
path('user/', profile_view, name='profile'),
]
| {"/src/academic/admin.py": ["/src/academic/models.py"], "/src/account/urls.py": ["/src/account/views.py"], "/src/transaction/admin.py": ["/src/transaction/models.py"], "/src/resource/views.py": ["/src/resource/models.py", "/src/resource/forms.py"], "/src/member/admin.py": ["/src/member/models.py"], "/src/service/urls.py": ["/src/service/views.py"], "/src/wishlist/admin.py": ["/src/wishlist/models.py"], "/src/resource/admin.py": ["/src/resource/models.py"], "/src/core/dev/views.py": ["/src/core/dev/automate.py", "/src/core/dev/forms.py"], "/src/core/dev/urls.py": ["/src/core/dev/views.py"], "/src/resource/forms.py": ["/src/resource/models.py"], "/src/core/coreurls.py": ["/src/core/coreviews.py"], "/src/amtd/admin.py": ["/src/amtd/models.py"], "/src/account/views.py": ["/src/account/forms.py", "/src/account/models.py"], "/src/service/admin.py": ["/src/service/models.py"], "/src/resource/urls.py": ["/src/resource/views.py"]} |
78,591 | belal-bh/CLIC_PUST | refs/heads/master | /src/transaction/admin.py | from django.contrib import admin
from .models import (
TrxBook,
TrxResource,
)
admin.site.register(TrxBook)
admin.site.register(TrxResource)
| {"/src/academic/admin.py": ["/src/academic/models.py"], "/src/account/urls.py": ["/src/account/views.py"], "/src/transaction/admin.py": ["/src/transaction/models.py"], "/src/resource/views.py": ["/src/resource/models.py", "/src/resource/forms.py"], "/src/member/admin.py": ["/src/member/models.py"], "/src/service/urls.py": ["/src/service/views.py"], "/src/wishlist/admin.py": ["/src/wishlist/models.py"], "/src/resource/admin.py": ["/src/resource/models.py"], "/src/core/dev/views.py": ["/src/core/dev/automate.py", "/src/core/dev/forms.py"], "/src/core/dev/urls.py": ["/src/core/dev/views.py"], "/src/resource/forms.py": ["/src/resource/models.py"], "/src/core/coreurls.py": ["/src/core/coreviews.py"], "/src/amtd/admin.py": ["/src/amtd/models.py"], "/src/account/views.py": ["/src/account/forms.py", "/src/account/models.py"], "/src/service/admin.py": ["/src/service/models.py"], "/src/resource/urls.py": ["/src/resource/views.py"]} |
78,592 | belal-bh/CLIC_PUST | refs/heads/master | /src/resource/views.py | from django.shortcuts import render
from django.db.models import Q
from django.utils import timezone
from django.http import HttpResponse, HttpResponseRedirect, Http404
from django.shortcuts import render, get_object_or_404, redirect
from django.urls import reverse
from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger
from django.contrib.auth.decorators import login_required
from .models import (
Book,
Resource,
Author,
)
from wishlist.models import (
BookCart,
ResourceCart
)
from .forms import (
BookCartForm,
ResourceCartForm
)
@login_required
def book_list(request):
today = timezone.now().date()
queryset_list = Book.objects.all()
query = request.GET.get("q")
by = request.GET.get("by")
if query:
if by == 'title':
queryset_list = queryset_list.filter(
Q(title__icontains=query)
).distinct()
elif by == 'author':
queryset_list = queryset_list.filter(
Q(author__name__icontains=query) |
Q(author__nicname__icontains=query)
).distinct()
elif by == 'accession_number':
queryset_list = queryset_list.filter(
Q(accession_number__icontains=query)
).distinct()
elif by == 'call_number':
queryset_list = queryset_list.filter(
Q(call_number__icontains=query)
).distinct()
else:
queryset_list = queryset_list.filter(
Q(isbn__icontains=query)
).distinct()
total_found = len(queryset_list)
paginator = Paginator(queryset_list, 10) # Show 25 contacts per page
page_request_var = "page"
page = request.GET.get(page_request_var)
try:
queryset = paginator.page(page)
except PageNotAnInteger:
# If page is not an integer, deliver first page.
queryset = paginator.page(1)
except EmptyPage:
# If page is out of range (e.g. 9999), deliver last page of results.
queryset = paginator.page(paginator.num_pages)
context = {
"object_list": queryset,
'total_found': total_found,
"title": "Books",
"page_request_var": page_request_var,
"today": today,
}
# print(context)
return render(request, "book_list.html", context)
@login_required
def book_detail(request, id):
instance = get_object_or_404(Book, id=id)
cart_added = BookCart.objects.all().filter(book=instance, user=request.user).first()
form = BookCartForm(request.POST or None, request.FILES or None)
if form.is_valid() and not cart_added:
cart_instance = form.save(commit=False)
cart_instance.book = instance
cart_instance.user = request.user
cart_instance.save()
print("Submitted BookCart", form)
# message success
# messages.success(request, "Successfully Added to BookCart")
context = {
"instance": instance,
"title": "Book Detail",
"form": form,
'cart_added': cart_added,
}
return render(request, "book_detail.html", context)
@login_required
def resource_list(request):
today = timezone.now().date()
queryset_list = Resource.objects.all()
query = request.GET.get("rq")
by = request.GET.get("by")
res_type = request.GET.get("rt")
if query:
if res_type != 'all':
queryset_list = queryset_list.filter(
Q(resource_type__icontains=res_type)
).distinct()
if by == 'title':
queryset_list = queryset_list.filter(
Q(title__icontains=query)
).distinct()
elif by == 'accession_number':
queryset_list = queryset_list.filter(
Q(accession_number__icontains=query)
).distinct()
elif by == 'call_number':
queryset_list = queryset_list.filter(
Q(call_number__icontains=query)
).distinct()
paginator = Paginator(queryset_list, 5) # Show 25 contacts per page
page_request_var = "page"
page = request.GET.get(page_request_var)
try:
queryset = paginator.page(page)
except PageNotAnInteger:
# If page is not an integer, deliver first page.
queryset = paginator.page(1)
except EmptyPage:
# If page is out of range (e.g. 9999), deliver last page of results.
queryset = paginator.page(paginator.num_pages)
context = {
"object_list": queryset,
"title": "Resources",
"page_request_var": page_request_var,
"today": today,
}
# print(context)
return render(request, "resource_list.html", context)
@login_required
def resource_detail(request, id):
instance = get_object_or_404(Resource, id=id)
cart_added = ResourceCart.objects.all().filter(resource=instance, user=request.user).first()
form = ResourceCartForm(request.POST or None, request.FILES or None)
if form.is_valid() and not cart_added:
cart_instance = form.save(commit=False)
cart_instance.resource = instance
cart_instance.user = request.user
cart_instance.save()
print("Submitted ResourceCart", form)
context = {
"instance": instance,
"title": "Resource Detail",
"form": form,
'cart_added': cart_added,
}
return render(request, "resource_detail.html", context)
@login_required
def resource_doclist(request):
return render(request, "under_constraction.html", {})
@login_required
def resource_newspaperlist(request):
return render(request, "under_constraction.html", {})
| {"/src/academic/admin.py": ["/src/academic/models.py"], "/src/account/urls.py": ["/src/account/views.py"], "/src/transaction/admin.py": ["/src/transaction/models.py"], "/src/resource/views.py": ["/src/resource/models.py", "/src/resource/forms.py"], "/src/member/admin.py": ["/src/member/models.py"], "/src/service/urls.py": ["/src/service/views.py"], "/src/wishlist/admin.py": ["/src/wishlist/models.py"], "/src/resource/admin.py": ["/src/resource/models.py"], "/src/core/dev/views.py": ["/src/core/dev/automate.py", "/src/core/dev/forms.py"], "/src/core/dev/urls.py": ["/src/core/dev/views.py"], "/src/resource/forms.py": ["/src/resource/models.py"], "/src/core/coreurls.py": ["/src/core/coreviews.py"], "/src/amtd/admin.py": ["/src/amtd/models.py"], "/src/account/views.py": ["/src/account/forms.py", "/src/account/models.py"], "/src/service/admin.py": ["/src/service/models.py"], "/src/resource/urls.py": ["/src/resource/views.py"]} |
78,593 | belal-bh/CLIC_PUST | refs/heads/master | /src/member/admin.py | from django.contrib import admin
from .models import (
Student,
Teacher,
Officer,
Staff,
Othermember,
Librarian
)
admin.site.register(Student)
admin.site.register(Teacher)
admin.site.register(Officer)
admin.site.register(Staff)
admin.site.register(Othermember)
admin.site.register(Librarian)
| {"/src/academic/admin.py": ["/src/academic/models.py"], "/src/account/urls.py": ["/src/account/views.py"], "/src/transaction/admin.py": ["/src/transaction/models.py"], "/src/resource/views.py": ["/src/resource/models.py", "/src/resource/forms.py"], "/src/member/admin.py": ["/src/member/models.py"], "/src/service/urls.py": ["/src/service/views.py"], "/src/wishlist/admin.py": ["/src/wishlist/models.py"], "/src/resource/admin.py": ["/src/resource/models.py"], "/src/core/dev/views.py": ["/src/core/dev/automate.py", "/src/core/dev/forms.py"], "/src/core/dev/urls.py": ["/src/core/dev/views.py"], "/src/resource/forms.py": ["/src/resource/models.py"], "/src/core/coreurls.py": ["/src/core/coreviews.py"], "/src/amtd/admin.py": ["/src/amtd/models.py"], "/src/account/views.py": ["/src/account/forms.py", "/src/account/models.py"], "/src/service/admin.py": ["/src/service/models.py"], "/src/resource/urls.py": ["/src/resource/views.py"]} |
78,594 | belal-bh/CLIC_PUST | refs/heads/master | /src/core/dev/readdata.py | import pandas as pd
import numpy as np
import math
# import python-slugify to convert product_name as slug_string
# pip install python-slugify
# from slugify import slugify
################### LOAD DATA ###########################
def load_data():
print("Loading Data...")
F_1 = 'data\\BX-Book-Ratings.csv'
F_2 = 'data\\BX-Books.csv'
F_3 = 'data\\BX-Users.csv'
ZIZE = 100
# df1 = pd.read_csv(F_1).iloc[1:ZIZE, [1,16]]
# df2 = pd.read_csv(F_2).iloc[1:ZIZE, [3,20]]
# df3 = pd.read_csv(F_3).iloc[1:ZIZE, [3,20]]
# "ISBN";"Book-Title";"Book-Author";"Year-Of-Publication";"Publisher";"Image-URL-S";"Image-URL-M";"Image-URL-L"
book_df = pd.read_csv(F_2, sep=';',engine='python', quotechar='"', error_bad_lines=False) #.iloc[1:ZIZE, [1,2]]
# book_df = pd.read_csv(F_2, header=None, error_bad_lines=False, encoding='utf-8').iloc[1:ZIZE, [1,2]]
print("Data Loaded")
return book_df
def load_csv():
# import requests
import csv
with open('data\\BX-Books.csv') as csvfile:
dialect = csv.Sniffer().sniff(csvfile.read(14734))
df = pd.read_csv('data\\BX-Books.csv', engine='python', dialect=dialect, error_bad_lines=False)
return df
bookdf = load_csv() #load_data()
book_list = bookdf.values.tolist()
# isbn = []
# authors = []
# year_of_pub = []
# publisher = [],
# img_url = []
book = [] #{'isbn': , 'authors': [], 'year_of_pub': , 'publisher': , 'img_urls': [] }
for i in range(len(book_list)):
isbn = book_list[i][0]
authors = book_list[i][1:-5]
year_of_pub = book_list[i][-5]
publisher = book_list[i][-4]
img_urls = book_list[i][-3:]
book.append({'isbn': isbn , 'authors': authors, 'year_of_pub':year_of_pub ,'publisher': publisher , 'img_urls': img_urls })
print('books:', book)
book_df = pd.DataFrame(book, columns=["isbn","authors","year_of_pub","publisher","img_urls"])
book_df.to_csv('data\\output\\books.csv')
# FILE_NAME = 'data\\output\\book_sniff.csv'
# df = pd.DataFrame(bookdf, columns=["ISBN","Book-Title","Book-Author","Year-Of-Publication","Publisher","Image-URL-S","Image-URL-M","Image-URL-L"])
# df.to_csv(FILE_NAME, index=True, index_label="ID", sep=';')
# bookdf.to_csv()
| {"/src/academic/admin.py": ["/src/academic/models.py"], "/src/account/urls.py": ["/src/account/views.py"], "/src/transaction/admin.py": ["/src/transaction/models.py"], "/src/resource/views.py": ["/src/resource/models.py", "/src/resource/forms.py"], "/src/member/admin.py": ["/src/member/models.py"], "/src/service/urls.py": ["/src/service/views.py"], "/src/wishlist/admin.py": ["/src/wishlist/models.py"], "/src/resource/admin.py": ["/src/resource/models.py"], "/src/core/dev/views.py": ["/src/core/dev/automate.py", "/src/core/dev/forms.py"], "/src/core/dev/urls.py": ["/src/core/dev/views.py"], "/src/resource/forms.py": ["/src/resource/models.py"], "/src/core/coreurls.py": ["/src/core/coreviews.py"], "/src/amtd/admin.py": ["/src/amtd/models.py"], "/src/account/views.py": ["/src/account/forms.py", "/src/account/models.py"], "/src/service/admin.py": ["/src/service/models.py"], "/src/resource/urls.py": ["/src/resource/views.py"]} |
78,595 | belal-bh/CLIC_PUST | refs/heads/master | /src/wishlist/models.py | from django.db import models
from django.conf import settings
from resource.models import (
Book,
Resource
)
class BookCartManager(models.Manager):
def active(self, *args, **kwargs):
return super(BookCartManager, self) #.filter(draft=False).filter(publish__lte=timezone.now())
class ResourceCartManager(models.Manager):
def active(self, *args, **kwargs):
return super(ResourceCartManager, self) #.filter(draft=False).filter(publish__lte=timezone.now())
class BookCart(models.Model):
book = models.ForeignKey(
Book, on_delete=models.CASCADE)
user = models.ForeignKey(
settings.AUTH_USER_MODEL, on_delete=models.CASCADE, null=False, blank=False)
comment = models.CharField(max_length=255, null=True, blank=True)
timestamp = models.DateTimeField(auto_now=False, auto_now_add=True)
objects = BookCartManager()
def __str__(self):
return self.book.title
class ResourceCart(models.Model):
resource = models.ForeignKey(
Resource, on_delete=models.CASCADE)
user = models.ForeignKey(
settings.AUTH_USER_MODEL, on_delete=models.CASCADE, null=False, blank=False)
comment = models.CharField(max_length=255, null=True, blank=True)
timestamp = models.DateTimeField(auto_now=False, auto_now_add=True)
objects = ResourceCartManager()
| {"/src/academic/admin.py": ["/src/academic/models.py"], "/src/account/urls.py": ["/src/account/views.py"], "/src/transaction/admin.py": ["/src/transaction/models.py"], "/src/resource/views.py": ["/src/resource/models.py", "/src/resource/forms.py"], "/src/member/admin.py": ["/src/member/models.py"], "/src/service/urls.py": ["/src/service/views.py"], "/src/wishlist/admin.py": ["/src/wishlist/models.py"], "/src/resource/admin.py": ["/src/resource/models.py"], "/src/core/dev/views.py": ["/src/core/dev/automate.py", "/src/core/dev/forms.py"], "/src/core/dev/urls.py": ["/src/core/dev/views.py"], "/src/resource/forms.py": ["/src/resource/models.py"], "/src/core/coreurls.py": ["/src/core/coreviews.py"], "/src/amtd/admin.py": ["/src/amtd/models.py"], "/src/account/views.py": ["/src/account/forms.py", "/src/account/models.py"], "/src/service/admin.py": ["/src/service/models.py"], "/src/resource/urls.py": ["/src/resource/views.py"]} |
78,596 | belal-bh/CLIC_PUST | refs/heads/master | /src/service/models.py | # service.models.py
from django.db import models
from django.conf import settings
import uuid
from account.helpers import UploadTo
class Request(models.Model):
title = models.CharField(max_length=255)
content = models.TextField()
image = models.ImageField(
upload_to=UploadTo('image', plus_id=True),
null=True,
blank=True,
width_field="width_field",
height_field="height_field"
)
height_field = models.IntegerField(default=0, null=True)
width_field = models.IntegerField(default=0, null=True)
attachments = models.FileField(
upload_to=UploadTo('attachments', plus_id=True),
null=True,
blank=True
)
draft = models.BooleanField(default=False)
published = models.DateTimeField(auto_now=False, auto_now_add=False)
user = models.ForeignKey(settings.AUTH_USER_MODEL,
on_delete=models.CASCADE)
ACCEPTED = 'accepted'
REJECTED = 'rejected'
PENDING = 'pending'
OPEN = 'open'
CLOSED = 'closed'
STATUS_CHOICES = (
(ACCEPTED, 'Accepted'),
(REJECTED, 'Rejected'),
(PENDING, 'Pending'),
(OPEN, 'Open'),
(CLOSED, 'Closed'),
)
status = models.CharField(
max_length=10,
choices=STATUS_CHOICES,
default=OPEN
)
timestamp = models.DateTimeField(auto_now=False, auto_now_add=True)
updated = models.DateTimeField(auto_now=True, auto_now_add=False)
class Report(models.Model):
title = models.CharField(max_length=255)
content = models.TextField()
image = models.ImageField(
upload_to=UploadTo('image', plus_id=True),
null=True,
blank=True,
width_field="width_field",
height_field="height_field"
)
height_field = models.IntegerField(default=0, null=True)
width_field = models.IntegerField(default=0, null=True)
attachments = models.FileField(
upload_to=UploadTo('attachments', plus_id=True),
null=True,
blank=True
)
draft = models.BooleanField(default=False)
published = models.DateTimeField(auto_now=False, auto_now_add=False)
user = models.ForeignKey(settings.AUTH_USER_MODEL,
on_delete=models.CASCADE)
ACCEPTED = 'accepted'
REJECTED = 'rejected'
PENDING = 'pending'
OPEN = 'open'
CLOSED = 'closed'
STATUS_CHOICES = (
(ACCEPTED, 'Accepted'),
(REJECTED, 'Rejected'),
(PENDING, 'Pending'),
(OPEN, 'Open'),
(CLOSED, 'Closed'),
)
status = models.CharField(
max_length=10,
choices=STATUS_CHOICES,
default=OPEN
)
timestamp = models.DateTimeField(auto_now=False, auto_now_add=True)
updated = models.DateTimeField(auto_now=True, auto_now_add=False)
class Notice(models.Model):
notice_id = models.UUIDField(
default=uuid.uuid4, editable=False, unique=True)
title = models.CharField(max_length=255)
content = models.TextField()
attachments = models.FileField(
upload_to=UploadTo('attachments', plus_id=True),
null=True,
blank=True
)
send_from = models.CharField(max_length=255, null=True, blank=True)
send_to = models.ManyToManyField(
settings.AUTH_USER_MODEL, related_name="service_user_send_to")
draft = models.BooleanField(default=False)
published = models.DateTimeField(auto_now=False, auto_now_add=False)
posted_by = models.ForeignKey(
settings.AUTH_USER_MODEL, on_delete=models.PROTECT, related_name="service_user_posted_by")
timestamp = models.DateTimeField(auto_now=False, auto_now_add=True)
updated = models.DateTimeField(auto_now=True, auto_now_add=False)
| {"/src/academic/admin.py": ["/src/academic/models.py"], "/src/account/urls.py": ["/src/account/views.py"], "/src/transaction/admin.py": ["/src/transaction/models.py"], "/src/resource/views.py": ["/src/resource/models.py", "/src/resource/forms.py"], "/src/member/admin.py": ["/src/member/models.py"], "/src/service/urls.py": ["/src/service/views.py"], "/src/wishlist/admin.py": ["/src/wishlist/models.py"], "/src/resource/admin.py": ["/src/resource/models.py"], "/src/core/dev/views.py": ["/src/core/dev/automate.py", "/src/core/dev/forms.py"], "/src/core/dev/urls.py": ["/src/core/dev/views.py"], "/src/resource/forms.py": ["/src/resource/models.py"], "/src/core/coreurls.py": ["/src/core/coreviews.py"], "/src/amtd/admin.py": ["/src/amtd/models.py"], "/src/account/views.py": ["/src/account/forms.py", "/src/account/models.py"], "/src/service/admin.py": ["/src/service/models.py"], "/src/resource/urls.py": ["/src/resource/views.py"]} |
78,597 | belal-bh/CLIC_PUST | refs/heads/master | /src/core/coreviews.py | from django.shortcuts import render, get_object_or_404, redirect
from django.contrib.auth.decorators import login_required
@login_required
def about_pust(request):
return render(request, "under_constraction.html", {})
@login_required
def about_clic(request):
return render(request, "under_constraction.html", {})
@login_required
def about_faculty(request):
return render(request, "under_constraction.html", {})
@login_required
def about_department(request):
return render(request, "under_constraction.html", {})
@login_required
def about_institute(request):
return render(request, "under_constraction.html", {})
@login_required
def about_administration(request):
return render(request, "under_constraction.html", {})
@login_required
def about_dormitory(request):
return render(request, "under_constraction.html", {})
@login_required
def about_contact(request):
return render(request, "under_constraction.html", {})
@login_required
def about_underconstruction(request):
return render(request, "under_constraction.html", {})
| {"/src/academic/admin.py": ["/src/academic/models.py"], "/src/account/urls.py": ["/src/account/views.py"], "/src/transaction/admin.py": ["/src/transaction/models.py"], "/src/resource/views.py": ["/src/resource/models.py", "/src/resource/forms.py"], "/src/member/admin.py": ["/src/member/models.py"], "/src/service/urls.py": ["/src/service/views.py"], "/src/wishlist/admin.py": ["/src/wishlist/models.py"], "/src/resource/admin.py": ["/src/resource/models.py"], "/src/core/dev/views.py": ["/src/core/dev/automate.py", "/src/core/dev/forms.py"], "/src/core/dev/urls.py": ["/src/core/dev/views.py"], "/src/resource/forms.py": ["/src/resource/models.py"], "/src/core/coreurls.py": ["/src/core/coreviews.py"], "/src/amtd/admin.py": ["/src/amtd/models.py"], "/src/account/views.py": ["/src/account/forms.py", "/src/account/models.py"], "/src/service/admin.py": ["/src/service/models.py"], "/src/resource/urls.py": ["/src/resource/views.py"]} |
78,598 | belal-bh/CLIC_PUST | refs/heads/master | /src/service/urls.py | from django.urls import path
from .views import (
notice_list,
)
app_name = 'service'
urlpatterns = [
path('notice/', notice_list, name='noticelist'),
]
| {"/src/academic/admin.py": ["/src/academic/models.py"], "/src/account/urls.py": ["/src/account/views.py"], "/src/transaction/admin.py": ["/src/transaction/models.py"], "/src/resource/views.py": ["/src/resource/models.py", "/src/resource/forms.py"], "/src/member/admin.py": ["/src/member/models.py"], "/src/service/urls.py": ["/src/service/views.py"], "/src/wishlist/admin.py": ["/src/wishlist/models.py"], "/src/resource/admin.py": ["/src/resource/models.py"], "/src/core/dev/views.py": ["/src/core/dev/automate.py", "/src/core/dev/forms.py"], "/src/core/dev/urls.py": ["/src/core/dev/views.py"], "/src/resource/forms.py": ["/src/resource/models.py"], "/src/core/coreurls.py": ["/src/core/coreviews.py"], "/src/amtd/admin.py": ["/src/amtd/models.py"], "/src/account/views.py": ["/src/account/forms.py", "/src/account/models.py"], "/src/service/admin.py": ["/src/service/models.py"], "/src/resource/urls.py": ["/src/resource/views.py"]} |
78,599 | belal-bh/CLIC_PUST | refs/heads/master | /src/account/migrations/0002_auto_20191002_0424.py | # Generated by Django 2.2.1 on 2019-10-01 22:24
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('account', '0001_initial'),
]
operations = [
migrations.AlterField(
model_name='user',
name='father_name',
field=models.CharField(blank=True, max_length=40, null=True),
),
migrations.AlterField(
model_name='user',
name='mother_name',
field=models.CharField(blank=True, max_length=40, null=True),
),
migrations.AlterField(
model_name='user',
name='name',
field=models.CharField(blank=True, max_length=40, null=True),
),
migrations.AlterField(
model_name='user',
name='validity',
field=models.DateTimeField(auto_now_add=True),
),
]
| {"/src/academic/admin.py": ["/src/academic/models.py"], "/src/account/urls.py": ["/src/account/views.py"], "/src/transaction/admin.py": ["/src/transaction/models.py"], "/src/resource/views.py": ["/src/resource/models.py", "/src/resource/forms.py"], "/src/member/admin.py": ["/src/member/models.py"], "/src/service/urls.py": ["/src/service/views.py"], "/src/wishlist/admin.py": ["/src/wishlist/models.py"], "/src/resource/admin.py": ["/src/resource/models.py"], "/src/core/dev/views.py": ["/src/core/dev/automate.py", "/src/core/dev/forms.py"], "/src/core/dev/urls.py": ["/src/core/dev/views.py"], "/src/resource/forms.py": ["/src/resource/models.py"], "/src/core/coreurls.py": ["/src/core/coreviews.py"], "/src/amtd/admin.py": ["/src/amtd/models.py"], "/src/account/views.py": ["/src/account/forms.py", "/src/account/models.py"], "/src/service/admin.py": ["/src/service/models.py"], "/src/resource/urls.py": ["/src/resource/views.py"]} |
78,600 | belal-bh/CLIC_PUST | refs/heads/master | /src/transaction/views.py | from django.shortcuts import render
from django.contrib.auth.decorators import login_required
| {"/src/academic/admin.py": ["/src/academic/models.py"], "/src/account/urls.py": ["/src/account/views.py"], "/src/transaction/admin.py": ["/src/transaction/models.py"], "/src/resource/views.py": ["/src/resource/models.py", "/src/resource/forms.py"], "/src/member/admin.py": ["/src/member/models.py"], "/src/service/urls.py": ["/src/service/views.py"], "/src/wishlist/admin.py": ["/src/wishlist/models.py"], "/src/resource/admin.py": ["/src/resource/models.py"], "/src/core/dev/views.py": ["/src/core/dev/automate.py", "/src/core/dev/forms.py"], "/src/core/dev/urls.py": ["/src/core/dev/views.py"], "/src/resource/forms.py": ["/src/resource/models.py"], "/src/core/coreurls.py": ["/src/core/coreviews.py"], "/src/amtd/admin.py": ["/src/amtd/models.py"], "/src/account/views.py": ["/src/account/forms.py", "/src/account/models.py"], "/src/service/admin.py": ["/src/service/models.py"], "/src/resource/urls.py": ["/src/resource/views.py"]} |
78,601 | belal-bh/CLIC_PUST | refs/heads/master | /src/account/models.py | # accounts.models.py
import time
from django.urls import reverse
from django.db import models
from django.db.models.signals import pre_save, post_save
from django.dispatch import receiver
from django.core.validators import RegexValidator
from django.contrib.auth.models import (
BaseUserManager, AbstractBaseUser
)
# from notifications.signals import notify
from account.helpers import UploadTo, DefaultPeriod
CONTACT_MOBILE_REGEX = '^(?:\+?88|0088)?01[15-9]\d{8}$'
CONTACT_PHONE_REGEX = '^(?:\+?88|0088)?0\d{10}$'
LIBRARY_ID_REGEX = '^[a-zA-Z0-9.+-]+$'
class UserManager(BaseUserManager):
def create_user(self, library_id, email, contact_mobile, password=None):
"""
Creates and saves a User with the given email and password.
"""
if not email:
raise ValueError('Users must have an email address')
user = self.model(
library_id=library_id,
email=self.normalize_email(email),
contact_mobile=contact_mobile
)
user.set_password(password)
user.save(using=self._db)
return user
def create_staffuser(self, library_id, email, contact_mobile, password):
"""
Creates and saves a staff user with the given email and password.
"""
user = self.create_user(
library_id,
email,
password=password,
contact_mobile=contact_mobile
)
user.staff = True
user.save(using=self._db)
return user
def create_superuser(self, library_id, email, contact_mobile, password):
"""
Creates and saves a superuser with the given email and password.
"""
user = self.create_user(
library_id,
email,
password=password,
contact_mobile=contact_mobile
)
user.admin = True
user.staff = True
user.save(using=self._db)
return user
def active(self, *args, **kwargs):
return super(UserManager, self).filter(active=True)
class User(AbstractBaseUser):
email = models.EmailField(
verbose_name='email address',
max_length=255,
unique=True,
)
name = models.CharField(max_length=40, null=True, blank=True)
father_name = models.CharField(max_length=40, null=True, blank=True)
mother_name = models.CharField(max_length=40, null=True, blank=True)
MALE = 'm'
FEMALE = 'f'
OTHERS = 'o'
GENDER_CHOICES = (
(MALE, 'Male'),
(FEMALE, 'Female'),
(OTHERS, 'Others'),
)
gender = models.CharField(
max_length=1,
choices=GENDER_CHOICES,
default=MALE
)
mailing_address = models.CharField(max_length=255, null=True, blank=True)
permanent_address = models.CharField(max_length=255, null=True, blank=True)
contact_mobile = models.CharField(
max_length=32,
validators=[
RegexValidator(
regex=CONTACT_MOBILE_REGEX,
message='Mobile number must be numeric',
code='invalid_contact_mobile'
)],
)
contact_phone = models.CharField(
max_length=32,
validators=[
RegexValidator(
regex=CONTACT_PHONE_REGEX,
message='Phone number must be numeric',
code='invalid_contact_phone'
)],
null=True,
blank=True
)
image = models.ImageField(
default='account/user/image/default.png',
upload_to=UploadTo('image', plus_id=True),
null=True,
blank=True,
width_field="width_field",
height_field="height_field"
)
height_field = models.IntegerField(default=0, null=True)
width_field = models.IntegerField(default=0, null=True)
STUDENT = 'sn'
TEACHER = 'tc'
OFFICER = 'of'
STAFF = 'sf'
OTHERMEMBER = 'om'
LIBRARIAN = 'lb'
ACCOUNT_TYPE_CHOICES = (
(STUDENT, 'Student'),
(TEACHER, 'Teacher'),
(OFFICER, 'Officer'),
(STAFF, 'Staff'),
(OTHERMEMBER, 'Others'),
(LIBRARIAN, 'Librarian'),
)
account_type = models.CharField(
max_length=2,
choices=ACCOUNT_TYPE_CHOICES,
default=STUDENT
)
registration_copy = models.FileField(
upload_to=UploadTo('registration', plus_id=True),
null=True,
blank=True
)
library_id = models.CharField(
max_length=15,
validators=[
RegexValidator(
regex=LIBRARY_ID_REGEX,
message='Library ID must be alphanumeric or contain numbers',
code='invalid_library_id'
)],
unique=True
)
no_borrowed_books = models.PositiveSmallIntegerField(
default=0,
null=True,
blank=True
)
no_borrowed_resources = models.PositiveSmallIntegerField(
default=0,
null=True,
blank=True
)
validity = models.DateTimeField(
auto_now=False, auto_now_add=False, default=DefaultPeriod(years=1, hour=10)) # need customization
active = models.BooleanField(default=True)
timestamp = models.DateTimeField(auto_now=False, auto_now_add=True)
updated = models.DateTimeField(auto_now=True, auto_now_add=False)
staff = models.BooleanField(default=False) # a admin user; non super-user
admin = models.BooleanField(default=False) # a superuser
# notice the absence of a "Password field", that's built in.
USERNAME_FIELD = 'email'
# Email & Password are required by default.
REQUIRED_FIELDS = ['library_id', 'contact_mobile']
objects = UserManager()
def __str__(self):
if self.name:
return self.name
return self.email
# def get_absolute_url(self):
# return reverse("accounts:profile")
# def get_user_url(self):
# return reverse("accounts:user", kwargs={'id': self.id})
# def get_profile_update_url(self):
# return reverse("accounts:profile_update")
def get_full_name(self):
# The user is identified by their email address
if self.name:
return self.name
return self.email
def get_short_name(self):
# The user is identified by their email address
return self.email
def has_perm(self, perm, obj=None):
# "Does the user have a specific permission?"
# Simplest possible answer: Yes, always
return True
def has_module_perms(self, app_label):
# "Does the user have permissions to view the app `app_label`?"
# Simplest possible answer: Yes, always
return True
@property
def is_staff(self):
# "Is the user a member of staff?"
return self.staff
@property
def is_superuser(self):
# "Is the user a admin member?"
return self.admin
@property
def is_active(self):
# "Is the user active?"
return self.active
@receiver(pre_save, sender=User)
def pre_save_user_receiver(sender, instance, *args, **kwargs):
if instance:
print("pre_save_user_receiver -> OK")
else:
print("pre_save_user_receiver -> instance was None!")
@receiver(post_save, sender=User)
def post_save_user_receiver(sender, instance, created, *args, **kwargs):
if instance:
print("post_save_user_receiver done!")
else:
print("post_save_user_receiver instance is None!")
| {"/src/academic/admin.py": ["/src/academic/models.py"], "/src/account/urls.py": ["/src/account/views.py"], "/src/transaction/admin.py": ["/src/transaction/models.py"], "/src/resource/views.py": ["/src/resource/models.py", "/src/resource/forms.py"], "/src/member/admin.py": ["/src/member/models.py"], "/src/service/urls.py": ["/src/service/views.py"], "/src/wishlist/admin.py": ["/src/wishlist/models.py"], "/src/resource/admin.py": ["/src/resource/models.py"], "/src/core/dev/views.py": ["/src/core/dev/automate.py", "/src/core/dev/forms.py"], "/src/core/dev/urls.py": ["/src/core/dev/views.py"], "/src/resource/forms.py": ["/src/resource/models.py"], "/src/core/coreurls.py": ["/src/core/coreviews.py"], "/src/amtd/admin.py": ["/src/amtd/models.py"], "/src/account/views.py": ["/src/account/forms.py", "/src/account/models.py"], "/src/service/admin.py": ["/src/service/models.py"], "/src/resource/urls.py": ["/src/resource/views.py"]} |
78,602 | belal-bh/CLIC_PUST | refs/heads/master | /src/resource/migrations/0007_auto_20200314_1820.py | # Generated by Django 2.2.1 on 2020-03-14 12:20
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('resource', '0006_auto_20200314_1249'),
]
operations = [
migrations.AlterField(
model_name='author',
name='name',
field=models.CharField(max_length=100),
),
migrations.AlterField(
model_name='author',
name='nicname',
field=models.CharField(max_length=30),
),
]
| {"/src/academic/admin.py": ["/src/academic/models.py"], "/src/account/urls.py": ["/src/account/views.py"], "/src/transaction/admin.py": ["/src/transaction/models.py"], "/src/resource/views.py": ["/src/resource/models.py", "/src/resource/forms.py"], "/src/member/admin.py": ["/src/member/models.py"], "/src/service/urls.py": ["/src/service/views.py"], "/src/wishlist/admin.py": ["/src/wishlist/models.py"], "/src/resource/admin.py": ["/src/resource/models.py"], "/src/core/dev/views.py": ["/src/core/dev/automate.py", "/src/core/dev/forms.py"], "/src/core/dev/urls.py": ["/src/core/dev/views.py"], "/src/resource/forms.py": ["/src/resource/models.py"], "/src/core/coreurls.py": ["/src/core/coreviews.py"], "/src/amtd/admin.py": ["/src/amtd/models.py"], "/src/account/views.py": ["/src/account/forms.py", "/src/account/models.py"], "/src/service/admin.py": ["/src/service/models.py"], "/src/resource/urls.py": ["/src/resource/views.py"]} |
78,603 | belal-bh/CLIC_PUST | refs/heads/master | /src/account/migrations/0001_initial.py | # Generated by Django 2.2.1 on 2019-10-01 21:48
import account.helpers
import django.core.validators
from django.db import migrations, models
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='User',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('password', models.CharField(max_length=128, verbose_name='password')),
('last_login', models.DateTimeField(blank=True, null=True, verbose_name='last login')),
('email', models.EmailField(max_length=255, unique=True, verbose_name='email address')),
('name', models.CharField(blank=True, max_length=40)),
('father_name', models.CharField(blank=True, max_length=40)),
('mother_name', models.CharField(blank=True, max_length=40)),
('gender', models.CharField(choices=[('m', 'Male'), ('f', 'Female'), ('o', 'Others')], default='m', max_length=1)),
('mailing_address', models.CharField(blank=True, max_length=255, null=True)),
('permanent_address', models.CharField(blank=True, max_length=255, null=True)),
('contact_mobile', models.CharField(max_length=32, validators=[django.core.validators.RegexValidator(code='invalid_contact_mobile', message='Mobile number must be numeric', regex='^(?:\\+?88|0088)?01[15-9]\\d{8}$')])),
('contact_phone', models.CharField(blank=True, max_length=32, null=True, validators=[django.core.validators.RegexValidator(code='invalid_contact_phone', message='Phone number must be numeric', regex='^(?:\\+?88|0088)?0\\d{10}$')])),
('image', models.ImageField(blank=True, default='account/user/image/default.png', height_field='height_field', null=True, upload_to=account.helpers.UploadTo('image'), width_field='width_field')),
('height_field', models.IntegerField(default=0, null=True)),
('width_field', models.IntegerField(default=0, null=True)),
('account_type', models.CharField(choices=[('sn', 'Student'), ('tc', 'Teacher'), ('of', 'Officer'), ('sf', 'Staff'), ('om', 'Others'), ('lb', 'Librarian')], default='sn', max_length=2)),
('registration_copy', models.FileField(blank=True, null=True, upload_to=account.helpers.UploadTo('registration'))),
('library_id', models.CharField(max_length=15, unique=True, validators=[django.core.validators.RegexValidator(code='invalid_library_id', message='Library ID must be alphanumeric or contain numbers', regex='^[a-zA-Z0-9.+-]+$')])),
('no_borrowed_books', models.PositiveSmallIntegerField(blank=True, default=0, null=True)),
('no_borrowed_resources', models.PositiveSmallIntegerField(blank=True, default=0, null=True)),
('validity', models.DateTimeField()),
('active', models.BooleanField(default=True)),
('timestamp', models.DateTimeField(auto_now_add=True)),
('updated', models.DateTimeField(auto_now=True)),
('staff', models.BooleanField(default=False)),
('admin', models.BooleanField(default=False)),
],
options={
'abstract': False,
},
),
]
| {"/src/academic/admin.py": ["/src/academic/models.py"], "/src/account/urls.py": ["/src/account/views.py"], "/src/transaction/admin.py": ["/src/transaction/models.py"], "/src/resource/views.py": ["/src/resource/models.py", "/src/resource/forms.py"], "/src/member/admin.py": ["/src/member/models.py"], "/src/service/urls.py": ["/src/service/views.py"], "/src/wishlist/admin.py": ["/src/wishlist/models.py"], "/src/resource/admin.py": ["/src/resource/models.py"], "/src/core/dev/views.py": ["/src/core/dev/automate.py", "/src/core/dev/forms.py"], "/src/core/dev/urls.py": ["/src/core/dev/views.py"], "/src/resource/forms.py": ["/src/resource/models.py"], "/src/core/coreurls.py": ["/src/core/coreviews.py"], "/src/amtd/admin.py": ["/src/amtd/models.py"], "/src/account/views.py": ["/src/account/forms.py", "/src/account/models.py"], "/src/service/admin.py": ["/src/service/models.py"], "/src/resource/urls.py": ["/src/resource/views.py"]} |
78,604 | belal-bh/CLIC_PUST | refs/heads/master | /src/wishlist/admin.py | from django.contrib import admin
from .models import (
BookCart,
ResourceCart,
)
admin.site.register(BookCart)
admin.site.register(ResourceCart)
| {"/src/academic/admin.py": ["/src/academic/models.py"], "/src/account/urls.py": ["/src/account/views.py"], "/src/transaction/admin.py": ["/src/transaction/models.py"], "/src/resource/views.py": ["/src/resource/models.py", "/src/resource/forms.py"], "/src/member/admin.py": ["/src/member/models.py"], "/src/service/urls.py": ["/src/service/views.py"], "/src/wishlist/admin.py": ["/src/wishlist/models.py"], "/src/resource/admin.py": ["/src/resource/models.py"], "/src/core/dev/views.py": ["/src/core/dev/automate.py", "/src/core/dev/forms.py"], "/src/core/dev/urls.py": ["/src/core/dev/views.py"], "/src/resource/forms.py": ["/src/resource/models.py"], "/src/core/coreurls.py": ["/src/core/coreviews.py"], "/src/amtd/admin.py": ["/src/amtd/models.py"], "/src/account/views.py": ["/src/account/forms.py", "/src/account/models.py"], "/src/service/admin.py": ["/src/service/models.py"], "/src/resource/urls.py": ["/src/resource/views.py"]} |
78,605 | belal-bh/CLIC_PUST | refs/heads/master | /src/account/migrations/0003_auto_20191016_0117.py | # Generated by Django 2.2.1 on 2019-10-15 19:17
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('account', '0002_auto_20191002_0424'),
]
operations = [
migrations.AlterField(
model_name='user',
name='validity',
field=models.DateTimeField(),
),
]
| {"/src/academic/admin.py": ["/src/academic/models.py"], "/src/account/urls.py": ["/src/account/views.py"], "/src/transaction/admin.py": ["/src/transaction/models.py"], "/src/resource/views.py": ["/src/resource/models.py", "/src/resource/forms.py"], "/src/member/admin.py": ["/src/member/models.py"], "/src/service/urls.py": ["/src/service/views.py"], "/src/wishlist/admin.py": ["/src/wishlist/models.py"], "/src/resource/admin.py": ["/src/resource/models.py"], "/src/core/dev/views.py": ["/src/core/dev/automate.py", "/src/core/dev/forms.py"], "/src/core/dev/urls.py": ["/src/core/dev/views.py"], "/src/resource/forms.py": ["/src/resource/models.py"], "/src/core/coreurls.py": ["/src/core/coreviews.py"], "/src/amtd/admin.py": ["/src/amtd/models.py"], "/src/account/views.py": ["/src/account/forms.py", "/src/account/models.py"], "/src/service/admin.py": ["/src/service/models.py"], "/src/resource/urls.py": ["/src/resource/views.py"]} |
78,606 | belal-bh/CLIC_PUST | refs/heads/master | /src/academic/models.py | from django.db import models
class Faculty(models.Model):
faculty_id = models.CharField(
max_length=20,
unique=True,
)
name = models.CharField(max_length=120)
abbreviation = models.CharField(max_length=15)
description = models.TextField()
timestamp = models.DateTimeField(auto_now=False, auto_now_add=True)
def __str__(self):
if self.name:
return self.name
return self.abbreviation
class Meta:
ordering = ["faculty_id", "name"]
class Department(models.Model):
dept_id = models.CharField(
max_length=20,
unique=True,
)
name = models.CharField(max_length=120)
abbreviation = models.CharField(max_length=15)
faculty = models.ForeignKey(
Faculty, on_delete=models.SET_NULL, blank=True,
null=True,
)
description = models.TextField()
timestamp = models.DateTimeField(auto_now=False, auto_now_add=True)
def __str__(self):
if self.name:
return self.name
return self.abbreviation
class Meta:
ordering = ["dept_id", "name"]
class Program(models.Model):
program_id = models.CharField(
max_length=20,
unique=True,
)
name = models.CharField(max_length=120)
abbreviation = models.CharField(max_length=15)
description = models.TextField()
timestamp = models.DateTimeField(auto_now=False, auto_now_add=True)
def __str__(self):
if self.name:
return self.name
return self.abbreviation
class Meta:
ordering = ["program_id", "name"]
| {"/src/academic/admin.py": ["/src/academic/models.py"], "/src/account/urls.py": ["/src/account/views.py"], "/src/transaction/admin.py": ["/src/transaction/models.py"], "/src/resource/views.py": ["/src/resource/models.py", "/src/resource/forms.py"], "/src/member/admin.py": ["/src/member/models.py"], "/src/service/urls.py": ["/src/service/views.py"], "/src/wishlist/admin.py": ["/src/wishlist/models.py"], "/src/resource/admin.py": ["/src/resource/models.py"], "/src/core/dev/views.py": ["/src/core/dev/automate.py", "/src/core/dev/forms.py"], "/src/core/dev/urls.py": ["/src/core/dev/views.py"], "/src/resource/forms.py": ["/src/resource/models.py"], "/src/core/coreurls.py": ["/src/core/coreviews.py"], "/src/amtd/admin.py": ["/src/amtd/models.py"], "/src/account/views.py": ["/src/account/forms.py", "/src/account/models.py"], "/src/service/admin.py": ["/src/service/models.py"], "/src/resource/urls.py": ["/src/resource/views.py"]} |
78,607 | belal-bh/CLIC_PUST | refs/heads/master | /src/resource/admin.py | from django.contrib import admin
from .models import (
Author,
Book,
Resource,
)
admin.site.register(Author)
admin.site.register(Book)
admin.site.register(Resource)
| {"/src/academic/admin.py": ["/src/academic/models.py"], "/src/account/urls.py": ["/src/account/views.py"], "/src/transaction/admin.py": ["/src/transaction/models.py"], "/src/resource/views.py": ["/src/resource/models.py", "/src/resource/forms.py"], "/src/member/admin.py": ["/src/member/models.py"], "/src/service/urls.py": ["/src/service/views.py"], "/src/wishlist/admin.py": ["/src/wishlist/models.py"], "/src/resource/admin.py": ["/src/resource/models.py"], "/src/core/dev/views.py": ["/src/core/dev/automate.py", "/src/core/dev/forms.py"], "/src/core/dev/urls.py": ["/src/core/dev/views.py"], "/src/resource/forms.py": ["/src/resource/models.py"], "/src/core/coreurls.py": ["/src/core/coreviews.py"], "/src/amtd/admin.py": ["/src/amtd/models.py"], "/src/account/views.py": ["/src/account/forms.py", "/src/account/models.py"], "/src/service/admin.py": ["/src/service/models.py"], "/src/resource/urls.py": ["/src/resource/views.py"]} |
78,608 | belal-bh/CLIC_PUST | refs/heads/master | /src/account/forms.py | # account.forms.py
from django import forms
from django.contrib.auth.forms import ReadOnlyPasswordHashField
# from pagedown.widgets import PagedownWidget
from django.contrib.auth import get_user_model
from django.db.models import Q
# datetimepicker
# from bootstrap_datepicker_plus import DateTimePickerInput, DatePickerInput
User = get_user_model()
# from .models import User
class RegisterForm(forms.ModelForm):
password1 = forms.CharField(label='Password', widget=forms.PasswordInput)
password2 = forms.CharField(
label='Confirm password', widget=forms.PasswordInput)
class Meta:
model = User
fields = (
'email',
'name',
'father_name',
'mother_name',
'gender',
'mailing_address',
'permanent_address',
'contact_mobile',
'contact_phone',
'image',
'account_type',
'registration_copy',
'library_id',
'validity',
'active',
'staff',
'admin'
)
def clean_library_id(self):
library_id = self.cleaned_data.get('library_id')
qs = User.objects.filter(library_id=library_id)
if qs.exists():
raise forms.ValidationError("library_id is taken")
return library_id
def clean_email(self):
email = self.cleaned_data.get('email')
qs = User.objects.filter(email=email)
if qs.exists():
raise forms.ValidationError("email is taken")
return email
def clean_password2(self):
# Check that the two password entries match
password1 = self.cleaned_data.get("password1")
password2 = self.cleaned_data.get("password2")
if password1 and password2 and password1 != password2:
raise forms.ValidationError("Passwords don't match")
return password2
def save(self, commit=True):
user = super(RegisterForm, self).save(commit=False)
user.set_password(self.cleaned_data['password1'])
if commit:
user.save()
return user
class UserUpdateForm(forms.ModelForm):
class Meta:
model = User
fields = (
'email',
'name',
'father_name',
'mother_name',
'gender',
'mailing_address',
'permanent_address',
'contact_mobile',
'contact_phone',
'image',
'account_type',
'registration_copy',
'library_id',
'validity',
'active',
'staff',
'admin'
)
def __init__(self, *args, **kwargs):
super(UserUpdateForm, self).__init__(*args, **kwargs)
def save(self, commit=True):
user = super(UserUpdateForm, self).save(commit=False)
# user.set_password(self.cleaned_data['password1'])
if commit:
user.save()
return user
class UserAdminCreationForm(forms.ModelForm):
"""A form for creating new users. Includes all the required
fields, plus a repeated password."""
password1 = forms.CharField(label='Password', widget=forms.PasswordInput)
password2 = forms.CharField(
label='Password confirmation', widget=forms.PasswordInput)
class Meta:
model = User
fields = ('email',)
def clean_password2(self):
# Check that the two password entries match
password1 = self.cleaned_data.get("password1")
password2 = self.cleaned_data.get("password2")
if password1 and password2 and password1 != password2:
raise forms.ValidationError("Passwords don't match")
return password2
def save(self, commit=True):
# Save the provided password in hashed format
user = super(UserAdminCreationForm, self).save(commit=False)
user.set_password(self.cleaned_data["password1"])
if commit:
user.save()
return user
class UserAdminChangeForm(forms.ModelForm):
"""A form for updating users. Includes all the fields on
the user, but replaces the password field with admin's
password hash display field.
"""
password = ReadOnlyPasswordHashField()
class Meta:
model = User
fields = ('email', 'password', 'active', 'admin')
def clean_password(self):
# Regardless of what the user provides, return the initial value.
# This is done here, rather than on the field, because the
# field does not have access to the initial value
return self.initial["password"]
class LoginForm(forms.Form):
query = forms.CharField(label='Library_id / Email')
password = forms.CharField(label='Password', widget=forms.PasswordInput)
def clean(self, *args, **kwargs):
query = self.cleaned_data.get('query')
password = self.cleaned_data.get('password')
user_qs_final = User.objects.filter(
Q(library_id__iexact=query) |
Q(email__iexact=query)
).distinct()
if not user_qs_final.exists() and user_qs_final.count != 1:
raise forms.ValidationError(
"Invalid credentials - user does note exist")
user_obj = user_qs_final.first()
if not user_obj.check_password(password):
raise forms.ValidationError("credentials are not correct")
if not user_obj.is_active:
raise forms.ValidationError("This user is not longer active.")
self.cleaned_data["user_obj"] = user_obj
return super(LoginForm, self).clean(*args, **kwargs)
| {"/src/academic/admin.py": ["/src/academic/models.py"], "/src/account/urls.py": ["/src/account/views.py"], "/src/transaction/admin.py": ["/src/transaction/models.py"], "/src/resource/views.py": ["/src/resource/models.py", "/src/resource/forms.py"], "/src/member/admin.py": ["/src/member/models.py"], "/src/service/urls.py": ["/src/service/views.py"], "/src/wishlist/admin.py": ["/src/wishlist/models.py"], "/src/resource/admin.py": ["/src/resource/models.py"], "/src/core/dev/views.py": ["/src/core/dev/automate.py", "/src/core/dev/forms.py"], "/src/core/dev/urls.py": ["/src/core/dev/views.py"], "/src/resource/forms.py": ["/src/resource/models.py"], "/src/core/coreurls.py": ["/src/core/coreviews.py"], "/src/amtd/admin.py": ["/src/amtd/models.py"], "/src/account/views.py": ["/src/account/forms.py", "/src/account/models.py"], "/src/service/admin.py": ["/src/service/models.py"], "/src/resource/urls.py": ["/src/resource/views.py"]} |
78,609 | belal-bh/CLIC_PUST | refs/heads/master | /src/resource/migrations/0001_initial.py | # Generated by Django 2.2.1 on 2019-10-03 21:47
import account.helpers
from django.conf import settings
import django.contrib.postgres.fields
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
('academic', '0001_initial'),
]
operations = [
migrations.CreateModel(
name='Author',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('name', models.CharField(max_length=40)),
('nicname', models.CharField(max_length=20)),
('gender', models.CharField(choices=[('m', 'Male'), ('f', 'Female'), ('o', 'Others')], default='m', max_length=1)),
('nationality', models.CharField(blank=True, max_length=20, null=True)),
('bio', models.TextField(blank=True, null=True)),
('weblinks', django.contrib.postgres.fields.ArrayField(base_field=models.CharField(max_length=120), blank=True, size=None)),
('email', models.EmailField(blank=True, max_length=255, null=True, verbose_name='email address')),
('timestamp', models.DateTimeField(auto_now_add=True)),
('updated', models.DateTimeField(auto_now=True)),
],
),
migrations.CreateModel(
name='Resource',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('title', models.CharField(max_length=255)),
('resource_type', models.CharField(choices=[('software', 'Software'), ('hardware', 'Hardware'), ('magazine', 'Magazine'), ('other', 'Other')], default='other', max_length=20)),
('accession_number', models.CharField(max_length=50)),
('call_number', models.CharField(max_length=20)),
('copy_number', models.CharField(max_length=20)),
('description', models.TextField(blank=True, null=True)),
('mrp', models.PositiveIntegerField(blank=True, null=True)),
('barcode', models.CharField(blank=True, max_length=255, null=True)),
('image', models.ImageField(blank=True, default='resource/resource/image/default.png', height_field='height_field', null=True, upload_to=account.helpers.UploadTo('image'), width_field='width_field')),
('height_field', models.IntegerField(default=0, null=True)),
('width_field', models.IntegerField(default=0, null=True)),
('tags', django.contrib.postgres.fields.ArrayField(base_field=models.CharField(max_length=50), blank=True, size=None)),
('work_done', models.PositiveIntegerField(default=0)),
('status', models.CharField(blank=True, max_length=15, null=True)),
('timestamp', models.DateTimeField(auto_now_add=True)),
('added_by', models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.SET_NULL, to=settings.AUTH_USER_MODEL)),
('departments', models.ManyToManyField(to='academic.Department')),
],
),
migrations.CreateModel(
name='Book',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('title', models.CharField(max_length=255)),
('edition', models.CharField(blank=True, max_length=20, null=True)),
('pagination', models.PositiveIntegerField(blank=True, null=True)),
('accession_number', models.CharField(max_length=50, unique=True)),
('call_number', models.CharField(max_length=20)),
('copy_number', models.CharField(max_length=20)),
('isbn', models.CharField(max_length=50)),
('publisher', models.CharField(blank=True, max_length=120, null=True)),
('description', models.TextField(blank=True, null=True)),
('language', models.CharField(max_length=20)),
('publication_date', models.DateField(blank=True, null=True)),
('last_revision_date', models.DateField(blank=True, null=True)),
('mrp', models.PositiveIntegerField(blank=True, null=True)),
('barcode', models.CharField(blank=True, max_length=255, null=True)),
('image', models.ImageField(blank=True, default='resource/book/image/default.png', height_field='height_field', null=True, upload_to=account.helpers.UploadTo('image'), width_field='width_field')),
('height_field', models.IntegerField(default=0, null=True)),
('width_field', models.IntegerField(default=0, null=True)),
('tags', django.contrib.postgres.fields.ArrayField(base_field=models.CharField(max_length=50), blank=True, size=None)),
('work_done', models.PositiveIntegerField(default=0)),
('status', models.CharField(blank=True, max_length=15, null=True)),
('timestamp', models.DateTimeField(auto_now_add=True)),
('added_by', models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.SET_NULL, to=settings.AUTH_USER_MODEL)),
('author', models.ManyToManyField(to='resource.Author')),
('departments', models.ManyToManyField(to='academic.Department')),
],
),
]
| {"/src/academic/admin.py": ["/src/academic/models.py"], "/src/account/urls.py": ["/src/account/views.py"], "/src/transaction/admin.py": ["/src/transaction/models.py"], "/src/resource/views.py": ["/src/resource/models.py", "/src/resource/forms.py"], "/src/member/admin.py": ["/src/member/models.py"], "/src/service/urls.py": ["/src/service/views.py"], "/src/wishlist/admin.py": ["/src/wishlist/models.py"], "/src/resource/admin.py": ["/src/resource/models.py"], "/src/core/dev/views.py": ["/src/core/dev/automate.py", "/src/core/dev/forms.py"], "/src/core/dev/urls.py": ["/src/core/dev/views.py"], "/src/resource/forms.py": ["/src/resource/models.py"], "/src/core/coreurls.py": ["/src/core/coreviews.py"], "/src/amtd/admin.py": ["/src/amtd/models.py"], "/src/account/views.py": ["/src/account/forms.py", "/src/account/models.py"], "/src/service/admin.py": ["/src/service/models.py"], "/src/resource/urls.py": ["/src/resource/views.py"]} |
78,610 | belal-bh/CLIC_PUST | refs/heads/master | /src/core/dev/views.py | from django.shortcuts import render
from django.contrib import messages
from django.contrib.contenttypes.models import ContentType
from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger
from django.db.models import Q
from django.http import HttpResponse, HttpResponseRedirect, Http404
from django.shortcuts import render, get_object_or_404, redirect
from django.utils import timezone
import datetime
from django.contrib.auth.decorators import login_required
from account.models import User
from resource.models import (
Book,
Resource,
)
from wishlist.models import (
BookCart,
ResourceCart,
)
from transaction.models import (
TrxBook,
TrxResource,
)
from .automate import *
from .forms import (
BookForm,
AuthorForm,
)
#D:\Challenges\pust\dev\CLIC_PUST\src\core\dev\data\cleaned\clean_books_6939.csv
CSV_DIRS = ['data', 'cleaned']
CSV_FILE = 'clean_books_6939.csv'
IMAGE_DIRS = ['data', 'cleaned','cleaned_image_all']
@login_required
def dev_view(request):
user_instance = request.user
if not request.user.is_superuser:
return redirect('/')
form = BookForm(request.POST or None, request.FILES or None)
if request.method == 'POST':
print(request.POST)
if 'automate' in request.POST.keys():
# FILE_NAME = 'core\\dev\\data\\abc.csv'
# print(os.getcwd())
# form = BookForm(request.POST or None, request.FILES or None)
# books = load_books(csv_dirs=CSV_DIRS,csv_file=FILE_NAME,size=10)
books = load_books(csv_dirs=CSV_DIRS,csv_file=CSV_FILE)
#['195153448', 'Classical Mythology', 'Mark P. O. Morford', 2002, 'Oxford University Press', 'http://images.amazon.com/images/P/0195153448.01.LZZZZZZZ.jpg', '0195153448.jpg']
# print('books=', books[0])
status = automate(books,user_instance,IMAGE_DIRS)
print(f'status = {status}')
# print(get_path(CSV_DIRS,CSV_FILE))
context = {
'title': "Dev Admin Section",
'instance': request.user,
'form': form,
}
return render(request, 'automate_admin.html', context) | {"/src/academic/admin.py": ["/src/academic/models.py"], "/src/account/urls.py": ["/src/account/views.py"], "/src/transaction/admin.py": ["/src/transaction/models.py"], "/src/resource/views.py": ["/src/resource/models.py", "/src/resource/forms.py"], "/src/member/admin.py": ["/src/member/models.py"], "/src/service/urls.py": ["/src/service/views.py"], "/src/wishlist/admin.py": ["/src/wishlist/models.py"], "/src/resource/admin.py": ["/src/resource/models.py"], "/src/core/dev/views.py": ["/src/core/dev/automate.py", "/src/core/dev/forms.py"], "/src/core/dev/urls.py": ["/src/core/dev/views.py"], "/src/resource/forms.py": ["/src/resource/models.py"], "/src/core/coreurls.py": ["/src/core/coreviews.py"], "/src/amtd/admin.py": ["/src/amtd/models.py"], "/src/account/views.py": ["/src/account/forms.py", "/src/account/models.py"], "/src/service/admin.py": ["/src/service/models.py"], "/src/resource/urls.py": ["/src/resource/views.py"]} |
78,611 | belal-bh/CLIC_PUST | refs/heads/master | /src/core/dev/urls.py | from django.urls import path
from .views import (
dev_view,
)
app_name = 'dev'
urlpatterns = [
path('secure/', dev_view, name='secure'),
]
| {"/src/academic/admin.py": ["/src/academic/models.py"], "/src/account/urls.py": ["/src/account/views.py"], "/src/transaction/admin.py": ["/src/transaction/models.py"], "/src/resource/views.py": ["/src/resource/models.py", "/src/resource/forms.py"], "/src/member/admin.py": ["/src/member/models.py"], "/src/service/urls.py": ["/src/service/views.py"], "/src/wishlist/admin.py": ["/src/wishlist/models.py"], "/src/resource/admin.py": ["/src/resource/models.py"], "/src/core/dev/views.py": ["/src/core/dev/automate.py", "/src/core/dev/forms.py"], "/src/core/dev/urls.py": ["/src/core/dev/views.py"], "/src/resource/forms.py": ["/src/resource/models.py"], "/src/core/coreurls.py": ["/src/core/coreviews.py"], "/src/amtd/admin.py": ["/src/amtd/models.py"], "/src/account/views.py": ["/src/account/forms.py", "/src/account/models.py"], "/src/service/admin.py": ["/src/service/models.py"], "/src/resource/urls.py": ["/src/resource/views.py"]} |
78,612 | belal-bh/CLIC_PUST | refs/heads/master | /src/messenger/models.py | # messenger.models.py
from django.db import models
from django.conf import settings
from account.helpers import UploadTo
class Message(models.Model):
content = models.TextField()
image = models.ImageField(
upload_to=UploadTo('image', plus_id=True),
null=True,
blank=True,
width_field="width_field",
height_field="height_field"
)
height_field = models.IntegerField(default=0)
width_field = models.IntegerField(default=0)
attachments = models.FileField(
upload_to=UploadTo('attachments', plus_id=True),
null=True,
blank=True
)
sender = models.ForeignKey(
settings.AUTH_USER_MODEL, on_delete=models.PROTECT,
related_name='messenger_user_sender')
receiver = models.ForeignKey(
settings.AUTH_USER_MODEL, on_delete=models.PROTECT,
related_name='messenger_user_receiver')
parent = models.ForeignKey(
"self", null=True, blank=True, on_delete=models.CASCADE)
timestamp = models.DateTimeField(auto_now=False, auto_now_add=True)
updated = models.DateTimeField(auto_now=True, auto_now_add=False)
| {"/src/academic/admin.py": ["/src/academic/models.py"], "/src/account/urls.py": ["/src/account/views.py"], "/src/transaction/admin.py": ["/src/transaction/models.py"], "/src/resource/views.py": ["/src/resource/models.py", "/src/resource/forms.py"], "/src/member/admin.py": ["/src/member/models.py"], "/src/service/urls.py": ["/src/service/views.py"], "/src/wishlist/admin.py": ["/src/wishlist/models.py"], "/src/resource/admin.py": ["/src/resource/models.py"], "/src/core/dev/views.py": ["/src/core/dev/automate.py", "/src/core/dev/forms.py"], "/src/core/dev/urls.py": ["/src/core/dev/views.py"], "/src/resource/forms.py": ["/src/resource/models.py"], "/src/core/coreurls.py": ["/src/core/coreviews.py"], "/src/amtd/admin.py": ["/src/amtd/models.py"], "/src/account/views.py": ["/src/account/forms.py", "/src/account/models.py"], "/src/service/admin.py": ["/src/service/models.py"], "/src/resource/urls.py": ["/src/resource/views.py"]} |
78,613 | belal-bh/CLIC_PUST | refs/heads/master | /src/service/views.py | from django.shortcuts import render
from django.contrib.auth.decorators import login_required
@login_required
def notice_list(request):
return render(request, "under_constraction.html", {})
| {"/src/academic/admin.py": ["/src/academic/models.py"], "/src/account/urls.py": ["/src/account/views.py"], "/src/transaction/admin.py": ["/src/transaction/models.py"], "/src/resource/views.py": ["/src/resource/models.py", "/src/resource/forms.py"], "/src/member/admin.py": ["/src/member/models.py"], "/src/service/urls.py": ["/src/service/views.py"], "/src/wishlist/admin.py": ["/src/wishlist/models.py"], "/src/resource/admin.py": ["/src/resource/models.py"], "/src/core/dev/views.py": ["/src/core/dev/automate.py", "/src/core/dev/forms.py"], "/src/core/dev/urls.py": ["/src/core/dev/views.py"], "/src/resource/forms.py": ["/src/resource/models.py"], "/src/core/coreurls.py": ["/src/core/coreviews.py"], "/src/amtd/admin.py": ["/src/amtd/models.py"], "/src/account/views.py": ["/src/account/forms.py", "/src/account/models.py"], "/src/service/admin.py": ["/src/service/models.py"], "/src/resource/urls.py": ["/src/resource/views.py"]} |
78,614 | belal-bh/CLIC_PUST | refs/heads/master | /src/post/forms.py | from django import forms
# from pagedown.widgets import PagedownWidget
from .models import Post
# datetimepicker
# from bootstrap_datepicker_plus import DateTimePickerInput, DatePickerInput
class PostForm(forms.ModelForm):
# content = forms.CharField(widget=PagedownWidget(show_preview=False))
# publish = forms.DateField(widget=DatePickerInput())
class Meta:
model = Post
fields = '__all__'
| {"/src/academic/admin.py": ["/src/academic/models.py"], "/src/account/urls.py": ["/src/account/views.py"], "/src/transaction/admin.py": ["/src/transaction/models.py"], "/src/resource/views.py": ["/src/resource/models.py", "/src/resource/forms.py"], "/src/member/admin.py": ["/src/member/models.py"], "/src/service/urls.py": ["/src/service/views.py"], "/src/wishlist/admin.py": ["/src/wishlist/models.py"], "/src/resource/admin.py": ["/src/resource/models.py"], "/src/core/dev/views.py": ["/src/core/dev/automate.py", "/src/core/dev/forms.py"], "/src/core/dev/urls.py": ["/src/core/dev/views.py"], "/src/resource/forms.py": ["/src/resource/models.py"], "/src/core/coreurls.py": ["/src/core/coreviews.py"], "/src/amtd/admin.py": ["/src/amtd/models.py"], "/src/account/views.py": ["/src/account/forms.py", "/src/account/models.py"], "/src/service/admin.py": ["/src/service/models.py"], "/src/resource/urls.py": ["/src/resource/views.py"]} |
78,615 | belal-bh/CLIC_PUST | refs/heads/master | /src/academic/migrations/0002_auto_20200307_0027.py | # Generated by Django 2.2.1 on 2020-03-06 18:27
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('academic', '0001_initial'),
]
operations = [
migrations.AlterModelOptions(
name='department',
options={'ordering': ['dept_id', 'name']},
),
migrations.AlterModelOptions(
name='faculty',
options={'ordering': ['faculty_id', 'name']},
),
migrations.AlterModelOptions(
name='program',
options={'ordering': ['program_id', 'name']},
),
]
| {"/src/academic/admin.py": ["/src/academic/models.py"], "/src/account/urls.py": ["/src/account/views.py"], "/src/transaction/admin.py": ["/src/transaction/models.py"], "/src/resource/views.py": ["/src/resource/models.py", "/src/resource/forms.py"], "/src/member/admin.py": ["/src/member/models.py"], "/src/service/urls.py": ["/src/service/views.py"], "/src/wishlist/admin.py": ["/src/wishlist/models.py"], "/src/resource/admin.py": ["/src/resource/models.py"], "/src/core/dev/views.py": ["/src/core/dev/automate.py", "/src/core/dev/forms.py"], "/src/core/dev/urls.py": ["/src/core/dev/views.py"], "/src/resource/forms.py": ["/src/resource/models.py"], "/src/core/coreurls.py": ["/src/core/coreviews.py"], "/src/amtd/admin.py": ["/src/amtd/models.py"], "/src/account/views.py": ["/src/account/forms.py", "/src/account/models.py"], "/src/service/admin.py": ["/src/service/models.py"], "/src/resource/urls.py": ["/src/resource/views.py"]} |
78,616 | belal-bh/CLIC_PUST | refs/heads/master | /src/resource/forms.py | from django import forms
from .models import Book
from wishlist.models import (
BookCart,
ResourceCart
)
class BookCartForm(forms.ModelForm):
class Meta:
model = BookCart
fields = []
class ResourceCartForm(forms.ModelForm):
class Meta:
model = ResourceCart
fields = [] | {"/src/academic/admin.py": ["/src/academic/models.py"], "/src/account/urls.py": ["/src/account/views.py"], "/src/transaction/admin.py": ["/src/transaction/models.py"], "/src/resource/views.py": ["/src/resource/models.py", "/src/resource/forms.py"], "/src/member/admin.py": ["/src/member/models.py"], "/src/service/urls.py": ["/src/service/views.py"], "/src/wishlist/admin.py": ["/src/wishlist/models.py"], "/src/resource/admin.py": ["/src/resource/models.py"], "/src/core/dev/views.py": ["/src/core/dev/automate.py", "/src/core/dev/forms.py"], "/src/core/dev/urls.py": ["/src/core/dev/views.py"], "/src/resource/forms.py": ["/src/resource/models.py"], "/src/core/coreurls.py": ["/src/core/coreviews.py"], "/src/amtd/admin.py": ["/src/amtd/models.py"], "/src/account/views.py": ["/src/account/forms.py", "/src/account/models.py"], "/src/service/admin.py": ["/src/service/models.py"], "/src/resource/urls.py": ["/src/resource/views.py"]} |
78,617 | belal-bh/CLIC_PUST | refs/heads/master | /src/core/coreurls.py | from django.urls import path
from .coreviews import (
about_pust,
about_clic,
about_faculty,
about_department,
about_institute,
about_administration,
about_dormitory,
about_contact,
about_underconstruction,
)
app_name = 'about'
urlpatterns = [
path('pust/', about_pust, name='pust'),
path('clic/', about_clic, name='clic'),
path('faculty/', about_faculty, name='faculty'),
path('department/', about_department, name='department'),
path('institute/', about_institute, name='institute'),
path('administration/', about_administration, name='administration'),
path('dormitory/', about_dormitory, name='dormitory'),
path('contact/', about_contact, name='contact'),
path('underconstruction/', about_contact, name='underconstruction'),
]
| {"/src/academic/admin.py": ["/src/academic/models.py"], "/src/account/urls.py": ["/src/account/views.py"], "/src/transaction/admin.py": ["/src/transaction/models.py"], "/src/resource/views.py": ["/src/resource/models.py", "/src/resource/forms.py"], "/src/member/admin.py": ["/src/member/models.py"], "/src/service/urls.py": ["/src/service/views.py"], "/src/wishlist/admin.py": ["/src/wishlist/models.py"], "/src/resource/admin.py": ["/src/resource/models.py"], "/src/core/dev/views.py": ["/src/core/dev/automate.py", "/src/core/dev/forms.py"], "/src/core/dev/urls.py": ["/src/core/dev/views.py"], "/src/resource/forms.py": ["/src/resource/models.py"], "/src/core/coreurls.py": ["/src/core/coreviews.py"], "/src/amtd/admin.py": ["/src/amtd/models.py"], "/src/account/views.py": ["/src/account/forms.py", "/src/account/models.py"], "/src/service/admin.py": ["/src/service/models.py"], "/src/resource/urls.py": ["/src/resource/views.py"]} |
78,618 | belal-bh/CLIC_PUST | refs/heads/master | /src/amtd/models.py | from django.db import models
from django.conf import settings
class Activity(models.Model):
user = models.ForeignKey(settings.AUTH_USER_MODEL,
on_delete=models.PROTECT)
messege = models.TextField()
link = models.CharField(max_length=255, null=True, blank=True)
timestamp = models.DateTimeField(auto_now=False, auto_now_add=True)
| {"/src/academic/admin.py": ["/src/academic/models.py"], "/src/account/urls.py": ["/src/account/views.py"], "/src/transaction/admin.py": ["/src/transaction/models.py"], "/src/resource/views.py": ["/src/resource/models.py", "/src/resource/forms.py"], "/src/member/admin.py": ["/src/member/models.py"], "/src/service/urls.py": ["/src/service/views.py"], "/src/wishlist/admin.py": ["/src/wishlist/models.py"], "/src/resource/admin.py": ["/src/resource/models.py"], "/src/core/dev/views.py": ["/src/core/dev/automate.py", "/src/core/dev/forms.py"], "/src/core/dev/urls.py": ["/src/core/dev/views.py"], "/src/resource/forms.py": ["/src/resource/models.py"], "/src/core/coreurls.py": ["/src/core/coreviews.py"], "/src/amtd/admin.py": ["/src/amtd/models.py"], "/src/account/views.py": ["/src/account/forms.py", "/src/account/models.py"], "/src/service/admin.py": ["/src/service/models.py"], "/src/resource/urls.py": ["/src/resource/views.py"]} |
78,619 | belal-bh/CLIC_PUST | refs/heads/master | /src/resource/migrations/0004_auto_20200309_1055.py | # Generated by Django 2.2.1 on 2020-03-09 04:55
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('resource', '0003_auto_20200309_1054'),
]
operations = [
migrations.AlterField(
model_name='book',
name='status',
field=models.CharField(blank=True, default='available', max_length=15, null=True),
),
]
| {"/src/academic/admin.py": ["/src/academic/models.py"], "/src/account/urls.py": ["/src/account/views.py"], "/src/transaction/admin.py": ["/src/transaction/models.py"], "/src/resource/views.py": ["/src/resource/models.py", "/src/resource/forms.py"], "/src/member/admin.py": ["/src/member/models.py"], "/src/service/urls.py": ["/src/service/views.py"], "/src/wishlist/admin.py": ["/src/wishlist/models.py"], "/src/resource/admin.py": ["/src/resource/models.py"], "/src/core/dev/views.py": ["/src/core/dev/automate.py", "/src/core/dev/forms.py"], "/src/core/dev/urls.py": ["/src/core/dev/views.py"], "/src/resource/forms.py": ["/src/resource/models.py"], "/src/core/coreurls.py": ["/src/core/coreviews.py"], "/src/amtd/admin.py": ["/src/amtd/models.py"], "/src/account/views.py": ["/src/account/forms.py", "/src/account/models.py"], "/src/service/admin.py": ["/src/service/models.py"], "/src/resource/urls.py": ["/src/resource/views.py"]} |
78,620 | belal-bh/CLIC_PUST | refs/heads/master | /src/member/migrations/0001_initial.py | # Generated by Django 2.2.1 on 2019-10-02 20:42
from django.conf import settings
import django.core.validators
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
('academic', '0001_initial'),
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
]
operations = [
migrations.CreateModel(
name='Teacher',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('teacher_id', models.CharField(max_length=20, unique=True)),
('designation', models.CharField(max_length=40)),
('timestamp', models.DateTimeField(auto_now_add=True)),
('updated', models.DateTimeField(auto_now=True)),
('department', models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.SET_NULL, to='academic.Department')),
('faculty', models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.SET_NULL, to='academic.Faculty')),
('user', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL)),
],
),
migrations.CreateModel(
name='Student',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('student_id', models.CharField(max_length=20, unique=True)),
('student_roll', models.CharField(max_length=20, unique=True)),
('local_guardian_name', models.CharField(blank=True, max_length=40, null=True)),
('guardian_contact_mobile', models.CharField(max_length=32, validators=[django.core.validators.RegexValidator(code='invalid_contact_mobile', message='Mobile number must be numeric', regex='^(?:\\+?88|0088)?01[15-9]\\d{8}$')])),
('guardian_contact_phone', models.CharField(blank=True, max_length=32, null=True, validators=[django.core.validators.RegexValidator(code='invalid_contact_phone', message='Phone number must be numeric', regex='^(?:\\+?88|0088)?0\\d{10}$')])),
('session', models.CharField(max_length=15)),
('year', models.CharField(max_length=15)),
('semester', models.CharField(max_length=15)),
('timestamp', models.DateTimeField(auto_now_add=True)),
('updated', models.DateTimeField(auto_now=True)),
('department', models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.SET_NULL, to='academic.Department')),
('faculty', models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.SET_NULL, to='academic.Faculty')),
('program', models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.SET_NULL, to='academic.Program')),
('user', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL)),
],
),
migrations.CreateModel(
name='Staff',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('staff_id', models.CharField(max_length=20, unique=True)),
('designation', models.CharField(max_length=40)),
('department', models.CharField(max_length=120)),
('timestamp', models.DateTimeField(auto_now_add=True)),
('updated', models.DateTimeField(auto_now=True)),
('user', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='staff_user', to=settings.AUTH_USER_MODEL)),
],
),
migrations.CreateModel(
name='Othermember',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('member_id', models.CharField(max_length=20, unique=True)),
('designation', models.CharField(max_length=40)),
('department', models.CharField(max_length=120)),
('timestamp', models.DateTimeField(auto_now_add=True)),
('updated', models.DateTimeField(auto_now=True)),
('user', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL)),
],
),
migrations.CreateModel(
name='Officer',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('officer_id', models.CharField(max_length=20, unique=True)),
('designation', models.CharField(max_length=40)),
('department', models.CharField(max_length=120)),
('timestamp', models.DateTimeField(auto_now_add=True)),
('updated', models.DateTimeField(auto_now=True)),
('user', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL)),
],
),
migrations.CreateModel(
name='Librarian',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('designation', models.CharField(max_length=40)),
('member_type', models.CharField(choices=[('staff', 'Staff'), ('admin', 'Admin')], default='staff', max_length=10)),
('active', models.BooleanField(default=True)),
('validity', models.DateTimeField(auto_now_add=True)),
('timestamp', models.DateTimeField(auto_now_add=True)),
('updated', models.DateTimeField(auto_now=True)),
('user', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL)),
],
),
]
| {"/src/academic/admin.py": ["/src/academic/models.py"], "/src/account/urls.py": ["/src/account/views.py"], "/src/transaction/admin.py": ["/src/transaction/models.py"], "/src/resource/views.py": ["/src/resource/models.py", "/src/resource/forms.py"], "/src/member/admin.py": ["/src/member/models.py"], "/src/service/urls.py": ["/src/service/views.py"], "/src/wishlist/admin.py": ["/src/wishlist/models.py"], "/src/resource/admin.py": ["/src/resource/models.py"], "/src/core/dev/views.py": ["/src/core/dev/automate.py", "/src/core/dev/forms.py"], "/src/core/dev/urls.py": ["/src/core/dev/views.py"], "/src/resource/forms.py": ["/src/resource/models.py"], "/src/core/coreurls.py": ["/src/core/coreviews.py"], "/src/amtd/admin.py": ["/src/amtd/models.py"], "/src/account/views.py": ["/src/account/forms.py", "/src/account/models.py"], "/src/service/admin.py": ["/src/service/models.py"], "/src/resource/urls.py": ["/src/resource/views.py"]} |
78,621 | belal-bh/CLIC_PUST | refs/heads/master | /src/amtd/admin.py | from django.contrib import admin
from .models import (
Activity,
)
admin.site.register(Activity)
| {"/src/academic/admin.py": ["/src/academic/models.py"], "/src/account/urls.py": ["/src/account/views.py"], "/src/transaction/admin.py": ["/src/transaction/models.py"], "/src/resource/views.py": ["/src/resource/models.py", "/src/resource/forms.py"], "/src/member/admin.py": ["/src/member/models.py"], "/src/service/urls.py": ["/src/service/views.py"], "/src/wishlist/admin.py": ["/src/wishlist/models.py"], "/src/resource/admin.py": ["/src/resource/models.py"], "/src/core/dev/views.py": ["/src/core/dev/automate.py", "/src/core/dev/forms.py"], "/src/core/dev/urls.py": ["/src/core/dev/views.py"], "/src/resource/forms.py": ["/src/resource/models.py"], "/src/core/coreurls.py": ["/src/core/coreviews.py"], "/src/amtd/admin.py": ["/src/amtd/models.py"], "/src/account/views.py": ["/src/account/forms.py", "/src/account/models.py"], "/src/service/admin.py": ["/src/service/models.py"], "/src/resource/urls.py": ["/src/resource/views.py"]} |
78,622 | belal-bh/CLIC_PUST | refs/heads/master | /src/account/views.py | from django.contrib.auth import (
# authenticate,
# get_user_model,
login,
logout,
)
from django.contrib import messages
from django.shortcuts import render, redirect
from django.http import HttpResponse, HttpResponseRedirect, Http404
from django.contrib.auth.decorators import login_required
from .forms import LoginForm, RegisterForm, UserUpdateForm
from .models import User
def login_view(request, *args, **kwargs):
if not request.user.is_authenticated:
next = request.GET.get('next')
title = "Login"
form = LoginForm(request.POST or None)
if form.is_valid():
user_obj = form.cleaned_data.get("user_obj")
login(request, user_obj)
print('user_obj:', user_obj)
if next:
return redirect(next)
return redirect("/account/user")
return render(request, "login_form.html", {"form": form, "title": title})
else:
return redirect("/account/user")
def register_view(request, *args, **kwargs):
if not request.user.is_authenticated:
next = request.GET.get('next')
title = "Register"
# form = RegisterForm(request.POST or None)
# if form.is_valid():
# instance = form.save(commit=False)
# instance.save()
# if next:
# return redirect(next)
# return redirect("/login")
procedure = '''To create an account of CLIC please contact at Central Library & Information Center of Pabna University of Science & Technology.'''
context = {
# "form": form,
"title": title,
"procedure": procedure,
}
return render(request, "registration.html", context)
else:
return redirect("/")
@login_required
def logout_view(request):
logout(request)
return redirect("/login")
@login_required
def profile_view(request):
'''
[user profile]
[user detal information]
'''
if request.user.is_authenticated:
user_obj = request.user
context = {
'instance': user_obj,
'title': "Profile"
}
return render(request, "profile_view.html", context)
else:
return redirect("/login")
@login_required
def index_page(request):
context = {
'title': 'CLIC, PUST'
}
return render(request, "home.html", context)
| {"/src/academic/admin.py": ["/src/academic/models.py"], "/src/account/urls.py": ["/src/account/views.py"], "/src/transaction/admin.py": ["/src/transaction/models.py"], "/src/resource/views.py": ["/src/resource/models.py", "/src/resource/forms.py"], "/src/member/admin.py": ["/src/member/models.py"], "/src/service/urls.py": ["/src/service/views.py"], "/src/wishlist/admin.py": ["/src/wishlist/models.py"], "/src/resource/admin.py": ["/src/resource/models.py"], "/src/core/dev/views.py": ["/src/core/dev/automate.py", "/src/core/dev/forms.py"], "/src/core/dev/urls.py": ["/src/core/dev/views.py"], "/src/resource/forms.py": ["/src/resource/models.py"], "/src/core/coreurls.py": ["/src/core/coreviews.py"], "/src/amtd/admin.py": ["/src/amtd/models.py"], "/src/account/views.py": ["/src/account/forms.py", "/src/account/models.py"], "/src/service/admin.py": ["/src/service/models.py"], "/src/resource/urls.py": ["/src/resource/views.py"]} |
78,623 | belal-bh/CLIC_PUST | refs/heads/master | /src/core/dev/download_img.py | import pandas as pd
import numpy as np
import csv
from urllib.request import urlretrieve
from urllib.parse import urlsplit
import os
from PIL import Image
import time
start_time = time.time()
def load_data(filename,sep=',', limit=None):
SIZE = 10
# book_df = pd.read_csv(filename, sep=';',engine='python', quotechar='"', error_bad_lines=False).iloc[1:SIZE, 1:]
book_df = pd.read_csv(filename, sep=sep,engine='python', quotechar='"', error_bad_lines=False).iloc[1:SIZE, 1:]
book_list = book_df.values.tolist()
books = [] #{'isbn': , 'authors': [], 'year_of_pub': , 'publisher': , 'img_urls': [] }
'''
for i in range(len(book_list)):
isbn = book_list[i][0]
title = book_list[i][1]
authors = book_list[i][2:-5]
year_of_pub = book_list[i][-5]
publisher = book_list[i][-4]
img_urls = book_list[i][-3:]
books.append({'isbn': isbn , 'title':title, 'authors': authors, 'year_of_pub':year_of_pub ,'publisher': publisher , 'img_urls': img_urls })
print('books:', book)
'''
return book_list
def load_csv(size=10, all=False):
SIZE = size
CSV_FILE_PATH = 'data\\BX-Books.csv'
with open(CSV_FILE_PATH) as csvfile:
dialect = csv.Sniffer().sniff(csvfile.read(14734))
if all:
bookdf = pd.read_csv(CSV_FILE_PATH, engine='python', dialect=dialect, error_bad_lines=False) #.iloc[:, :]
else:
bookdf = pd.read_csv(CSV_FILE_PATH, engine='python', dialect=dialect, error_bad_lines=False).iloc[:SIZE, :]
book_list = bookdf.values.tolist()
books = []
multiple_author = 0
for i in range(len(book_list)):
isbn = book_list[i][0]
title = book_list[i][1]
author = book_list[i][2]
year_of_pub = book_list[i][3]
publisher = book_list[i][4]
img_urls = book_list[i][-3:]
url = book_list[i][-1]
# if len(authors)>1:
# multiple_author += 1
# print(f'len= {len(authors)} and authors= {authors}')
if type(year_of_pub) != int:
print(year_of_pub)
books.append({'isbn': isbn , 'title':title, 'author': author, 'year_of_pub':year_of_pub ,'publisher': publisher , 'img_urls': img_urls, 'url': url })
# print(f'Found multiple_author = {multiple_author}')
return books
def check_img(filename,min_w=10, min_h=10, remove=False):
# try:
# img = Image.open(path)
# except IOError:
# pass
ok = False
with Image.open(filename) as image:
width, height = image.size
if width >= min_w or height >= min_h:
ok = True
# print('width:',width, 'height:',height, 'Status:',ok)
if not ok:
if remove and os.path.isfile(filename):
## If file exists, delete it ##
os.remove(filename)
return ok
def img_download(url, filename, filedir=None):
status = False
if filedir:
if os.path.isdir(filedir):
pass
else:
os.mkdir(filedir)
filename = os.path.join(filedir, filename)
# dirpath = ''
# for dir in filedir:
# dirpath = os.path.join(dirpath, dir)
# if os.path.exists(dirpath):
# filename = os.path.join(dirpath, filename)
# else:
# os.mkdir(dirpath)
# filename = os.path.join(dirpath, filename)
try:
img, header = urlretrieve(url, filename) # returns (filename, headers)
status = check_img(img, remove=True)
# print('filename=', filename)
# print('url=',url)
# print('img=',img)
# print('header=',header)
except:
print("ERROR in download img! url=",url)
return status
def img_offline_check(filename, filedir=None):
status = False
if filedir:
if os.path.isdir(filedir):
filename = os.path.join(filedir, filename)
if os.path.exists(filename):
status = True
return status
def to_url_list(url_str):
url_str_list = url_str.lstrip('[] ').split(',')
urls = [urlsplit(url) for url in url_str_list]
print(urls)
print([url.geturl for url in urls])
# from urllib.parse import urlsplit
# url = 'HTTP://www.Python.org/doc/#'
# r1 = urlsplit(url)
# r1.geturl()
# 'http://www.Python.org/doc/'
# r2 = urlsplit(r1.geturl())
# r2.geturl()
# 'http://www.Python.org/doc/'
return urls
def get_cleaned_data(books, filedir, download=False):
clean_books = []
succeed = 0
failed = 0
for i, book in zip(range(len(books)), books):
# {'isbn': isbn , 'title':title, 'author': author, 'year_of_pub':year_of_pub ,'publisher': publisher , 'img_urls': img_urls, 'url': url }
filename = book['isbn'] + '.jpg'
url = book['url']
if download:
result = img_download(url, filename, filedir)
else:
result = img_offline_check(filename, filedir)
# result = True
if result:
succeed += 1
isbn = book['isbn']
title = book['title']
author = book['author']
year_of_pub = book['year_of_pub']
publisher = book['publisher']
url = book['url']
image = filename
clean_books.append({'isbn': isbn, 'title': title, 'author': author, 'year_of_pub':year_of_pub ,'publisher': publisher , 'url': url, 'image': image})
else:
failed += 1
# print('Result:', result)
print(f'Total={succeed+failed}, succeed={succeed}, failed={failed}')
return clean_books
books = load_csv(size=10, all=True)
clean_books = get_cleaned_data(books, filedir='test')
print('book=', books[0])
print('clean Book=', clean_books[0])
if False:
FILE_NAME = 'data\\cleaned\\clean_books.csv'
clean_df = pd.DataFrame(clean_books, columns=['isbn','title','author','year_of_pub','publisher','url', 'image'])
clean_df.to_csv(FILE_NAME, index=False) #, index_label="ID", sep=','
print(f'book_len={len(books)} and cleaned_book_len={len(clean_books)}')
print('Time needed=', (time.time() - start_time)/60) | {"/src/academic/admin.py": ["/src/academic/models.py"], "/src/account/urls.py": ["/src/account/views.py"], "/src/transaction/admin.py": ["/src/transaction/models.py"], "/src/resource/views.py": ["/src/resource/models.py", "/src/resource/forms.py"], "/src/member/admin.py": ["/src/member/models.py"], "/src/service/urls.py": ["/src/service/views.py"], "/src/wishlist/admin.py": ["/src/wishlist/models.py"], "/src/resource/admin.py": ["/src/resource/models.py"], "/src/core/dev/views.py": ["/src/core/dev/automate.py", "/src/core/dev/forms.py"], "/src/core/dev/urls.py": ["/src/core/dev/views.py"], "/src/resource/forms.py": ["/src/resource/models.py"], "/src/core/coreurls.py": ["/src/core/coreviews.py"], "/src/amtd/admin.py": ["/src/amtd/models.py"], "/src/account/views.py": ["/src/account/forms.py", "/src/account/models.py"], "/src/service/admin.py": ["/src/service/models.py"], "/src/resource/urls.py": ["/src/resource/views.py"]} |
78,624 | belal-bh/CLIC_PUST | refs/heads/master | /src/account/helpers.py | # account.helpers.py
import time
import datetime
from django.contrib.contenttypes.models import ContentType
from dateutil.relativedelta import relativedelta
class UploadTo:
''' UploadTo
UploadTo('folder_name', [plus_id=True]): To automate upload_to callable function for file uploading path
'''
def __init__(self, folder_name, plus_id=False, plus_date=False):
self.folder_name = folder_name
self.plus_id = plus_id
self.plus_date = plus_date
def __call__(self, instance, filename):
''' CALL UploadTo
[instance]: instance is an instance of a dango_model of an django_app
[filename]: filename is the file name of a file comming from Field of django_model
'''
path = self.upload_location(instance, filename)
# return 'documents/{}/{}.pdf'.format(instance.user.rfc, self.name)
return path
def upload_location(self, instance, filename):
'''UPLOAD LOCATION
It's generate path according to the given instance.
PATH: <app_label>/<model>/<new_generated_filename>.<file_extension>
Challenge: How can I get the field_name for which this function. In this case 'image' field name given by user. Then automate the upload_location function. [May be this is the solution]
Solution: UploadTo('field_name')
'''
splitlist = filename.split(".")
filebase, extension = splitlist[0], splitlist[-1]
new_filename = f"{ int(time.time() * 1000) }_{filebase}.{extension}"
content_type = ContentType.objects.get_for_model(instance.__class__)
app_label = content_type.app_label
model_name = content_type.model
folder_name = self.folder_name
if self.plus_id:
folder_name = f'{folder_name}/{instance.id}'
if self.plus_date:
# "%Y/%m/%d/%H_%M_%S/"
folder_name = f'{folder_name}/{datetime.date.today().strftime("%Y/%m/%d")}'
return "%s/%s/%s/%s" % (app_label, model_name, folder_name, new_filename)
# need to find out what is the purpose of
# ValueError: Cannot serialize: <accounts.helpers.UploadTo object at 0x0000022264685C88>
# There are some values Django cannot serialize into migration files.
# For more, see https://docs.djangoproject.com/en/2.0/topics/migrations/#migration-serializing
def deconstruct(self):
return ('account.helpers.UploadTo', [self.folder_name], {})
class DefaultPeriod:
def __init__(self, years=0, months=0, weeks=0, days=0, hour=10):
self.years = years
self.months = months
self.weeks = weeks
self.days = days
self.hour = hour
def __call__(self):
'''
CALL DefaultPeriod
'''
period = self.set_period()
return period
def set_period(self):
NOW = datetime.datetime.now()
period = NOW + relativedelta(
years=+self.years,
months=+self.months,
weeks=+self.weeks,
days=+self.days,
hour=10
)
return period
def deconstruct(self):
return ('account.helpers.DefaultPeriod', [], {})
| {"/src/academic/admin.py": ["/src/academic/models.py"], "/src/account/urls.py": ["/src/account/views.py"], "/src/transaction/admin.py": ["/src/transaction/models.py"], "/src/resource/views.py": ["/src/resource/models.py", "/src/resource/forms.py"], "/src/member/admin.py": ["/src/member/models.py"], "/src/service/urls.py": ["/src/service/views.py"], "/src/wishlist/admin.py": ["/src/wishlist/models.py"], "/src/resource/admin.py": ["/src/resource/models.py"], "/src/core/dev/views.py": ["/src/core/dev/automate.py", "/src/core/dev/forms.py"], "/src/core/dev/urls.py": ["/src/core/dev/views.py"], "/src/resource/forms.py": ["/src/resource/models.py"], "/src/core/coreurls.py": ["/src/core/coreviews.py"], "/src/amtd/admin.py": ["/src/amtd/models.py"], "/src/account/views.py": ["/src/account/forms.py", "/src/account/models.py"], "/src/service/admin.py": ["/src/service/models.py"], "/src/resource/urls.py": ["/src/resource/views.py"]} |
78,625 | belal-bh/CLIC_PUST | refs/heads/master | /src/post/urls.py | from django.urls import path
from .views import (
post_list,
post_create,
post_detail,
# post_update,
# post_delete,
)
app_name = 'blog'
urlpatterns = [
path('post/', post_list, name='postlist'),
path('post/create/', post_create),
path('post/<int:id>/', post_detail, name='postdetail'),
# path('post/<id:int>/edit/', post_update, name='postupdate'),
# path('post/<id:int>/delete/', post_delete),
]
| {"/src/academic/admin.py": ["/src/academic/models.py"], "/src/account/urls.py": ["/src/account/views.py"], "/src/transaction/admin.py": ["/src/transaction/models.py"], "/src/resource/views.py": ["/src/resource/models.py", "/src/resource/forms.py"], "/src/member/admin.py": ["/src/member/models.py"], "/src/service/urls.py": ["/src/service/views.py"], "/src/wishlist/admin.py": ["/src/wishlist/models.py"], "/src/resource/admin.py": ["/src/resource/models.py"], "/src/core/dev/views.py": ["/src/core/dev/automate.py", "/src/core/dev/forms.py"], "/src/core/dev/urls.py": ["/src/core/dev/views.py"], "/src/resource/forms.py": ["/src/resource/models.py"], "/src/core/coreurls.py": ["/src/core/coreviews.py"], "/src/amtd/admin.py": ["/src/amtd/models.py"], "/src/account/views.py": ["/src/account/forms.py", "/src/account/models.py"], "/src/service/admin.py": ["/src/service/models.py"], "/src/resource/urls.py": ["/src/resource/views.py"]} |
78,626 | belal-bh/CLIC_PUST | refs/heads/master | /src/core/dev/automate.py | import os
import pandas as pd
import numpy as np
import csv
# from django.shortcuts import render
# from django.contrib import messages
# from django.contrib.contenttypes.models import ContentType
# from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger
# from django.db.models import Q
# from django.http import HttpResponse, HttpResponseRedirect, Http404
# from django.shortcuts import render, get_object_or_404, redirect
# from django.utils import timezone
# import datetime
# from django.contrib.auth.decorators import login_required
from resource.models import (
Book,
Resource,
Author
)
# from .forms import (
# BookForm,
# AuthorForm,
# )
def create_author(name):
# form = AuthorForm(None, None)
nicname = name.split(' ')[0]
if len(name)> 99:
print(f'WOW!!! Author name({len(name)}:{name})')
name = name[:99]
if len(nicname) > 30:
print(f'WOW!!! Author nicname({len(nicname)}:{nicname}) [ Author= {name}]')
nicname = nicname[:30]
obj, created = Author.objects.get_or_create(name=name, nicname=nicname)
if created:
print(f'author created={obj.name}')
return obj, created
elif obj:
print(f'author got={obj.name}')
return obj, created
else:
print('ERROR in author creation!')
print('name=',name,' and nicname=',nicname)
return None, False
def create_book(user, isbn, title, author, publisher, image):
# title =
# author =
accession_number = isbn
call_number = isbn
copy_number = isbn
# isbn =
# publisher =
language = 'English'
image_path = image
# user =
work_done = 10
obj, created = Book.objects.get_or_create(title=title, accession_number=accession_number,call_number=call_number,copy_number=copy_number,isbn=isbn, publisher=publisher,language=language,added_by=user,work_done=work_done)
# obj, created = Book.objects.get_or_create(title=title, author=author, accession_number=accession_number,call_number=call_number,copy_number=copy_number,isbn=isbn, publisher=publisher,language=language,added_by=user,work_done=work_done)
# obj, created = Book.objects.get_or_create(title=title, author=author, accession_number=accession_number,call_number=call_number,copy_number=copy_number,isbn=isbn, publisher=publisher,language=language,image=image_path,added_by=user,work_done=work_done)
if created:
obj.image = image_path
obj.author.add(author)
obj.save()
print(f'Book Created = {obj.title} image={obj.image.url}')
return obj, created
elif obj:
obj.image = image_path
if author not in obj.author.all():
obj.author.add(author)
obj.save()
print(f'Book got = {obj.title} and image={obj.image.url}')
return obj, created
else:
print(f'ERROR book creation! isbn={isbn}')
return None, False
def get_path(dirs=[], filename=None, abs_path=False):
if abs_path:
path = os.path.abspath('')
else:
path = ''
path_exist = False
for filedir in dirs:
path = os.path.join(path, filedir)
if filename:
path = os.path.join(path, filename)
print('path=',path)
if os.path.exists(path):
path_exist = True
return path_exist, path
def load_books(csv_dirs, csv_file, size=None, all=False):
if size:
SIZE = size
else:
all = True
status, CSV_FILE_PATH = get_path(dirs=csv_dirs, filename=csv_file)
if status:
print('CSV_FILE_PATH=',CSV_FILE_PATH)
else:
return []
if all:
bookdf = pd.read_csv(CSV_FILE_PATH, engine='python', error_bad_lines=False) #.iloc[:, :] #, dialect=dialect
else:
bookdf = pd.read_csv(CSV_FILE_PATH, engine='python', error_bad_lines=False).iloc[:SIZE, :] #dialect=dialect,
books = bookdf.values.tolist()
return books
def automate(books, user, image_dirs):
new_author_created = 0
new_book_created = 0
succeed = 0
failed = 0
total_book = len(books)
for book in books:
# {'isbn': 0, 'title': 1, 'author': 2, 'year_of_pub':3 ,'publisher': 4 , 'url': 5, 'image': 6}
author_name = book[2]
author_obj, author_created = create_author(author_name)
# print(f'user={user}, image_dir={get_path(dirs=image_dirs,filename=book[-1])}')
if author_created:
new_author_created += 1
if author_obj:
book_isbn = book[0]
book_title = book[1]
book_author = author_obj
book_publisher = book[4]
# ########################
# Note: manualy have to copy all required file before book creation in media_cdn/automated/ directory
# book_image = book[6]
img_exsists, img_path = get_path(dirs=['automated'],filename=book[-1])
# img_exsists, img_path = get_path(dirs=image_dirs,filename=book[-1])
if img_exsists:
book_image = img_path
else:
book_image = img_path
# ########################
book_obj, book_created = create_book(user=user, isbn=book_isbn, title=book_title, author=book_author, publisher=book_publisher, image=book_image)
if book_created:
new_book_created += 1
print(f'Book created= {book_obj.title}, Author= {book_obj.author} , Image_url={book_obj.image.url}')
elif book_obj:
succeed += 1
print(f'Book got= {book_obj.title}, Author= {book_obj.author}, Image_url={book_obj.image.url}')
else:
failed += 1
print(f'FAILED!! isbn={book_isbn}')
status = {
'new_author_created': new_author_created,
'new_book_created': new_book_created,
'succeed': succeed,
'failed': failed,
'total_book': total_book,
}
return status
| {"/src/academic/admin.py": ["/src/academic/models.py"], "/src/account/urls.py": ["/src/account/views.py"], "/src/transaction/admin.py": ["/src/transaction/models.py"], "/src/resource/views.py": ["/src/resource/models.py", "/src/resource/forms.py"], "/src/member/admin.py": ["/src/member/models.py"], "/src/service/urls.py": ["/src/service/views.py"], "/src/wishlist/admin.py": ["/src/wishlist/models.py"], "/src/resource/admin.py": ["/src/resource/models.py"], "/src/core/dev/views.py": ["/src/core/dev/automate.py", "/src/core/dev/forms.py"], "/src/core/dev/urls.py": ["/src/core/dev/views.py"], "/src/resource/forms.py": ["/src/resource/models.py"], "/src/core/coreurls.py": ["/src/core/coreviews.py"], "/src/amtd/admin.py": ["/src/amtd/models.py"], "/src/account/views.py": ["/src/account/forms.py", "/src/account/models.py"], "/src/service/admin.py": ["/src/service/models.py"], "/src/resource/urls.py": ["/src/resource/views.py"]} |
78,627 | belal-bh/CLIC_PUST | refs/heads/master | /src/service/migrations/0001_initial.py | # Generated by Django 2.2.1 on 2019-10-09 18:08
import account.helpers
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
import uuid
class Migration(migrations.Migration):
initial = True
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
]
operations = [
migrations.CreateModel(
name='Request',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('title', models.CharField(max_length=255)),
('content', models.TextField()),
('image', models.ImageField(blank=True, height_field='height_field', null=True, upload_to=account.helpers.UploadTo('image'), width_field='width_field')),
('height_field', models.IntegerField(default=0, null=True)),
('width_field', models.IntegerField(default=0, null=True)),
('attachments', models.FileField(blank=True, null=True, upload_to=account.helpers.UploadTo('attachments'))),
('draft', models.BooleanField(default=False)),
('published', models.DateTimeField()),
('status', models.CharField(choices=[('accepted', 'Accepted'), ('rejected', 'Rejected'), ('pending', 'Pending'), ('open', 'Open'), ('closed', 'Closed')], default='open', max_length=10)),
('timestamp', models.DateTimeField(auto_now_add=True)),
('updated', models.DateTimeField(auto_now=True)),
('user', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL)),
],
),
migrations.CreateModel(
name='Report',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('title', models.CharField(max_length=255)),
('content', models.TextField()),
('image', models.ImageField(blank=True, height_field='height_field', null=True, upload_to=account.helpers.UploadTo('image'), width_field='width_field')),
('height_field', models.IntegerField(default=0, null=True)),
('width_field', models.IntegerField(default=0, null=True)),
('attachments', models.FileField(blank=True, null=True, upload_to=account.helpers.UploadTo('attachments'))),
('draft', models.BooleanField(default=False)),
('published', models.DateTimeField()),
('status', models.CharField(choices=[('accepted', 'Accepted'), ('rejected', 'Rejected'), ('pending', 'Pending'), ('open', 'Open'), ('closed', 'Closed')], default='open', max_length=10)),
('timestamp', models.DateTimeField(auto_now_add=True)),
('updated', models.DateTimeField(auto_now=True)),
('user', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL)),
],
),
migrations.CreateModel(
name='Notice',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('notice_id', models.UUIDField(default=uuid.uuid4, editable=False, unique=True)),
('title', models.CharField(max_length=255)),
('content', models.TextField()),
('attachments', models.FileField(blank=True, null=True, upload_to=account.helpers.UploadTo('attachments'))),
('send_from', models.CharField(blank=True, max_length=255, null=True)),
('draft', models.BooleanField(default=False)),
('published', models.DateTimeField()),
('timestamp', models.DateTimeField(auto_now_add=True)),
('updated', models.DateTimeField(auto_now=True)),
('posted_by', models.ForeignKey(on_delete=django.db.models.deletion.PROTECT, related_name='service_user_posted_by', to=settings.AUTH_USER_MODEL)),
('send_to', models.ManyToManyField(related_name='service_user_send_to', to=settings.AUTH_USER_MODEL)),
],
),
]
| {"/src/academic/admin.py": ["/src/academic/models.py"], "/src/account/urls.py": ["/src/account/views.py"], "/src/transaction/admin.py": ["/src/transaction/models.py"], "/src/resource/views.py": ["/src/resource/models.py", "/src/resource/forms.py"], "/src/member/admin.py": ["/src/member/models.py"], "/src/service/urls.py": ["/src/service/views.py"], "/src/wishlist/admin.py": ["/src/wishlist/models.py"], "/src/resource/admin.py": ["/src/resource/models.py"], "/src/core/dev/views.py": ["/src/core/dev/automate.py", "/src/core/dev/forms.py"], "/src/core/dev/urls.py": ["/src/core/dev/views.py"], "/src/resource/forms.py": ["/src/resource/models.py"], "/src/core/coreurls.py": ["/src/core/coreviews.py"], "/src/amtd/admin.py": ["/src/amtd/models.py"], "/src/account/views.py": ["/src/account/forms.py", "/src/account/models.py"], "/src/service/admin.py": ["/src/service/models.py"], "/src/resource/urls.py": ["/src/resource/views.py"]} |
78,628 | belal-bh/CLIC_PUST | refs/heads/master | /src/transaction/models.py | from django.db import models
from django.conf import settings
import uuid
from resource.models import (
Book,
Resource
)
class TrxBookManager(models.Manager):
# def get_queryset(self, *args, **kwargs):
# return super(TrxBookManager, self).get_queryset().filter(status="open")
def all(self, *args, **kwargs):
return super(TrxBookManager, self)
class TrxResourceManager(models.Manager):
def get_queryset(self, *args, **kwargs):
return super(TrxResourceManager, self).get_queryset() #.filter(status="open")
class TrxBook(models.Model):
trxid = models.UUIDField(default=uuid.uuid4, editable=False, unique=True)
issue_date = models.DateTimeField(auto_now=False, auto_now_add=False)
due_date = models.DateTimeField(auto_now=False, auto_now_add=False)
return_date = models.DateTimeField(auto_now=False, auto_now_add=False)
comment = models.CharField(max_length=255, null=True, blank=True)
user = models.ForeignKey(
settings.AUTH_USER_MODEL, on_delete=models.PROTECT, related_name="trxbook_user_borrower")
book = models.ForeignKey(
Book, on_delete=models.PROTECT)
issued_by = models.ForeignKey(
settings.AUTH_USER_MODEL, on_delete=models.SET_NULL, related_name="trxbook_user_issued_by", null=True, blank=True)
status = models.CharField(max_length=15, null=True, blank=True)
timestamp = models.DateTimeField(auto_now=False, auto_now_add=True)
updated = models.DateTimeField(auto_now=True, auto_now_add=False)
objects = TrxBookManager()
def __str__(self):
return self.book.title
class TrxResource(models.Model):
trxid = models.UUIDField(default=uuid.uuid4, editable=False, unique=True)
issue_date = models.DateTimeField(auto_now=False, auto_now_add=False)
due_date = models.DateTimeField(auto_now=False, auto_now_add=False)
return_date = models.DateTimeField(auto_now=False, auto_now_add=False)
comment = models.CharField(max_length=255, null=True, blank=True)
user = models.ForeignKey(
settings.AUTH_USER_MODEL, on_delete=models.PROTECT, related_name="trxresource_user_borrower")
resource = models.ForeignKey(
Resource, on_delete=models.PROTECT)
issued_by = models.ForeignKey(
settings.AUTH_USER_MODEL, on_delete=models.SET_NULL, related_name="trxresource_user_issued_by", null=True, blank=True)
status = models.CharField(max_length=15, null=True, blank=True)
timestamp = models.DateTimeField(auto_now=False, auto_now_add=True)
updated = models.DateTimeField(auto_now=True, auto_now_add=False)
objects = TrxResourceManager()
def __str__(self):
return self.resource.title | {"/src/academic/admin.py": ["/src/academic/models.py"], "/src/account/urls.py": ["/src/account/views.py"], "/src/transaction/admin.py": ["/src/transaction/models.py"], "/src/resource/views.py": ["/src/resource/models.py", "/src/resource/forms.py"], "/src/member/admin.py": ["/src/member/models.py"], "/src/service/urls.py": ["/src/service/views.py"], "/src/wishlist/admin.py": ["/src/wishlist/models.py"], "/src/resource/admin.py": ["/src/resource/models.py"], "/src/core/dev/views.py": ["/src/core/dev/automate.py", "/src/core/dev/forms.py"], "/src/core/dev/urls.py": ["/src/core/dev/views.py"], "/src/resource/forms.py": ["/src/resource/models.py"], "/src/core/coreurls.py": ["/src/core/coreviews.py"], "/src/amtd/admin.py": ["/src/amtd/models.py"], "/src/account/views.py": ["/src/account/forms.py", "/src/account/models.py"], "/src/service/admin.py": ["/src/service/models.py"], "/src/resource/urls.py": ["/src/resource/views.py"]} |
78,629 | belal-bh/CLIC_PUST | refs/heads/master | /src/account/migrations/0004_auto_20191016_0414.py | # Generated by Django 2.2.1 on 2019-10-15 22:14
import account.helpers
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('account', '0003_auto_20191016_0117'),
]
operations = [
migrations.AlterField(
model_name='user',
name='validity',
field=models.DateTimeField(default=account.helpers.DefaultPeriod()),
),
]
| {"/src/academic/admin.py": ["/src/academic/models.py"], "/src/account/urls.py": ["/src/account/views.py"], "/src/transaction/admin.py": ["/src/transaction/models.py"], "/src/resource/views.py": ["/src/resource/models.py", "/src/resource/forms.py"], "/src/member/admin.py": ["/src/member/models.py"], "/src/service/urls.py": ["/src/service/views.py"], "/src/wishlist/admin.py": ["/src/wishlist/models.py"], "/src/resource/admin.py": ["/src/resource/models.py"], "/src/core/dev/views.py": ["/src/core/dev/automate.py", "/src/core/dev/forms.py"], "/src/core/dev/urls.py": ["/src/core/dev/views.py"], "/src/resource/forms.py": ["/src/resource/models.py"], "/src/core/coreurls.py": ["/src/core/coreviews.py"], "/src/amtd/admin.py": ["/src/amtd/models.py"], "/src/account/views.py": ["/src/account/forms.py", "/src/account/models.py"], "/src/service/admin.py": ["/src/service/models.py"], "/src/resource/urls.py": ["/src/resource/views.py"]} |
78,630 | belal-bh/CLIC_PUST | refs/heads/master | /src/amtd/apps.py | from django.apps import AppConfig
class AmtdConfig(AppConfig):
name = 'amtd'
| {"/src/academic/admin.py": ["/src/academic/models.py"], "/src/account/urls.py": ["/src/account/views.py"], "/src/transaction/admin.py": ["/src/transaction/models.py"], "/src/resource/views.py": ["/src/resource/models.py", "/src/resource/forms.py"], "/src/member/admin.py": ["/src/member/models.py"], "/src/service/urls.py": ["/src/service/views.py"], "/src/wishlist/admin.py": ["/src/wishlist/models.py"], "/src/resource/admin.py": ["/src/resource/models.py"], "/src/core/dev/views.py": ["/src/core/dev/automate.py", "/src/core/dev/forms.py"], "/src/core/dev/urls.py": ["/src/core/dev/views.py"], "/src/resource/forms.py": ["/src/resource/models.py"], "/src/core/coreurls.py": ["/src/core/coreviews.py"], "/src/amtd/admin.py": ["/src/amtd/models.py"], "/src/account/views.py": ["/src/account/forms.py", "/src/account/models.py"], "/src/service/admin.py": ["/src/service/models.py"], "/src/resource/urls.py": ["/src/resource/views.py"]} |
78,631 | belal-bh/CLIC_PUST | refs/heads/master | /src/core/urls.py | """core URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/2.2/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.conf import settings
from django.contrib import admin
from django.urls import path, include
# from django.conf.urls import include
from django.conf.urls.static import static
import notifications.urls
from account.views import (
login_view,
register_view,
logout_view,
index_page,
)
urlpatterns = [
path('', index_page, name='index'),
path('admin/', admin.site.urls),
path('lib/', include("core.lib.urls", namespace='lib')),
path('dev/', include('core.dev.urls', namespace='dev')),
path('about/', include("core.coreurls", namespace='about')),
path('account/', include("account.urls", namespace='account')),
path('register/', register_view, name='register'),
path('login/', login_view, name='login'),
path('logout/', logout_view, name='logout'),
path('resource/', include("resource.urls", namespace='resource')),
path('blog/', include("post.urls", namespace='blog')),
path('service/', include("service.urls", namespace='service')),
path('inbox/notifications/',
include(notifications.urls, namespace='notifications')),
]
if settings.DEBUG:
urlpatterns += static(settings.STATIC_URL,
document_root=settings.STATIC_ROOT)
urlpatterns += static(settings.MEDIA_URL,
document_root=settings.MEDIA_ROOT)
| {"/src/academic/admin.py": ["/src/academic/models.py"], "/src/account/urls.py": ["/src/account/views.py"], "/src/transaction/admin.py": ["/src/transaction/models.py"], "/src/resource/views.py": ["/src/resource/models.py", "/src/resource/forms.py"], "/src/member/admin.py": ["/src/member/models.py"], "/src/service/urls.py": ["/src/service/views.py"], "/src/wishlist/admin.py": ["/src/wishlist/models.py"], "/src/resource/admin.py": ["/src/resource/models.py"], "/src/core/dev/views.py": ["/src/core/dev/automate.py", "/src/core/dev/forms.py"], "/src/core/dev/urls.py": ["/src/core/dev/views.py"], "/src/resource/forms.py": ["/src/resource/models.py"], "/src/core/coreurls.py": ["/src/core/coreviews.py"], "/src/amtd/admin.py": ["/src/amtd/models.py"], "/src/account/views.py": ["/src/account/forms.py", "/src/account/models.py"], "/src/service/admin.py": ["/src/service/models.py"], "/src/resource/urls.py": ["/src/resource/views.py"]} |
78,632 | belal-bh/CLIC_PUST | refs/heads/master | /src/member/models.py | from django.db import models
from django.conf import settings
from django.core.validators import RegexValidator
from academic.models import Faculty, Department, Program
CONTACT_MOBILE_REGEX = '^(?:\+?88|0088)?01[15-9]\d{8}$'
CONTACT_PHONE_REGEX = '^(?:\+?88|0088)?0\d{10}$'
class Student(models.Model):
user = models.ForeignKey(settings.AUTH_USER_MODEL,
on_delete=models.CASCADE)
student_id = models.CharField(
max_length=20,
unique=True
)
student_roll = models.CharField(
max_length=20,
unique=True
)
local_guardian_name = models.CharField(
max_length=40, null=True, blank=True)
guardian_contact_mobile = models.CharField(
max_length=32,
validators=[
RegexValidator(
regex=CONTACT_MOBILE_REGEX,
message='Mobile number must be numeric',
code='invalid_contact_mobile'
)],
)
guardian_contact_phone = models.CharField(
max_length=32,
validators=[
RegexValidator(
regex=CONTACT_PHONE_REGEX,
message='Phone number must be numeric',
code='invalid_contact_phone'
)],
null=True,
blank=True
)
faculty = models.ForeignKey(
Faculty, on_delete=models.SET_NULL, blank=True,
null=True,
)
program = models.ForeignKey(
Program, on_delete=models.SET_NULL, blank=True,
null=True,
)
department = models.ForeignKey(
Department, on_delete=models.SET_NULL, blank=True,
null=True,
)
session = models.CharField(max_length=15)
year = models.CharField(max_length=15)
semester = models.CharField(max_length=15)
timestamp = models.DateTimeField(auto_now=False, auto_now_add=True)
updated = models.DateTimeField(auto_now=True, auto_now_add=False)
class Teacher(models.Model):
user = models.ForeignKey(settings.AUTH_USER_MODEL,
on_delete=models.CASCADE)
teacher_id = models.CharField(
max_length=20,
unique=True
)
designation = models.CharField(max_length=40)
faculty = models.ForeignKey(
Faculty, on_delete=models.SET_NULL, blank=True,
null=True,
)
department = models.ForeignKey(
Department, on_delete=models.SET_NULL, blank=True,
null=True,
)
timestamp = models.DateTimeField(auto_now=False, auto_now_add=True)
updated = models.DateTimeField(auto_now=True, auto_now_add=False)
class Officer(models.Model):
user = models.ForeignKey(settings.AUTH_USER_MODEL,
on_delete=models.CASCADE)
officer_id = models.CharField(
max_length=20,
unique=True
)
designation = models.CharField(max_length=40)
department = models.CharField(max_length=120)
timestamp = models.DateTimeField(auto_now=False, auto_now_add=True)
updated = models.DateTimeField(auto_now=True, auto_now_add=False)
class Staff(models.Model):
user = models.ForeignKey(
settings.AUTH_USER_MODEL,
related_name='staff_user',
on_delete=models.CASCADE,
)
staff_id = models.CharField(
max_length=20,
unique=True
)
designation = models.CharField(max_length=40)
department = models.CharField(max_length=120)
timestamp = models.DateTimeField(auto_now=False, auto_now_add=True)
updated = models.DateTimeField(auto_now=True, auto_now_add=False)
class Othermember(models.Model):
user = models.ForeignKey(settings.AUTH_USER_MODEL,
on_delete=models.CASCADE)
member_id = models.CharField(
max_length=20,
unique=True
)
designation = models.CharField(max_length=40)
department = models.CharField(max_length=120)
timestamp = models.DateTimeField(auto_now=False, auto_now_add=True)
updated = models.DateTimeField(auto_now=True, auto_now_add=False)
class Librarian(models.Model):
user = models.ForeignKey(settings.AUTH_USER_MODEL,
on_delete=models.CASCADE)
designation = models.CharField(max_length=40)
# need to discuss about various member_type
STAFF = 'staff'
ADMIN = 'admin'
MEMBER_TYPE_CHOICES = (
(STAFF, 'Staff'),
(ADMIN, 'Admin'),
)
member_type = models.CharField(
max_length=10,
choices=MEMBER_TYPE_CHOICES,
default=STAFF
)
active = models.BooleanField(default=True)
validity = models.DateTimeField(
auto_now=False, auto_now_add=True) # need customization
timestamp = models.DateTimeField(auto_now=False, auto_now_add=True)
updated = models.DateTimeField(auto_now=True, auto_now_add=False)
| {"/src/academic/admin.py": ["/src/academic/models.py"], "/src/account/urls.py": ["/src/account/views.py"], "/src/transaction/admin.py": ["/src/transaction/models.py"], "/src/resource/views.py": ["/src/resource/models.py", "/src/resource/forms.py"], "/src/member/admin.py": ["/src/member/models.py"], "/src/service/urls.py": ["/src/service/views.py"], "/src/wishlist/admin.py": ["/src/wishlist/models.py"], "/src/resource/admin.py": ["/src/resource/models.py"], "/src/core/dev/views.py": ["/src/core/dev/automate.py", "/src/core/dev/forms.py"], "/src/core/dev/urls.py": ["/src/core/dev/views.py"], "/src/resource/forms.py": ["/src/resource/models.py"], "/src/core/coreurls.py": ["/src/core/coreviews.py"], "/src/amtd/admin.py": ["/src/amtd/models.py"], "/src/account/views.py": ["/src/account/forms.py", "/src/account/models.py"], "/src/service/admin.py": ["/src/service/models.py"], "/src/resource/urls.py": ["/src/resource/views.py"]} |
78,633 | belal-bh/CLIC_PUST | refs/heads/master | /src/service/admin.py | from django.contrib import admin
from .models import (
Request,
Report,
Notice,
)
admin.site.register(Request)
admin.site.register(Report)
admin.site.register(Notice)
| {"/src/academic/admin.py": ["/src/academic/models.py"], "/src/account/urls.py": ["/src/account/views.py"], "/src/transaction/admin.py": ["/src/transaction/models.py"], "/src/resource/views.py": ["/src/resource/models.py", "/src/resource/forms.py"], "/src/member/admin.py": ["/src/member/models.py"], "/src/service/urls.py": ["/src/service/views.py"], "/src/wishlist/admin.py": ["/src/wishlist/models.py"], "/src/resource/admin.py": ["/src/resource/models.py"], "/src/core/dev/views.py": ["/src/core/dev/automate.py", "/src/core/dev/forms.py"], "/src/core/dev/urls.py": ["/src/core/dev/views.py"], "/src/resource/forms.py": ["/src/resource/models.py"], "/src/core/coreurls.py": ["/src/core/coreviews.py"], "/src/amtd/admin.py": ["/src/amtd/models.py"], "/src/account/views.py": ["/src/account/forms.py", "/src/account/models.py"], "/src/service/admin.py": ["/src/service/models.py"], "/src/resource/urls.py": ["/src/resource/views.py"]} |
78,634 | belal-bh/CLIC_PUST | refs/heads/master | /src/resource/urls.py | from django.urls import path
from .views import (
book_list,
book_detail,
resource_list,
resource_detail,
resource_doclist,
resource_newspaperlist,
)
app_name = 'resource'
urlpatterns = [
path('book/', book_list, name='booklist'),
path('book/<int:id>/', book_detail, name='bookdetail'),
path('res/', resource_list, name='reslist'),
path('res/<int:id>/', resource_detail, name='resdetail'),
path('doc/', resource_doclist, name='doclist'),
path('newspaper/', resource_newspaperlist, name='newspaperlist'),
]
| {"/src/academic/admin.py": ["/src/academic/models.py"], "/src/account/urls.py": ["/src/account/views.py"], "/src/transaction/admin.py": ["/src/transaction/models.py"], "/src/resource/views.py": ["/src/resource/models.py", "/src/resource/forms.py"], "/src/member/admin.py": ["/src/member/models.py"], "/src/service/urls.py": ["/src/service/views.py"], "/src/wishlist/admin.py": ["/src/wishlist/models.py"], "/src/resource/admin.py": ["/src/resource/models.py"], "/src/core/dev/views.py": ["/src/core/dev/automate.py", "/src/core/dev/forms.py"], "/src/core/dev/urls.py": ["/src/core/dev/views.py"], "/src/resource/forms.py": ["/src/resource/models.py"], "/src/core/coreurls.py": ["/src/core/coreviews.py"], "/src/amtd/admin.py": ["/src/amtd/models.py"], "/src/account/views.py": ["/src/account/forms.py", "/src/account/models.py"], "/src/service/admin.py": ["/src/service/models.py"], "/src/resource/urls.py": ["/src/resource/views.py"]} |
78,635 | m-wessler/wxdisco-tools | refs/heads/master | /wxdisco.py | #!/uufs/chpc.utah.edu/sys/installdir/anaconda3/2018.12/bin/python
import sys
import numpy as np
import pandas as pd
import matplotlib.dates as mdates
import matplotlib.pyplot as plt
from datetime import datetime
from funcs import *
from config import *
from plotfuncs import *
import warnings
warnings.filterwarnings('ignore')
wd = '/uufs/chpc.utah.edu/common/home/u1070830/public_html/wxdisco/'
if __name__ == '__main__':
site = 'KSLC'
init_req = sys.argv[1] if len(sys.argv) > 1 else None
init_time = get_init(init_req)
pdata = load_plumedata(init_time, site)
time = pd.to_datetime(pdata.time.values)
timefmt = '%Y-%m-%d %H:%M'
p1i = np.where(np.array([t.hour for t in time]) == 18)[0][0]
pop, pos = [], []
for i, t in enumerate(time):
n = pdata.isel(time=i).dqpf.size
p_yes = np.where(pdata.isel(time=i).dqpf >= 0.01)[0].size
pop.append(np.round(p_yes/n*100, 0).astype(int))
s_yes = np.where(pdata.isel(time=i).snow >= 0.1)[0].size
pos.append(np.round(s_yes/n*100, 0).astype(int))
pop, pos = np.array(pop), np.array(pos)
pqpf = pdata.dqpf.quantile([.1, .5, .9], dim='member')
pqsf = pdata.snow.quantile([.1, .5, .9], dim='member')
p1 = pdata.isel(time=slice(p1i+1, p1i+3))
n1 = p1.isel(time=0).member.size
p1_pop = int(np.round((np.where(p1.dqpf.sum(dim='time') > 0.01)[0].size/n1)*100, 0))
p1_pos = int(np.round((np.where(p1.snow.sum(dim='time') > 0.1)[0].size/n1)*100, 0))
p2 = pdata.isel(time=slice(p1i+4, p1i+11))
n2 = p2.isel(time=0).member.size
p2_pop = int(np.round((np.where(p2.dqpf.sum(dim='time') > 0.01)[0].size/n2)*100, 0))
p2_pos = int(np.round((np.where(p2.snow.sum(dim='time') > 0.1)[0].size/n2)*100, 0))
p1['dqpf'].values[np.where(p1.dqpf <= 0.01)] = 0.
p1['snow'].values[np.where(p1.dqpf <= 0.1)] = 0.
p1_pqpf = [np.round(v, 2) for v in p1.dqpf.sum(dim='time').quantile([.1, .5, .9], dim='member').values]
p1_pqsf = [np.round(v, 2) for v in p1.snow.sum(dim='time').quantile([.1, .5, .9], dim='member').values]
p2['dqpf'].values[np.where(p2.dqpf <= 0.01)] = 0.
p2['snow'].values[np.where(p2.dqpf <= 0.1)] = 0.
p2_pqpf = p2.dqpf.sum(dim='time').quantile([.1, .5, .9], dim='member').values
p2_pqsf = p2.snow.sum(dim='time').quantile([.1, .5, .9], dim='member').values
try:
with open(wd + 'forecast.csv', 'r+') as rfp:
lines = rfp.readlines()
lenlines = len(lines)
except:
lines = []
lenlines = 0
maxlines = 91 if lenlines > 91 else None
with open(wd + 'forecast.csv', 'w+') as wfp:
wfp.write(' , , , , \n')
wfp.write('{}, {}, {}, {}, {}\n'.format(
'KSLC Downscaled SREF Init: '+init_time.strftime('%Y-%m-%d %H%M UTC'),
'PoP (%)',
'PQPF 10/50/90 (in)',
'PoS (%)',
'PQSF 10/50/90 (in)'))
for i in range(11):
# wfp.write('{}, {}, {}, {}, {}\n'.format(
# '3-h period ending: ' + time[p1i+i].strftime(timefmt),
# pop[p1i+i],
# str(['{:6.3f}'.format(round(v[0], 3)) for v in pqpf.isel(time=[p1i+i]).values]).replace(',', ' ').replace("'",'').replace('[', '').replace(']', ''),
# pos[p1i+i],
# str(['{:6.3f}'.format(round(v[0], 3)) for v in pqsf.isel(time=[p1i+i]).values]).replace(',', ' ').replace("'",'').replace('[', '').replace(']', '')))
if i in [2, 10]:
period = 'Period 1 (%s – %s)'%(time[p1i], time[p1i+i]) if i == 2 else 'Period 2 (%s – %s)'%(time[p1i+10], time[p1i+i])
_pop, _pos = (p1_pop, p1_pos) if i == 2 else (p2_pop, p2_pos)
_pqpf, _pqsf = (p1_pqpf, p1_pqsf) if i == 2 else (p2_pqpf, p2_pqsf)
wfp.write('{}, {}, {}, {}, {}\n'.format(
period,
_pop,
str(['{:6.3f}'.format(round(v, 3)) for v in _pqpf]).replace(',', ' ').replace("'",'').replace('[', '').replace(']', ''),
_pos,
str(['{:6.3f}'.format(round(v, 3)) for v in _pqsf]).replace(',', ' ').replace("'",'').replace('[', '').replace(']', '')
))
[wfp.write(line) for line in lines[:maxlines]]
plt.rcParams.update({'font.size': 16})
fig, axs = plt.subplots(2, 2, figsize=(30, 16), facecolor='w', sharex=True)
fig.subplots_adjust(hspace=0.03, wspace=0.015)
axs = axs.flatten()
axs[0].scatter(time, pop, s=250, marker="+", color='g', label='PoP')
axs[0].set_ylabel('Probability of Precipitation\n')
axs[0].set_yticks(np.arange(0, 101, 10))
axs[1].scatter(time, pos, s=250, marker="+", color='b', label='PoS')
axs[1].set_ylim(top=100)
axs[1].set_yticks(np.arange(0, 101, 10))
axs[2].plot(time, pqpf.sel(quantile=.5), c='g', label='PQPF Median')
axs[2].fill_between(time, pqpf.sel(quantile=.1), pqpf.sel(quantile=.9), alpha=0.3, color='g', label='PQPF 10/90 Spread')
axs[2].set_ylabel('Precipitation [in]\n')
pqpf_max = np.round(pqpf.sel(quantile=.9).max().values, 2)
pqpf_max = 1 if pqpf_max < 0.01 else pqpf_max
axs[2].set_yticks(np.array([np.round(x, 2) for x in np.linspace(0, pqpf_max + (pqpf_max*1.10), 10)]))
axs[3].plot(time, pqsf.sel(quantile=.5), c='b', label='PQSF Median')
axs[3].fill_between(time, pqsf.sel(quantile=.1), pqsf.sel(quantile=.9), alpha=0.3, color='b', label='PQSF 10/90 Spread')
pqsf_max = np.round(pqsf.sel(quantile=.9).max().values, 2)
pqsf_max = 1 if pqsf_max < 0.1 else pqsf_max
axs[3].set_yticks(np.array([np.round(x, 2) for x in np.linspace(0, pqsf_max + (pqsf_max*1.10), 10)]))
for i, ax in enumerate(axs):
if i in [1, 3]:
ax.yaxis.tick_right()
ax.set_ylim(bottom=0)
ax.legend(loc='upper right', fontsize='x-large')
ax.set_xlim([time[0], time[-1]])
ax.set_xlabel('\nTime [UTC]')
hours = mdates.HourLocator(interval = 6)
h_fmt = mdates.DateFormatter('%m/%d %H:%M')
ax.xaxis.set_major_locator(hours)
ax.xaxis.set_major_formatter(h_fmt)
for tick in ax.get_xticklabels():
tick.set_rotation(70)
if i in [0, 1]:
ax.set_xticklabels([])
ax.grid(True)
plt.suptitle('%s Downscaled SREF Precipitation Probabiltiies\nInitialized %s UTC\n' %(site, init_time), y=.95, x=0.51)
plt.savefig(wd + 'current_sref.png')
| {"/wxdisco.py": ["/funcs.py", "/config.py", "/plotfuncs.py"], "/plotfuncs.py": ["/funcs.py", "/config.py", "/colortables.py"], "/funcs.py": ["/config.py", "/colortables.py"], "/colortables.py": ["/config.py"]} |
78,636 | m-wessler/wxdisco-tools | refs/heads/master | /plotfuncs.py | import gc
import numpy as np
import xarray as xr
from funcs import *
from config import *
from colortables import *
def mkdir_p(ipath):
from os import makedirs, path
import errno
try:
makedirs(ipath)
except OSError as exc: # Python >2.5
if exc.errno == errno.EEXIST and path.isdir(ipath):
pass
else:
raise
return ipath
def xrsum(xarr):
return xarr.sum(dim='time')
def load_mapdata(init_time, load_var, temp=True):
from os import path, stat
from multiprocessing import Pool, cpu_count
dateH = init_time.strftime('%Y%m%d%H')
date = init_time.strftime('%Y%m%d')
dataset = []
for i, model in enumerate(models):
for j in range(mcount):
# Add future support for other model downloads here
if ensemble == 'sref':
if j == 0:
member = model + '_ctl'
elif j <= (mcount-1)/len(models):
member = model + '_n%i'%j
elif j > (mcount-1)/len(models):
member = model + '_p%i'%(j-((mcount-1)/len(models)))
elif ensemble == 'naefs':
if j == 0:
member = model + '_c00'
else:
member = model + '_p%02d'%j
if temp == True:
df = tmpdir + '%s/models/%s/%s/%s_%s_downscaled.nc'%(
date, ensemble, dateH, dateH, member)
else:
df = datadir + '%s/models/%s/%s/%s_%s_downscaled.nc'%(
date, ensemble, dateH, dateH, member)
dataset.append(
xr.open_dataset(df,
decode_times=False,
drop_variables=[v for v in output_vars
if v not in load_var])[load_var])
with Pool(cpu_count()-1) as p:
acc_data = p.map(xrsum, dataset)
p.close()
p.join()
[f.close() for f in dataset]
[f.close() for f in acc_data]
del dataset
gc.collect()
acc_data = xr.concat(acc_data, dim='member').load()
acc_data.rename('acc_' + load_var)
return acc_data
def calc_stats(acc_data, init_time):
dd = {}
dd['init'] = init_time
dd['lat'] = acc_data.lat
dd['lon'] = acc_data.lon
dd['mcount'] = acc_data.member.size
dd['max'] = acc_data.max(dim='member')
dd['min'] = acc_data.min(dim='member')
dd['mean'] = acc_data.mean(dim='member')
dd['med'] = acc_data.median(dim='member')
dd['stdev'] = acc_data.std(dim='member')
thresholds = snowthresh if 'snow' in acc_data.name else qpfthresh
probs = [((xr.where(acc_data > thresh, 1, 0).sum(dim='member')/
acc_data.member.size)*100) for thresh in thresholds]
for k, v in zip(thresholds, probs):
nk = 'prob_' + str(k)
dd[nk] = v
return dd
def load_plumedata(init_time, site, temp=False):
from os import path, stat
from multiprocessing import Pool, cpu_count
dateH = init_time.strftime('%Y%m%d%H')
date = init_time.strftime('%Y%m%d')
print('Loading plume data for %s from file'%site)
_dataset = []
for i, model in enumerate(models):
for j in range(mcount):
# Add future support for other model downloads here
if ensemble == 'sref':
if j == 0:
member = model + '_ctl'
elif j <= (mcount-1)/len(models):
member = model + '_n%i'%j
elif j > (mcount-1)/len(models):
member = model + '_p%i'%(j-((mcount-1)/len(models)))
elif ensemble == 'naefs':
if j == 0:
member = model + '_c00'
else:
member = model + '_p%02d'%j
if temp == True:
df = tmpdir + '%s/models/%s/%s/%s_%s_downscaled.nc'%(
date, ensemble, dateH, dateH, member)
else:
df = datadir + '%s/models/%s/%s/%s_%s_downscaled.nc'%(
date, ensemble, dateH, dateH, member)
sitelat, sitelon = point_locs[site]
_dataset.append(xr.open_dataset(df,
decode_times=False))
lons = _dataset[0].lon.values
lats = _dataset[0].lat.values
idx1d = (np.abs(lons-sitelon) + np.abs(lats-sitelat))
idx = np.unravel_index(np.argmin(idx1d, axis=None), idx1d.shape)
dataset = xr.concat(
[mem.isel(x=idx[1], y=idx[0]).load() for mem in _dataset],
dim='member').compute()
# Close the files immediately to free up the read for multiprocessing
[f.close() for f in _dataset]
dataset['acc_qpf'] = dataset.dqpf.cumsum(dim='time')
dataset['acc_snow'] = dataset.snow.cumsum(dim='time')
return dataset
def adjacent_values(vals, q1, q3):
upper_adjacent_value = q3 + (q3 - q1) * 1.5
upper_adjacent_value = np.clip(upper_adjacent_value, q3, vals[-1])
lower_adjacent_value = q1 - (q3 - q1) * 1.5
lower_adjacent_value = np.clip(lower_adjacent_value, vals[0], q1)
return lower_adjacent_value, upper_adjacent_value
def custom_violin(xr_data, axis, scale=1):
vio_data = xr_data.values
parts = axis.violinplot(
vio_data, showmeans=False, showmedians=False,
showextrema=False, widths=0.75)
for ii, pc in enumerate(parts['bodies']):
if ii == 0:
iqrlab = 'IQR'
medlab = 'Median'
elif ii == 1:
iqrlab, medlab = '', ''
kdecolor = [0,0.4,0] if xr_data.name == 'dqpf' else [0,0,0.6]
pc.set_facecolor(kdecolor)
pc.set_edgecolor(kdecolor)
pc.set_alpha(.5)
quartile1, medians, quartile3 = np.percentile(
vio_data, [25, 50, 75], axis=0)
hiex, loex = np.percentile(vio_data, [5, 95], axis=0)
whiskers = np.array([
adjacent_values(sorted_array, q1, q3)
for sorted_array, q1, q3 in zip(vio_data, quartile1, quartile3)])
whiskersMin, whiskersMax = hiex, loex
inds = np.arange(1, len(medians) + 1)
axis.vlines(inds, quartile1, quartile3, color='k', linestyle='-',
lw=3*scale, label=iqrlab)
axis.scatter(inds, medians, marker='_', color='r', s=25, zorder=3,
linewidth=2*scale, label=medlab)
axis.vlines(inds, whiskersMin, whiskersMax, color='r',
linestyle='-', lw=1*scale, label='')
axis.scatter(0,0, color='r', marker='|', label='5th/95th Percentile')
axis.plot(0, 0, c=kdecolor, linewidth=5*scale, label='Density')
return axis
def slr_spreadplot(data, axis, scale=1):
slr = data.slr
slr_iqr = slr.quantile([0, .25, 0.50, .75, 1],
dim='member', interpolation='linear')
axslr = axis.twinx()
inds = range(1, slr.time.size+1)
axslr.plot(inds, slr_iqr.sel(quantile=.50),
color='gray', alpha=0.75, zorder=-100,
linewidth=3.5*scale, label=('Median SLR'))
# MEDIAN, IQR LINES
# axslr.plot(inds, slr_iqr.sel(quantile=.75),
# color='blue', alpha=0.75, zorder=-100,
# linewidth=3.5*scale, label=('75th Percentile SLR'))
# axslr.plot(inds, slr_iqr.sel(quantile=.25),
# color='red', alpha=0.75, zorder=-100,
# linewidth=3.5*scale, label=('25th Percentile SLR'))
# MEDIAN, IQR SHADE
axslr.fill_between(inds,
slr_iqr.sel(quantile=0.25), slr_iqr.sel(quantile=0.75),
color='gray', alpha=0.4, zorder=-100,
linewidth=3*scale, label=('IQR'))
# Median +/- STDEV
# mslr = slr.median(dim='member')
# slrstd = slr.std(dim='member')
# axslr.fill_between(inds, mslr - slrstd, mslr + slrstd,
# color='gray', alpha=0.4, zorder=-100,
# linewidth=3*scale, label=(r'$\pm$ 1 SD'),)
axslr.set_ylim(bottom=0,top=30)
axslr.set_ylabel('Snow:Liqud Ratio')
leg = axslr.legend(loc='upper right', fontsize='x-small')
for line in leg.get_lines():
line.set_linewidth(3.0)
return None
def ensemble_plume(site, init_time, scale=0.75, temp=True):
from os import remove as rm
from os import system as sys
import matplotlib
matplotlib.use('agg')
import matplotlib.pyplot as plt
import matplotlib.dates as dates
import matplotlib.image as mimage
from pandas import to_datetime
from subprocess import call as sys
from datetime import datetime, timedelta
data = load_plumedata(init_time, site, temp=temp)
print('Plotting plume for %s'%site)
sitelat, sitelon = point_locs[site]
elev = xr.open_dataset(terrainfile)
elats = elev.latitude.values
elons = elev.longitude.values
ilat = np.argmin(np.abs(elats - sitelat))
ilon = np.argmin(np.abs(elons - sitelon))
siteelev = elev.elevation.isel(latitude=ilat, longitude=ilon).values
siteelev = int(round(siteelev * 3.28084, 0))
elev.close()
del elev
plt.style.use('classic')
matplotlib.rcParams.update({'font.size': 22*scale})
fig, axs = plt.subplots(2, 2, figsize=(28*scale, 18*scale),
facecolor='w', edgecolor='k')
fig.subplots_adjust(hspace=0.54, left=0.15,
bottom=0.13, right=0.96, top=0.88)
axs = axs.flatten()
if site in point_names.keys():
plt.suptitle(('{} Downscaled Guidance at {:s} ({:s}: ' +
'{:.2f} N {:.2f} W {:d} ft AMSL)\n' +
'Model Run: {} ({:d} Members)').format(
ensemble.upper(), point_names[site],
site, sitelat, sitelon, siteelev,
init_time.strftime("%HZ %Y-%m-%d"),
data.member.size, fontsize=14))
else:
plt.suptitle(('{} Downscaled Guidance at ' +
'{:s} ({:.2f} N {:.2f} W {:d} ft AMSL)\n' +
'Model Run: {} ({:d} Members)').format(
ensemble.upper(), site, sitelat, sitelon, siteelev,
init_time.strftime("%HZ %Y-%m-%d"),
data.member.size, fontsize=14))
half = int(data.member.size / 2)
dtarr = to_datetime(data.time.values)
for i, member in data.groupby('member'):
lw, mlw = 1.5*scale, 5*scale
if member.member == 1:
label = (str(member.member_id.values).split('_')[0].upper() +
' Members')
qcol = [0,0.9,0]
scol = [0,0,1.0]
elif member.member == half+1:
label = (str(member.member_id.values).split('_')[0].upper() +
' Members')
qcol = [0.7,0.9,0]
scol = [0,0.6,0.9]
else:
label = ''
axs[0].plot(dtarr, member.acc_qpf,
color=qcol, linewidth=lw, label=label)
axs[2].plot(dtarr, member.acc_snow,
color=scol, linewidth=lw, label=label)
halflab0 = str(data.member_id[:half][0].values).split('_')[0].upper()
halflab1 = str(data.member_id[half:][0].values).split('_')[0].upper()
axs[0].plot(dtarr, data.acc_qpf[:half].mean(dim='member'),
'-', color='r', linewidth=mlw, label='%s Mean'%halflab0)
axs[0].plot(dtarr, data.acc_qpf[half:].mean(dim='member'),
'--', color='r', linewidth=mlw, label='%s Mean'%halflab1)
axs[0].plot(dtarr, data.acc_qpf[:].mean(dim='member'),
'-', color=[0,0.4,0], linewidth=mlw,
label='%s Mean'%ensemble.upper())
axs[2].plot(dtarr, data.acc_snow[:half].mean(dim='member'),
'-', color='r', linewidth=mlw, label='%s Mean'%halflab0)
axs[2].plot(dtarr, data.acc_snow[half:].mean(dim='member'),
'--', color='r', linewidth=mlw, label='%s Mean'%halflab1)
axs[2].plot(dtarr, data.acc_snow[:].mean(dim='member'),
'-', color=[0,0,0.6], linewidth=mlw,
label='%s Mean'%ensemble.upper())
axs[1] = custom_violin(data.dqpf, axs[1], scale=scale)
axs[3] = custom_violin(data.snow, axs[3], scale=scale)
slr_spreadplot(data, axs[3], scale=scale)
subtitles = ['Accumulated Precipitation',
'%d-Hourly Precipitation'%fhrstep,
'Accumulated Snow',
'%d-Hourly Snow'%fhrstep]
ylabels = ['Precipitation (Inches)', 'Precipitation (Inches)',
'Snow (Inches)', 'Snow (Inches)']
logo = mimage.imread(scriptdir + '../Ulogo_400p.png')
axs_water = [[0.16, 0.73, .065, .11],
[0.89, 0.73, .065, .11],
[0.16, 0.27, .065, .11],
[0.89, 0.27, .065, .11]]
for i, ax in enumerate(axs):
ax.set_title(subtitles[i])
ax.set_xlabel('Day/Hour')
ax.set_ylabel(ylabels[i])
if i%2 == 0:
_ytop = 0.5 if i == 0 else 1.0
ytop = (ax.get_ylim()[1] * 1.2
if ax.get_ylim()[1] >= _ytop else _ytop)
ax.set_ylim([0, ytop])
ax.set_xlim([dtarr.min(), dtarr.max()])
if ensemble == 'sref':
ax.xaxis.set_major_locator(dates.HourLocator(
byhour=range(0, 24, 6)))
ax.xaxis.set_major_formatter(dates.DateFormatter('%d/%HZ'))
plt.setp(ax.xaxis.get_majorticklabels(), rotation=80)
leg = ax.legend(loc=2, handlelength=5*scale,
fontsize='x-small', ncol=3)
ax.grid(b=True, linestyle='dotted')
else:
ytop = ax.get_ylim()[1] * 1.05 if ax.get_ylim()[1] >= 0.5 else 0.5
ax.set_ylim([0, ytop])
tick_hack = [(dti.strftime('%d/%HZ') if dti.hour % 6 == 0
else '') for dti in dtarr]
if ensemble == 'sref':
ax.set_xticks(np.arange(1, len(tick_hack)+1))
ax.set_xticklabels(tick_hack, rotation=80)
ax.set_xlim([1.5, len(tick_hack) + 0.5])
leg = ax.legend(loc=2, handlelength=5*scale, markerscale=5*scale,
scatterpoints=1, fontsize='x-small', ncol=2)
ax.grid(b=True, axis='y', linestyle='dotted')
if ensemble == 'naefs':
disptype = 'date'
monthlist = ['Jan','Feb','Mar','Apr','May','Jun',
'Jul','Aug','Sep','Oct','Nov','Dec']
ticklabs = []
ticksites = np.arange(fhrstart, fhrend + fhrstep, fhrstep)
for t in ticksites:
d = init_time + timedelta(float(t) / 24.0)
ticklab = ''
if np.floor(float(t)/12.0) == float(t) / 12.0:
ticklab = '%02d'%d.hour + 'z'
if np.floor(float(t)/24.0) == float(t) / 24.0:
ticklab = (ticklab + '\n%02d'%d.day + '-' +
monthlist[d.month - 1])
ticklabs.append(ticklab)
ticklocs = dtarr if i%2 == 0 else np.arange(1, len(tick_hack) + 1)
ax.set_xticks(ticklocs)
ax.set_xticklabels(ticklabs)
for line in leg.get_lines():
line.set_linewidth(8*scale)
ax_water = fig.add_axes(axs_water[i])
ax_water.axis('off')
ax_water.imshow(logo, aspect='auto', zorder=10, alpha=0.35)
date = init_time.strftime('%Y%m%d')
dateH = init_time.strftime('%Y%m%d%H')
figdir = mkdir_p(imgdir + '%s/images/models/%s/'%(date, ensemble))
figpath = figdir + '{}PL_{}{}F{:03d}.png'.format(
ensemble.upper(), site, dateH, int(fhrend-fhrstart))
figpath_gif = figpath[:-4] + '.gif'
plt.savefig(figpath, bbox_inches='tight')
plt.close()
sys('convert ' + figpath + ' ' + figpath_gif, shell=True)
rm(figpath)
return None
def ensemble_qpf6panel(region, dd):
import os
from scipy import ndimage
from os import remove as rm
from subprocess import call as sys
from datetime import datetime, timedelta
import matplotlib
matplotlib.use('agg')
import matplotlib.pyplot as plt
import matplotlib.image as mimage
from mpl_toolkits.basemap import Basemap, maskoceans
# Other very nice styles available. See the docs
plt.style.use('classic')
print('Plotting QPF 6-panel for %s'%region)
# Gather the metadata needed
init_time = dd['init']
fx_len = int(fhrend)-int(fhrstart)
# Crop the desired region
lons, lats = dd['lon'].values, dd['lat'].values
minlon, maxlon, minlat, maxlat = map_regions[region]
# Initialize the figure frame
fig = plt.figure(num=None, figsize=(11.0*scale,8.0*scale), dpi=300*scale,
facecolor='w', edgecolor='k')
# Customize the subplots
fig.subplots_adjust(top=0.89, bottom=0.02, left=0.055,
right=0.99, hspace=0.1*scale, wspace=0.22)
plt.suptitle(('{} Downscaled QPF ({:d} members) Initialized {}\n' +
'{:d}-{:d}-h Forecast Valid {} to {}').format(
ensemble.upper(),
dd['mcount'],
dd['init'].strftime('%HZ %Y-%m-%d'),
fhrstart, fhrend,
dd['init'].strftime('%HZ %Y-%m-%d'),
(dd['init'] + timedelta(
hours=fx_len)).strftime(
'%HZ %Y-%m-%d')), fontsize=14)
# Initialize the basemap object
bmap = Basemap(
llcrnrlon=minlon-0.01,
llcrnrlat=minlat-0.01,
urcrnrlon=maxlon+0.01,
urcrnrlat=maxlat+0.01,
resolution='i',
# Project as 'aea', 'lcc', or 'mill'
projection='mill')
# Project the lat/lon grid
x, y = bmap(lons, lats)
# Types of plots to draw
plottype = (['mean', 'max', 'min'] +
['prob_' + str(threshold)
for threshold in qpfthresh])
# Titles for the plots (indexes must align with above)
titles = ['Ensemble Mean %d-hr Accum Precip'%fx_len,
'Ensemble Max %d-hr Accum Precip'%fx_len,
'Ensemble Min %d-hr Accum Precip'%fx_len,
'Prob of %d-hr Precip > %s" (%%)'%(fx_len, qpfthresh[0]),
'Prob of %d-hr Precip > %s" (%%)'%(fx_len, qpfthresh[1]),
'Prob of %d-hr Precip > %s" (%%)'%(fx_len, qpfthresh[2])]
# Painstakingly placed colorbars...
cbar_axes = [[0.01,0.52,0.012,0.32],
[0.34,0.52,0.012,0.32],
[0.67,0.52,0.012,0.32],
[0.01,0.08,0.012,0.32],
[0.34,0.08,0.012,0.32],
[0.67,0.08,0.012,0.32]]
# Painstakingly placed logo...
logo = mimage.imread(scriptdir + '../Ulogo_400p.png')
bot, top, left = .05, 0.505, 0.245
axs_water = [[left, top, .065, .11],
[left+0.332, top, .065, .11],
[left+0.664, top, .065, .11],
[left, bot, .065, .11],
[left+0.332, bot, .065, .11],
[left+0.664, bot, .065, .11]]
# If choosing to plot elevation contours
if plot_elevation == True:
zsmooth, zint = elev_smoothing[region]
# Contour interval
zlevs = np.arange(0, 4500+.01, zint)
# Smoothing parameters
efold = (res_ensemble/zsmooth) / res_prism + 1
sigma = efold / (np.pi*np.sqrt(2))
# Smooth the terrain DEM as desired
z = ndimage.filters.gaussian_filter(
get_elev(dd[plottype[0]]),
sigma, mode='nearest')
# List to store the colorbar data
cbd = []
for i in range(6):
# Basemap likes explicit subplots
ax = plt.subplot(2,3,i+1)
ax.set_title(titles[i], fontsize=11)
bmap.drawcoastlines(linewidth=1.0, color='black')
bmap.drawcountries(linewidth=0.85, color='black')
bmap.drawstates(linewidth=1.25, color='black')
if plot_elevation == True:
bmap.contour(x, y, z, levels=zlevs, colors='black', alpha=0.75,
linewidths=1)
# Choose the appropriate colormaps and levels for the plot
# Edit these in colortables.py
if 'prob' in plottype[i]:
levs, norml, cmap, tickloc, ticks = (problevs, probnorml,
probcmap, problevloc,
probticks)
else:
levs, norml, cmap, tickloc, ticks = (qpflevs, qpfnorml,
qpfcmap, qpflevloc, qpfticks)
# Mask the oceans, inlands=False to prevent masking lakes (e.g. GSL)
data_lsmask = maskoceans(lons, lats, dd[plottype[i]], inlands=False)
# Allow for precip beyond the maximum contourf
extend = 'max' if 'prob' not in plottype[i] else 'neither'
cbd.append(bmap.contourf(x, y, data_lsmask, extend=extend,
levels=levs, norm=norml, cmap=cmap,
alpha=0.80))
# Manually establish the colorbar
cax = fig.add_axes(cbar_axes[i])
cbar = plt.colorbar(cbd[i], cax=cax, orientation='vertical')
cbar.set_ticks(tickloc)
cbar.set_ticklabels(ticks)
cbar.ax.tick_params(size=0)
cbytick_obj = plt.getp(cbar.ax.axes, 'yticklabels')
plt.setp(cbytick_obj, fontsize=8*scale, rotation=0)
# Add the U watermark
ax_water = fig.add_axes(axs_water[i])
ax_water.axis('off')
ax_water.imshow(logo, aspect='auto', zorder=10, alpha=0.40)
# Determine the max precip in the visible frame
ld = dd[plottype[i]]
if 'prob' not in plottype[i]:
ld_mask = xr.where(
((minlat <= ld.lat) & (ld.lat <= maxlat)) &
((minlon <= ld.lon) & (ld.lon <= maxlon)), ld, np.nan)
localmax = ld_mask.max()
xlon, xlat = np.where(ld_mask == localmax)
# Mark the max precip in the frame with an 'x' (Off for now)
# Basemap is improperly placing the lat lon point... why?
# xx, yy = x[xlon, xlat], y[xlon, xlat]
# bmap.scatter(xx, yy, marker='x', c='k', s=100)
ax.set_xlabel('Max: {:.02f} in ({:.02f}, {:.02f})'.format(
localmax.values,
lats[xlon, xlat][0], lons[xlon, xlat][0]), fontsize=8*scale)
elif ((i == 4) & (plot_elevation == True)):
# Annotate the bottom of the plot to explain the elevation contour
ax.set_xlabel('Elevation (Gray Contours) Every 1000 m',
fontsize=8*scale)
# Save the file according to previous convention
date = init_time.strftime('%Y%m%d')
dateH = init_time.strftime('%Y%m%d%H')
figdir = mkdir_p(imgdir + '%s/images/models/%s/'%(date, ensemble))
figpath = figdir + '{}PP_{}{}F{:03d}.png'.format(
ensemble.upper(), region, dateH, int(fhrend-fhrstart))
figpath_gif = figpath[:-4] + '.gif'
plt.savefig(figpath, bbox_inches='tight')
plt.close()
# Convert to gif using imagemagick
sys('convert ' + figpath + ' ' + figpath_gif, shell=True)
rm(figpath)
return None
def ensemble_snow6panel(region, dd):
import os
from scipy import ndimage
from os import remove as rm
from subprocess import call as sys
from datetime import datetime, timedelta
import matplotlib
matplotlib.use('agg')
import matplotlib.pyplot as plt
import matplotlib.image as mimage
from mpl_toolkits.basemap import Basemap, maskoceans
# Other very nice styles available. See the docs
plt.style.use('classic')
print('Plotting Snow 6-panel for %s'%region)
# Gather the metadata needed
init_time = dd['init']
fx_len = int(fhrend)-int(fhrstart)
# Crop the desired region
lons, lats = dd['lon'].values, dd['lat'].values
minlon, maxlon, minlat, maxlat = map_regions[region]
# Initialize the figure frame
fig = plt.figure(num=None, figsize=(11.0*scale,8.0*scale), dpi=300*scale,
facecolor='w', edgecolor='k')
# Customize the subplots
fig.subplots_adjust(top=0.89, bottom=0.02, left=0.055,
right=0.99, hspace=0.1*scale, wspace=0.22)
plt.suptitle(('{} Downscaled QPF/Snow ({:d} members) Initialized {}\n' +
'{:d}-{:d}-h Forecast Valid {} to {}').format(
ensemble.upper(),
dd['mcount'],
dd['init'].strftime('%HZ %Y-%m-%d'),
fhrstart, fhrend,
dd['init'].strftime('%HZ %Y-%m-%d'),
(dd['init'] + timedelta(
hours=fx_len)).strftime(
'%HZ %Y-%m-%d')), fontsize=14)
# Initialize the basemap object
bmap = Basemap(
llcrnrlon=minlon-0.01,
llcrnrlat=minlat-0.01,
urcrnrlon=maxlon+0.01,
urcrnrlat=maxlat+0.01,
resolution='i',
# Project as 'aea', 'lcc', or 'mill'
projection='mill')
# Project the lat/lon grid
x, y = bmap(lons, lats)
# Types of plots to draw
plottype = (['mqpf', 'mean'] +
['prob_' + str(threshold)
for threshold in snowthresh])
# Titles for the plots (indexes must align with above)
titles = ['Ensemble Mean %d-hr Accum Precip'%fx_len,
'Ensemble Mean %d-hr Accum Snow'%fx_len,
'Prob of %d-hr Snow > %s" (%%)'%(fx_len, snowthresh[0]),
'Prob of %d-hr Snow > %s" (%%)'%(fx_len, snowthresh[1]),
'Prob of %d-hr Snow > %s" (%%)'%(fx_len, snowthresh[2]),
'Prob of %d-hr Snow > %s" (%%)'%(fx_len, snowthresh[3])]
# Painstakingly placed colorbars...
cbar_axes = [[0.01,0.52,0.012,0.32],
[0.34,0.52,0.012,0.32],
[0.67,0.52,0.012,0.32],
[0.01,0.08,0.012,0.32],
[0.34,0.08,0.012,0.32],
[0.67,0.08,0.012,0.32]]
# Painstakingly placed logo...
logo = mimage.imread(scriptdir + '../Ulogo_400p.png')
bot, top, left = .05, 0.505, 0.245
axs_water = [[left, top, .065, .11],
[left+0.332, top, .065, .11],
[left+0.664, top, .065, .11],
[left, bot, .065, .11],
[left+0.332, bot, .065, .11],
[left+0.664, bot, .065, .11]]
# If choosing to plot elevation contours
if plot_elevation == True:
zsmooth, zint = elev_smoothing[region]
# Contour interval
zlevs = np.arange(0, 4500+.01, zint)
# Smoothing parameters
efold = (res_ensemble/zsmooth) / res_prism + 1
sigma = efold / (np.pi*np.sqrt(2))
# Smooth the terrain DEM as desired
z = ndimage.filters.gaussian_filter(
get_elev(dd[plottype[0]]),
sigma, mode='nearest')
# List to store the colorbar data
cbd = []
for i in range(6):
# Basemap likes explicit subplots
ax = plt.subplot(2,3,i+1)
ax.set_title(titles[i], fontsize=11)
bmap.drawcoastlines(linewidth=1.0, color='black')
bmap.drawcountries(linewidth=0.85, color='black')
bmap.drawstates(linewidth=1.25, color='black')
# Choose the appropriate colormaps and levels for the plot
# Edit these in colortables.py
if plot_elevation == True:
bmap.contour(x, y, z,
levels=zlevs, colors='black', alpha=0.75, linewidths=1)
if 'prob' in plottype[i]:
levs, norml, cmap, tickloc, ticks = (problevs, probnorml,
probcmap, problevloc,
probticks)
else:
if 'qpf' in plottype[i]:
levs, norml, cmap, tickloc, ticks = (qpflevs, qpfnorml,
qpfcmap, qpflevloc, qpfticks)
else:
levs, norml, cmap, tickloc, ticks = (snowlevs, snownorml,
snowcmap, snowlevloc,
snowticks)
# Mask the oceans, inlands=False to prevent masking lakes (e.g. GSL)
data_lsmask = maskoceans(lons, lats, dd[plottype[i]], inlands=False)
# Allow for precip beyond the maximum contourf
extend = 'max' if 'prob' not in plottype[i] else 'neither'
cbd.append(bmap.contourf(x, y, data_lsmask, extend=extend,
levels=levs, norm=norml,
cmap=cmap, alpha=0.90))
# Manually establish the colorbar
cax = fig.add_axes(cbar_axes[i])
cbar = plt.colorbar(cbd[i], cax=cax, orientation='vertical')
cbar.set_ticks(tickloc)
cbar.set_ticklabels(ticks)
cbar.ax.tick_params(size=0)
cbytick_obj = plt.getp(cbar.ax.axes, 'yticklabels')
plt.setp(cbytick_obj, fontsize=8*scale, rotation=0)
# Add the U watermark
ax_water = fig.add_axes(axs_water[i])
ax_water.axis('off')
ax_water.imshow(logo, aspect='auto', zorder=10, alpha=0.40)
# Determine the max precip in the visible frame
ld = dd[plottype[i]]
if 'prob' not in plottype[i]:
ld_mask = xr.where(
((minlat <= ld.lat) & (ld.lat <= maxlat)) &
((minlon <= ld.lon) & (ld.lon <= maxlon)), ld, np.nan)
localmax = ld_mask.max()
xlon, xlat = np.where(ld_mask == localmax)
# Mark the max precip in the frame with an 'x' (Off for now)
# Basemap is improperly placing the lat lon point... why?
# xx, yy = x[xlon, xlat], y[xlon, xlat]
# bmap.scatter(xx, yy, marker='x', c='k', s=100)
ax.set_xlabel('Max: {:.02f} in ({:.02f}, {:.02f})'.format(
localmax.values,
lats[xlon, xlat][0], lons[xlon, xlat][0]), fontsize=8*scale)
elif ((i == 4) & (plot_elevation == True)):
# Annotate the bottom of the plot to explain the elevation contour
ax.set_xlabel('Elevation (Gray Contours) Every 1000 m',
fontsize=8*scale)
# Save the file according to previous convention
date = init_time.strftime('%Y%m%d')
dateH = init_time.strftime('%Y%m%d%H')
figdir = mkdir_p(imgdir + '%s/images/models/%s/'%(date, ensemble))
figpath = figdir + '{}PS_{}{}F{:03d}.png'.format(
ensemble.upper(), region, dateH, int(fhrend-fhrstart))
figpath_gif = figpath[:-4] + '.gif'
plt.savefig(figpath, bbox_inches='tight')
plt.close()
# Convert to gif using imagemagick
sys('convert ' + figpath + ' ' + figpath_gif, shell=True)
rm(figpath)
return None | {"/wxdisco.py": ["/funcs.py", "/config.py", "/plotfuncs.py"], "/plotfuncs.py": ["/funcs.py", "/config.py", "/colortables.py"], "/funcs.py": ["/config.py", "/colortables.py"], "/colortables.py": ["/config.py"]} |
78,637 | m-wessler/wxdisco-tools | refs/heads/master | /funcs.py | import gc
import numpy as np
import xarray as xr
from config import *
from colortables import *
def mkdir_p(ipath):
from os import makedirs, path
import errno
try:
makedirs(ipath)
except OSError as exc: # Python >2.5
if exc.errno == errno.EEXIST and path.isdir(ipath):
pass
else:
raise
return ipath
def bytes2human(n):
''' http://code.activestate.com/recipes/578019 '''
symbols = ('K', 'M', 'G', 'T', 'P', 'E', 'Z', 'Y')
prefix = {}
for i, s in enumerate(symbols):
prefix[s] = 1 << (i + 1) * 10
for s in reversed(symbols):
if n >= prefix[s]:
value = float(n) / prefix[s]
return '%.1f%s' % (value, s)
return "%sB" % n
def get_init(req_time=None):
from sys import exit
from datetime import datetime, timedelta
if req_time is not None:
try:
mostrecent = datetime.strptime(req_time, '%Y%m%d%H')
except:
print('Invalid time requested, please enter as YYYYMMDDHH')
exit()
else:
qinit = datetime.utcnow() - timedelta(hours=delay)
qinitH = qinit.hour
inits = naefs_inits if ensemble == 'naefs' else sref_inits
mostrecent = None
for i in inits:
if qinitH >= i:
mostrecent = qinit.strftime('%Y%m%d') + str(i)
mostrecent = datetime.strptime(mostrecent, '%Y%m%d%H')
break
if mostrecent is None:
# When hour outside of the above cases, must catch exception
mostrecent = ((qinit - timedelta(days=1)).strftime('%Y%m%d')
+ str(inits[0]))
mostrecent = datetime.strptime(mostrecent, '%Y%m%d%H')
return mostrecent
def get_grids(init_time):
from os import path, stat, remove
from multiprocessing import Pool, cpu_count, get_context
from datetime import datetime
dateH = init_time.strftime('%Y%m%d%H')
date = init_time.strftime('%Y%m%d')
gribdir = mkdir_p(tmpdir + '%s/models/%s/'%(date, ensemble))
dl_list = []
dl_start = datetime.utcnow()
for i, model in enumerate(models):
for j in range(mcount):
# Add future support for other model downloads here
if ensemble == 'sref':
if j == 0:
member = model + '_ctl'
elif j <= (mcount-1)/len(models):
member = model + '_n%i'%j
elif j > (mcount-1)/len(models):
member = model + '_p%i'%(j-((mcount-1)/len(models)))
elif ensemble == 'naefs':
if j == 0:
member = model + '_c00'
else:
member = model + '_p%02d'%j
for fhr in range(fhrstart, fhrend+1, fhrstep):
uuname = '%s%sF%02i.grib2'%(dateH, member, fhr)
checkfile = gribdir + uuname
# Check if file exists
if (path.isfile(checkfile)):
pass
# Check for valid filesize (junk data)
if (stat(checkfile).st_size < minsize):
# If not, download grids to disk
dl_list.append([init_time, fhr, member, checkfile])
remove(checkfile)
else:
pass
else:
# If not, download grids to disk
dl_list.append(
[init_time, fhr, member, checkfile, dl_start])
# Since most of the download verification is now happening within
# the worker pool, this isn't actually being utilized as a while loop
# should right now. Can either finish setting this up to only delete a
# sucessful return from the list or remove the loop entirely...
# though leaving as-is is not a problem either.
while len(dl_list) > 0:
cores = len(dl_list) if len(dl_list) < cpu_count()-1 else cpu_count()-1
if mpi_limit is not None:
cores = cores if cores <= mpi_limit else mpi_limit
print('Downloading %i files on %i cores'%(len(dl_list), cores))
with get_context(spawntype).Pool(cores) as p:
post_dl_list = p.map(download_grib, dl_list)
p.close()
p.join()
[dl_list.remove(dl) for dl in post_dl_list]
del post_dl_list
print('Found all files for %s %s'%(ensemble, init_time))
return None
def download_grib(params):
# Download the desired model run and verify
import urllib.request
from sys import exit
from time import sleep
from datetime import datetime
from os import remove, stat, path
from subprocess import call
date = params[0].strftime('%Y%m%d')
ihr = params[0].hour
fhr = params[1]
family = params[2].split('_')[0]
member = params[2].split('_')[1]
fpath = params[3]
start_time = params[4]
# Add future support for other model downloads here
# Use NCDC NOMADS filterscripts
# http://nomads.ncep.noaa.gov/
if ensemble == 'sref':
base = ('https://nomads.ncep.noaa.gov/cgi-bin/' +
'filter_sref_132.pl?file=sref')
mid = '_{}.t{:02d}z.pgrb132.{}.f{:02d}.grib2'.format(
family, ihr, member, fhr)
webdir = '&dir=%2Fsref.{}%2F{:02d}%2Fpgrb'.format(date, ihr)
elif ensemble == 'naefs':
if family == 'gefs':
base = 'https://nomads.ncep.noaa.gov/cgi-bin/filter_gens_0p50.pl'
mid = '?file=ge{}.t{:02d}z.pgrb2a.0p50.f{:03d}'.format(
member, ihr, fhr)
webdir = '&dir=%2Fgefs.{}%2F{:02d}%2Fpgrb2ap5'.format(date, ihr)
elif family == 'cmce':
base = 'https://nomads.ncep.noaa.gov/cgi-bin/filter_cmcens.pl'
mid = '?file=cmc_ge{}.t{:02d}z.pgrb2a.0p50.f{:03d}'.format(
member, ihr, fhr)
webdir = '&dir=%2Fcmce.{}%2F{:02d}%2Fpgrb2ap5'.format(date, ihr)
mvars = '&var_APCP=on&var_HGT=on&var_TMP=on&var_RH=on'
mlevs = ('&lev_500_mb=on&lev_700_mb=on&lev_850_mb=on' +
'&lev_925_mb=on&lev_1000_mb=on&lev_surface=on')
subset = ('&subregion=&leftlon={}&rightlon={}'.format(
minlon, maxlon) + '&toplat={}&bottomlat={}'.format(
maxlat, minlat))
url = base + mid + mvars + mlevs + subset + webdir
# Download the grib to disk
while not path.isfile(fpath):
try:
urllib.request.urlretrieve(url, fpath)
except OSError:
# Sometimes urllib struggles. Before totally giving up, try this
# the old fashioned way first...
curlcommand = 'curl -s -m {} -o {} {}'.format(timeout, fpath, url)
call(curlcommand, shell=True)
try:
fsize = stat(fpath).st_size
except:
print('FILE NOT FOUND Data not yet available. Waiting',
wait, 'seconds...')
else:
if (fsize > minsize):
pass
else:
print('FSIZE ERROR JUNK FILE Data not yet available. Waiting',
wait, 'seconds...')
remove(fpath)
sleep(wait)
now = datetime.utcnow()
if ((now-start_time).days >= 1
or (now-start_time).seconds > killtime * 3600):
exit()
return params
def gen_paths(init_time):
from glob import glob
from os import remove
dateH = init_time.strftime('%Y%m%d%H')
date = init_time.strftime('%Y%m%d')
# Purge preexisting index files if any exist and start fresh
try:
idxpaths = glob(tmpdir + '%s/models/%s/%s*.idx'%(
date, ensemble, dateH))
[remove(idx) for idx in idxpaths]
except:
pass
else:
print('\nRemoved preexisting index files')
# Read in the data files [one member at a time]
member_paths = list()
for i, model in enumerate(models):
for j in range(mcount):
# Add future support for other model downloads here
if ensemble == 'sref':
if j == 0:
member = model + '_ctl'
elif j <= (mcount-1)/len(models):
member = model + '_n%i'%j
elif j > (mcount-1)/len(models):
member = model + '_p%i'%(j-((mcount-1)/len(models)))
elif ensemble == 'naefs':
if j == 0:
member = model + '_c00'
else:
member = model + '_p%02d'%j
# Adapt this for init time
member_paths.append([member, np.sort(glob(tmpdir +
'%s/models/%s/%s%s*.grib2'%(date, ensemble, dateH, member)))])
return member_paths
def openmfd(paths, lset, cdim):
""" Dask-free """
# paths[0] gives the member name
# paths[1] gives a list of filepaths by hour
# Open each forecast hour as a dataset...
datasets = [xr.open_dataset(
path, engine='cfgrib', #concat_dim=cdim,
backend_kwargs={"filter_by_keys":{"typeOfLevel":lset}})
for path in paths[1]]
if ( (ensemble == 'naefs') & (lset == 'surface') ):
# Fix the silly issue where CMCE calls tp unknown
tp = 'unknown' if 'cmce' in str(paths[1]) else 'tp'
# The NAEFS doesn't include a tp field at hour 0
# We don't need orog so just swap it for tp with zeros
datasets[0] = datasets[0].rename({'orog':tp})
datasets[0][tp].values = np.zeros(datasets[0][tp].shape)
#...then concatenate them into a single member dataset
dataset = xr.concat(datasets, dim=cdim)
dataset = dataset.assign_coords(member_id=paths[0])
if ( ('cmce' in str(paths[1])) & (lset == 'surface') ):
dataset = dataset.rename({'unknown':'tp'})
# ARW comes in as a total accumulated precip to fhr
# Deconstruct into 3-hour precip to match the NMB
if ((lset == 'surface') & ('arw' in paths[0])):
print("Deconstructing %s from accumulated to step precip"%paths[0])
arw_tp = np.zeros(dataset.tp.shape)
arw_tp[0,:,:] = dataset.tp[0,:,:]
for i in range(1, arw_tp.shape[0]):
arw_tp[i,:,:] = dataset['tp'][i,:,:] - dataset['tp'][i-1,:,:]
dataset['tp'].values = arw_tp
# Clean up the coordinate names a bit
if lset == 'surface':
del dataset['surface']
elif lset == 'isobaricInhPa':
dataset = dataset.rename({'isobaricInhPa':'level'})
del dataset['step'], dataset['time']
return dataset
def concat_clean_xarray(xarr_split, cdim):
xarr = xr.concat(xarr_split, dim=cdim)
xarr = xarr.rename(
{'number':'member', 'latitude':'lat', 'longitude':'lon'})
xarr['lon'] -= 360
# Fix member number (otherwise cyclic 0 to mcount)
xarr.member.values = np.arange(1, xarr.member.size+1)
# Swap the 'valid_time' coordinate for 'time' (which is just init)
# xarr = xarr.assign_coords(time=xarr.valid_time.values)
# del xarr['valid_time'], xarr['step']
xarr = xarr.rename({'valid_time':'time'})
return xarr
def interpolate_prism_daily(doy, year, bounds):
from netCDF4 import Dataset
from datetime import datetime
""" Interpolates monthly PRISM totals to a daily total. Assumes the 15th
(14th for February) is most representative of the month.
## Parameters
doy: The day of year as an int
year: The year with century as a int
bounds: A tuple containing boundaries of the domain as indices of
the PRISM grid. In order xmin, xmax, ymin, ymax.
prism_dir: The directory the PRISM files are in
## Returns
pclimo: A 2D grid representing a monthly PRISM total were that month
centered around doy
Alex Weech
"""
# Unpack the bounds
xmin, xmax, ymin, ymax = bounds
# List of centers of each month
prism_day = [15] * 12
prism_day[1] = 14
# Convert doy and year to a datetime object
date = datetime.strptime(str(doy) + '-' + str(year), '%j-%Y')
# Simple case of it being the center day
center = prism_day[date.month-1]
if date.day == center:
prism_path = prism_dir + '/us_' + date.strftime('%m') + '_prcp.nc'
with Dataset(prism_path, 'r') as prism_cd:
pclimo = prism_cd.variables['prcp'][0, :, xmin:xmax]
pclimo = np.flipud(pclimo)[ymin:ymax, :]
# Else interpolate the two closest months
else:
# Check which side of center today is
if date.day > center:
month1 = date.month
year_wrap, month2 = divmod(date.month + 1, 12)
if month2 == 0:
year_wrap = 0
month2 = 12
centdt1 = datetime(int(year), month1, center)
centdt2 = datetime(int(year) + year_wrap, month2,
prism_day[month2 - 1])
weight1 = (date - centdt1).days / (centdt2 - centdt1).days
weight2 = (centdt2 - date).days / (centdt2 - centdt1).days
# Else today is before the center
else:
month1 = date.month
year_wrap, month2 = divmod(date.month - 1, 12)
if month2 == 0:
year_wrap = -1
month2 = 12
centdt1 = datetime(int(year), month1, center)
centdt2 = datetime(int(year) + year_wrap, month2,
prism_day[month2 - 1])
weight1 = (centdt1 - date).days / (centdt1 - centdt2).days
weight2 = (date - centdt2).days / (centdt1 - centdt2).days
# Open the two files
file1 = prism_dir + '/us_' + str(month1).zfill(2) + '_prcp.nc'
file2 = prism_dir + '/us_' + str(month2).zfill(2) + '_prcp.nc'
with Dataset(file1, 'r') as prism_cd:
pclimo1 = prism_cd.variables['prcp'][0, :, xmin:xmax]
pclimo1 = np.flipud(pclimo1)[ymin:ymax, :]
with Dataset(file2, 'r') as prism_cd:
pclimo2 = prism_cd.variables['prcp'][0, :, xmin:xmax]
pclimo2 = np.flipud(pclimo2)[ymin:ymax, :]
# Interpolate
pclimo = weight1 * pclimo1 + weight2 * pclimo2
return pclimo
def downscale_prism(init_time, forecast_time):
import warnings
warnings.filterwarnings("ignore")
from scipy import ndimage
from pandas import to_datetime
from datetime import datetime, timedelta
# Get the PRISM lats and lons from a sample file
print('Getting PRISM lats and lons')
prism = xr.open_dataset(prism_dir + 'us_05_prcp.nc', decode_times=False)
# Get boundary max and mins using full domain
xmin = np.max(np.argwhere(prism['lon'].values < -125))
xmax = np.min(np.argwhere(prism['lon'].values > -100))
ymin = np.max(np.argwhere(prism['lat'][::-1].values < 30))
ymax = len(prism['lat'].values) - 1 # Go all the way up
bounds = (xmin, xmax, ymin, ymax)
# Subset and mesh
grid_lons, grid_lats = np.meshgrid(
prism['lon'][xmin:xmax], prism['lat'][::-1][ymin:ymax])
# Figure out which days are in this run and put them in a set
print('Getting PRISM climo')
date_set = set()
for i in range(fhrstart, fhrend+1, fhrstep):
hour_time = init_time + timedelta(hours=i)
day_of_year = int(hour_time.strftime('%j'))
date_set.add((day_of_year, hour_time.year))
# Smoothing algebra
efold = res_ensemble * 2 / res_prism + 1
sigma = efold / (np.pi*np.sqrt(2))
# Loop through the days of this run gathering the climo ratios
ratios = list()
for day in date_set:
pclimo = interpolate_prism_daily(day[0], day[1], bounds)
# Clip out the missing data
fixed_prism = np.where(np.logical_and(np.greater(pclimo, 0),
np.isfinite(pclimo)), pclimo, 0)
# Wyndham's algorithim
print('Downscaling PRISM for day of year: {}'.format(
datetime.strptime(str(day[0]),'%j').strftime('%m/%d')))
# Create an image smoothed to the model resolution
smooth_prism = ndimage.filters.gaussian_filter(fixed_prism, sigma,
mode='nearest')
smooth_prism = np.where(np.logical_and(np.greater(smooth_prism, 0),
np.isfinite(smooth_prism)),
smooth_prism, 0)
# Divide the real data by the smoothed data to get ratios
ratios.append([np.where(np.logical_and(np.greater(smooth_prism, 0),
np.greater(fixed_prism, 0)),
fixed_prism/smooth_prism, 0), day[0]])
# Sort the prism data back into days (was produced as an unordered set)
ratios = np.array(ratios)
ratios = ratios[np.argsort(ratios[:,1].astype(int))]
prism_doy = ratios[:,1]
prism_data = np.array([x for x in ratios[:,0]])
# Shape into an xarray for easy manipulation
# Can also save with .to_netcdf if desired
prism_climo = xr.DataArray(prism_data,
coords={"time":("time", prism_doy),
"lat":(("y", "x"), grid_lats),
"lon":(("y", "x"), grid_lons)},
dims=["time", "y", "x"])
# Do some clipping (Based on Trevor's limits)
# Not present in old SREF code, added by MW 01/2019
prism_climo = xr.where(prism_climo < minclip, minclip, prism_climo)
prism_climo = xr.where(prism_climo > maxclip, maxclip, prism_climo)
return prism_climo
def get_elev(prism_grid):
# Load the elevation DEM
# Terrainfile is set in config.py
dem = xr.open_dataset(terrainfile)
dem = dem.rename({'latitude':'lat', 'longitude':'lon'})
demlats = dem['lat']
demlons = dem['lon']
final_lats = prism_grid.lat.values
final_lons = prism_grid.lon.values
# As trevor noted, the DEM isn't a perfect match --
# Need to find something better
xmin = np.where(demlons == demlons.sel(
lon=final_lons.min(), method='ffill').values)[0][0]
xmax = np.where(demlons == demlons.sel(
lon=final_lons.max(), method='bfill').values)[0][0]+1
ymin = np.where(demlats == demlats.sel(
lat=final_lats.min(), method='ffill').values)[0][0]
ymax = np.where(demlats == demlats.sel(
lat=final_lats.max(), method='bfill').values)[0][0]
bounds = (xmin, xmax, ymin, ymax)
elev = dem['elevation'][ymin:ymax, xmin:xmax]
dem.close()
elevxr = xr.DataArray(elev.values,
coords={"lat":(("y", "x"), final_lats),
"lon":(("y", "x"), final_lons)},
dims=["y", "x"], name='elev')
return elevxr
def calctw(_t, _rh):
import warnings
warnings.filterwarnings("ignore")
""" Trevor Alcott """
_tw = (-5.806 + 0.672*(_t-0.006*_t**2 +
(0.61 + 0.004*_t + 0.000099*_t**2) *
_rh + (-0.000033 - 0.000005*_t -
0.0000001*_t**2)*_rh**2))
return xr.where(_tw > _t, _t, _tw)
def calcwbz(_tw, _gh):
import warnings
warnings.filterwarnings("ignore")
from xarray.ufuncs import logical_and
wbz = []
for i in range(_tw.level.size)[:0:-1]:
# Hi is 'prior' level
levLO = _tw.level[i-1]
levHI = _tw.level[i]
twLO = _tw.isel(level=i-1)
twHI = _tw.isel(level=i)
ghLO = _gh.isel(level=i-1)
ghHI = _gh.isel(level=i)
print('Searching for WBZ between %d and %d hPa'%(levHI, levLO))
twdiff = twLO / (twLO - twHI)
wbzh = ghLO * twdiff + ghHI * (1 - twdiff)
select = logical_and(twHI < 0., twLO > 0.)
wbzi = xr.where(select, wbzh, np.nan)
wbz.append(wbzi)
return xr.concat(wbz, dim='level').sum(dim='level')
def calct500(_t, _gh, topo):
# Geo Height - Surface Elev + 500 m
# Gives Geo Heights ABOVE GROUND LEVEL + 500 m buffer
gh_agl = (_gh - (topo + 500.0)).compute()
# Where this is zero, set to 1.0
gh_agl = xr.where(gh_agl == 0.0, 1.0, gh_agl)
# If the 1000mb height is > 0, use the 1000 mb temperature to start
# Otherwise assign t=0
tvals = xr.where(gh_agl.sel(level=1000) > 0, _t.sel(level=1000), 0) # - 273.15, 0)
for i in range(_t.level.size)[:0:-1]:
# current level
lc = _t.level.isel(level=i).values
zc = gh_agl.isel(level=i)
tc = _t.isel(level=i)# - 273.15
# level above (correct for 'wraparound')
up = i+1 if i+1 < _t.level.size else 0
lup = _t.level.isel(level=up).values
zup = gh_agl.isel(level=up)
tup = _t.isel(level=up)# - 273.15
# level below
ldn = _t.level.isel(level=i-1).values
zdn = gh_agl.isel(level=i-1)
tdn = _t.isel(level=i-1)# - 273.15
# print(i, lc, lup, ldn)
# Where the geo height AGL > 0 at this level and geo height AGL < 0 at level below...
tvals = xr.where(((zc > 0.0) & (zdn < 0.0)),
# Do this
( ( zc / ( zc - zup ) ) * ( tup - tc ) + tc ),
# Else use tvals already determined
tvals )
tvals = xr.where(gh_agl.sel(level=500) < 0, _t.sel(level=500), tvals)
return tvals
def calc_slr(t500, wbz, elev):
''' Sometimes the old fashioned way of doing things is still the best way.
Sticking to Trevor's stepwise method which is a little slower but produces
a reliable result.'''
import warnings
warnings.filterwarnings("ignore")
snowlevel = wbz - allsnow
snowlevel = xr.where(snowlevel < 0., 0., snowlevel)
initslr = xr.where(t500 < 0., 5. - t500, 5.)
initslr = xr.where(t500 < -15., 20. + (t500 + 15.), initslr)
initslr = xr.where(t500 < -20., 15., initslr)
slr = xr.where(elev >= snowlevel, initslr, 0.)
slr = xr.where(
((elev < snowlevel) & (elev > (snowlevel - melt))),
(initslr * (elev - (snowlevel - melt)) / melt), slr)
return slr
def gridfunc(lrdata, lrxy, hrxy):
from scipy.interpolate import griddata
hrdata = griddata(lrxy, lrdata.values.flatten(), hrxy,
method='linear', fill_value=0)
hrxr = xr.DataArray(hrdata,
coords={"lat":(("y", "x"), hrxy[1]),
"lon":(("y", "x"), hrxy[0])},
dims=["y", "x"])
return hrxr
# Do not use... Xarray builds entire netcdf in memory and then dumps
# Extremely memory inefficient.
# def downscale_calc_slr(lr_swapfile, hr_swapfile, iterp_mode='linear'):
# from os import remove
# from datetime import datetime
# from functools import partial
# from pickle import loads as pl
# from pandas import to_datetime
# ''' The real meat and potatoes. '''
# lr = pl(np.load(lr_swapfile))
# hr = pl(np.load(hr_swapfile))
# dst = datetime.utcnow()
# mid = lr.member_id.values
# print('Processing member %s'%mid)
# # Reshape the PRISM array from days to forecast hours
# forecast_time = lr.time.values
# forecast_doy = to_datetime(forecast_time).strftime('%j').astype(int)
# prism_ratios = hr.prism.sel(time=forecast_doy)
# prism_ratios['time'].values = forecast_time
# # Set up the low res and hi res xy lat lon arrays
# if ensemble == 'naefs':
# lrlon, lrlat = np.meshgrid(lr.lon.values, lr.lat.values)
# lrxy = (lrlon.flatten(), lrlat.flatten())
# elif ensemble == 'sref':
# lrxy = (lr.lon.values.flatten(), lr.lat.values.flatten())
# hrxy = (hr.lon.values, hr.lat.values)
# gridwrap = partial(gridfunc, lrxy=lrxy, hrxy=hrxy)
# slrst = datetime.utcnow()
# # Broadcast the elevation to appropriate dimensions...
# # There's a bug in xr.where() and it fails to do so properly
# # Submit to github if feeling nice and want to spare others' suffering
# elev3d = np.broadcast_to(hr.elev.values, (prism_ratios.shape))
# # Downscale t500, wbz
# hrt500 = lr.t500.groupby('time').apply(gridwrap)
# del lr['t500']
# hrwbz = lr.wbz.groupby('time').apply(gridwrap)
# del lr['wbz']
# gc.collect()
# # print('Downscaled SLR variables for member %s'%mid)
# # Save all vars in dict for easy selection of which to save
# # Modify in config file only
# data = {}
# data['slr'] = calc_slr(hrt500, hrwbz, elev3d)
# data['slr'] = xr.where(data['slr'] < 0., 0., data['slr'])
# del hrt500, hrwbz, elev3d
# gc.collect()
# # print('Calculated SLR for member {} in {}s'.format(
# # mid, (datetime.utcnow()-slrst).seconds))
# # Downscale the QPF
# hrqpf = lr.qpf.groupby('time').apply(gridwrap)
# data['dqpf'] = hrqpf * prism_ratios.values
# # print('Downscaled QPF for member %s'%mid)
# del lr['qpf'], prism_ratios, hrqpf, hr
# gc.collect()
# data['dqpf'] /= 25.4 # mm to inches
# data['dqpf'] = xr.where(data['dqpf'] < 0., 0., data['dqpf'])
# # Create the hi res downscaled snow grids
# data['snow'] = data['dqpf'] * data['slr']
# data['snow'] = xr.where(data['snow'] < 0., 0., data['snow'])
# # print('Downscaled snow for member %s'%mid)
# # Cumulative sum the dqpf and snow grids to obtain plumes
# # Easier to save the per-step precip to file and construct later
# # Rather than save the accumulated. Huge memory drain otherwise.
# # data['acc_dqpf'] = data['dqpf'].cumsum(dim='time')
# # data['acc_snow'] = data['snow'].cumsum(dim='time')
# # Set which variables are saved in config.py
# # print('Saving member %s to netCDF4...'%mid)
# saveset = xr.Dataset({k:data[k] for k in output_vars})
# # The metadata is getting lost in the upsample regrid, fix here
# saveset['member'] = lr.member.values
# saveset['member_id'] = lr.member_id.values
# # Follow prior directory and naming conventions!
# inittime = to_datetime(lr.time[0].values)
# date = inittime.strftime('%Y%m%d')
# dateH = inittime.strftime('%Y%m%d%H')
# # Write netcdf to temp for speed
# ncpath = mkdir_p(tmpdir + '%s/models/%s/%s/'%(date, ensemble, dateH))
# filename = '{}_{}_downscaled.nc'.format(dateH, lr.member_id.values)
# filepath = ncpath + filename
# saveset.to_netcdf(filepath,
# format=ncformat)
# print('Member {} completed at {} in {}s total'.format(
# mid, datetime.utcnow(),
# (datetime.utcnow() - dst).seconds))
# del lr
# remove(lr_swapfile)
# return None
def downscale_calc_slr_chunked(lr_swapfile, hr_swapfile, iterp_mode='linear'):
from os import remove
from datetime import datetime
from functools import partial
from pickle import loads as pl
from pandas import to_datetime
''' The real meat and potatoes. '''
_lr = pl(np.load(lr_swapfile))
hr = pl(np.load(hr_swapfile))
dst = datetime.utcnow()
mid = _lr.member_id.values
inittime = to_datetime(_lr.time[0].values)
date = inittime.strftime('%Y%m%d')
dateH = inittime.strftime('%Y%m%d%H')
tsize = _lr.time.size
print('Processing member %s'%mid)
for i, lr in enumerate(_lr.groupby('time')):
# print('Processing forecast valid {}'.format(to_datetime(lr[0])))
forecast_time = [lr[0]]
lr = lr[1]
# Reshape the PRISM array from days to forecast hours
forecast_doy = to_datetime(forecast_time).strftime('%j').astype(int)
prism_ratios = hr.prism.sel(time=forecast_doy)
prism_ratios['time'].values = forecast_time
# Set up the low res and hi res xy lat lon arrays
if ensemble == 'naefs':
lrlon, lrlat = np.meshgrid(lr.lon.values, lr.lat.values)
lrxy = (lrlon.flatten(), lrlat.flatten())
elif ensemble == 'sref':
lrxy = (lr.lon.values.flatten(), lr.lat.values.flatten())
hrxy = (hr.lon.values, hr.lat.values)
gridwrap = partial(gridfunc, lrxy=lrxy, hrxy=hrxy)
hrt = xr.concat([gridwrap(lr.t.isel(level=l))
for l in range(lr.level.size)],
dim='level').assign_coords(
level = lr.t.level.values)
hrgh = xr.concat([gridwrap(lr.gh.isel(level=l))
for l in range(lr.level.size)],
dim='level').assign_coords(
level = lr.t.level.values)
# Downscale t500, wbz
hrt500 = calct500(hrt, hrgh, hr.elev)
del hrt, hrgh, lr['t'], lr['gh'], lr['level']
gc.collect()
hrwbz = gridwrap(lr.wbz)
del lr['wbz']
gc.collect()
# Save all vars in dict for easy selection of which to save
# Modify in config file only
data = {}
data['slr'] = calc_slr(hrt500, hrwbz, hr.elev.values)
data['slr'] = xr.where(data['slr'] < 0., 0., data['slr'])
del hrt500, hrwbz
gc.collect()
# Downscale the QPF
hrqpf = gridwrap(lr.qpf)
prism_ratios = prism_ratios.isel(time=0)
data['dqpf'] = hrqpf * prism_ratios.values
del lr['qpf'], prism_ratios, hrqpf
gc.collect()
data['dqpf'] /= 25.4 # mm to inches
data['dqpf'] = xr.where(data['dqpf'] < 0., 0., data['dqpf'])
# Create the hi res downscaled snow grids
data['snow'] = data['dqpf'] * data['slr']
data['snow'] = xr.where(data['snow'] < 0., 0., data['snow'])
# Cumulative sum the dqpf and snow grids to obtain plumes
# Easier to save the per-step precip to file and construct later
# Rather than save the accumulated. Huge memory drain otherwise.
# data['acc_dqpf'] = data['dqpf'].cumsum(dim='time')
# data['acc_snow'] = data['snow'].cumsum(dim='time')
# Set which variables are saved in config.py
# print('Saving member %s to netCDF4...'%mid)
saveset = xr.Dataset({k:data[k] for k in output_vars})
# The metadata is getting lost in the upsample regrid, fix here
saveset['member'] = lr.member.values
saveset['member_id'] = lr.member_id.values
# Follow prior directory and naming conventions!
# Write netcdf to temp for speed
ncpath = mkdir_p(tmpdir + '%s/models/%s/%s/'%(date, ensemble, dateH))
filename = '{}_{}_downscaled.nc'.format(dateH, lr.member_id.values)
filepath = ncpath + filename
saveset = saveset.expand_dims('time').assign_coords(
time = forecast_time)
# Write new file or append timestemp depending...
if to_datetime(forecast_time) == inittime:
build_netCDF(saveset, i, tsize, dateH, filepath, 'w')
else:
build_netCDF(saveset, i, tsize, dateH, filepath, 'a')
print('Member {} completed at {} in {}s total'.format(
mid, datetime.utcnow(),
(datetime.utcnow() - dst).seconds))
del lr
remove(lr_swapfile)
return None
def build_netCDF(xarr, i, tsize, init, fpath, mode):
from datetime import datetime
from pandas import to_datetime
from netCDF4 import Dataset, date2num
''' A custom netCDF writer since xarray's doesn't properly append files '''
with Dataset(fpath, mode, format=ncformat) as dataset:
if mode == 'w':
dataset.description = ('Downscaled {} QPF/Snow Grids ' +
'Init {} UTC'.format(ensemble.upper(), init))
dataset.history = 'Created {}'.format(datetime.utcnow())
dataset.source = 'University of Utah - Steenburgh Research Group'
x = dataset.createDimension('x', xarr.x.size)
y = dataset.createDimension('y', xarr.y.size)
t = dataset.createDimension('time', tsize)
ts = dataset.createVariable('time',
'double', ('time',), fill_value=np.nan)
#ts.calendar = 'gregorian'
ts.units = 'datetime64' #'hours since 0001-01-01 00:00:00'
ts.standard_name = 'time'
ts.long_name = 'time'
ts.CoordinateAxisType = 'Time'
lat = dataset.createVariable('lat',
np.float32, ('y', 'x'), fill_value=np.nan)
lat.CoordinateAxisType = 'Lat'
lat.units = 'degrees_north'
lon = dataset.createVariable('lon',
np.float32, ('y', 'x'), fill_value=np.nan)
lon.CoordinateAxisType = 'Lon'
lon.units = 'degrees_east'
m = dataset.createVariable('member', 'double')
mid = dataset.createVariable('member_id', 'U10')
# datenum = date2num(
# to_datetime(xarr.time[0].values),
# units=ts.units, calendar=ts.calendar)
ts[i] = xarr.time.values
lat[:, :] = xarr.lat.values
lon[:, :] = xarr.lon.values
m[0] = xarr.member.values
mid[:] = xarr.member_id.values
vardat = {}
varunits = {'dqpf':'inches', 'snow':'inches', 'slr':'ratio'}
for var in output_vars:
vardat[var] = dataset.createVariable(
var, np.float32, ('time', 'y', 'x'), fill_value=np.nan)
vardat[var].coordinates = ('lon lat member member_id')
vardat[var].units = varunits[var]
vardat[var][i, :, :] = xarr[var].values
elif mode == 'a':
dataset.variables['time'][i] = xarr.time.values
for var in output_vars:
dataset.variables[var][i, : :] = xarr[var].values
return None
def dump2swap(xarr, hires, init_time):
from glob import glob
from os import path
from pickle import dumps as pd
print('Dumping to swapfiles on temp as needed')
# Check if any members already exist, we don't need to waste time
# recreating them.
dateH = init_time.strftime('%Y%m%d%H')
date = init_time.strftime('%Y%m%d')
tflist = []
tmppath = mkdir_p(tmpdir + '%s/models/%s/%s/'%(date, ensemble, dateH))
for mno, mid in zip(xarr.member.values, xarr.member_id.values):
checkfile_archive = tmpdir + '%s/models/%s/%s/%s_%s_downscaled.nc'%(
date, ensemble, dateH, dateH, mid)
# If the file exists in temp, it will be copied later. If the
# file already exists in archive, leave it there and the rest will join
if path.isfile(checkfile_archive):
pass
else:
# Otherwise, save a swapfile for a worker to operate on
# and add to list
tmpfile = tmppath + '%s_swap.npy'%mid
np.save(tmpfile, pd(xarr.sel(member=mno).compute(), protocol=-1))
tflist.append(tmpfile)
if len(tflist) > 0:
hrswapfile = tmppath + 'hires_swap.npy'
np.save(hrswapfile, pd(hires.compute()))
else:
hrswapfile = None
xarr.close()
del xarr
gc.collect()
return tflist, hrswapfile
def check_nc_exists(init_time, checkwhere='temp'):
from os import path, stat
dateH = init_time.strftime('%Y%m%d%H')
date = init_time.strftime('%Y%m%d')
ncfound = []
for i, model in enumerate(models):
for j in range(mcount):
# Add future support for other model downloads here
if ensemble == 'sref':
if j == 0:
member = model + '_ctl'
elif j <= (mcount-1)/len(models):
member = model + '_n%i'%j
elif j > (mcount-1)/len(models):
member = model + '_p%i'%(j-((mcount-1)/len(models)))
elif ensemble == 'naefs':
if j == 0:
member = model + '_c00'
else:
member = model + '_p%02d'%j
if checkwhere == 'temp':
checkfile = tmpdir + '%s/models/%s/%s/%s_%s_downscaled.nc'%(
date, ensemble, dateH, dateH, member)
elif checkwhere == 'archive':
checkfile = datadir + '%s/models/%s/%s/%s_%s_downscaled.nc'%(
date, ensemble, dateH, dateH, member)
# Consider removing this... sometimes an unfinished file
# is big enough to pass the test... better to just recreate it
if path.isfile(checkfile):
if stat(checkfile).st_size > ncminsize:
ncfound.append(True)
else:
ncfound.append(False)
else:
ncfound.append(False)
if (np.where(np.array(ncfound) == False)[0].size) == 0:
print('Found complete downscaled %s for %s in %s'%(
ensemble, dateH, checkwhere))
return True
else:
return False
def nccopy(ncpath):
from subprocess import call as sys
cp_command = 'nccopy -d {} {:s} {:s}'.format(
complevel, ncpath[0], ncpath[1])
sys(cp_command, shell=True)
return None
def gribcopy(gribpath):
from subprocess import call as sys
# While I'm aware there is a pythonic copy function, it does
cp_command = 'cp {:s} {:s}'.format(gribpath[0], gribpath[1])
sys(cp_command, shell=True)
return None
def temp2archive(init_time, remove_temp=True):
from glob import glob
from os import remove as rm
from multiprocessing import Pool, cpu_count
dateH = init_time.strftime('%Y%m%d%H')
date = init_time.strftime('%Y%m%d')
ncdir = mkdir_p(datadir + '%s/models/%s/%s/'%(
date, ensemble, dateH))
nc_temp = glob(tmpdir + '%s/models/%s/%s/%s*.nc'%(
date, ensemble, dateH, dateH))
nc_archive = [(ncdir + f.split('/')[-1]) for f in nc_temp]
nc_paths = [[t, f] for t, f in zip(nc_temp, nc_archive)]
if len(nc_temp) > 0:
print('Compressing/Copying netCDF files from temp to archive')
with Pool(cpu_count()-1) as p:
p.map(nccopy, nc_paths, chunksize=1)
p.close()
p.join()
if copy_gribs:
gribdir = mkdir_p(datadir + '%s/models/%s/'%(date, ensemble))
grib_temp = glob(tmpdir + '%s/models/%s/%s*.grib2'%(
date, ensemble, dateH))
grib_archive = [(gribdir + f.split('/')[-1]) for f in grib_temp]
grib_paths = [[t, f] for t, f in zip(grib_temp, grib_archive)]
if len(grib_temp) > 0:
print('Copying grib files from temp to archive')
with Pool(cpu_count()-1) as p:
p.map(gribcopy, grib_paths, chunksize=1)
p.close()
p.join()
else:
grib_temp = glob(tmpdir + '%s/models/%s/%s*.grib2'%(
date, ensemble, dateH))
# Clean up the temp files if desired
if remove_temp:
# Note that check_nc_exists returns FALSE if any netcdf files missing
if check_nc_exists(init_time, checkwhere='archive'):
print('NetCDF files copied, removing from temp')
[rm(f) for f in nc_temp]
else:
print('Error copying netCDF files, did not delete. Check temp!')
grib_check = glob(datadir + '%s/models/%s/%s*.grib2'%(
date, ensemble, dateH))
if len(grib_temp) == len(grib_check):
print('Removing grib files from temp')
[rm(f) for f in grib_temp]
grib_idx = glob(tmpdir + '%s/models/%s/%s*.idx'%(
date, ensemble, dateH))
[rm(f) for f in grib_idx]
return None | {"/wxdisco.py": ["/funcs.py", "/config.py", "/plotfuncs.py"], "/plotfuncs.py": ["/funcs.py", "/config.py", "/colortables.py"], "/funcs.py": ["/config.py", "/colortables.py"], "/colortables.py": ["/config.py"]} |
78,638 | m-wessler/wxdisco-tools | refs/heads/master | /colortables.py | import numpy as np
from matplotlib import colors
from config import ensemble
if ensemble == 'naefs':
# NAEFS-specific colortables
()
elif ensemble == 'sref':
# SREF-specific colortables
()
qpflevs = [.01, .02, .05, .10, .25, .50, .75, 1, 2, 3, 5, 10, 20]
qpfticks = [str(x) for x in qpflevs]
#gnbuylrd (Tri Color)
# qpfcolors = ['#ffffff','#a3a3a3','#92d28f','#3ca659',
# '#006d2c','#c1f0f0','#8ec1dd','#3d8cc3',
# '#ffe672','#ffc63b','#ff9a13','#ff5232','#ff0000']
#gnylrd (Bi Color)
# qpfcolors = ['#ffffff','#c3c3c3','#898989','#84a281','#77c37d',
# '#349c51','#006d2c','#d9d266','#ffd14f','#ffb029',
# '#ff8522','#ff4a2b','#ff0000']
qpfcolors = ['#ffffff','#c3c3c3','#898989','#84a281','#77c37d',
'#349c51','#006d2c','#c8df00','#ffff00','#ffd100',
'#ffa100','#ff6c00','#ff0000']
qpflevloc = qpflevs
qpfcmap = colors.ListedColormap(qpfcolors[:-1], name='qpfmap')
qpfcmap.set_over(qpfcolors[-1])
qpfnorml = colors.BoundaryNorm(qpflevs, len(qpfcolors)-1, clip=False)
# SNOW (inches)
# Ticks to break the color at
snowlevs = [.5, 1, 3, 6, 12, 18, 24, 36, 48, 60, 120]
# Which values to actually label (can differ from levs)
snowticks = [str(x) for x in snowlevs]
snowcolors = ['#ffffff','#d3d3d3','#a9a9a9','#abd9e9','#74add1','#4575b4',
'#313695','#e2c5df','#a2529f','#5f0f5f','#240f23']
snowlevloc = snowlevs
snowcmap = colors.ListedColormap(snowcolors[:-1], name='snowmap')
snowcmap.set_over(snowcolors[-1])
snownorml = colors.BoundaryNorm(snowlevs, len(snowcolors)-1)
# Probability
problevs = np.arange(-5, 105.1, 10)
probticks = ['%d'%p for p in np.arange(0, 100.1, 10)] + ['']
probcolors = ['#a50026','#d73027','#f46d43','#fdae61','#313695','#4575b4',
'#74add1','#abd9e9','#A9A9A9','#D3D3D3','#ffffff'][::-1] # Diverging WhBuRd
problevloc = problevs+5
probcmap = colors.ListedColormap(probcolors, name='probmap')
probnorml = colors.BoundaryNorm(problevs, len(probcolors))
if __name__ == '__main__':
import matplotlib.pyplot as plt
a=np.outer(np.arange(0,1,0.01),np.ones(10)).T
fig, ax = plt.subplots(3, 1, facecolor='w', figsize=(10, 6))
ax[0].imshow(a, aspect='auto', cmap=qpfcmap, origin="lower")
ax[0].set_title('QPF')
ax[1].imshow(a, aspect='auto', cmap=snowcmap, origin="lower")
ax[1].set_title('SNOW')
ax[2].imshow(a, aspect='auto', cmap=probcmap, origin="lower")
ax[2].set_title('PROBABILITY')
plt.show() | {"/wxdisco.py": ["/funcs.py", "/config.py", "/plotfuncs.py"], "/plotfuncs.py": ["/funcs.py", "/config.py", "/colortables.py"], "/funcs.py": ["/config.py", "/colortables.py"], "/colortables.py": ["/config.py"]} |
78,639 | m-wessler/wxdisco-tools | refs/heads/master | /config.py | # Which config file am I?
# Available: ['naefs', 'sref']
ensemble = 'sref'
##########
# mpi
##########
# Number of cores to limit to (overrides all else)
# If None, memory limits still enforced
mpi_limit = None
# Pool worker chunksize
chunksize = 1
# Pool worker spawn method for downscaling jobs
# ['fork', 'forkserver', 'spawn']
spawntype = 'fork'
# Virtual memory needed for pool workers
# Approx 3.2 GB @ 0-87-3
mem_need = 3.2e9
##########
# paths
##########
# Full chpc path
chpcpath = ('/uufs/chpc.utah.edu/sys/pkg/ldm/' +
'oper/models/sref/')
# Parent grib/netCDF file directory
datadir = ('/uufs/chpc.utah.edu/common/home/horel-group/' +
'archive/')
# Parent grib/netCDF temp file directory
# Set tmpdir = datadir if not using a temp dir
tmpdir = ('/scratch/general/lustre/ldm/rt/')
# Image output directory
imgdir = datadir
# USA terrain file
terrainfile = chpcpath + 'usterrain.nc'
# PRISM files
prism_dir = chpcpath + 'prism/'
# Main script directory
scriptdir = chpcpath + 'scripts/'
# Save the .grib2 files?
copy_gribs = True
###############
# Output files
###############
# Variables to save to netCDF: *(required for plotting)
# {*slr, *dqpf, *snow}
output_vars = ['slr', 'dqpf', 'snow']
# Filetype options
# http://xarray.pydata.org/en/stable/generated/xarray.Dataset.to_netcdf.html
# for notes on compatibility
# Format {‘NETCDF4’, ‘NETCDF4_CLASSIC’, ‘NETCDF3_64BIT’, 'NETCDF3_CLASSIC’}
ncformat = 'NETCDF4'
# Set compression 1-9, with 9 being the smallest file but
# greatest write time (or use None)
complevel = 9
#################
# ensemble options
#################
# Model init hours to check for
sref_inits = [21, 15, 9, 3]
# Model families
models = ['arw', 'nmb']
# Number of members in each model family
mcount = 13
# Hours to process
# fhrstart must remain 0 but
# fhrend, fhrstep are mutable
fhrstart = 0
fhrend = 87
fhrstep = 3
# Spatial subset to grab from NOMADS
# use -180 <= lon <= 180
minlon = -130
maxlon = -100
minlat = 30
maxlat = 50
##################
# Download options
##################
# Reject file if it comes in smaller than X bytes (default 10 kb)
minsize = 10000
# When checking for existing ncfile, min size allowed
# 300 mb would still be smaller than using complevel 9
# in almost all cases
ncminsize = 3e8
# Curl command timeout limit (sec)
timeout = 60
# Don't try to download a new run until X
# hours after init time (may use decimal e.g. 4.5)
delay = 4
# wait time between attempts (sec)
# when data is not yet available
wait = 30
# stop the get function X hours after it starts
# prevents multiple runs downloading at once
killtime = 3
############################
# physics/algorithm options
############################
# Resolution of PRISM in km
res_prism = 0.8
# Resolution of model in km
res_ensemble = 16.0
# Max and min multiplier for QPF downscaling
minclip = 0.3
maxclip = 5.0
# SLR Params
allsnow = 150
melt = 300
# # # # # # # # # # # #
# Plotting Options
# # # # # # # # # # # #
# Figures to produce [True or False]
make_maps = True
make_plumes = True
# Scale is relative to Trevor's old figures
# (made higher res to handle terrain contours and rich colormap)
scale = 1.25
# Plot the elevation contours [True or False]
plot_elevation = False
# (A) How much to smooth the DEM (factor 1-10)
# Low values = smoother terrain, high values = finer detail
# (B) Contour interval, in meters
# Enter dictionary item as {region:(A, B)}
elev_smoothing = {'UT':(3, 1000),
'WM':(3, 1000),
'CO':(3, 1000),
'SN':(3, 1000),
'WE':(2, 1000),
'NW':(3, 1000),
'NU':(6, 500)}
# Thresholds to use for the probability plots (inches)
qpfthresh = [0.01, 1, 2]
snowthresh = [1, 6, 12, 24]
point_locs = {
'KSLC':(40.77, -111.97), 'CLN':(40.57, -111.65),
'MTMET':(40.766605, -111.828325), 'PCB':(40.65, -111.52),
'CLK':(40.67, -111.57), 'PKCU1':(40.6, -111.57),
'SNI':(41.2, -111.87), 'BLPU1':(41.38, -111.94),
'TRLU1':(40.68, -110.95), 'DVO':(40.621, -111.496),
'PWD':(41.37, -111.76), 'SND':(40.37, -111.6),
'BSK':(45.27, -111.45), 'TOWC2':(40.55, -106.67),
'CACMP':(40.52, -105.90), 'CABTP':(39.8, -105.77),
'TUNEP':(39.67, -105.9), 'VAILP':(39.52, -106.22),
'MONAP':(38.5, -106.32), 'CAMCP':(39.12, -107.27),
'CARED':(37.9, -107.72), 'CAGMS':(39.05, -108.07),
'CACBP':(37.7, -107.77), 'CAWCP':(37.47, -106.8),
'CUMC2':(37.02, -106.45), 'SNO':(47.42, -121.41),
'CSSL':(39.33, -120.37), 'TGLU1':(41.90, -111.57),
'SRAC1':(38.32, -119.60), 'SEE':(39.312, -111.429),
'MSA':(37.65, -119.04), 'MTB':(48.86, -121.68),
'STV':(47.75, -121.09), 'CMT':(46.93, -121.47),
'PRS':(46.79, -121.74), 'QUI':(47.47, -123.85),
'TIM':(45.33, -121.71), 'MBB':(44.0, -121.66),
'MSB':(41.36, -122.20), 'SQV':(39.2, -120.24),
'TTSID':(43.86,-114.71), 'JHRV':(43.59, -110.87),
'LSMU1':(38.48,-109.27),
#NEW#
'WDYPK':(40.84148,-111.02062), 'PCCAT':(40.7904494,-111.1053804),
'STORM':(40.455111, -106.74428), 'SVSID':(43.6612, -114.4121),
'ASBTP':(35.32581, -111.68559), 'MBNCA':(34.274425, -117.610439),
'BBEAR':(34.212482, -116.867175), 'TAONM':(36.57443, -105.45328),
'BASI1':(44.306003, -115.231829), 'LPSI1':(46.63448, -114.58072),
'BKSI1':(44.62642, -115.79370)
}
point_names = {
'KSLC':'Salt Lake City Intl. Airport, UT',
'CLN':'Alta Collins, UT',
'MTMET':'UofU Mountain Met Lab, UT',
'PCB':'Park City Mountain Resort Base, UT',
'DVO':'Deer Valley Ontario, UT',
'SND':'Sundance Mountain Resort, UT',
'VAILP':'Vail Pass, CO',
'JHRV':'Jackson Hole Rendezvous Bowl, WY',
'CSSL':'Central Sierra Snow Lab, CA',
'SEE':'Seely Creek Manti Skyline, UT',
'STORM':'Storm Peak Lab',
'SVSID':'Sun Valley Study Plot',
'WDYPK':'Windy Peak Uintas',
'PCCAT':'Park City Powder Cats',
'PKCU1':'Brighton Crest',
'BLPU1':'Ben Lomond Peak',
'ASBTP':'Arizona Snow Bowl Top Patrol',
'MBNCA':'Mount Baldy Notch CA',
'BBEAR':'Big Bear CA',
'TAONM':'Taos Ski Valley, NM',
'BASI1':'Banner Summit ID',
'BKSI1':'Big Creek Summit ID',
'LPSI1':'Lolo Pass ID'
}
# Region Boundaries (minlat, matlat, minlon, maxlon)
map_regions = {
#'FULL':(-125, -100, 30, 50),
'UT':(-114.7, -108.5, 36.7, 42.5),
'WM':(-117, -108.5, 43, 49),
'CO':(-110, -104, 36, 41.9),
'SN':(-123.5, -116.0, 33.5, 41),
'WE':(-125, -102.5, 31.0, 49.2),
'NW':(-125, -116.5, 42.0, 49.1),
'NU':(-113.4, -110.7, 39.5, 41.9),
} | {"/wxdisco.py": ["/funcs.py", "/config.py", "/plotfuncs.py"], "/plotfuncs.py": ["/funcs.py", "/config.py", "/colortables.py"], "/funcs.py": ["/config.py", "/colortables.py"], "/colortables.py": ["/config.py"]} |
78,647 | LordAmit/mobile-monkey | refs/heads/master | /run_monkey_only.py | import time
import subprocess
import util
import api_commands
import emulator_manager
import config_reader as config
from apk import Apk
import mobile_monkey
from telnet_connector import TelnetAdb
from adb_logcat import Logcat, TestType
from log_analyzer import Analyzer
def run(apk: Apk, emulator_name: str, emulator_port: int):
'''
runs only monkey
'''
api_commands.adb_start_server_safe()
mobile_monkey.start_emulator()
emulator = emulator_manager.get_adb_instance_from_emulators(
config.EMULATOR_NAME)
# api_commands.adb_uninstall_apk(emulator, apk)
# api_commands.adb_install_apk(emulator, apk)
api_commands.adb_start_launcher_of_apk(emulator, apk)
log = Logcat(emulator, apk, TestType.Monkey)
log.start_logcat()
telnet_connector = TelnetAdb(config.LOCALHOST, emulator.port)
print("Monkey started at: {}".format(time.ctime()))
subprocess.check_call([
config.adb, 'shell', 'monkey',
'-p', apk.package_name,
'--throttle', config.MONKEY_INTERVAL,
'-s', str(config.SEED),
'-v', '-v', '-v',
str(config.DURATION)])
print("Monkey stopped at: {}".format(time.ctime()))
api_commands.adb_stop_activity_of_apk(emulator, apk)
log.stop_logcat()
analyzer = Analyzer(log.file_address)
print(analyzer)
api_commands.adb_uninstall_apk(emulator, apk)
# telnet_connector.kill_avd()
# emulator_manager.emulator_wipe_data(emulator)
if __name__ == '__main__':
run(Apk(config.APK_FULL_PATH), config.EMULATOR_NAME, config.EMULATOR_PORT)
| {"/run_monkey_only.py": ["/util.py", "/api_commands.py", "/emulator_manager.py", "/config_reader.py", "/apk.py", "/mobile_monkey.py", "/telnet_connector.py", "/adb_logcat.py", "/log_analyzer.py"], "/adb_monkey.py": ["/config_reader.py", "/api_commands.py", "/emulator.py", "/apk.py", "/adb_settings.py", "/emulator_manager.py", "/adb_logcat.py"], "/log_analyzer.py": ["/util.py"], "/kill_emulator.py": ["/emulator_manager.py"], "/fuzz_context.py": ["/adb_logcat.py", "/emulator.py", "/adb_settings.py", "/mutex.py", "/telnet_connector.py", "/config_reader.py", "/interval_event.py"], "/interval_event.py": ["/adb_settings.py", "/telnet_connector.py", "/util.py", "/config_reader.py"], "/apk.py": ["/util.py", "/config_reader.py"], "/adb_settings.py": ["/config_reader.py", "/api_commands.py", "/util.py"], "/config_reader.py": ["/util.py"], "/api_commands.py": ["/config_reader.py", "/util.py", "/emulator.py", "/apk.py"], "/monkey.py": ["/config_reader.py", "/adb_logcat.py", "/apk.py", "/emulator.py", "/fuzz_context.py", "/adb_settings.py", "/telnet_connector.py", "/interval_event.py"], "/mobile_monkey.py": ["/config_reader.py", "/emulator_manager.py", "/api_commands.py", "/telnet_connector.py", "/emulator.py", "/fuzz_context.py", "/adb_settings.py", "/util.py", "/adb_monkey.py", "/apk.py", "/adb_logcat.py", "/log_analyzer.py"], "/adb_logcat.py": ["/api_commands.py", "/config_reader.py", "/emulator.py", "/apk.py"], "/telnet_connector.py": ["/config_reader.py", "/util.py"], "/install_app.py": ["/config_reader.py", "/emulator_manager.py", "/api_commands.py", "/telnet_connector.py", "/emulator.py", "/fuzz_context.py", "/adb_settings.py", "/util.py", "/adb_monkey.py", "/apk.py", "/adb_logcat.py", "/log_analyzer.py"], "/mobicomonkey.py": ["/config_reader.py", "/emulator.py", "/api_commands.py", "/apk.py", "/emulator_manager.py", "/xml_element.py", "/adb_settings.py", "/telnet_connector.py", "/util.py", "/monkey.py", "/adb_logcat.py", "/mutex.py", "/adb_monkey.py"], "/contextConfig_reader.py": ["/config_reader.py"], "/emulator_manager.py": ["/emulator.py", "/config_reader.py", "/contextConfig_reader.py", "/api_commands.py", "/util.py"], "/test.py": ["/api_commands.py", "/emulator_manager.py", "/config_reader.py", "/apk.py", "/adb_logcat.py", "/telnet_connector.py", "/adb_monkey.py", "/emulator.py", "/fuzz_context.py", "/adb_settings.py", "/interval_event.py"]} |
78,648 | LordAmit/mobile-monkey | refs/heads/master | /xml_element.py | from typing import Union
class XML_Element:
'''This class contains element attributes'''
def __init__(self, resource_id: str, element_class: str, checkable: str,
checked: str, clickable: str, enabled: str, focusable: str,
focused: str, scrollable: str, long_clickable: str,
password: str, selected: str, xpos: Union[float, int],
ypos: Union[float, int]) ->\
None:
self.resource_id = resource_id
self.element_class = element_class
self.checkable = checkable
self.checked = checked
self.clickable = clickable
self.enabled = enabled
self.focusable = focusable
self.focused = focused
self.scrollable = scrollable
self.long_clickable = long_clickable
self.password = password
self.selected = selected
self.xpos = xpos
self.ypos = ypos
def __str__(self) -> str:
# return "[event_type: {}, step: {}, interval: {}, event: {}]".format(
# self.event_type, self.step, self.interval, self.event)
return "{}".format(
self.resource_id)
__repr__ = __str__
| {"/run_monkey_only.py": ["/util.py", "/api_commands.py", "/emulator_manager.py", "/config_reader.py", "/apk.py", "/mobile_monkey.py", "/telnet_connector.py", "/adb_logcat.py", "/log_analyzer.py"], "/adb_monkey.py": ["/config_reader.py", "/api_commands.py", "/emulator.py", "/apk.py", "/adb_settings.py", "/emulator_manager.py", "/adb_logcat.py"], "/log_analyzer.py": ["/util.py"], "/kill_emulator.py": ["/emulator_manager.py"], "/fuzz_context.py": ["/adb_logcat.py", "/emulator.py", "/adb_settings.py", "/mutex.py", "/telnet_connector.py", "/config_reader.py", "/interval_event.py"], "/interval_event.py": ["/adb_settings.py", "/telnet_connector.py", "/util.py", "/config_reader.py"], "/apk.py": ["/util.py", "/config_reader.py"], "/adb_settings.py": ["/config_reader.py", "/api_commands.py", "/util.py"], "/config_reader.py": ["/util.py"], "/api_commands.py": ["/config_reader.py", "/util.py", "/emulator.py", "/apk.py"], "/monkey.py": ["/config_reader.py", "/adb_logcat.py", "/apk.py", "/emulator.py", "/fuzz_context.py", "/adb_settings.py", "/telnet_connector.py", "/interval_event.py"], "/mobile_monkey.py": ["/config_reader.py", "/emulator_manager.py", "/api_commands.py", "/telnet_connector.py", "/emulator.py", "/fuzz_context.py", "/adb_settings.py", "/util.py", "/adb_monkey.py", "/apk.py", "/adb_logcat.py", "/log_analyzer.py"], "/adb_logcat.py": ["/api_commands.py", "/config_reader.py", "/emulator.py", "/apk.py"], "/telnet_connector.py": ["/config_reader.py", "/util.py"], "/install_app.py": ["/config_reader.py", "/emulator_manager.py", "/api_commands.py", "/telnet_connector.py", "/emulator.py", "/fuzz_context.py", "/adb_settings.py", "/util.py", "/adb_monkey.py", "/apk.py", "/adb_logcat.py", "/log_analyzer.py"], "/mobicomonkey.py": ["/config_reader.py", "/emulator.py", "/api_commands.py", "/apk.py", "/emulator_manager.py", "/xml_element.py", "/adb_settings.py", "/telnet_connector.py", "/util.py", "/monkey.py", "/adb_logcat.py", "/mutex.py", "/adb_monkey.py"], "/contextConfig_reader.py": ["/config_reader.py"], "/emulator_manager.py": ["/emulator.py", "/config_reader.py", "/contextConfig_reader.py", "/api_commands.py", "/util.py"], "/test.py": ["/api_commands.py", "/emulator_manager.py", "/config_reader.py", "/apk.py", "/adb_logcat.py", "/telnet_connector.py", "/adb_monkey.py", "/emulator.py", "/fuzz_context.py", "/adb_settings.py", "/interval_event.py"]} |
78,649 | LordAmit/mobile-monkey | refs/heads/master | /adb_monkey.py | '''
adb monkey interface
'''
import subprocess
import time
import config_reader as config
import api_commands
from emulator import Emulator
from apk import Apk
PRINT_FLAG = False
class AdbMonkey:
'''
AdbMonkey executes the monkey adb tool
'''
adb = config.adb
def __init__(self, emulator: Emulator, apk: Apk, seed: int,
number_of_events: int)-> None:
api_commands.adb_start_server_safe()
if seed > 500 or seed < 0:
raise ValueError("seed must be within the range of 0 to 500")
if number_of_events > 4200 or number_of_events < 10:
raise ValueError(
"number of events must be at least 10 seconds and at most 4200")
# adb shell pm list packages | grep com.ebooks.ebookreader
self.number_of_events = number_of_events
self.seed = seed
# output = subprocess.check_output(
# [self.adb, 'shell', 'pm', 'list', 'packages', '|', 'grep',
# app_package_name]).decode().strip().split('\r\n')
# util.debug_print(output, len(output), flag=PRINT_FLAG)
output = api_commands.adb_is_package_present(
emulator, apk.package_name)
if output < 1:
raise ValueError("Provided {} not found.".format(apk.package_name))
elif output > 1:
raise ValueError(
"Provided {} is too unspecific," +
" multiple entries found.".format(apk.package_name))
self.app_package_name = apk.package_name
def start_monkey(self):
'''
starts monkey
'''
# adb shell monkey -p com.eatl.appstore -v -v -v -s 314 --throttle
# 1000 100
command = "{} shell monkey -p {} --throttle {} -s {} \
-v -v -v {}".format(
self.adb, self.app_package_name, config.MONKEY_INTERVAL, self.seed,
str(self.number_of_events)
)
print(command)
# subprocess.check_call([
# self.adb, 'shell', 'monkey',
# '-p', self.app_package_name,
# '--throttle', config.MONKEY_INTERVAL,
# # '--pct-touch', '60',
# # '--pct-trackball', '20',
# # '--pct-motion', '20',
# '-s', str(self.seed),
# '-v', '-v', '-v',
# str(self.number_of_events)])
import shlex
subprocess.check_call(shlex.split(command))
print('Monkey finished at: {}'.format(time.ctime()))
def main():
import config_reader as config
from apk import Apk
from adb_settings import AdbSettings
import emulator_manager
from adb_logcat import Logcat, TestType
# print("resetting emulator")
import os
import api_commands
import os
dir = os.path.dirname(__file__)
activity = os.path.join(dir, 'test/activity')
activity_list = os.path.join(dir, 'test/activity_list')
activities = []
apk = Apk(config.APK_FULL_PATH)
emulator = emulator_manager.get_adb_instance_from_emulators(
config.EMULATOR_NAME)
# file = open("test/activity", "w")
file = open(activity, 'w')
file.write(api_commands.adb_get_activity_list(emulator, apk))
file.close()
# file = open('test/activity', 'r')
file = open(activity, 'r')
# file2 = open('test/activity_list', 'w')
file2 = open(activity_list, 'w')
for l in file.readlines():
if 'A: android:name' in l and 'Activity' in l:
arr = l.split('"')
activities.append(arr[1])
file2.write(arr[1] + "\n")
print(arr[1])
file.close()
file2.close()
os.remove('test/activity')
# log = Logcat(emulator, apk, TestType.MobileMonkey)
# log.start_logcat()
AdbMonkey(emulator, apk, config.SEED, config.DURATION*10).start_monkey()
# log.stop_logcat()
if __name__ == '__main__':
main()
| {"/run_monkey_only.py": ["/util.py", "/api_commands.py", "/emulator_manager.py", "/config_reader.py", "/apk.py", "/mobile_monkey.py", "/telnet_connector.py", "/adb_logcat.py", "/log_analyzer.py"], "/adb_monkey.py": ["/config_reader.py", "/api_commands.py", "/emulator.py", "/apk.py", "/adb_settings.py", "/emulator_manager.py", "/adb_logcat.py"], "/log_analyzer.py": ["/util.py"], "/kill_emulator.py": ["/emulator_manager.py"], "/fuzz_context.py": ["/adb_logcat.py", "/emulator.py", "/adb_settings.py", "/mutex.py", "/telnet_connector.py", "/config_reader.py", "/interval_event.py"], "/interval_event.py": ["/adb_settings.py", "/telnet_connector.py", "/util.py", "/config_reader.py"], "/apk.py": ["/util.py", "/config_reader.py"], "/adb_settings.py": ["/config_reader.py", "/api_commands.py", "/util.py"], "/config_reader.py": ["/util.py"], "/api_commands.py": ["/config_reader.py", "/util.py", "/emulator.py", "/apk.py"], "/monkey.py": ["/config_reader.py", "/adb_logcat.py", "/apk.py", "/emulator.py", "/fuzz_context.py", "/adb_settings.py", "/telnet_connector.py", "/interval_event.py"], "/mobile_monkey.py": ["/config_reader.py", "/emulator_manager.py", "/api_commands.py", "/telnet_connector.py", "/emulator.py", "/fuzz_context.py", "/adb_settings.py", "/util.py", "/adb_monkey.py", "/apk.py", "/adb_logcat.py", "/log_analyzer.py"], "/adb_logcat.py": ["/api_commands.py", "/config_reader.py", "/emulator.py", "/apk.py"], "/telnet_connector.py": ["/config_reader.py", "/util.py"], "/install_app.py": ["/config_reader.py", "/emulator_manager.py", "/api_commands.py", "/telnet_connector.py", "/emulator.py", "/fuzz_context.py", "/adb_settings.py", "/util.py", "/adb_monkey.py", "/apk.py", "/adb_logcat.py", "/log_analyzer.py"], "/mobicomonkey.py": ["/config_reader.py", "/emulator.py", "/api_commands.py", "/apk.py", "/emulator_manager.py", "/xml_element.py", "/adb_settings.py", "/telnet_connector.py", "/util.py", "/monkey.py", "/adb_logcat.py", "/mutex.py", "/adb_monkey.py"], "/contextConfig_reader.py": ["/config_reader.py"], "/emulator_manager.py": ["/emulator.py", "/config_reader.py", "/contextConfig_reader.py", "/api_commands.py", "/util.py"], "/test.py": ["/api_commands.py", "/emulator_manager.py", "/config_reader.py", "/apk.py", "/adb_logcat.py", "/telnet_connector.py", "/adb_monkey.py", "/emulator.py", "/fuzz_context.py", "/adb_settings.py", "/interval_event.py"]} |
78,650 | LordAmit/mobile-monkey | refs/heads/master | /log_analyzer.py | '''
log analyzer module, has Analyzer class.
xInstantiated by file path of log file
'''
from pathlib import Path
import time
import util
from enum import Enum
from typing import List
class Priority(Enum):
Verbose = 'V'
Debug = 'D'
Info = 'I'
Warning = 'W'
Error = 'E'
Fatal = 'F'
Silent = 'S'
class Log():
'''
Log class is instantiated by single logs generated by Logcat
in `threadtime` format. It cleans the line, and assigns the
proper values to the following properties:
log_time: time
log_pid: str
log_tid: str
log_priority: str
log_tag: str
log_message: str
eg. "06-14 22:08:27.424 2987 3046 W System.err:
at java.lang.Thread.run(Thread.java:761)"
will be used to create:
```
log_time = time.struct_time(tm_year=1900, tm_mon=6, tm_mday=14,
tm_hour=22, tm_min=8, tm_sec=27, tm_wday=3,tm_yday=165, tm_isdst=-1)
log_pid = "2987"
log_tid = "3046"
log_priority = "W"
log_tag = "System.err"
log_message = "at java.lang.Thread.run(Thread.java:761)"
```
'''
def __init__(self, log_line: str, mode: int=None)-> None:
if len(log_line) < 1:
raise ValueError("Error: Empty Line Detected from Log.")
# "06-14 22:08:27.424 2987 3046 W System.err: at java.lang.Thread.run(Thread.java:761) # noqa
log_line_split = log_line.split(' ', maxsplit=8)
current_line = log_line_split[0] + " " + log_line_split[1][:-4]
# print(log_line[1][:-4])
try:
self.log_time = time.strptime(current_line, "%m-%d %H:%M:%S")
except ValueError:
self.log_time = None
self.log_pid = None
self.log_tid = None
self.log_priority = None
self.log_tag = None
self.log_message = None
return None
if mode is 1:
try:
self.log_pid = log_line_split[3]
self.log_tid = log_line_split[5]
self.log_priority = log_line_split[6]
self.log_tag = log_line_split[7]
self.log_message = log_line_split[8].strip().strip(":").strip()
except IndexError:
self.log_time = None
self.log_pid = None
self.log_tid = None
self.log_priority = None
self.log_tag = None
self.log_message = None
return None
if mode is 2:
log_line_split = log_line.split(' ', maxsplit=6)
self.log_pid = log_line_split[2]
self.log_tid = log_line_split[3]
self.log_priority = log_line_split[4]
self.log_tag = log_line_split[5].strip('\t')
self.log_message = log_line_split[6].strip().strip(":").strip()
def __str__(self):
return "{}, {}, {}, {}, {}, {}".format(self.log_time,
self.log_pid,
self.log_tid,
self.log_priority,
self.log_tag,
self.log_message)
__repr__ = __str__
class Analyzer():
'''
Analyzer class, instantiated by file path of log file
when object is returned as string, it gives output in following format:
```
return "Unique Warnings: {}\nUnique Errors: {}\
\nTotal Warnings: \
{}\nTotal Errors: {}\n".format(self.count_unique_warnings,
self.count_unique_errors,
self.count_warnings,
self.count_errors)
```
'''
def __init__(self, file_path):
self.file_path = file_path
if not util.check_file_directory_exists(file_path, False):
raise ValueError("File path does not exist.")
self.file_contents = Path(file_path).read_text().split('\n')
self.unique_warnings = set()
self.all_warnings = list()
self.unique_errors = set()
self.all_errors = list()
self.unique_fatals = set()
self.all_fatals = list()
self.count_warnings = None
self.count_errors = None
self.count_fatals = None
self.count_unique_warnings = None
self.count_unique_errors = None
self.count_unique_fatals = None
self.logs = self.__logfile_to_logs(mode=1)
self.__calculate_stats()
if self.count_errors == 0 and\
self.count_unique_errors == 0 and\
self.count_unique_warnings == 0 and self.count_warnings == 0:
print("something went wrong. recalculating")
self.logs = self.__logfile_to_logs(mode=2)
self.__calculate_stats()
def return_unique_stats(self):
'''
Returns a tuple containing numbers of unique
`(warnings, errors, fatals)`
'''
return (self.count_unique_warnings, self.count_unique_errors,
self.count_unique_fatals)
def __logfile_to_logs(self, mode: int=None) -> List[Log]:
'''
converts logfile entries to a `List[Log]`
'''
log_list = []
for line in self.file_contents:
if len(line) < 1:
continue
if mode is 1:
log_list.append(Log(line, mode))
else:
log_list.append(Log(line, 2))
return log_list
def return_stats(self):
'''
Returns a tuple containing numbers of `(warnings, errors, fatals)`
'''
return (self.count_warnings, self.count_errors, self.count_fatals)
def __calculate_stats(self):
avc_counter = 0
non_jni_counter = 0
text_speech_counter = 0
long_monitor_counter = 0
ad_counter = 0
# failed_load_counter = 0
# time_out_ad = 0
facebook_katana_counter = 0
for log in self.logs:
if log.log_message is None or log.log_pid is None:
continue
if log.log_message.startswith('at ') or\
log.log_message.startswith('*') or\
log.log_message.endswith("more"):
continue
if "avc: denied" in log.log_message.lower():
if avc_counter > 0:
continue
avc_counter += 1
if "long monitor contention" in log.log_message.lower():
if long_monitor_counter > 0:
continue
long_monitor_counter += 1
if "remove non-jni" in log.log_message.lower():
if non_jni_counter > 0:
continue
non_jni_counter += 1
if "texttospeech" in log.log_tag.lower():
if text_speech_counter > 0:
continue
text_speech_counter += 1
# if "failed to load ad" in log.log_message.lower():
# failed_load_counter += 1
# if failed_load_counter > 0:
# continue
# if "timed out waiting for ad response" in log.log_message.lower():# noqa
# time_out_ad += 1
# if time_out_ad > 0:
# continue
if "Ads".lower() is log.log_tag.lower() or(
"MMSDK-PlayList".lower() in log.log_tag.lower()):
if ad_counter > 0:
continue
ad_counter += 1
if "com.facebook.katana.provider.AttributionIdProvider".lower() \
in log.log_message.lower():
if facebook_katana_counter > 0:
continue
facebook_katana_counter += 1
# print(log.log_message)
if "attempted to finish an input event" in log.log_message.lower()\
or "bluetooth" in log.log_message.lower() \
or "dropping event" in log.log_message.lower() \
or "cancelling event" in log.log_message.lower() \
or "discarding hit" in log.log_message.lower():
# print("dropping/cancelling event")
continue
# print(log.log_message)
if log.log_priority is 'E':
self.unique_errors.add(log.log_message)
self.all_errors.append(log.log_message)
if log.log_priority is 'W':
self.unique_warnings.add(log.log_message)
self.all_warnings.append(log.log_message)
if log.log_priority is 'F':
self.unique_fatals.add(log.log_message)
self.all_fatals.append(log.log_message)
self.count_unique_errors = len(self.unique_errors)
self.count_unique_warnings = len(self.unique_warnings)
self.count_unique_fatals = len(self.unique_fatals)
self.count_errors = len(self.all_errors)
self.count_warnings = len(self.all_warnings)
self.count_fatals = len(self.all_fatals)
# for line in self.file_contents:
# if len(line) < 1 or ':' not in line:
# continue
# line = str(line)
# message = line.split(':', maxsplit=1)[1].strip()
# if message.startswith('at '):
# continue
# if line[0] == 'W':
# self.unique_warnings.add(message)
# self.all_warnings.append(message)
# if line[0] == 'E':
# self.unique_errors.add(message)
# self.all_errors.append(message)
# self.count_unique_errors = len(self.unique_errors)
# self.count_unique_warnings = len(self.unique_warnings)
# self.count_errors = len(self.all_errors)
# self.count_warnings = len(self.all_warnings)
def return_file_contents(self) -> List:
'''
returns the contents of the log file in List
'''
return self.file_contents
# def print_file_contents_experimental(self):
# for line in self.file_contents:
# Log(line)
def __str__(self):
return "Total Warnings: {}\nUnique Warnings: {}\
\nTotal Errors: {}\nUnique Errors: {}\
\nTotal Fatals: {}\nUnique Fatals: {}".format(self.count_warnings,
self.count_unique_warnings, # noqa
self.count_errors,
self.count_unique_errors,
self.count_fatals,
self.count_unique_fatals)
| {"/run_monkey_only.py": ["/util.py", "/api_commands.py", "/emulator_manager.py", "/config_reader.py", "/apk.py", "/mobile_monkey.py", "/telnet_connector.py", "/adb_logcat.py", "/log_analyzer.py"], "/adb_monkey.py": ["/config_reader.py", "/api_commands.py", "/emulator.py", "/apk.py", "/adb_settings.py", "/emulator_manager.py", "/adb_logcat.py"], "/log_analyzer.py": ["/util.py"], "/kill_emulator.py": ["/emulator_manager.py"], "/fuzz_context.py": ["/adb_logcat.py", "/emulator.py", "/adb_settings.py", "/mutex.py", "/telnet_connector.py", "/config_reader.py", "/interval_event.py"], "/interval_event.py": ["/adb_settings.py", "/telnet_connector.py", "/util.py", "/config_reader.py"], "/apk.py": ["/util.py", "/config_reader.py"], "/adb_settings.py": ["/config_reader.py", "/api_commands.py", "/util.py"], "/config_reader.py": ["/util.py"], "/api_commands.py": ["/config_reader.py", "/util.py", "/emulator.py", "/apk.py"], "/monkey.py": ["/config_reader.py", "/adb_logcat.py", "/apk.py", "/emulator.py", "/fuzz_context.py", "/adb_settings.py", "/telnet_connector.py", "/interval_event.py"], "/mobile_monkey.py": ["/config_reader.py", "/emulator_manager.py", "/api_commands.py", "/telnet_connector.py", "/emulator.py", "/fuzz_context.py", "/adb_settings.py", "/util.py", "/adb_monkey.py", "/apk.py", "/adb_logcat.py", "/log_analyzer.py"], "/adb_logcat.py": ["/api_commands.py", "/config_reader.py", "/emulator.py", "/apk.py"], "/telnet_connector.py": ["/config_reader.py", "/util.py"], "/install_app.py": ["/config_reader.py", "/emulator_manager.py", "/api_commands.py", "/telnet_connector.py", "/emulator.py", "/fuzz_context.py", "/adb_settings.py", "/util.py", "/adb_monkey.py", "/apk.py", "/adb_logcat.py", "/log_analyzer.py"], "/mobicomonkey.py": ["/config_reader.py", "/emulator.py", "/api_commands.py", "/apk.py", "/emulator_manager.py", "/xml_element.py", "/adb_settings.py", "/telnet_connector.py", "/util.py", "/monkey.py", "/adb_logcat.py", "/mutex.py", "/adb_monkey.py"], "/contextConfig_reader.py": ["/config_reader.py"], "/emulator_manager.py": ["/emulator.py", "/config_reader.py", "/contextConfig_reader.py", "/api_commands.py", "/util.py"], "/test.py": ["/api_commands.py", "/emulator_manager.py", "/config_reader.py", "/apk.py", "/adb_logcat.py", "/telnet_connector.py", "/adb_monkey.py", "/emulator.py", "/fuzz_context.py", "/adb_settings.py", "/interval_event.py"]} |
78,651 | LordAmit/mobile-monkey | refs/heads/master | /kill_emulator.py | '''
a simple script for killing the emulator.
'''
import emulator_manager as emu
emu.kill_emulator() | {"/run_monkey_only.py": ["/util.py", "/api_commands.py", "/emulator_manager.py", "/config_reader.py", "/apk.py", "/mobile_monkey.py", "/telnet_connector.py", "/adb_logcat.py", "/log_analyzer.py"], "/adb_monkey.py": ["/config_reader.py", "/api_commands.py", "/emulator.py", "/apk.py", "/adb_settings.py", "/emulator_manager.py", "/adb_logcat.py"], "/log_analyzer.py": ["/util.py"], "/kill_emulator.py": ["/emulator_manager.py"], "/fuzz_context.py": ["/adb_logcat.py", "/emulator.py", "/adb_settings.py", "/mutex.py", "/telnet_connector.py", "/config_reader.py", "/interval_event.py"], "/interval_event.py": ["/adb_settings.py", "/telnet_connector.py", "/util.py", "/config_reader.py"], "/apk.py": ["/util.py", "/config_reader.py"], "/adb_settings.py": ["/config_reader.py", "/api_commands.py", "/util.py"], "/config_reader.py": ["/util.py"], "/api_commands.py": ["/config_reader.py", "/util.py", "/emulator.py", "/apk.py"], "/monkey.py": ["/config_reader.py", "/adb_logcat.py", "/apk.py", "/emulator.py", "/fuzz_context.py", "/adb_settings.py", "/telnet_connector.py", "/interval_event.py"], "/mobile_monkey.py": ["/config_reader.py", "/emulator_manager.py", "/api_commands.py", "/telnet_connector.py", "/emulator.py", "/fuzz_context.py", "/adb_settings.py", "/util.py", "/adb_monkey.py", "/apk.py", "/adb_logcat.py", "/log_analyzer.py"], "/adb_logcat.py": ["/api_commands.py", "/config_reader.py", "/emulator.py", "/apk.py"], "/telnet_connector.py": ["/config_reader.py", "/util.py"], "/install_app.py": ["/config_reader.py", "/emulator_manager.py", "/api_commands.py", "/telnet_connector.py", "/emulator.py", "/fuzz_context.py", "/adb_settings.py", "/util.py", "/adb_monkey.py", "/apk.py", "/adb_logcat.py", "/log_analyzer.py"], "/mobicomonkey.py": ["/config_reader.py", "/emulator.py", "/api_commands.py", "/apk.py", "/emulator_manager.py", "/xml_element.py", "/adb_settings.py", "/telnet_connector.py", "/util.py", "/monkey.py", "/adb_logcat.py", "/mutex.py", "/adb_monkey.py"], "/contextConfig_reader.py": ["/config_reader.py"], "/emulator_manager.py": ["/emulator.py", "/config_reader.py", "/contextConfig_reader.py", "/api_commands.py", "/util.py"], "/test.py": ["/api_commands.py", "/emulator_manager.py", "/config_reader.py", "/apk.py", "/adb_logcat.py", "/telnet_connector.py", "/adb_monkey.py", "/emulator.py", "/fuzz_context.py", "/adb_settings.py", "/interval_event.py"]} |
78,652 | LordAmit/mobile-monkey | refs/heads/master | /fuzz_context.py | '''
Fuzz contexts - to conduct contextual testing of app
'''
import time
from typing import List, Union, Type
import random
from adb_logcat import FatalWatcher
from emulator import Emulator
from adb_settings import AdbSettings
from adb_settings import UserRotation
from adb_settings import Airplane
from adb_settings import KeyEvent
import mutex
from telnet_connector import TelnetAdb
from telnet_connector import GsmProfile, NetworkDelay, NetworkStatus
import config_reader as config
from interval_event import IntervalEvent
import os
dir = os.path.dirname(__file__)
StopFlagWatcher = os.path.join(dir, 'test/StopFlagWatcher')
ContextEventLog = os.path.join(dir, 'test/ContextEventLog')
PRINT_FLAG = True
EVENT_TYPES = Type[Union[GsmProfile, NetworkDelay,
NetworkStatus, Airplane, UserRotation, KeyEvent]]
class Fuzzer:
'''
Fuzzer Class
'''
# continue_airplane_fuzz = True
# continue_rotation = True
# continue_gsm_profile = True
# continue_network_delay = True
# continue_network_speed = True
def __init__(self, interval_minimum: int,
interval_maximum: int,
seed: int, duration: int,
fatal_watcher: FatalWatcher,
uniform_interval: int = config.UNIFORM_INTERVAL)->None:
'''
`interval_minimum`, `interval_maximum`, `seed`, and `duration`
are all integers.
`interval_minimum`, `interval_maximum`, and `duration`
are in seconds.
'''
if not isinstance(interval_minimum, int):
raise ValueError("interval_minimum must be int")
if not isinstance(interval_maximum, int):
raise ValueError("interval_maximum must be int")
if not isinstance(seed, int):
raise ValueError("seed must be int")
if not isinstance(duration, int):
raise ValueError("duration must be int")
if duration > 4200 or duration < 10:
raise ValueError(
"duration must be at least 10 seconds and at most 500 seconds")
if seed > 500 or seed < 0:
raise ValueError("seed must be within the range of 0 to 500")
self.interval_maximum = interval_maximum
self.interval_minimum = interval_minimum
self.seed = seed
self.duration = int(duration)
self.uniform_interval = int(uniform_interval)
self.fatal_watcher = fatal_watcher
random.seed(self.seed)
# self.__setup_intervals(uniform_interval)
# self.__setup_interval_events()
# def __setup_intervals(self, uniform_interval: int=config.UNIFORM_INTERVAL): # noqa
# '''
# sets up intervals for event types. It configures:
# self.network_delay_interval,
# self.network_speed_interval,
# self.gsm_profile_interval,
# self.airplane_interval,
# self.rotation_interval
# '''
# self.network_delay_interval = self.duration_interval_steps_generator() # noqa
# self.network_speed_interval = self.duration_interval_steps_generator() # noqa
# self.gsm_profile_interval = self.uniform_duration_interval_steps_generator( # noqa
# int(uniform_interval))
# self.airplane_interval = self.duration_interval_steps_generator()
# self.rotation_interval = self.duration_interval_steps_generator()
# def __setup_interval_events(self):
# '''
# sets up events for the following types:
# self.network_delay_events
# self.network_speed_events
# self.gsm_profile_events
# self.airplane_events
# self.rotation_events
# '''
# self.network_delay_events = self.event_per_step_generator(
# self.network_delay_interval, NetworkDelay)
# self.network_speed_events = self.event_per_step_generator(
# self.network_speed_interval, NetworkStatus)
# self.gsm_profile_events = self.event_per_step_generator(
# self.gsm_profile_interval, GsmProfile)
# self.airplane_events = self.event_per_step_generator(
# self.airplane_interval, Airplane)
# self.rotation_events = self.event_per_step_generator(
# self.rotation_interval, UserRotation)
# def print_intervals_events(self):
# '''
# prints intervals with events
# '''
# print("Gsm profile interval: events")
# util.print_dual_list(self.gsm_profile_interval,
# util.list_as_enum_name_list(self.gsm_profile_events, GsmProfile)) # noqa
# print("airplane interval: events")
# util.print_dual_list(self.airplane_interval, util.list_as_enum_name_list(# noqa
# self.airplane_events, Airplane))
# print("Network Delay interval: events")
# util.print_dual_list(self.network_delay_interval,
# util.list_as_enum_name_list(self.network_delay_events, NetworkDelay))# noqa
# print("Rotation interval: events")
# util.print_dual_list(self.rotation_interval, util.list_as_enum_name_list(# noqa
# self.rotation_events, UserRotation))
# print("Network speed interval: events")
# util.print_dual_list(self.network_speed_interval, util.list_as_enum_name_list(# noqa
# self.network_speed_events, NetworkStatus))
def __random_value_generator(self, lower_limit: int, upper_limit: int):
if not isinstance(lower_limit, int):
raise ValueError("lower_limit must be int")
if not isinstance(upper_limit, int):
raise ValueError("upper_limit must be int")
return random.randint(lower_limit, upper_limit)
# def duration_interval_steps_generator(self)->List[int]:
# '''
# returns a List of duration event steps
# '''
# total_duration = self.duration
# cumulative_duration = 0
# intervals = []
# while True:
# interval_step = self.__random_value_generator(
# int(self.interval_minimum), int(self.interval_maximum))
# if (cumulative_duration + interval_step) < total_duration:
# cumulative_duration += interval_step
# intervals.append(interval_step)
# else:
# intervals.append(total_duration - cumulative_duration)
# break
# self.intervals = intervals
# return intervals
# def list_intervalevent_to_IntervalEvent(self,
# list_intervalevent: List[Tuple[int, EVENT_TYPES]], # noqa
# event_type: EVENT_TYPES
# ) -> List[IntervalEvent]:
# # pylint: disable=invalid-name, E1126
# '''
# converts list to IntervalEvent type
# '''
# interval_events = []
# for i in range(0, len(list_intervalevent)):
# entity = IntervalEvent(
# i, list_intervalevent[i][0], list_intervalevent[i][1].name,
# event_type)
# interval_events.append(entity)
# return interval_events
def generate_step_interval_event(self,
event_type: EVENT_TYPES
) -> List[IntervalEvent]:
'''
returns a List of Interval_Event for each step
'''
total_duration = self.duration
cumulative_duration = 0
interval_events = []
step = 0
while True:
interval = self.__random_value_generator(
int(self.interval_minimum), int(self.interval_maximum))
event = self.__random_value_generator(0, len(event_type) - 1)
if (cumulative_duration + interval) < total_duration:
cumulative_duration += interval
interval_events.append(IntervalEvent(
step, interval, event_type(event).name, event_type))
step += 1
else:
interval = total_duration - cumulative_duration
interval_events.append(IntervalEvent(
step, interval, event_type(event).name, event_type))
break
return interval_events
def generate_step_uniforminterval_event(self,
event_type: EVENT_TYPES
) -> List[IntervalEvent]:
'''
returns a List of interval_event for each step
'''
cumulative_duration = 0
interval_events = []
step = 0
while True:
event = self.__random_value_generator(0, len(event_type) - 1)
if cumulative_duration + self.uniform_interval < self.duration:
cumulative_duration += self.uniform_interval
interval_events.append(IntervalEvent(
step, self.uniform_interval,
event_type(event).name, event_type))
step += 1
else:
interval_events.append(IntervalEvent(
step, self.duration - cumulative_duration,
event_type(event).name, event_type))
break
return interval_events
# def uniform_duration_interval_steps_generator(self, uniform_interval: int)->List[int]: # noqa
# '''
# makes uniform interval steps by dividing `total_duration` with
# `uniform_interval`
# '''
# total_duration = self.duration
# intervals = []
# cumulative_duration = 0
# while True:
# if cumulative_duration + uniform_interval < total_duration:
# cumulative_duration += uniform_interval
# intervals.append(uniform_interval)
# else:
# intervals.append(total_duration - cumulative_duration)
# break
# return intervals
# def event_per_step_generator(self,
# intervals: List[int],
# event_type: Union[GsmProfile, NetworkDelay, NetworkStatus])->\ # noqa
# List[Union[GsmProfile, NetworkDelay, NetworkStatus]]:
# event_types = []
# for dummy in intervals:
# event = self.__random_value_generator(
# 0, len(event_type) - 1)
# event_types.append(event)
# return event_types
# def __interval_event_execution(self, method_name, event_type: str,
# intervals, events, enum_type: enum):
# for i in range(0, len(intervals) - 1):
# if PRINT_FLAG:
# print("{} - {}: {}".format(event_type,
# intervals[i], enum_type(events[i]).name))# noqa
# method_name(enum_type(events[i]))
# time.sleep(intervals[i])
def __execute_interval_event(self, method_name,
interval_events: List[IntervalEvent]):
# util.debug_print("Execution: ", interval_events, flag=PRINT_FLAG)
# file = open('test/StopFlagWatcher', 'r')
file = open(StopFlagWatcher, 'r')
for interval_event in interval_events:
if "1" in file.readline(1):
print("Contextual event finished")
break
if self.fatal_watcher.has_fatal_exception_watch():
print("Fatal Exception Detected. Breaking from " +
interval_event.event_type.__name__)
break
# if self.fatal_exception:
# print("fatal crash. Stopping " +
# interval_event.event_type.__name__)
# break
# util.debug_print(interval_event, flag=PRINT_FLAG)
print(interval_event)
# file2 = open("test/ContextEventLog", 'r')
file2 = open(ContextEventLog, 'r')
filedata = file2.read()
# file2 = open("test/ContextEventLog", "w")
file2 = open(ContextEventLog, 'w')
if len(filedata) < 10:
file2.write(IntervalEvent.__str__(interval_event))
else:
file2.write(filedata + "\n" +
IntervalEvent.__str__(interval_event))
file2.close()
method_name(interval_event.event_type[interval_event.event])
time.sleep(interval_event.interval)
# for i in range(0, len(intervals) - 1):
# if PRINT_FLAG:
# print("{} - {}: {}".format(event_type,
# intervals[i], enum_type(events[i]).name))# noqa
# method_name(enum_type(events[i]))
# time.sleep(intervals[i])
def random_airplane_mode_call(self, adb_device: str,
interval_events: List[IntervalEvent] = None):
'''
randomly fuzzes airplane_mode_call for the specified
running virtual device identified by `adb_device`
'''
device = AdbSettings(adb_device)
if interval_events is None:
interval_events = self.generate_step_interval_event(Airplane)
# util.debug_print(interval_events, flag=PRINT_FLAG)
self.__execute_interval_event(
device.set_airplane_mode, interval_events)
# self.__interval_event_execution(
# device.set_airplane_mode, "airplane_mode",
# self.airplane_interval, self.airplane_events, Airplane)
# device.set_airplane_mode(Airplane.MODE_OFF)
def random_key_event(self, adb_device: str,
interval_events: List[IntervalEvent]=None):
'''
random fuzz of random key events
and KeyEvent type IntervalEvent
'''
device = AdbSettings(adb_device)
if interval_events is None:
interval_events = self.generate_step_interval_event(KeyEvent)
self.__execute_interval_event(
device.adb_send_key_event, interval_events)
def random_rotation(self, adb_device: str,
interval_events: List[IntervalEvent] = None):
'''
randomly fuzzes airplane_mode_call for the specified
running virtual device identified by `adb_device`
and UserRotation type IntervalEvent
'''
device = AdbSettings(adb_device)
if interval_events is None:
interval_events = self.generate_step_interval_event(UserRotation)
# self.__interval_event_execution(
# device.set_user_rotation, "rotation_mode",
# self.rotation_interval, self.rotation_events, UserRotation)
# util.debug_print(interval_events, flag=PRINT_FLAG)
# self.__execute_interval_event(
# device.set_user_rotation, interval_events)
# device.set_user_rotation(UserRotation.ROTATION_POTRAIT)
# file = open('test/StopFlagWatcher', 'r')
file = open(StopFlagWatcher, 'r')
for interval_event in interval_events:
if "1" in file.readline(1):
print("Contextual event finished")
break
if self.fatal_watcher.has_fatal_exception_watch():
print("Fatal Exception Detected. Breaking from " +
interval_event.event_type.__name__)
break
# if self.fatal_exception:
# print("fatal crash. Stopping " +
# interval_event.event_type.__name__)
# break
# util.debug_print(interval_event, flag=PRINT_FLAG)
print(interval_event)
file2 = open(ContextEventLog, 'r')
filedata = file2.read()
file2 = open(ContextEventLog, "w")
if len(filedata) < 10:
file2.write(IntervalEvent.__str__(interval_event))
else:
file2.write(filedata + "\n" +
IntervalEvent.__str__(interval_event))
file2.close()
device.set_user_rotation(
interval_event.event_type[interval_event.event])
print("testing rotation manual service")
mutex.ROTATION_MUTEX = 1
print("ROTATION_MUTEX set to 1 for forcing update")
time.sleep(interval_event.interval)
# device.set_user_rotation(UserRotation.ROTATION_POTRAIT)
def random_network_speed(self, host: str, emulator: Emulator,
interval_events: List[IntervalEvent]=None):
'''
randomly fuzzes network speed by `TelnetAdb(host, port)` type object
and NetworkStatus type IntervalEvent
'''
telnet_obj = TelnetAdb(host, emulator.port)
if interval_events is None:
interval_events = self.generate_step_interval_event(NetworkStatus)
# util.debug_print(interval_events, flag=PRINT_FLAG)
# self.__interval_event_execution(
# telnet_obj.set_connection_speed, "network_speed",
# self.network_speed_interval, self.network_speed_events,
# NetworkStatus)
self.__execute_interval_event(
telnet_obj.set_connection_speed, interval_events)
# telnet_obj.reset_network_speed()
def random_network_delay(self, host: str, emulator: Emulator,
interval_events: List[IntervalEvent]=None):
'''
randomly fuzzes network delay by `TelnetAdb(host, port)` type object
and NetworkDelay type IntervalEvent
'''
telnet_obj = TelnetAdb(host, emulator.port)
if interval_events is None:
interval_events = self.generate_step_interval_event(NetworkDelay)
# util.debug_print(interval_events, flag=PRINT_FLAG)
self.__execute_interval_event(
telnet_obj.set_connection_delay, interval_events)
# self.__interval_event_execution(
# telnet_obj.set_connection_delay, "connection_delay",
# self.network_delay_interval, self.network_delay_events, NetworkDelay)
# telnet_obj.reset_network_delay()
def random_gsm_profile(self, host: str, emulator: Emulator,
uniform_interval: int,
interval_events: List[IntervalEvent]=None):
'''
randomly fuzzes gsm_profile by `TelnetAdb(host, port)` type object
and GsmProfile type IntervalEvent
'''
if uniform_interval >= self.duration:
raise ValueError(
"uniform interval must be smaller than total duration")
if interval_events is None:
interval_events = self.generate_step_uniforminterval_event(
GsmProfile)
telnet_obj = TelnetAdb(host, emulator.port)
# self.__interval_event_execution(
# telnet_obj.set_gsm_profile, "gsm_profile",
# self.gsm_profile_interval, self.gsm_profile_events, GsmProfile)
# util.debug_print(interval_events, flag=PRINT_FLAG)
self.__execute_interval_event(
telnet_obj.set_gsm_profile, interval_events)
# telnet_obj.reset_gsm_profile()
def reset_adb(self, adb_device):
'''
resets to default for adb_device
'''
device = AdbSettings(adb_device)
device.reset_all()
def reset_telnet_obj(self, host: str, emulator: Emulator):
"""
resets the emulator for telnet specific contexts
"""
telnet_obj = TelnetAdb(host, emulator.port)
telnet_obj.reset_all()
| {"/run_monkey_only.py": ["/util.py", "/api_commands.py", "/emulator_manager.py", "/config_reader.py", "/apk.py", "/mobile_monkey.py", "/telnet_connector.py", "/adb_logcat.py", "/log_analyzer.py"], "/adb_monkey.py": ["/config_reader.py", "/api_commands.py", "/emulator.py", "/apk.py", "/adb_settings.py", "/emulator_manager.py", "/adb_logcat.py"], "/log_analyzer.py": ["/util.py"], "/kill_emulator.py": ["/emulator_manager.py"], "/fuzz_context.py": ["/adb_logcat.py", "/emulator.py", "/adb_settings.py", "/mutex.py", "/telnet_connector.py", "/config_reader.py", "/interval_event.py"], "/interval_event.py": ["/adb_settings.py", "/telnet_connector.py", "/util.py", "/config_reader.py"], "/apk.py": ["/util.py", "/config_reader.py"], "/adb_settings.py": ["/config_reader.py", "/api_commands.py", "/util.py"], "/config_reader.py": ["/util.py"], "/api_commands.py": ["/config_reader.py", "/util.py", "/emulator.py", "/apk.py"], "/monkey.py": ["/config_reader.py", "/adb_logcat.py", "/apk.py", "/emulator.py", "/fuzz_context.py", "/adb_settings.py", "/telnet_connector.py", "/interval_event.py"], "/mobile_monkey.py": ["/config_reader.py", "/emulator_manager.py", "/api_commands.py", "/telnet_connector.py", "/emulator.py", "/fuzz_context.py", "/adb_settings.py", "/util.py", "/adb_monkey.py", "/apk.py", "/adb_logcat.py", "/log_analyzer.py"], "/adb_logcat.py": ["/api_commands.py", "/config_reader.py", "/emulator.py", "/apk.py"], "/telnet_connector.py": ["/config_reader.py", "/util.py"], "/install_app.py": ["/config_reader.py", "/emulator_manager.py", "/api_commands.py", "/telnet_connector.py", "/emulator.py", "/fuzz_context.py", "/adb_settings.py", "/util.py", "/adb_monkey.py", "/apk.py", "/adb_logcat.py", "/log_analyzer.py"], "/mobicomonkey.py": ["/config_reader.py", "/emulator.py", "/api_commands.py", "/apk.py", "/emulator_manager.py", "/xml_element.py", "/adb_settings.py", "/telnet_connector.py", "/util.py", "/monkey.py", "/adb_logcat.py", "/mutex.py", "/adb_monkey.py"], "/contextConfig_reader.py": ["/config_reader.py"], "/emulator_manager.py": ["/emulator.py", "/config_reader.py", "/contextConfig_reader.py", "/api_commands.py", "/util.py"], "/test.py": ["/api_commands.py", "/emulator_manager.py", "/config_reader.py", "/apk.py", "/adb_logcat.py", "/telnet_connector.py", "/adb_monkey.py", "/emulator.py", "/fuzz_context.py", "/adb_settings.py", "/interval_event.py"]} |
78,653 | LordAmit/mobile-monkey | refs/heads/master | /emulator.py | '''
nothing here really.
'''
class Emulator:
'''
Emulator class. Holds information about port, PID and model of running emulators
'''
def __init__(self, emulator_port: int, emulator_pid: int,
emulator_model: str)-> None:
self.port = emulator_port
self.pid = emulator_pid
self.model = emulator_model
def __str__(self):
return "Port: " + str(self.port) + "\n" + "PID: " + \
str(self.pid) + "\n" + "Model: " + self.model + "\n"
| {"/run_monkey_only.py": ["/util.py", "/api_commands.py", "/emulator_manager.py", "/config_reader.py", "/apk.py", "/mobile_monkey.py", "/telnet_connector.py", "/adb_logcat.py", "/log_analyzer.py"], "/adb_monkey.py": ["/config_reader.py", "/api_commands.py", "/emulator.py", "/apk.py", "/adb_settings.py", "/emulator_manager.py", "/adb_logcat.py"], "/log_analyzer.py": ["/util.py"], "/kill_emulator.py": ["/emulator_manager.py"], "/fuzz_context.py": ["/adb_logcat.py", "/emulator.py", "/adb_settings.py", "/mutex.py", "/telnet_connector.py", "/config_reader.py", "/interval_event.py"], "/interval_event.py": ["/adb_settings.py", "/telnet_connector.py", "/util.py", "/config_reader.py"], "/apk.py": ["/util.py", "/config_reader.py"], "/adb_settings.py": ["/config_reader.py", "/api_commands.py", "/util.py"], "/config_reader.py": ["/util.py"], "/api_commands.py": ["/config_reader.py", "/util.py", "/emulator.py", "/apk.py"], "/monkey.py": ["/config_reader.py", "/adb_logcat.py", "/apk.py", "/emulator.py", "/fuzz_context.py", "/adb_settings.py", "/telnet_connector.py", "/interval_event.py"], "/mobile_monkey.py": ["/config_reader.py", "/emulator_manager.py", "/api_commands.py", "/telnet_connector.py", "/emulator.py", "/fuzz_context.py", "/adb_settings.py", "/util.py", "/adb_monkey.py", "/apk.py", "/adb_logcat.py", "/log_analyzer.py"], "/adb_logcat.py": ["/api_commands.py", "/config_reader.py", "/emulator.py", "/apk.py"], "/telnet_connector.py": ["/config_reader.py", "/util.py"], "/install_app.py": ["/config_reader.py", "/emulator_manager.py", "/api_commands.py", "/telnet_connector.py", "/emulator.py", "/fuzz_context.py", "/adb_settings.py", "/util.py", "/adb_monkey.py", "/apk.py", "/adb_logcat.py", "/log_analyzer.py"], "/mobicomonkey.py": ["/config_reader.py", "/emulator.py", "/api_commands.py", "/apk.py", "/emulator_manager.py", "/xml_element.py", "/adb_settings.py", "/telnet_connector.py", "/util.py", "/monkey.py", "/adb_logcat.py", "/mutex.py", "/adb_monkey.py"], "/contextConfig_reader.py": ["/config_reader.py"], "/emulator_manager.py": ["/emulator.py", "/config_reader.py", "/contextConfig_reader.py", "/api_commands.py", "/util.py"], "/test.py": ["/api_commands.py", "/emulator_manager.py", "/config_reader.py", "/apk.py", "/adb_logcat.py", "/telnet_connector.py", "/adb_monkey.py", "/emulator.py", "/fuzz_context.py", "/adb_settings.py", "/interval_event.py"]} |
78,654 | LordAmit/mobile-monkey | refs/heads/master | /interval_event.py | from typing import Union, Type, List
from adb_settings import UserRotation
from adb_settings import Airplane
from adb_settings import KeyEvent
from telnet_connector import GsmProfile
from telnet_connector import NetworkDelay
from telnet_connector import NetworkStatus
import util
import config_reader as config
EVENT_TYPES = Union[Type[GsmProfile], Type[NetworkDelay],
Type[NetworkStatus], Type[Airplane],
Type[UserRotation], Type[KeyEvent]]
class IntervalEvent:
'''
`Interval Event` class contains the steps,
for each of which, an interval, an event and an event_type is assigned
e.g.
>>> [event_type: <enum 'NetworkStatus'>, step: 0, interval: 4, event: full]
where `event_type` represents one of the Event Types:
- GsmProfile,
- NetworkDelay,
- NetworkStatus,
- Airplane,
- UserRotation
`step` is a 0 indexed list, against which an `interval` in seconds
and an `event` of event_type is assigned.
'''
def __init__(self, step: int, interval: int,
event: str, event_type: EVENT_TYPES)->None:
self.step = step
self.interval = interval
self.event = event
self.event_type = event_type
def __str__(self) -> str:
# return "[event_type: {}, step: {}, interval: {}, event: {}]".format(
# self.event_type, self.step, self.interval, self.event)
return "{} {} {} {} {}".format(
util.return_current_time_in_logcat_style(),
self.event_type.__name__, self.step, self.interval, self.event)
__repr__ = __str__
def read_interval_event_from_file(file_address: str,
event_type:
EVENT_TYPES)->List[IntervalEvent]:
'''
imports event from file and returns `List[IntervalEvent]`
'''
util.check_file_directory_exists(file_address, True)
lines: list = open(file_address).read().split('\n')
step: int = 0
event_type_name = None
events: List[IntervalEvent] = []
total_event_duration: int = 0
for line in lines:
in_values = line.split(',')
if len(in_values) is 3:
try:
event_value = int(in_values[0])
event_interval = int(in_values[1])
event_type_name = str(in_values[2])
except ValueError:
print('Caught Error! Please check value of: ' + in_values)
if in_values[2] == 'GsmProfile':
i_event = IntervalEvent(
step, event_interval, GsmProfile(event_value).name,
GsmProfile)
elif in_values[2] == 'NetworkDelay':
i_event = IntervalEvent(
step, event_interval, NetworkDelay(event_value).name,
NetworkDelay)
elif in_values[2] == 'NetworkStatus':
i_event = IntervalEvent(
step, event_interval, NetworkStatus(event_value).name,
NetworkStatus)
elif in_values[2] == 'UserRotation':
i_event = IntervalEvent(
step, event_interval, UserRotation(event_value).name,
UserRotation)
else:
raise ValueError(
"incorrect format of Event type: " + in_values[2])
events.append(i_event)
total_event_duration += event_interval
if total_event_duration > config.DURATION:
print("total event interval duration from file (" +
str(total_event_duration)
+ ") can not be larger than " + str(config.DURATION))
raise ValueError()
print("successfully imported from file. Type: " +
event_type_name + "; total duration=" + str(total_event_duration))
return events
def main():
pass
if __name__ == '__main__':
main()
| {"/run_monkey_only.py": ["/util.py", "/api_commands.py", "/emulator_manager.py", "/config_reader.py", "/apk.py", "/mobile_monkey.py", "/telnet_connector.py", "/adb_logcat.py", "/log_analyzer.py"], "/adb_monkey.py": ["/config_reader.py", "/api_commands.py", "/emulator.py", "/apk.py", "/adb_settings.py", "/emulator_manager.py", "/adb_logcat.py"], "/log_analyzer.py": ["/util.py"], "/kill_emulator.py": ["/emulator_manager.py"], "/fuzz_context.py": ["/adb_logcat.py", "/emulator.py", "/adb_settings.py", "/mutex.py", "/telnet_connector.py", "/config_reader.py", "/interval_event.py"], "/interval_event.py": ["/adb_settings.py", "/telnet_connector.py", "/util.py", "/config_reader.py"], "/apk.py": ["/util.py", "/config_reader.py"], "/adb_settings.py": ["/config_reader.py", "/api_commands.py", "/util.py"], "/config_reader.py": ["/util.py"], "/api_commands.py": ["/config_reader.py", "/util.py", "/emulator.py", "/apk.py"], "/monkey.py": ["/config_reader.py", "/adb_logcat.py", "/apk.py", "/emulator.py", "/fuzz_context.py", "/adb_settings.py", "/telnet_connector.py", "/interval_event.py"], "/mobile_monkey.py": ["/config_reader.py", "/emulator_manager.py", "/api_commands.py", "/telnet_connector.py", "/emulator.py", "/fuzz_context.py", "/adb_settings.py", "/util.py", "/adb_monkey.py", "/apk.py", "/adb_logcat.py", "/log_analyzer.py"], "/adb_logcat.py": ["/api_commands.py", "/config_reader.py", "/emulator.py", "/apk.py"], "/telnet_connector.py": ["/config_reader.py", "/util.py"], "/install_app.py": ["/config_reader.py", "/emulator_manager.py", "/api_commands.py", "/telnet_connector.py", "/emulator.py", "/fuzz_context.py", "/adb_settings.py", "/util.py", "/adb_monkey.py", "/apk.py", "/adb_logcat.py", "/log_analyzer.py"], "/mobicomonkey.py": ["/config_reader.py", "/emulator.py", "/api_commands.py", "/apk.py", "/emulator_manager.py", "/xml_element.py", "/adb_settings.py", "/telnet_connector.py", "/util.py", "/monkey.py", "/adb_logcat.py", "/mutex.py", "/adb_monkey.py"], "/contextConfig_reader.py": ["/config_reader.py"], "/emulator_manager.py": ["/emulator.py", "/config_reader.py", "/contextConfig_reader.py", "/api_commands.py", "/util.py"], "/test.py": ["/api_commands.py", "/emulator_manager.py", "/config_reader.py", "/apk.py", "/adb_logcat.py", "/telnet_connector.py", "/adb_monkey.py", "/emulator.py", "/fuzz_context.py", "/adb_settings.py", "/interval_event.py"]} |
78,655 | LordAmit/mobile-monkey | refs/heads/master | /apk.py | import util
from typing import List
import subprocess
import config_reader as config
class Apk:
'''
Apk class that contains apk_path, apk_name, and apk_permissions
'''
def __init__(self, apk_path: str)-> None:
util.check_file_directory_exists(apk_path, True)
self.apk_path = apk_path
self.package_name = self.__adb_package_name_from_apk(apk_path)
self.permissions = self.__adb_permissions_from_apk(apk_path)
def __adb_package_name_from_apk(self, apk_path):
'''
returns the package_name by executing
>>> aapt d permissions file.apk
'''
# ./aapt d permissions ~/git/testApps/Ringdroid_2.7.4_apk-dl.com.apk
util.check_file_directory_exists(apk_path, True)
result = subprocess.check_output(
[config.AAPT, 'd', 'permissions', apk_path]).decode()
return result.split("\n")[0].split('package:')[1].strip()
def __adb_permissions_from_apk(self, apk_path: str):
'''
returns list of permissions defined in APK
'''
def extract_permission(value: str):
'''
internal function
'''
if ".permission." in value:
if value.endswith('\''):
permission = value.split("=")[1].strip('\'')
else:
permission = value.split(": ")[1]
return permission
util.check_file_directory_exists(apk_path, True)
output = subprocess.check_output(
[config.AAPT, 'd', 'permissions', apk_path]).decode().split('\n')
result = list(filter(None, map(extract_permission, output)))
return result
def __str__(self):
return "path: {}, package: {}, permissions: {}".format(
self.apk_path, self.package_name, self.permissions
)
| {"/run_monkey_only.py": ["/util.py", "/api_commands.py", "/emulator_manager.py", "/config_reader.py", "/apk.py", "/mobile_monkey.py", "/telnet_connector.py", "/adb_logcat.py", "/log_analyzer.py"], "/adb_monkey.py": ["/config_reader.py", "/api_commands.py", "/emulator.py", "/apk.py", "/adb_settings.py", "/emulator_manager.py", "/adb_logcat.py"], "/log_analyzer.py": ["/util.py"], "/kill_emulator.py": ["/emulator_manager.py"], "/fuzz_context.py": ["/adb_logcat.py", "/emulator.py", "/adb_settings.py", "/mutex.py", "/telnet_connector.py", "/config_reader.py", "/interval_event.py"], "/interval_event.py": ["/adb_settings.py", "/telnet_connector.py", "/util.py", "/config_reader.py"], "/apk.py": ["/util.py", "/config_reader.py"], "/adb_settings.py": ["/config_reader.py", "/api_commands.py", "/util.py"], "/config_reader.py": ["/util.py"], "/api_commands.py": ["/config_reader.py", "/util.py", "/emulator.py", "/apk.py"], "/monkey.py": ["/config_reader.py", "/adb_logcat.py", "/apk.py", "/emulator.py", "/fuzz_context.py", "/adb_settings.py", "/telnet_connector.py", "/interval_event.py"], "/mobile_monkey.py": ["/config_reader.py", "/emulator_manager.py", "/api_commands.py", "/telnet_connector.py", "/emulator.py", "/fuzz_context.py", "/adb_settings.py", "/util.py", "/adb_monkey.py", "/apk.py", "/adb_logcat.py", "/log_analyzer.py"], "/adb_logcat.py": ["/api_commands.py", "/config_reader.py", "/emulator.py", "/apk.py"], "/telnet_connector.py": ["/config_reader.py", "/util.py"], "/install_app.py": ["/config_reader.py", "/emulator_manager.py", "/api_commands.py", "/telnet_connector.py", "/emulator.py", "/fuzz_context.py", "/adb_settings.py", "/util.py", "/adb_monkey.py", "/apk.py", "/adb_logcat.py", "/log_analyzer.py"], "/mobicomonkey.py": ["/config_reader.py", "/emulator.py", "/api_commands.py", "/apk.py", "/emulator_manager.py", "/xml_element.py", "/adb_settings.py", "/telnet_connector.py", "/util.py", "/monkey.py", "/adb_logcat.py", "/mutex.py", "/adb_monkey.py"], "/contextConfig_reader.py": ["/config_reader.py"], "/emulator_manager.py": ["/emulator.py", "/config_reader.py", "/contextConfig_reader.py", "/api_commands.py", "/util.py"], "/test.py": ["/api_commands.py", "/emulator_manager.py", "/config_reader.py", "/apk.py", "/adb_logcat.py", "/telnet_connector.py", "/adb_monkey.py", "/emulator.py", "/fuzz_context.py", "/adb_settings.py", "/interval_event.py"]} |
78,656 | LordAmit/mobile-monkey | refs/heads/master | /adb_settings.py | import subprocess
from enum import Enum, auto
import config_reader as config
import api_commands
import util
ADB = config.adb
PRINT_FLAG = False
class KeyboardEvent(Enum):
'''
Keyboard events
'''
KEYCODE_0 = 0
KEYCODE_1 = auto()
KEYCODE_2 = auto()
KEYCODE_3 = auto()
KEYCODE_4 = auto()
KEYCODE_5 = auto()
KEYCODE_6 = auto()
KEYCODE_7 = auto()
KEYCODE_8 = auto()
KEYCODE_9 = auto()
KEYCODE_A = auto()
KEYCODE_B = auto()
KEYCODE_C = auto()
KEYCODE_D = auto()
KEYCODE_E = auto()
KEYCODE_F = auto()
KEYCODE_G = auto()
KEYCODE_H = auto()
KEYCODE_I = auto()
KEYCODE_J = auto()
KEYCODE_K = auto()
KEYCODE_L = auto()
KEYCODE_M = auto()
KEYCODE_N = auto()
KEYCODE_O = auto()
KEYCODE_P = auto()
KEYCODE_Q = auto()
KEYCODE_R = auto()
KEYCODE_S = auto()
KEYCODE_T = auto()
KEYCODE_U = auto()
KEYCODE_V = auto()
KEYCODE_W = auto()
KEYCODE_X = auto()
KEYCODE_Y = auto()
KEYCODE_Z = auto()
KEYCODE_STAR = auto()
KEYCODE_POUND = auto()
KEYCODE_COMMA = auto()
KEYCODE_PERIOD = auto()
KEYCODE_PLUS = auto()
KEYCODE_MINUS = auto()
KEYCODE_EQUALS = auto()
KEYCODE_LEFT_BRACKET = auto()
KEYCODE_RIGHT_BRACKET = auto()
KEYCODE_BACKSLASH = auto()
KEYCODE_SEMICOLON = auto()
KEYCODE_APOSTROPHE = auto()
KEYCODE_SLASH = auto()
KEYCODE_AT = auto()
# KEYCODE_NUM = auto()
KEYCODE_SPACE = auto()
class KeyEvent(Enum):
'''
Key events
'''
# KEYCODE_UNKNOWN = ()
# KEYCODE_SOFT_RIGHT = ()
# KEYCODE_HOME = ()
# KEYCODE_BACK = ()
# KEYCODE_CALL = ()
# KEYCODE_ENDCALL = auto()
# KEYCODE_DPAD_UP = auto()
# KEYCODE_DPAD_DOWN = auto()
# KEYCODE_DPAD_LEFT = auto()
# KEYCODE_DPAD_RIGHT = auto()
# KEYCODE_DPAD_CENTER = auto()
KEYCODE_ENTER = auto()
KEYCODE_DEL = auto()
KEYCODE_VOLUME_UP = auto()
KEYCODE_VOLUME_DOWN = auto()
# KEYCODE_POWER = auto()
# KEYCODE_CAMERA = auto()
KEYCODE_CLEAR = auto()
# KEYCODE_ALT_LEFT = auto()
# KEYCODE_ALT_RIGHT = auto()
# KEYCODE_SHIFT_LEFT = auto()
# KEYCODE_SHIFT_RIGHT = auto()
# KEYCODE_TAB = auto()
# KEYCODE_SYM = auto()
# KEYCODE_EXPLORER = auto()
# KEYCODE_ENVELOPE = auto()
# KEYCODE_GRAVE = auto()
# KEYCODE_HEADSETHOOK = auto()
# KEYCODE_FOCUS = auto()
# KEYCODE_MENU = auto()
# KEYCODE_NOTIFICATION = auto()
# KEYCODE_SEARCH = auto()
# TAG_LAST_KEYCOD = auto()
class UserRotation(Enum):
'''
possible values of User_Rotation
'''
ROTATION_POTRAIT = 0
ROTATION_LANDSCAPE = 1
ROTATION_REVERSE_POTRAIT = 2
ROTATION_REVERSE_LANDSCAPE = 3
class Namespace(Enum):
'''
possible values of namespace
'''
SYSTEM = 'system'
GLOBAL = 'global'
SECURE = 'secure'
class Airplane(Enum):
'''
possible values of Airplane mode
'''
MODE_ON = 1
MODE_OFF = 0
class AdbSettings:
'''
AdbSettings api - for controlling adb devices
'''
emulator_name = ''
# TODO: Fix so that emulator_device is replaced by emulator.
def __init__(self, emulator_device: str)-> None:
emulators = api_commands.adb_list_avd_devices()
if emulator_device not in emulators:
util.detail_print(emulator_device)
print('error. possible choices are: ')
util.detail_print(emulators)
raise ValueError()
self.emulator_name = emulator_device
def subprocess_call_set(self, value: str, namespace: Namespace):
'''
calls subprocess to set `value`
'''
options = [ADB, '-s', self.emulator_name,
'shell', 'settings', 'put', namespace.value]
values = value.split(' ')
options = options + values
# print(options)
try:
subprocess.check_output(options)
except subprocess.CalledProcessError as exception:
print(exception)
def adb_send_key_event(self, event: KeyEvent):
'''
sends key event to the emulator
'''
subprocess.check_output(
[ADB, '-s', self.emulator_name, 'shell', 'input', 'keyevent',
str(event.name)])
# http://stackoverflow.com/questions/6236340/how-to-limit-speed-of-internet-connection-on-android-emulator
def adb_send_key_event_test(self, event_name: str):
'''
sends key event to the emulator for testing purpose
'''
subprocess.check_output(
[ADB, '-s', self.emulator_name, 'shell', 'input', 'keyevent',
event_name])
def subprocess_call_get(self, value, namespace: Namespace):
'''
sets a value. for example,
>>> adb -s emulator_name shell settings get system values:
'''
# adb shell settings get system accelerometer_rotation
options = [ADB, '-s', self.emulator_name,
'shell', 'settings', 'get', namespace.value]
values = value.split(' ')
options = options + values
util.debug_print(options, flag=PRINT_FLAG)
try:
value = subprocess.check_output(options).decode().strip()
print(value)
return value
except subprocess.CalledProcessError as exception:
print(exception)
def reset_all(self):
'''
defaults to settings.
accelerometer_rotation on
airplane_mode_off
user_rotation POTRAIT
'''
print("setting airplane mode to False")
self.set_airplane_mode(False)
print("setting user rotation to potrait")
self.set_user_rotation(UserRotation.ROTATION_POTRAIT)
print("setting accelerometer rotation to True")
self.set_accelerometer_rotation(True)
# def adb_start_server_safe(self):
# '''
# checks if `adb server` is running. if not, starts it.
# '''
# try:
# status = subprocess.check_output(['pidof', ADB])
# print('adb already running in PID: ' + status.decode())
# return True
# except subprocess.CalledProcessError as exception:
# print('adb is not running, returned status: ' +
# str(exception.returncode))
# print('adb was not started. starting...')
# try:
# subprocess.check_output([ADB, 'start-server'])
# return True
# except subprocess.SubprocessError as exception:
# print('something disastrous happened. maybe ' +
# ADB + ' was not found')
# return False
def get_accelerometer_rotation(self):
'''
gets the accelerometer rotation value
'''
return self.subprocess_call_get('accelerometer_rotation',
Namespace.SYSTEM)
def set_accelerometer_rotation(self, value: bool):
'''
sets the accelerometer rotation value
'''
if value:
self.subprocess_call_set(
'accelerometer_rotation 1', Namespace.SYSTEM)
else:
self.subprocess_call_set(
'accelerometer_rotation 0', Namespace.SYSTEM)
def set_user_rotation(self, rotation: UserRotation):
'''
sets user rotation based on rotation
'''
self.set_accelerometer_rotation(False)
self.subprocess_call_set(
'user_rotation ' + str(rotation.value), Namespace.SYSTEM)
def get_airplane_mode(self) -> bool:
'''
gets airplane mode by `mood`
'''
if self.subprocess_call_get('airplane_mode_on',
Namespace.GLOBAL) == '0':
return False
else:
return True
def set_airplane_mode(self, mode: Airplane):
'''
sets airplane mode by `mode`
'''
if mode == Airplane.MODE_ON:
self.subprocess_call_set('airplane_mode_on 1',
Namespace.GLOBAL)
else:
self.subprocess_call_set(
'airplane_mode_on 0', Namespace.GLOBAL)
# TODO: WIFI On:
# https://developer.android.com/reference/android/provider/Settings.Global.html#WIFI_ON
| {"/run_monkey_only.py": ["/util.py", "/api_commands.py", "/emulator_manager.py", "/config_reader.py", "/apk.py", "/mobile_monkey.py", "/telnet_connector.py", "/adb_logcat.py", "/log_analyzer.py"], "/adb_monkey.py": ["/config_reader.py", "/api_commands.py", "/emulator.py", "/apk.py", "/adb_settings.py", "/emulator_manager.py", "/adb_logcat.py"], "/log_analyzer.py": ["/util.py"], "/kill_emulator.py": ["/emulator_manager.py"], "/fuzz_context.py": ["/adb_logcat.py", "/emulator.py", "/adb_settings.py", "/mutex.py", "/telnet_connector.py", "/config_reader.py", "/interval_event.py"], "/interval_event.py": ["/adb_settings.py", "/telnet_connector.py", "/util.py", "/config_reader.py"], "/apk.py": ["/util.py", "/config_reader.py"], "/adb_settings.py": ["/config_reader.py", "/api_commands.py", "/util.py"], "/config_reader.py": ["/util.py"], "/api_commands.py": ["/config_reader.py", "/util.py", "/emulator.py", "/apk.py"], "/monkey.py": ["/config_reader.py", "/adb_logcat.py", "/apk.py", "/emulator.py", "/fuzz_context.py", "/adb_settings.py", "/telnet_connector.py", "/interval_event.py"], "/mobile_monkey.py": ["/config_reader.py", "/emulator_manager.py", "/api_commands.py", "/telnet_connector.py", "/emulator.py", "/fuzz_context.py", "/adb_settings.py", "/util.py", "/adb_monkey.py", "/apk.py", "/adb_logcat.py", "/log_analyzer.py"], "/adb_logcat.py": ["/api_commands.py", "/config_reader.py", "/emulator.py", "/apk.py"], "/telnet_connector.py": ["/config_reader.py", "/util.py"], "/install_app.py": ["/config_reader.py", "/emulator_manager.py", "/api_commands.py", "/telnet_connector.py", "/emulator.py", "/fuzz_context.py", "/adb_settings.py", "/util.py", "/adb_monkey.py", "/apk.py", "/adb_logcat.py", "/log_analyzer.py"], "/mobicomonkey.py": ["/config_reader.py", "/emulator.py", "/api_commands.py", "/apk.py", "/emulator_manager.py", "/xml_element.py", "/adb_settings.py", "/telnet_connector.py", "/util.py", "/monkey.py", "/adb_logcat.py", "/mutex.py", "/adb_monkey.py"], "/contextConfig_reader.py": ["/config_reader.py"], "/emulator_manager.py": ["/emulator.py", "/config_reader.py", "/contextConfig_reader.py", "/api_commands.py", "/util.py"], "/test.py": ["/api_commands.py", "/emulator_manager.py", "/config_reader.py", "/apk.py", "/adb_logcat.py", "/telnet_connector.py", "/adb_monkey.py", "/emulator.py", "/fuzz_context.py", "/adb_settings.py", "/interval_event.py"]} |
78,657 | LordAmit/mobile-monkey | refs/heads/master | /config_reader.py | """
config_reader module
"""
import configparser as ConfigParser
import util
import os
"""
ConfigReader takes care of config file reading
"""
def get(value):
"""
:rtype: str
:param value: available options are directory, uploads, projects,
:return: string that contains value from config file.
"""
config = ConfigParser.ConfigParser()
# config.read("configFile")
config.read(os.path.join(os.path.abspath(
os.path.dirname(__file__)), 'configFile'))
return config.get('emulator', value)
TELNET_KEY = get("telnet_key")
LOCALHOST = get("localhost")
directory = get("directory")
# apk = get("apk")
# apk_unaligned = get("apk_unaligned")
# apk_test_unaligned = get("apk_test_unaligned")
adb = get("adb")
# avds = get("avds")
emulator = get("emulator")
# test_class = get("test_class")
# test_method = get("test_method")
# SERVER_FILE_ADDRESS = get("server_file_address")
# SERVER_FILE_PORT = get("server_file_port")
TEMP = get("temp")
CURRENT_DIRECTORY = get("current_directory")
# UID = get("uid")
# PROJECT_NAME = get("project_name")
EMULATOR = get("emulator")
MINIMUM_INTERVAL = int(get("minimum_interval"))
MAXIMUM_INTERVAL = int(get("maximum_interval"))
SEED = int(get("seed"))
DURATION = int(get("duration"))
# APP_PACKAGE_NAME = get("app_package_name")
UNIFORM_INTERVAL = int(get("uniform_interval"))
APK_FULL_PATH = get("apk_full_path")
AAPT = get("aapt")
EMULATOR_NAME = get("emulator_name")
EMULATOR_PORT = get("emulator_port")
LOG_ADDRESS = get("log_address")
SAMPLE_LOG = get("sample_log")
MONKEY_INTERVAL = get("monkey_interval")
MONKEY_LOG = get("monkey_log")
MOBILE_MONKEY_LOG = get("mobile_monkey_log")
DUMP_ADDRESS = get("dump_address")
HEADLESS = util.StringToBoolean((get("headless")))
MINIMUM_KEYEVENT = int(get("minimum_keyevent"))
MAXIMUM_KEYEVENT = int(get("maximum_keyevent"))
GUIDED_APPROACH = int(get("guided_approach"))
JARSIGNER = get("jarsigner")
KEY = get("key_address")
ALIAS = get("key_alias")
PASSWORD = get("key_password")
OVERRIDE_UNSIGNED = bool(int(get('override_unsigned')))
CONTEXT_FILE = bool(int(get('context_file')))
# def avd_file_reader():
# """
# returns the list of avds
# """
# txt = open(avds)
# print(txt)
# list_avds = txt.read().split('\n')
# print(list_avds)
# return list_avds
| {"/run_monkey_only.py": ["/util.py", "/api_commands.py", "/emulator_manager.py", "/config_reader.py", "/apk.py", "/mobile_monkey.py", "/telnet_connector.py", "/adb_logcat.py", "/log_analyzer.py"], "/adb_monkey.py": ["/config_reader.py", "/api_commands.py", "/emulator.py", "/apk.py", "/adb_settings.py", "/emulator_manager.py", "/adb_logcat.py"], "/log_analyzer.py": ["/util.py"], "/kill_emulator.py": ["/emulator_manager.py"], "/fuzz_context.py": ["/adb_logcat.py", "/emulator.py", "/adb_settings.py", "/mutex.py", "/telnet_connector.py", "/config_reader.py", "/interval_event.py"], "/interval_event.py": ["/adb_settings.py", "/telnet_connector.py", "/util.py", "/config_reader.py"], "/apk.py": ["/util.py", "/config_reader.py"], "/adb_settings.py": ["/config_reader.py", "/api_commands.py", "/util.py"], "/config_reader.py": ["/util.py"], "/api_commands.py": ["/config_reader.py", "/util.py", "/emulator.py", "/apk.py"], "/monkey.py": ["/config_reader.py", "/adb_logcat.py", "/apk.py", "/emulator.py", "/fuzz_context.py", "/adb_settings.py", "/telnet_connector.py", "/interval_event.py"], "/mobile_monkey.py": ["/config_reader.py", "/emulator_manager.py", "/api_commands.py", "/telnet_connector.py", "/emulator.py", "/fuzz_context.py", "/adb_settings.py", "/util.py", "/adb_monkey.py", "/apk.py", "/adb_logcat.py", "/log_analyzer.py"], "/adb_logcat.py": ["/api_commands.py", "/config_reader.py", "/emulator.py", "/apk.py"], "/telnet_connector.py": ["/config_reader.py", "/util.py"], "/install_app.py": ["/config_reader.py", "/emulator_manager.py", "/api_commands.py", "/telnet_connector.py", "/emulator.py", "/fuzz_context.py", "/adb_settings.py", "/util.py", "/adb_monkey.py", "/apk.py", "/adb_logcat.py", "/log_analyzer.py"], "/mobicomonkey.py": ["/config_reader.py", "/emulator.py", "/api_commands.py", "/apk.py", "/emulator_manager.py", "/xml_element.py", "/adb_settings.py", "/telnet_connector.py", "/util.py", "/monkey.py", "/adb_logcat.py", "/mutex.py", "/adb_monkey.py"], "/contextConfig_reader.py": ["/config_reader.py"], "/emulator_manager.py": ["/emulator.py", "/config_reader.py", "/contextConfig_reader.py", "/api_commands.py", "/util.py"], "/test.py": ["/api_commands.py", "/emulator_manager.py", "/config_reader.py", "/apk.py", "/adb_logcat.py", "/telnet_connector.py", "/adb_monkey.py", "/emulator.py", "/fuzz_context.py", "/adb_settings.py", "/interval_event.py"]} |
78,658 | LordAmit/mobile-monkey | refs/heads/master | /api_commands.py | '''
api commands from python to gain information about android avds
'''
import xml.etree.ElementTree as ET
import subprocess
import shlex
from typing import List, Union
import config_reader as config
import util
from emulator import Emulator
from apk import Apk
ADB = config.adb
PRINT_FLAG = True
def decode_apk(apk: Apk):
'''
decodes provided apk to a folder
'''
util.check_file_directory_exists(apk.apk_path, True)
try:
result = subprocess.check_output(
['apktool', 'if', apk.apk_path]).decode()
util.debug_print(result, flag=PRINT_FLAG)
result = subprocess.check_output(
['apktool', 'd', apk.apk_path, '-o',
config.APK_FULL_PATH.split('.apk')[0], '-f']).decode()
util.debug_print(result, flag=PRINT_FLAG)
except subprocess.SubprocessError as error:
print(error)
raise ValueError("error decoding.")
def overwrite_android_manifest():
'''
adds android:exported="true" to AndroidManifest.xml
'''
file_address = config.APK_FULL_PATH.split(
'.apk')[0] + '/AndroidManifest.xml'
tree = ET.parse(file_address)
root = tree.getroot()
for activity in root.iter('activity'):
activity.set('android:exported', 'true')
tree.write(file_address)
f = open(file_address, 'r')
filedata = f.read()
f.close()
newdata = filedata.replace("ns0", "android")
f = open(file_address, 'w')
f.write(newdata)
f.close()
def build_apk(apk: Apk):
'''
builds modified apk
'''
result = subprocess.check_output(
['apktool', 'b', config.APK_FULL_PATH.split('.apk')[0], '-o',
apk.apk_path]).decode()
util.debug_print(result, flag=PRINT_FLAG)
def sign_apk(apk: Apk):
result = subprocess.check_output(
[config.JARSIGNER, '-keystore',
config.KEY, '-verbose', apk.apk_path,
config.ALIAS], input=config.PASSWORD.encode()).decode()
util.debug_print(result, flag=PRINT_FLAG)
def adb_install_apk(emulator: Emulator, apk: Apk):
'''
installs provided apk to specified emulator
'''
util.check_file_directory_exists(apk.apk_path, True)
try:
result = subprocess.check_output(
[config.adb, '-s', 'emulator-' + str(emulator.port), 'install',
apk.apk_path]).decode()
util.debug_print(result, flag=PRINT_FLAG)
except subprocess.SubprocessError as error:
print(error)
raise ValueError("error installing.")
def adb_get_activity_list(emulator: Emulator, apk: Apk):
'''
returns list of activities
'''
command = "{} dump xmltree {} AndroidManifest.xml".format(
config.AAPT, apk.apk_path)
result = subprocess.check_output(shlex.split(command)).decode()
return result
def adb_stop_activity_of_apk(emulator: Emulator, apk: Apk):
'''
stops activity specified by the apk
'''
# adb shell am force-stop com.my.app.package
emulator_name = 'emulator-' + str(emulator.port)
subprocess.check_output(
[config.adb, '-s', emulator_name, 'shell', 'am', 'force-stop',
apk.package_name])
print("package_name: " + apk.package_name + " is stopped")
def adb_start_launcher_of_apk(emulator: Emulator, apk: Apk):
'''
starts the specified apk.
'''
# adb shell monkey -p com.android.chrome -c
# android.intent.category.LAUNCHER 1
emulator_name = 'emulator-' + str(emulator.port)
subprocess.check_output(
[config.adb, '-s', emulator_name, 'shell', 'monkey', '-p',
apk.package_name, '-c', 'android.intent.category.LAUNCHER', '1'])
print("package_name: " + apk.package_name + " is started")
def adb_start_activity(emulator: Emulator, apk: Apk, activity: str):
'''
starts the specified activity.
'''
subprocess.check_output(
[config.adb, 'shell', 'am', 'start', '-n',
apk.package_name+"/"+activity])
print(activity+" is started")
def adb_display_properties():
result = subprocess.check_output(
[config.adb, 'shell', 'dumpsys', 'display'])
return result
def adb_display_scroll(height: str):
subprocess.check_output(
[config.adb, 'shell', 'input', 'swipe 0 '+height+' 0 0'])
print("scrolling up")
def adb_is_package_present(emulator: Emulator, app_package_name: str) -> int:
'''
returns 1 if the specified package is present.
returns 0 if the specified package is not present.
returns 1 if multiple entries for specified package is present.
'''
output = subprocess.check_output(
[config.adb, '-s', 'emulator-' + str(emulator.port), 'shell', 'pm',
'list', 'packages', '|', 'grep',
app_package_name]).decode().strip().split('\r\n')
# util.debug_print(output, len(output), flag=PRINT_FLAG)
# self.number_of_events = number_of_events
# self.seed = seed
if len(output) < 1:
return 0
elif len(output) > 1:
return 2
return 1
def adb_uninstall_package(emulator: Emulator, package: str):
'''
uninstalls the provided package if only one entry with the specified
package is found.
'''
# if adb_is_package_present(emulator, package) is not 1:
# raise ValueError("Package not found / Too generic.")
try:
subprocess.check_output(
[config.adb, '-s', 'emulator-' + str(emulator.port),
'uninstall', package])
print("uninstalled " + package)
except subprocess.SubprocessError as error:
print("maybe not found/uninstalled already")
def adb_uninstall_apk(emulator: Emulator, apk: Apk):
'''
uninstalls the provided apk if installed.
'''
adb_uninstall_package(emulator, apk.package_name)
def adb_start_server_safe():
'''
checks if `adb server` is running. if not, starts it.
'''
try:
status = subprocess.check_output(['pidof', ADB])
util.debug_print('adb already running in PID: ' +
status.decode(), flag=PRINT_FLAG)
return True
except subprocess.CalledProcessError as exception:
print('adb is not running, returned status: ' +
str(exception.returncode))
print('adb was not started. starting...')
try:
subprocess.check_output([ADB, 'start-server'])
return True
except subprocess.SubprocessError as exception:
print(
'something disastrous happened. maybe ' + ADB +
' was not found')
return False
def adb_list_avd_devices() -> List:
'''
returns list of running adb_devices after formatting as a list.
returns:
List of adb_devices
'''
adb_devices = subprocess.check_output([ADB, 'devices'])
adb_devices = adb_devices.decode().strip().split('\n')[1:]
adb_devices_without_attached = []
for device in adb_devices:
adb_devices_without_attached.append(device.split('\t')[0])
return adb_devices_without_attached
def adb_input_tap(emulator: Emulator, xpos: Union[int, float],
ypos: Union[int, float]):
'''
sends tap event to specified `emulator` via adb at the `X`, `Y` coordinates
'''
command = "{} -s emulator-{} shell input tap {} {}".format(config.adb,
emulator.port,
xpos, ypos)
subprocess.check_output(shlex.split(command))
def adb_uiautomator_dump(emulator: Emulator):
'''
dumps the current uiautomator view to the default dump directory in
YYYYMMDDHHmm format
'''
command = "{} -s emulator-{} shell uiautomator dump".format(
config.adb, emulator.port)
subprocess.check_output(shlex.split(command))
dump_file_address = config.DUMP_ADDRESS + \
util.return_current_time() + "_dump.xml"
command_cat = "{} -s emulator-{} shell cat /sdcard/window_dump.xml "
command_cat = command_cat.format(config.adb, emulator.port)
dump_content = subprocess.check_output(shlex.split(command_cat)).decode()
dump_file = open(dump_file_address, mode='w')
dump_file.write(dump_content)
dump_file.close()
return dump_file_address
def adb_list_avd_ports() -> List[str]:
'''
returns:
List of port of avd devices
'''
emulator_ports = []
adb_devices = adb_list_avd_devices()
for adb_device in adb_devices:
emulator_port = adb_device.split('-')[1]
if len(emulator_port) > 3:
emulator_ports.append(emulator_port)
return emulator_ports
def avd_model_from_pid(pid: int) -> str:
'''
returns:
avd_model from `pid`
'''
device_details = util.ps_details_of_pid(pid)
# print(output_raw)
"""
PID TTY STAT TIME COMMAND
15522 tty2 Rl+ 128:13 /home/amit/Android/Sdk/tools/emulator64-x86 -port 5557 -avd nexus_s # noqa
"""
device_detail = device_details.split('\n')[1:][:1][0]
print(device_detail)
"""
15521 tty2 Rl+ 134:48 /home/amit/Android/Sdk/tools/emulator64-x86 -port 5555 -avd nexus_4 # noqa
or
11803 ? Sl 9:56 /home/amit/Android/Sdk/emulator/qemu/linux-x86_64/qemu-system-i386 # noqa
-port 5555 -avd Nexus6 -use-system-libs
"""
index_of_avd = device_detail.index('-avd')
device_model = device_detail[index_of_avd + 5:].split(' ')[0]
"""
nexus_s
"""
return device_model
def adb_pidof_app(emulator: Emulator, apk: Apk):
'''
returns PID of running apk
'''
try:
result = subprocess.check_output(
[config.adb, '-s', 'emulator-' + str(emulator.port),
'shell', 'pidof',
apk.package_name])
result = result.decode().split('\n')[0]
util.debug_print(result, flag=PRINT_FLAG)
return result
except subprocess.SubprocessError:
print("maybe not found/uninstalled already")
def emulator_list_of_avds():
'''
returns the list of possible avds by executing `emulator -list-avds`
'''
list_avds = subprocess.check_output([config.EMULATOR, '-list-avds'])
return list_avds.decode().strip().split('\n')
def gradle_install(gradlew_path: str, project_path: str):
'''
`gradlew_path` is the full path of the gradlew inside the project folder
'''
util.check_file_directory_exists(gradlew_path, True)
util.check_file_directory_exists(project_path, True)
util.change_file_permission(gradlew_path, 555)
print(gradlew_path, project_path)
try:
subprocess.check_output(
[gradlew_path, '-p', project_path, 'tasks', 'installDebug',
'--info', '--debug',
'--stacktrace'])
except subprocess.CalledProcessError:
print('error: gradle problem executing: ' + gradlew_path)
def gradle_test(gradlew_path: str, project_path: str):
'''
`gradlew_path` is the full path of the gradlew inside the project folder
'''
util.check_file_directory_exists(gradlew_path, True)
util.check_file_directory_exists(project_path, True)
util.change_file_permission(gradlew_path, 555)
print(gradlew_path, project_path)
try:
subprocess.check_output(
[gradlew_path, '-p', project_path, 'tasks', 'connectedAndroidTest',
'--info', '--debug',
'--stacktrace'])
except subprocess.CalledProcessError:
print('error: gradle problem executing: ' + gradlew_path)
def main():
'''
main function
'''
devices = adb_list_avd_ports()
print(devices)
if __name__ == '__main__':
main()
| {"/run_monkey_only.py": ["/util.py", "/api_commands.py", "/emulator_manager.py", "/config_reader.py", "/apk.py", "/mobile_monkey.py", "/telnet_connector.py", "/adb_logcat.py", "/log_analyzer.py"], "/adb_monkey.py": ["/config_reader.py", "/api_commands.py", "/emulator.py", "/apk.py", "/adb_settings.py", "/emulator_manager.py", "/adb_logcat.py"], "/log_analyzer.py": ["/util.py"], "/kill_emulator.py": ["/emulator_manager.py"], "/fuzz_context.py": ["/adb_logcat.py", "/emulator.py", "/adb_settings.py", "/mutex.py", "/telnet_connector.py", "/config_reader.py", "/interval_event.py"], "/interval_event.py": ["/adb_settings.py", "/telnet_connector.py", "/util.py", "/config_reader.py"], "/apk.py": ["/util.py", "/config_reader.py"], "/adb_settings.py": ["/config_reader.py", "/api_commands.py", "/util.py"], "/config_reader.py": ["/util.py"], "/api_commands.py": ["/config_reader.py", "/util.py", "/emulator.py", "/apk.py"], "/monkey.py": ["/config_reader.py", "/adb_logcat.py", "/apk.py", "/emulator.py", "/fuzz_context.py", "/adb_settings.py", "/telnet_connector.py", "/interval_event.py"], "/mobile_monkey.py": ["/config_reader.py", "/emulator_manager.py", "/api_commands.py", "/telnet_connector.py", "/emulator.py", "/fuzz_context.py", "/adb_settings.py", "/util.py", "/adb_monkey.py", "/apk.py", "/adb_logcat.py", "/log_analyzer.py"], "/adb_logcat.py": ["/api_commands.py", "/config_reader.py", "/emulator.py", "/apk.py"], "/telnet_connector.py": ["/config_reader.py", "/util.py"], "/install_app.py": ["/config_reader.py", "/emulator_manager.py", "/api_commands.py", "/telnet_connector.py", "/emulator.py", "/fuzz_context.py", "/adb_settings.py", "/util.py", "/adb_monkey.py", "/apk.py", "/adb_logcat.py", "/log_analyzer.py"], "/mobicomonkey.py": ["/config_reader.py", "/emulator.py", "/api_commands.py", "/apk.py", "/emulator_manager.py", "/xml_element.py", "/adb_settings.py", "/telnet_connector.py", "/util.py", "/monkey.py", "/adb_logcat.py", "/mutex.py", "/adb_monkey.py"], "/contextConfig_reader.py": ["/config_reader.py"], "/emulator_manager.py": ["/emulator.py", "/config_reader.py", "/contextConfig_reader.py", "/api_commands.py", "/util.py"], "/test.py": ["/api_commands.py", "/emulator_manager.py", "/config_reader.py", "/apk.py", "/adb_logcat.py", "/telnet_connector.py", "/adb_monkey.py", "/emulator.py", "/fuzz_context.py", "/adb_settings.py", "/interval_event.py"]} |
78,659 | LordAmit/mobile-monkey | refs/heads/master | /monkey.py | '''
monkey
'''
from threading import Thread
from typing import List
import os
import config_reader as config
from adb_logcat import FatalWatcher, Logcat
from apk import Apk
from emulator import Emulator
from fuzz_context import Fuzzer
from adb_settings import Airplane, UserRotation
from telnet_connector import GsmProfile, NetworkDelay, NetworkStatus
import interval_event
PRINT_FLAG = True
TIME_PRINT_FLAG = True
dir = os.path.dirname(__file__)
network_delay = os.path.join(dir, 'test/networkdelay.txt')
network_status = os.path.join(dir, 'test/networkstatus.txt')
gsm_profile = os.path.join(dir, 'test/gsmprofile.txt')
def _context_threads_only(emulator: Emulator, fuzz: Fuzzer) -> List:
threads = []
emulator_name = 'emulator-' + str(emulator.port)
if config.CONTEXT_FILE == 1:
network_delay_interval_events =\
interval_event.read_interval_event_from_file(
network_delay, NetworkDelay)
else:
network_delay_interval_events = fuzz.generate_step_interval_event(
NetworkDelay)
threads.append(Thread(target=fuzz.random_network_delay, args=(
config.LOCALHOST, emulator, network_delay_interval_events)))
if config.CONTEXT_FILE == 1:
network_speed_interval_event =\
interval_event.read_interval_event_from_file(
network_status, NetworkStatus)
else:
network_speed_interval_event = fuzz.generate_step_interval_event(
NetworkStatus)
threads.append(Thread(target=fuzz.random_network_speed, args=(
config.LOCALHOST, emulator, network_speed_interval_event)))
# airplane_mode_interval_events = fuzz.generate_step_interval_event(
# Airplane)
# threads.append(Thread(
# target=fuzz.random_airplane_mode_call,
# args=(emulator_name, airplane_mode_interval_events)))
if config.CONTEXT_FILE == 1:
gsm_profile_interval_events = \
interval_event.read_interval_event_from_file(
gsm_profile, GsmProfile)
else:
gsm_profile_interval_events = fuzz.generate_step_interval_event(
GsmProfile)
threads.append(Thread(target=fuzz.random_gsm_profile, args=(
config.LOCALHOST, emulator, config.UNIFORM_INTERVAL,
gsm_profile_interval_events)))
# # ROTATION EVENT #FIXME
user_rotation_interval_events = fuzz.generate_step_interval_event(
UserRotation)
# contextual_events += len(user_rotation_interval_events)
threads.append(Thread(
target=fuzz.random_rotation, args=((emulator_name,
user_rotation_interval_events))))
return threads
def threads_to_run(emulator: Emulator, apk: Apk, fuzz: Fuzzer) -> List:
'''
runs the threads after checking permissions.
'''
threads = []
emulator_name = 'emulator-' + str(emulator.port)
if "android.permission.INTERNET" in apk.permissions or \
"android.permission.ACCESS_NETWORK_STATE" in apk.permissions:
if config.GUIDED_APPROACH == 1:
network_delay_interval_events =\
interval_event.read_interval_event_from_file(
network_delay, NetworkDelay)
else:
network_delay_interval_events = fuzz.generate_step_interval_event(
NetworkDelay)
threads.append(Thread(target=fuzz.random_network_delay, args=(
config.LOCALHOST, emulator, network_delay_interval_events)))
if config.GUIDED_APPROACH == 1:
network_speed_interval_event =\
interval_event.read_interval_event_from_file(
network_status, NetworkStatus)
else:
network_speed_interval_event = fuzz.generate_step_interval_event(
NetworkStatus)
threads.append(Thread(target=fuzz.random_network_speed, args=(
config.LOCALHOST, emulator, network_speed_interval_event)))
airplane_mode_interval_events = fuzz.generate_step_interval_event(
Airplane)
threads.append(Thread(
target=fuzz.random_airplane_mode_call,
args=(emulator_name, airplane_mode_interval_events)))
if "android.permission.ACCESS_NETWORK_STATE" in apk.permissions:
if config.GUIDED_APPROACH == 1:
gsm_profile_interval_events = \
interval_event.read_interval_event_from_file(
gsm_profile, GsmProfile)
else:
gsm_profile_interval_events = fuzz.generate_step_interval_event(
GsmProfile)
threads.append(Thread(target=fuzz.random_gsm_profile, args=(
config.LOCALHOST, emulator, config.UNIFORM_INTERVAL,
gsm_profile_interval_events)))
# ROTATION EVENT # FIXME
user_rotation_interval_events = fuzz.generate_step_interval_event(
UserRotation)
# contextual_xevents += len(user_rotation_interval_events)
threads.append(Thread(
target=fuzz.random_rotation, args=((emulator_name,
user_rotation_interval_events))))
return threads
def run(emulator: Emulator, apk: Apk, emulator_name: str, emulator_port: int,
seed: int, log: Logcat):
'''
runs things
'''
# telnet_connector = TelnetAdb(config.LOCALHOST, config.EMULATOR_PORT)
fuzz = Fuzzer(config.MINIMUM_INTERVAL,
config.MAXIMUM_INTERVAL, seed, config.DURATION,
FatalWatcher(log.file_address))
threads = threads_to_run(emulator, apk, fuzz)
[thread.start() for thread in threads]
[thread.join() for thread in threads]
def run_contexts_only(emulator: Emulator, emulator_name: str,
emulator_port: int, seed: int, log: Logcat):
fuzz = Fuzzer(config.MINIMUM_INTERVAL,
config.MAXIMUM_INTERVAL, seed, config.DURATION,
FatalWatcher(log.file_address))
threads = _context_threads_only(emulator, fuzz)
[thread.start() for thread in threads]
[thread.join() for thread in threads]
| {"/run_monkey_only.py": ["/util.py", "/api_commands.py", "/emulator_manager.py", "/config_reader.py", "/apk.py", "/mobile_monkey.py", "/telnet_connector.py", "/adb_logcat.py", "/log_analyzer.py"], "/adb_monkey.py": ["/config_reader.py", "/api_commands.py", "/emulator.py", "/apk.py", "/adb_settings.py", "/emulator_manager.py", "/adb_logcat.py"], "/log_analyzer.py": ["/util.py"], "/kill_emulator.py": ["/emulator_manager.py"], "/fuzz_context.py": ["/adb_logcat.py", "/emulator.py", "/adb_settings.py", "/mutex.py", "/telnet_connector.py", "/config_reader.py", "/interval_event.py"], "/interval_event.py": ["/adb_settings.py", "/telnet_connector.py", "/util.py", "/config_reader.py"], "/apk.py": ["/util.py", "/config_reader.py"], "/adb_settings.py": ["/config_reader.py", "/api_commands.py", "/util.py"], "/config_reader.py": ["/util.py"], "/api_commands.py": ["/config_reader.py", "/util.py", "/emulator.py", "/apk.py"], "/monkey.py": ["/config_reader.py", "/adb_logcat.py", "/apk.py", "/emulator.py", "/fuzz_context.py", "/adb_settings.py", "/telnet_connector.py", "/interval_event.py"], "/mobile_monkey.py": ["/config_reader.py", "/emulator_manager.py", "/api_commands.py", "/telnet_connector.py", "/emulator.py", "/fuzz_context.py", "/adb_settings.py", "/util.py", "/adb_monkey.py", "/apk.py", "/adb_logcat.py", "/log_analyzer.py"], "/adb_logcat.py": ["/api_commands.py", "/config_reader.py", "/emulator.py", "/apk.py"], "/telnet_connector.py": ["/config_reader.py", "/util.py"], "/install_app.py": ["/config_reader.py", "/emulator_manager.py", "/api_commands.py", "/telnet_connector.py", "/emulator.py", "/fuzz_context.py", "/adb_settings.py", "/util.py", "/adb_monkey.py", "/apk.py", "/adb_logcat.py", "/log_analyzer.py"], "/mobicomonkey.py": ["/config_reader.py", "/emulator.py", "/api_commands.py", "/apk.py", "/emulator_manager.py", "/xml_element.py", "/adb_settings.py", "/telnet_connector.py", "/util.py", "/monkey.py", "/adb_logcat.py", "/mutex.py", "/adb_monkey.py"], "/contextConfig_reader.py": ["/config_reader.py"], "/emulator_manager.py": ["/emulator.py", "/config_reader.py", "/contextConfig_reader.py", "/api_commands.py", "/util.py"], "/test.py": ["/api_commands.py", "/emulator_manager.py", "/config_reader.py", "/apk.py", "/adb_logcat.py", "/telnet_connector.py", "/adb_monkey.py", "/emulator.py", "/fuzz_context.py", "/adb_settings.py", "/interval_event.py"]} |
78,660 | LordAmit/mobile-monkey | refs/heads/master | /mobile_monkey.py | '''
mobile monkey
'''
import time
from typing import List
from threading import Thread
import config_reader as config
import emulator_manager
import api_commands
from telnet_connector import TelnetAdb
from telnet_connector import GsmProfile
from telnet_connector import NetworkDelay
from telnet_connector import NetworkStatus
from emulator import Emulator
from fuzz_context import Fuzzer
from adb_settings import Airplane, KeyboardEvent, UserRotation
# import adb_settings as AdbSettings
import util
from adb_monkey import AdbMonkey
from apk import Apk
from adb_logcat import Logcat, TestType, FatalWatcher
from log_analyzer import Analyzer
PRINT_FLAG = True
TIME_PRINT_FLAG = True
emulator_model = config.EMULATOR_NAME
emulator_port = config.EMULATOR_PORT
contextual_events = 0
WILL_MONKEY = True
def start_emulator() -> bool:
'''
starts emulator
'''
global emulator_model
if emulator_manager.adb_instances_manager():
util.debug_print('already emulators are running.', flag=PRINT_FLAG)
return True
else:
util.debug_print(
str.format("No emulator instance running. starting {} at port {}",
emulator_model, emulator_port), flag=PRINT_FLAG)
api_commands.adb_start_server_safe()
emulator_manager.emulator_start_avd(emulator_port, emulator_model)
# subprocess.Popen([command,
# '-port', str(emulator_port), '-avd',
# emulator_name, '-use-system-libs'],
# stdout=subprocess.PIPE)
emulator_manager.check_avd_booted_completely(emulator_port)
return True
def threads_to_run(emulator: Emulator, apk: Apk, fuzz: Fuzzer,
will_monkey: bool) -> List:
'''
runs the threads after checking permissions.
'''
threads = []
global contextual_events
util.debug_print(apk.permissions, flag=PRINT_FLAG)
emulator_name = 'emulator-' + str(emulator.port)
if "android.permission.INTERNET" in apk.permissions or \
"android.permission.ACCESS_NETWORK_STATE" in apk.permissions:
util.debug_print("Internet permission detected", flag=PRINT_FLAG)
network_delay_interval_events = fuzz.generate_step_interval_event(
NetworkDelay)
# print(network_delay_interval_events)
contextual_events += len(network_delay_interval_events)
threads.append(Thread(target=fuzz.random_network_delay, args=(
config.LOCALHOST, emulator, network_delay_interval_events)))
network_speed_interval_event = fuzz.generate_step_interval_event(
NetworkStatus)
# print(network_speed_interval_event)
contextual_events += len(network_speed_interval_event)
threads.append(Thread(target=fuzz.random_network_speed, args=(
config.LOCALHOST, emulator, network_speed_interval_event)))
airplane_mode_interval_events = fuzz.generate_step_interval_event(
Airplane)
# print(airplane_mode_interval_events)
contextual_events += len(airplane_mode_interval_events)
threads.append(Thread(
target=fuzz.random_airplane_mode_call,
args=(emulator_name, airplane_mode_interval_events)))
if "android.permission.ACCESS_NETWORK_STATE" in apk.permissions:
util.debug_print("access_network_state detected", flag=PRINT_FLAG)
gsm_profile_interval_events = fuzz.generate_step_uniforminterval_event(
GsmProfile)
contextual_events += len(gsm_profile_interval_events)
threads.append(Thread(target=fuzz.random_gsm_profile, args=(
config.LOCALHOST, emulator,
config.UNIFORM_INTERVAL, gsm_profile_interval_events)))
user_rotation_interval_events = fuzz.generate_step_interval_event(
UserRotation)
contextual_events += len(user_rotation_interval_events)
threads.append(Thread(
target=fuzz.random_rotation, args=((emulator_name,
user_rotation_interval_events))))
key_event_interval_events = fuzz.generate_step_interval_event(
KeyboardEvent)
contextual_events += len(key_event_interval_events)
threads.append(Thread(
target=fuzz.random_key_event, args=((emulator_name,
key_event_interval_events))))
if will_monkey:
monkey = AdbMonkey(emulator, apk,
config.SEED, config.DURATION)
thread_monkey = Thread(target=monkey.start_monkey)
threads.append(thread_monkey)
return threads
def run(apk: Apk, emulator_name: str, emulator_port: int):
'''
runs things
'''
to_kill = False
to_test = True
to_full_run = True
wipe_after_finish = False
# test_time_seconds = 30
if not start_emulator():
return
emulator = emulator_manager.get_adb_instance_from_emulators(emulator_name)
# emulator_name = 'emulator-' + emulator.port
telnet_connector = TelnetAdb(config.LOCALHOST, emulator.port)
# apk = Apk(config.APK_FULL_PATH)
# api_commands.adb_uninstall_apk(emulator, apk)
# api_commands.adb_install_apk(emulator, apk)
# api_commands.adb_start_launcher_of_apk(emulator, apk)
log = Logcat(emulator, apk, TestType.MobileMonkey)
# api_commands.adb_pidof_app(emulator, apk)
if to_kill:
telnet_connector.kill_avd()
quit()
if not to_test:
return
log.start_logcat()
fuzz = Fuzzer(config.MINIMUM_INTERVAL,
config.MAXIMUM_INTERVAL, config.SEED,
config.DURATION, FatalWatcher(log.file_address))
# log.experimental_start_logcat(fuzz)
# fuzz.print_intervals_events()
threads = threads_to_run(emulator, apk, fuzz, WILL_MONKEY)
# log_thread = Thread(target=log.start, args=(fuzz,))
global contextual_events
print("Total contextual events: " + str(contextual_events))
# print(threads)
# return
# device = AdbSettings.AdbSettings('emulator-' + adb_instance.port)
# triggers = [fuzz.set_continue_network_speed,
# fuzz.set_continue_gsm_profile,
# fuzz.set_continue_network_delay]
# thread_test = Thread(target=time_to_test, args=[
# test_time_seconds, triggers, ])
# thread_fuzz_delay = Thread(target=fuzz.random_network_delay, args=(
# config.LOCALHOST, emulator.port,))
# thread_fuzz_profile = Thread(target=fuzz.random_gsm_profile, args=(
# config.LOCALHOST, emulator.port, 12,))
# thread_fuzz_speed = Thread(target=fuzz.random_network_speed, args=(
# config.LOCALHOST, emulator.port,))
# thread_fuzz_rotation = Thread(
# target=fuzz.random_rotation, args=((emulator_name,)))
# thread_fuzz_airplane = Thread(
# target=fuzz.random_airplane_mode_call, args=(emulator_name,))
# monkey = AdbMonkey(emulator, config.APP_PACKAGE_NAME,
# config.SEED, config.DURATION)
# thread_monkey = Thread(target=monkey.start_monkey)
if to_full_run:
util.debug_print(
"started testing at {}".format(time.ctime()), flag=TIME_PRINT_FLAG)
[thread.start() for thread in threads]
# log_thread.start()
[thread.join() for thread in threads]
# log.log_process.kill()
# log.stop_logcat()
# log_thread.join()
# thread_monkey.start()
# thread_fuzz_rotation.start()
# thread_fuzz_delay.start()
# thread_fuzz_profile.start()
# thread_fuzz_speed.start()
# thread_fuzz_airplane.start()
# thread_test.start()
# thread_test.join()
# thread_fuzz_delay.join()
# thread_fuzz_profile.join()
# thread_fuzz_speed.join()
# thread_fuzz_rotation.join()
# thread_fuzz_airplane.join()
# thread_monkey.join()
# telnet_connector.kill_avd()
api_commands.adb_stop_activity_of_apk(emulator, apk)
log.stop_logcat()
api_commands.adb_uninstall_apk(emulator, apk)
util.debug_print(
'Finished testing and uninstalling app at {}'.format(time.ctime()),
flag=TIME_PRINT_FLAG)
print(Analyzer(log.file_address))
if wipe_after_finish:
print("successfully completed testing app. Closing emulator")
telnet_connector.kill_avd()
emulator_manager.emulator_wipe_data(emulator)
if __name__ == '__main__':
import os
dir = os.path.dirname(__file__)
StopFlagWatcher = os.path.join(dir, 'test/StopFlagWatcher')
file = open(StopFlagWatcher, 'w')
file.truncate()
file.close()
run(Apk(config.APK_FULL_PATH), config.EMULATOR_NAME, config.EMULATOR_PORT)
| {"/run_monkey_only.py": ["/util.py", "/api_commands.py", "/emulator_manager.py", "/config_reader.py", "/apk.py", "/mobile_monkey.py", "/telnet_connector.py", "/adb_logcat.py", "/log_analyzer.py"], "/adb_monkey.py": ["/config_reader.py", "/api_commands.py", "/emulator.py", "/apk.py", "/adb_settings.py", "/emulator_manager.py", "/adb_logcat.py"], "/log_analyzer.py": ["/util.py"], "/kill_emulator.py": ["/emulator_manager.py"], "/fuzz_context.py": ["/adb_logcat.py", "/emulator.py", "/adb_settings.py", "/mutex.py", "/telnet_connector.py", "/config_reader.py", "/interval_event.py"], "/interval_event.py": ["/adb_settings.py", "/telnet_connector.py", "/util.py", "/config_reader.py"], "/apk.py": ["/util.py", "/config_reader.py"], "/adb_settings.py": ["/config_reader.py", "/api_commands.py", "/util.py"], "/config_reader.py": ["/util.py"], "/api_commands.py": ["/config_reader.py", "/util.py", "/emulator.py", "/apk.py"], "/monkey.py": ["/config_reader.py", "/adb_logcat.py", "/apk.py", "/emulator.py", "/fuzz_context.py", "/adb_settings.py", "/telnet_connector.py", "/interval_event.py"], "/mobile_monkey.py": ["/config_reader.py", "/emulator_manager.py", "/api_commands.py", "/telnet_connector.py", "/emulator.py", "/fuzz_context.py", "/adb_settings.py", "/util.py", "/adb_monkey.py", "/apk.py", "/adb_logcat.py", "/log_analyzer.py"], "/adb_logcat.py": ["/api_commands.py", "/config_reader.py", "/emulator.py", "/apk.py"], "/telnet_connector.py": ["/config_reader.py", "/util.py"], "/install_app.py": ["/config_reader.py", "/emulator_manager.py", "/api_commands.py", "/telnet_connector.py", "/emulator.py", "/fuzz_context.py", "/adb_settings.py", "/util.py", "/adb_monkey.py", "/apk.py", "/adb_logcat.py", "/log_analyzer.py"], "/mobicomonkey.py": ["/config_reader.py", "/emulator.py", "/api_commands.py", "/apk.py", "/emulator_manager.py", "/xml_element.py", "/adb_settings.py", "/telnet_connector.py", "/util.py", "/monkey.py", "/adb_logcat.py", "/mutex.py", "/adb_monkey.py"], "/contextConfig_reader.py": ["/config_reader.py"], "/emulator_manager.py": ["/emulator.py", "/config_reader.py", "/contextConfig_reader.py", "/api_commands.py", "/util.py"], "/test.py": ["/api_commands.py", "/emulator_manager.py", "/config_reader.py", "/apk.py", "/adb_logcat.py", "/telnet_connector.py", "/adb_monkey.py", "/emulator.py", "/fuzz_context.py", "/adb_settings.py", "/interval_event.py"]} |
78,661 | LordAmit/mobile-monkey | refs/heads/master | /adb_logcat.py | from pathlib import Path
import shlex
import time
from enum import Enum
import subprocess
import api_commands
import config_reader as config
from emulator import Emulator
from apk import Apk
class TestType(Enum):
'''
Test types to be used by the logcat
'''
Monkey = 0
MobileMonkey = 1
class FatalWatcher():
def __init__(self, log_file_path: str) -> None:
self.log_file_path = log_file_path
self.file_contents = None
self.stop_watching = False
def has_fatal_exception_watch(self):
self.file_contents = Path(self.log_file_path).read_text()
if "FATAL" in self.file_contents:
return True
return False
def continuous_fatal_exception_watch(self):
while self.has_fatal_exception_watch():
if self.stop_watching is True:
break
time.sleep(3)
return False
class Logcat:
'''
Class logcat. instantiated by `Emulator` and `Apk`
'''
def __init__(self, emulator: Emulator, apk: Apk,
test_type: TestType)-> None:
self.emulator = emulator
self.apk = apk
self.package_name = apk.package_name
self.app_pid = None
self.log_process = None
self.test_type = test_type
self.file_address = config.CURRENT_DIRECTORY + "/test/logcat.log"
self.logfile = None
def start_logcat(self):
'''
starts logcat of this instance.
'''
self.app_pid = api_commands.adb_pidof_app(self.emulator, self.apk)
print("app_pid: " + self.app_pid)
self.clear_logcat()
command = config.adb + \
" logcat --format=threadtime *:W --pid=" + self.app_pid
self.logfile = open(self.file_address, 'w')
self.log_process = subprocess.Popen(
shlex.split(command), stdout=self.logfile)
# def experimental_start_logcat(self, fuzz: Fuzzer):
# '''
# starts logcat of this instance.
# '''
# self.app_pid = api_commands.adb_pidof_app(self.emulator, self.apk)
# print("app_pid: " + self.app_pid)
# print("experimental log")
# self.clear_logcat()
# command = "adb logcat --format=threadtime *:W --pid=" + self.app_pid
# self.logfile = open(self.file_address, 'w')
# self.log_process = subprocess.Popen(
# shlex.split(command), universal_newlines=True, stdout=subprocess.PIPE)
# while True:
# line = self.log_process.stdout.readline()
# self.logfile.write(line)
# if len(line) < 1:
# print("Fault")
# break
# print(line)
# if "FATAL" in line:
# fuzz.fatal_exception = True
# self.log_process = subprocess.Popen(
# shlex.split(command), stdout=subprocess.PIPE)
# while True:
# output = str(self.log_process.stdout.readline().decode())
# if output == '' and self.log_process.poll() is not None:
# self.logfile.close()
# self.log_process.kill()
# break
# if output:
# print(output.strip())
# self.logfile.write(output)
# if "FATAL" in output:
# print("fatal exception detected.")
# fuzz.fatal_exception = True
# self.logfile.close()
# self.log_process.kill()
# self.logfile.flush()
def stop_logcat(self):
'''
stops logcat of this instance and closes the file.
'''
self.logfile.close()
self.log_process.kill()
def clear_logcat(self):
'''
clears logcat
'''
command = config.adb + " logcat --clear"
subprocess.check_output(shlex.split(command))
| {"/run_monkey_only.py": ["/util.py", "/api_commands.py", "/emulator_manager.py", "/config_reader.py", "/apk.py", "/mobile_monkey.py", "/telnet_connector.py", "/adb_logcat.py", "/log_analyzer.py"], "/adb_monkey.py": ["/config_reader.py", "/api_commands.py", "/emulator.py", "/apk.py", "/adb_settings.py", "/emulator_manager.py", "/adb_logcat.py"], "/log_analyzer.py": ["/util.py"], "/kill_emulator.py": ["/emulator_manager.py"], "/fuzz_context.py": ["/adb_logcat.py", "/emulator.py", "/adb_settings.py", "/mutex.py", "/telnet_connector.py", "/config_reader.py", "/interval_event.py"], "/interval_event.py": ["/adb_settings.py", "/telnet_connector.py", "/util.py", "/config_reader.py"], "/apk.py": ["/util.py", "/config_reader.py"], "/adb_settings.py": ["/config_reader.py", "/api_commands.py", "/util.py"], "/config_reader.py": ["/util.py"], "/api_commands.py": ["/config_reader.py", "/util.py", "/emulator.py", "/apk.py"], "/monkey.py": ["/config_reader.py", "/adb_logcat.py", "/apk.py", "/emulator.py", "/fuzz_context.py", "/adb_settings.py", "/telnet_connector.py", "/interval_event.py"], "/mobile_monkey.py": ["/config_reader.py", "/emulator_manager.py", "/api_commands.py", "/telnet_connector.py", "/emulator.py", "/fuzz_context.py", "/adb_settings.py", "/util.py", "/adb_monkey.py", "/apk.py", "/adb_logcat.py", "/log_analyzer.py"], "/adb_logcat.py": ["/api_commands.py", "/config_reader.py", "/emulator.py", "/apk.py"], "/telnet_connector.py": ["/config_reader.py", "/util.py"], "/install_app.py": ["/config_reader.py", "/emulator_manager.py", "/api_commands.py", "/telnet_connector.py", "/emulator.py", "/fuzz_context.py", "/adb_settings.py", "/util.py", "/adb_monkey.py", "/apk.py", "/adb_logcat.py", "/log_analyzer.py"], "/mobicomonkey.py": ["/config_reader.py", "/emulator.py", "/api_commands.py", "/apk.py", "/emulator_manager.py", "/xml_element.py", "/adb_settings.py", "/telnet_connector.py", "/util.py", "/monkey.py", "/adb_logcat.py", "/mutex.py", "/adb_monkey.py"], "/contextConfig_reader.py": ["/config_reader.py"], "/emulator_manager.py": ["/emulator.py", "/config_reader.py", "/contextConfig_reader.py", "/api_commands.py", "/util.py"], "/test.py": ["/api_commands.py", "/emulator_manager.py", "/config_reader.py", "/apk.py", "/adb_logcat.py", "/telnet_connector.py", "/adb_monkey.py", "/emulator.py", "/fuzz_context.py", "/adb_settings.py", "/interval_event.py"]} |
78,662 | LordAmit/mobile-monkey | refs/heads/master | /telnet_connector.py | '''
telnet to adb connection and management module
'''
import telnetlib
from enum import Enum
import time
import config_reader as config
import util
PRINT_FLAG = True
class NetworkStatus(Enum):
'''
Network status possible values
'''
gsm = 0
hscsd = 1
gprs = 2
umts = 3
edge = 4
hsdpa = 5
lte = 6
evdo = 7
full = 8
class NetworkDelay(Enum):
'''
Network delay constants
'''
gsm = 0
edge = 1
umts = 2
none = 3
class GsmProfile(Enum):
'''
Gsm profile constants
'''
STRENGTH0 = 0
STRENGTH1 = 1
STRENGTH2 = 2
STRENGTH3 = 3
STRENGTH4 = 4
class TelnetAdb:
'''
Telnet to Android connector API
'''
GSM_BREAK = 10
telnet = None
def __init__(self, host: str='localhost',
port: int=int(config.EMULATOR_PORT))-> None:
'''initiates the telnet to adb connection at provided `host`:`port`'''
self.__establish_connection(host, port)
def __establish_connection(self, host: str, port: int):
try:
self.telnet = telnetlib.Telnet(host, int(port))
except ConnectionRefusedError:
raise ConnectionRefusedError("Connection refused")
self.__telnet_read_until()
self.__telnet_write_command('auth ' + config.TELNET_KEY)
def __telnet_write_command(self, command: str):
util.debug_print(command, flag=PRINT_FLAG)
telnet_command = bytes("{}\n".format(command), "ascii")
self.telnet.write(telnet_command)
def __telnet_read_until(self):
print(self.telnet.read_until(b'OK'))
def set_connection_speed(self, speed: NetworkStatus):
'''
sets connection speed, where `speed` is `NetworkStatus` type
'''
self.__telnet_write_command(
'network speed ' + str(speed.name))
def set_connection_delay(self, delay: NetworkDelay):
'''
sets connection delay, where `delay` is `NetworkDelay` type
'''
self.__telnet_write_command(
'network delay ' + delay.name)
def set_gsm_profile(self, profile: GsmProfile):
'''
sets GSM profile, where `profile` is `GsmProfile` type.
takes around 15 seconds for android OS to detect it
'''
self.__telnet_write_command('gsm signal-profile ' + str(profile.value))
time.sleep(self.GSM_BREAK)
def kill_avd(self):
'''
self destructs
'''
self.__telnet_write_command('kill')
def reset_gsm_profile(self):
'''
resets GSM profile to signal strength 4
'''
self.__telnet_write_command('gsm signal-profile 4')
time.sleep(self.GSM_BREAK)
def reset_network_delay(self):
'''
resets network delay to 0
'''
self.__telnet_write_command('network delay 0')
def reset_network_speed(self):
'''
resets network speed to full
'''
self.__telnet_write_command('network speed full')
def reset_all(self):
'''
resets by calling
>>> self.reset_network_delay()
>>> self.reset_network_speed()
>>> self.reset_gsm_profile()
'''
print("setting network delay to 0")
self.reset_network_delay()
print("setting network speed to full")
self.reset_network_speed()
print("resetting GSM profile")
self.reset_gsm_profile()
if __name__ == '__main__':
TNC = TelnetAdb(config.LOCALHOST, int(config.EMULATOR_PORT))
TNC.kill_avd()
| {"/run_monkey_only.py": ["/util.py", "/api_commands.py", "/emulator_manager.py", "/config_reader.py", "/apk.py", "/mobile_monkey.py", "/telnet_connector.py", "/adb_logcat.py", "/log_analyzer.py"], "/adb_monkey.py": ["/config_reader.py", "/api_commands.py", "/emulator.py", "/apk.py", "/adb_settings.py", "/emulator_manager.py", "/adb_logcat.py"], "/log_analyzer.py": ["/util.py"], "/kill_emulator.py": ["/emulator_manager.py"], "/fuzz_context.py": ["/adb_logcat.py", "/emulator.py", "/adb_settings.py", "/mutex.py", "/telnet_connector.py", "/config_reader.py", "/interval_event.py"], "/interval_event.py": ["/adb_settings.py", "/telnet_connector.py", "/util.py", "/config_reader.py"], "/apk.py": ["/util.py", "/config_reader.py"], "/adb_settings.py": ["/config_reader.py", "/api_commands.py", "/util.py"], "/config_reader.py": ["/util.py"], "/api_commands.py": ["/config_reader.py", "/util.py", "/emulator.py", "/apk.py"], "/monkey.py": ["/config_reader.py", "/adb_logcat.py", "/apk.py", "/emulator.py", "/fuzz_context.py", "/adb_settings.py", "/telnet_connector.py", "/interval_event.py"], "/mobile_monkey.py": ["/config_reader.py", "/emulator_manager.py", "/api_commands.py", "/telnet_connector.py", "/emulator.py", "/fuzz_context.py", "/adb_settings.py", "/util.py", "/adb_monkey.py", "/apk.py", "/adb_logcat.py", "/log_analyzer.py"], "/adb_logcat.py": ["/api_commands.py", "/config_reader.py", "/emulator.py", "/apk.py"], "/telnet_connector.py": ["/config_reader.py", "/util.py"], "/install_app.py": ["/config_reader.py", "/emulator_manager.py", "/api_commands.py", "/telnet_connector.py", "/emulator.py", "/fuzz_context.py", "/adb_settings.py", "/util.py", "/adb_monkey.py", "/apk.py", "/adb_logcat.py", "/log_analyzer.py"], "/mobicomonkey.py": ["/config_reader.py", "/emulator.py", "/api_commands.py", "/apk.py", "/emulator_manager.py", "/xml_element.py", "/adb_settings.py", "/telnet_connector.py", "/util.py", "/monkey.py", "/adb_logcat.py", "/mutex.py", "/adb_monkey.py"], "/contextConfig_reader.py": ["/config_reader.py"], "/emulator_manager.py": ["/emulator.py", "/config_reader.py", "/contextConfig_reader.py", "/api_commands.py", "/util.py"], "/test.py": ["/api_commands.py", "/emulator_manager.py", "/config_reader.py", "/apk.py", "/adb_logcat.py", "/telnet_connector.py", "/adb_monkey.py", "/emulator.py", "/fuzz_context.py", "/adb_settings.py", "/interval_event.py"]} |
78,663 | LordAmit/mobile-monkey | refs/heads/master | /install_app.py | '''
mobile monkey
'''
import time
from typing import List
from threading import Thread
import config_reader as config
import emulator_manager
import api_commands
from telnet_connector import TelnetAdb
from telnet_connector import GsmProfile
from telnet_connector import NetworkDelay
from telnet_connector import NetworkStatus
from emulator import Emulator
from fuzz_context import Fuzzer
from adb_settings import Airplane, KeyEvent, UserRotation
# import adb_settings as AdbSettings
import util
from adb_monkey import AdbMonkey
from apk import Apk
from adb_logcat import Logcat, TestType, FatalWatcher
from log_analyzer import Analyzer
PRINT_FLAG = True
TIME_PRINT_FLAG = True
emulator_model = config.EMULATOR_NAME
emulator_port = config.EMULATOR_PORT
contextual_events = 0
WILL_MONKEY = True
def start_emulator() -> bool:
'''
starts emulator
'''
command = config.EMULATOR
global emulator_model
if emulator_manager.adb_instances_manager():
util.debug_print('already emulators are running.', flag=PRINT_FLAG)
return True
else:
util.debug_print(
str.format("No emulator instance running. starting {} at port {}",
emulator_model, emulator_port), flag=PRINT_FLAG)
api_commands.adb_start_server_safe()
emulator_manager.emulator_start_avd(
emulator_port, emulator_model)
# subprocess.Popen([command,
# '-port', str(emulator_port), '-avd',
# emulator_name, '-use-system-libs'],
# stdout=subprocess.PIPE)
emulator_manager.check_avd_booted_completely(emulator_port)
return True
def run(apk: Apk, emulator_name: str, emulator_port: int):
'''
runs things
'''
to_kill = False
to_test = True
to_full_run = True
wipe_after_finish = True
# test_time_seconds = 30
if not start_emulator():
return
emulator = emulator_manager.get_adb_instance_from_emulators(emulator_name)
# emulator_name = 'emulator-' + emulator.port
# telnet_connector = TelnetAdb(config.LOCALHOST, emulator.port)
# apk = Apk(config.APK_FULL_PATH)
api_commands.adb_uninstall_apk(emulator, apk)
if config.OVERRIDE_UNSIGNED:
api_commands.decode_apk(apk)
api_commands.overwrite_android_manifest()
api_commands.build_apk(apk)
api_commands.sign_apk(apk)
api_commands.adb_install_apk(emulator, apk)
api_commands.adb_start_launcher_of_apk(emulator, apk)
# mobicomonkey.start_test()
if __name__ == '__main__':
run(Apk(config.APK_FULL_PATH), config.EMULATOR_NAME, config.EMULATOR_PORT)
| {"/run_monkey_only.py": ["/util.py", "/api_commands.py", "/emulator_manager.py", "/config_reader.py", "/apk.py", "/mobile_monkey.py", "/telnet_connector.py", "/adb_logcat.py", "/log_analyzer.py"], "/adb_monkey.py": ["/config_reader.py", "/api_commands.py", "/emulator.py", "/apk.py", "/adb_settings.py", "/emulator_manager.py", "/adb_logcat.py"], "/log_analyzer.py": ["/util.py"], "/kill_emulator.py": ["/emulator_manager.py"], "/fuzz_context.py": ["/adb_logcat.py", "/emulator.py", "/adb_settings.py", "/mutex.py", "/telnet_connector.py", "/config_reader.py", "/interval_event.py"], "/interval_event.py": ["/adb_settings.py", "/telnet_connector.py", "/util.py", "/config_reader.py"], "/apk.py": ["/util.py", "/config_reader.py"], "/adb_settings.py": ["/config_reader.py", "/api_commands.py", "/util.py"], "/config_reader.py": ["/util.py"], "/api_commands.py": ["/config_reader.py", "/util.py", "/emulator.py", "/apk.py"], "/monkey.py": ["/config_reader.py", "/adb_logcat.py", "/apk.py", "/emulator.py", "/fuzz_context.py", "/adb_settings.py", "/telnet_connector.py", "/interval_event.py"], "/mobile_monkey.py": ["/config_reader.py", "/emulator_manager.py", "/api_commands.py", "/telnet_connector.py", "/emulator.py", "/fuzz_context.py", "/adb_settings.py", "/util.py", "/adb_monkey.py", "/apk.py", "/adb_logcat.py", "/log_analyzer.py"], "/adb_logcat.py": ["/api_commands.py", "/config_reader.py", "/emulator.py", "/apk.py"], "/telnet_connector.py": ["/config_reader.py", "/util.py"], "/install_app.py": ["/config_reader.py", "/emulator_manager.py", "/api_commands.py", "/telnet_connector.py", "/emulator.py", "/fuzz_context.py", "/adb_settings.py", "/util.py", "/adb_monkey.py", "/apk.py", "/adb_logcat.py", "/log_analyzer.py"], "/mobicomonkey.py": ["/config_reader.py", "/emulator.py", "/api_commands.py", "/apk.py", "/emulator_manager.py", "/xml_element.py", "/adb_settings.py", "/telnet_connector.py", "/util.py", "/monkey.py", "/adb_logcat.py", "/mutex.py", "/adb_monkey.py"], "/contextConfig_reader.py": ["/config_reader.py"], "/emulator_manager.py": ["/emulator.py", "/config_reader.py", "/contextConfig_reader.py", "/api_commands.py", "/util.py"], "/test.py": ["/api_commands.py", "/emulator_manager.py", "/config_reader.py", "/apk.py", "/adb_logcat.py", "/telnet_connector.py", "/adb_monkey.py", "/emulator.py", "/fuzz_context.py", "/adb_settings.py", "/interval_event.py"]} |
78,664 | LordAmit/mobile-monkey | refs/heads/master | /mutex.py | ROTATION_MUTEX = 0
| {"/run_monkey_only.py": ["/util.py", "/api_commands.py", "/emulator_manager.py", "/config_reader.py", "/apk.py", "/mobile_monkey.py", "/telnet_connector.py", "/adb_logcat.py", "/log_analyzer.py"], "/adb_monkey.py": ["/config_reader.py", "/api_commands.py", "/emulator.py", "/apk.py", "/adb_settings.py", "/emulator_manager.py", "/adb_logcat.py"], "/log_analyzer.py": ["/util.py"], "/kill_emulator.py": ["/emulator_manager.py"], "/fuzz_context.py": ["/adb_logcat.py", "/emulator.py", "/adb_settings.py", "/mutex.py", "/telnet_connector.py", "/config_reader.py", "/interval_event.py"], "/interval_event.py": ["/adb_settings.py", "/telnet_connector.py", "/util.py", "/config_reader.py"], "/apk.py": ["/util.py", "/config_reader.py"], "/adb_settings.py": ["/config_reader.py", "/api_commands.py", "/util.py"], "/config_reader.py": ["/util.py"], "/api_commands.py": ["/config_reader.py", "/util.py", "/emulator.py", "/apk.py"], "/monkey.py": ["/config_reader.py", "/adb_logcat.py", "/apk.py", "/emulator.py", "/fuzz_context.py", "/adb_settings.py", "/telnet_connector.py", "/interval_event.py"], "/mobile_monkey.py": ["/config_reader.py", "/emulator_manager.py", "/api_commands.py", "/telnet_connector.py", "/emulator.py", "/fuzz_context.py", "/adb_settings.py", "/util.py", "/adb_monkey.py", "/apk.py", "/adb_logcat.py", "/log_analyzer.py"], "/adb_logcat.py": ["/api_commands.py", "/config_reader.py", "/emulator.py", "/apk.py"], "/telnet_connector.py": ["/config_reader.py", "/util.py"], "/install_app.py": ["/config_reader.py", "/emulator_manager.py", "/api_commands.py", "/telnet_connector.py", "/emulator.py", "/fuzz_context.py", "/adb_settings.py", "/util.py", "/adb_monkey.py", "/apk.py", "/adb_logcat.py", "/log_analyzer.py"], "/mobicomonkey.py": ["/config_reader.py", "/emulator.py", "/api_commands.py", "/apk.py", "/emulator_manager.py", "/xml_element.py", "/adb_settings.py", "/telnet_connector.py", "/util.py", "/monkey.py", "/adb_logcat.py", "/mutex.py", "/adb_monkey.py"], "/contextConfig_reader.py": ["/config_reader.py"], "/emulator_manager.py": ["/emulator.py", "/config_reader.py", "/contextConfig_reader.py", "/api_commands.py", "/util.py"], "/test.py": ["/api_commands.py", "/emulator_manager.py", "/config_reader.py", "/apk.py", "/adb_logcat.py", "/telnet_connector.py", "/adb_monkey.py", "/emulator.py", "/fuzz_context.py", "/adb_settings.py", "/interval_event.py"]} |
78,665 | LordAmit/mobile-monkey | refs/heads/master | /mobicomonkey.py | import config_reader as config
from emulator import Emulator
import api_commands
from apk import Apk
import emulator_manager
from xml.dom import minidom # type: ignore
from xml_element import XML_Element
from adb_settings import AdbSettings
from telnet_connector import TelnetAdb
import random
from typing import List
from threading import Thread
from adb_settings import KeyboardEvent
import os
import util
import monkey
from adb_logcat import Logcat, TestType
import mutex
dir = os.path.dirname(__file__)
eventFile = os.path.join(dir, 'test/EventLog')
StopFlagWatcher = os.path.join(dir, 'test/StopFlagWatcher')
eventlog = open(eventFile, 'w')
def reset_emulator(
host: str = config.LOCALHOST,
emulator_port: str = config.EMULATOR_PORT):
print("resetting emulator")
telnet_object = TelnetAdb(host, int(emulator_port))
telnet_object.reset_all()
adb_device = AdbSettings("emulator-" + str(emulator_port))
adb_device.reset_all()
def start_test():
apk = Apk(config.APK_FULL_PATH)
emulator = emulator_manager.get_adb_instance_from_emulators(
config.EMULATOR_NAME)
adb_settings = AdbSettings("emulator-" + str(emulator.port))
activities = []
log = Logcat(emulator, apk, TestType.MobileMonkey)
if config.GUIDED_APPROACH == 3:
monkey.run_contexts_only(
emulator, config.EMULATOR_NAME, config.EMULATOR_PORT,
config.SEED, log)
return
log.start_logcat()
activity = os.path.join(dir, 'test/activity')
activity_list = os.path.join(dir, 'test/activity_list')
if config.GUIDED_APPROACH == 2:
# file = open("test/activity", "w")
file = open(activity, "w")
file.write(api_commands.adb_get_activity_list(emulator, apk))
file.close()
# file = open('test/activity', 'r')
file = open(activity, 'r')
# file2 = open('test/activity_list', 'w')
file2 = open(activity_list, 'w')
for l in file.readlines():
if 'A: android:name' in l and 'Activity' in l:
arr = l.split('"')
activities.append(arr[1])
file2.write(arr[1] + "\n")
print(arr[1])
file.close()
file2.close()
# os.remove('test/activity')
os.remove(activity)
print(len(activities))
seed = config.SEED
for activity in activities:
try:
api_commands.adb_start_activity(emulator, apk, activity)
except Exception:
print(Exception)
threads = []
threads.append(Thread(target=monkey.run, args=(
emulator, apk, config.EMULATOR_NAME, config.EMULATOR_PORT,
seed, log)))
# monkey.run(emulator, apk, config.EMULATOR_NAME,
# config.EMULATOR_PORT, seed, log)
# threads.append(Thread(target=test_ui, args=(
# activity, emulator, adb_settings, display_height)))
from adb_monkey import AdbMonkey
ad_monkey = AdbMonkey(emulator, apk, seed, config.DURATION)
# ad_monkey.start_monkey()
threads.append(Thread(target=ad_monkey.start_monkey))
[thread.start() for thread in threads]
[thread.join() for thread in threads]
seed = seed + 1
log.stop_logcat()
eventlog.close()
return
if config.GUIDED_APPROACH == 1:
# file = open('test/activity_list', 'r')
file = open(activity_list, 'r')
for l in file.readlines():
activities.append(l.strip())
print(l.strip())
file.close()
else:
# file = open("test/activity", "w")
file = open(activity, "w")
file.write(api_commands.adb_get_activity_list(emulator, apk))
file.close()
# file = open('test/activity', 'r')
# file2 = open('test/activity_list', 'w')
file = open(activity, 'r')
file2 = open(activity_list, 'w')
for l in file.readlines():
if 'A: android:name' in l and 'Activity' in l:
arr = l.split('"')
activities.append(arr[1])
file2.write(arr[1] + "\n")
print(arr[1])
file.close()
file2.close()
# os.remove('test/activity')
os.remove(activity)
print(len(activities))
display_properties = api_commands.adb_display_properties().decode()
if 'DisplayDeviceInfo' in display_properties:
arr = display_properties.split('height=')[1]
display_height = arr.split(',')[0]
seed = config.SEED
for activity in activities:
try:
api_commands.adb_start_activity(emulator, apk, activity)
except Exception:
print(Exception)
threads = []
threads.append(Thread(target=monkey.run, args=(
emulator, apk, config.EMULATOR_NAME, config.EMULATOR_PORT,
seed, log)))
# monkey.run(emulator, apk, config.EMULATOR_NAME,
# config.EMULATOR_PORT, seed, log)
threads.append(Thread(target=test_ui, args=(
activity, emulator, adb_settings, display_height)))
[thread.start() for thread in threads]
[thread.join() for thread in threads]
seed = seed + 1
log.stop_logcat()
eventlog.close()
def force_update_element_list(emulator: Emulator, adb_settings: AdbSettings):
print("found mutex = " + str(mutex.ROTATION_MUTEX))
print("element list force update here.")
element_list = get_elements_list(emulator, adb_settings)
mutex.ROTATION_MUTEX = 0
print("reset the MUTEX after update.")
return element_list
def test_ui(activity: str, emulator: Emulator, adb_settings: AdbSettings,
display_height: str):
# file = open('test/StopFlagWatcher', 'w')
file = open(StopFlagWatcher, 'w')
file.truncate()
element_list = get_elements_list(emulator, adb_settings)
while len(element_list) > 0:
traverse_elements(activity, element_list, emulator, adb_settings)
previous_elements = element_list
api_commands.adb_display_scroll("{}".format(
int(display_height) - int(display_height) / 10))
element_list = get_elements_list(emulator, adb_settings)
element_list = element_list_compare(previous_elements, element_list)
file.write("1")
def element_list_compare(previous_elements: List[XML_Element],
current_elements: List[XML_Element]):
for previous_item in previous_elements:
for current_item in current_elements:
if previous_item.resource_id == current_item.resource_id:
print('matched')
current_elements.remove(current_item)
return current_elements
def traverse_elements(activity: str, element_list: List[XML_Element],
emulator: Emulator, adb_settings: AdbSettings):
for i in range(0, len(element_list)):
if(mutex.ROTATION_MUTEX):
element_list = element_list_compare(element_list[0:i],
force_update_element_list(
emulator, adb_settings))
for j in range(0, len(element_list)):
input_key_event(
activity, element_list[j], emulator, adb_settings)
break
# print(item.resource_id, item.xpos, item.ypos)
input_key_event(activity, element_list[i], emulator, adb_settings)
def input_key_event(activity: str, item: XML_Element,
emulator: Emulator, adb_settings: AdbSettings):
api_commands.adb_input_tap(emulator, item.xpos, item.ypos)
rand = random.randint(config.MINIMUM_KEYEVENT, config.MAXIMUM_KEYEVENT)
for i in range(rand):
KeyCode = KeyboardEvent(random.randint(0, 40)).name
print("Sending event " + KeyCode)
adb_settings.adb_send_key_event_test(KeyCode)
eventlog.write(util.return_current_time_in_logcat_style() + '\t' +
activity + '\t' + item.resource_id +
'\t' + KeyCode + '\n')
adb_settings.adb_send_key_event_test("KEYCODE_BACK")
def get_elements_list(emulator: Emulator, adb_settings: AdbSettings) -> List:
xmldoc = minidom.parse(api_commands.adb_uiautomator_dump(emulator))
element_list = []
itemlist = xmldoc.getElementsByTagName('node')
for s in itemlist:
if s.attributes['class'].value in ["android.widget.EditText"]:
bounds = s.attributes['bounds'].value.split("][")
Lpos = bounds[0][1:]
Rpos = bounds[1][:len(bounds[1]) - 1]
x1 = int(Lpos.split(",")[0])
y1 = int(Lpos.split(",")[1])
x2 = int(Rpos.split(",")[0])
y2 = int(Rpos.split(",")[1])
x = XML_Element(s.attributes['resource-id'].value,
s.attributes['class'].value,
s.attributes['checkable'].value,
s.attributes['checked'].value,
s.attributes['clickable'].value,
s.attributes['enabled'].value,
s.attributes['focusable'].value,
s.attributes['focused'].value,
s.attributes['scrollable'].value,
s.attributes['long-clickable'].value,
s.attributes['password'].value,
s.attributes['selected'].value,
(x1 + x2) / 2,
(y1 + y2) / 2)
element_list.append(x)
return element_list
if __name__ == '__main__':
file = open(StopFlagWatcher, 'w')
file.truncate()
file.close()
start_test()
reset_emulator()
| {"/run_monkey_only.py": ["/util.py", "/api_commands.py", "/emulator_manager.py", "/config_reader.py", "/apk.py", "/mobile_monkey.py", "/telnet_connector.py", "/adb_logcat.py", "/log_analyzer.py"], "/adb_monkey.py": ["/config_reader.py", "/api_commands.py", "/emulator.py", "/apk.py", "/adb_settings.py", "/emulator_manager.py", "/adb_logcat.py"], "/log_analyzer.py": ["/util.py"], "/kill_emulator.py": ["/emulator_manager.py"], "/fuzz_context.py": ["/adb_logcat.py", "/emulator.py", "/adb_settings.py", "/mutex.py", "/telnet_connector.py", "/config_reader.py", "/interval_event.py"], "/interval_event.py": ["/adb_settings.py", "/telnet_connector.py", "/util.py", "/config_reader.py"], "/apk.py": ["/util.py", "/config_reader.py"], "/adb_settings.py": ["/config_reader.py", "/api_commands.py", "/util.py"], "/config_reader.py": ["/util.py"], "/api_commands.py": ["/config_reader.py", "/util.py", "/emulator.py", "/apk.py"], "/monkey.py": ["/config_reader.py", "/adb_logcat.py", "/apk.py", "/emulator.py", "/fuzz_context.py", "/adb_settings.py", "/telnet_connector.py", "/interval_event.py"], "/mobile_monkey.py": ["/config_reader.py", "/emulator_manager.py", "/api_commands.py", "/telnet_connector.py", "/emulator.py", "/fuzz_context.py", "/adb_settings.py", "/util.py", "/adb_monkey.py", "/apk.py", "/adb_logcat.py", "/log_analyzer.py"], "/adb_logcat.py": ["/api_commands.py", "/config_reader.py", "/emulator.py", "/apk.py"], "/telnet_connector.py": ["/config_reader.py", "/util.py"], "/install_app.py": ["/config_reader.py", "/emulator_manager.py", "/api_commands.py", "/telnet_connector.py", "/emulator.py", "/fuzz_context.py", "/adb_settings.py", "/util.py", "/adb_monkey.py", "/apk.py", "/adb_logcat.py", "/log_analyzer.py"], "/mobicomonkey.py": ["/config_reader.py", "/emulator.py", "/api_commands.py", "/apk.py", "/emulator_manager.py", "/xml_element.py", "/adb_settings.py", "/telnet_connector.py", "/util.py", "/monkey.py", "/adb_logcat.py", "/mutex.py", "/adb_monkey.py"], "/contextConfig_reader.py": ["/config_reader.py"], "/emulator_manager.py": ["/emulator.py", "/config_reader.py", "/contextConfig_reader.py", "/api_commands.py", "/util.py"], "/test.py": ["/api_commands.py", "/emulator_manager.py", "/config_reader.py", "/apk.py", "/adb_logcat.py", "/telnet_connector.py", "/adb_monkey.py", "/emulator.py", "/fuzz_context.py", "/adb_settings.py", "/interval_event.py"]} |
78,666 | LordAmit/mobile-monkey | refs/heads/master | /util.py | """
util module
"""
from time import strftime, localtime
from typing import List, Any
import enum
import os
import shutil
import subprocess
def show_step(step):
"""
shows step
"""
if True:
print(step)
def check_file_directory_exists(address: str, to_quit: bool):
"""
checks if specified directory exists. if not, exits.
:param address: address of file or directory to be checked.
:param to_quit: determines if to exit if address does not exist.
"""
if os.path.exists(address):
return True
else:
print(address + " does not exist")
if not to_quit:
return False
else:
quit()
return False
def move_dir_safe(source: str, destination: str):
'''
moves directory from `source` to `destination`
'''
if os.path.isdir(source) and os.path.isdir(destination):
print('checked. Moving ', source, destination)
remove_existing_file_directory(destination)
shutil.move(source, destination)
else:
print('something wrong with safe_move: ')
print(source, destination)
def StringToBoolean(value: str):
if value == "True":
return True
elif value == "False":
return False
else:
raise ValueError("value must be True/False. You provided: "+value)
def remove_existing_file_directory(address: str):
"""
checks if the file/directory exists is provided address.
if exists, removes. if not, nothing!
:param address: address of file or directory
"""
if check_file_directory_exists(address, False):
try:
shutil.rmtree(address)
except NotADirectoryError:
os.remove(address)
def kill_process_using_pid(pid: str):
'''
kills a process using specified `pid`
'''
if pid:
try:
subprocess.check_output(['kill', '-9', pid])
print('killed process using pid: ' + pid)
except subprocess.CalledProcessError:
print('error. most possibly there is no pid by ' + pid)
def detail_print(variable):
'''
pretty prints the `variable`. If it is a `List`, it prints accordingly.
'''
import pprint
if isinstance(variable, List):
for i in variable:
try:
pprint.pprint(i.__dict__)
except AttributeError:
if isinstance(i, str):
print(i)
else:
pprint.pprint(variable.__dict__)
def list_as_enum_name_list(integer_list: List[int], enum_type) -> List[str]:
'''
replaces values based on names of enums
'''
if not integer_list:
raise ValueError("List must not be empty")
if not isinstance(enum_type, enum.EnumMeta):
raise ValueError("enum_type must be enum")
enum_name_list = []
for i in integer_list:
enum_name_list.append(enum_type(i).name)
return enum_name_list
def return_current_time():
'''
returns current time in YYYYMMDDHHmm format.
'''
return strftime("%Y%m%d%H%M", localtime())
def return_current_time_in_logcat_style():
'''
return current time in logcat threadtime style
"%m-%d %H::%M::%S"
'''
return strftime("%m-%d %H:%M:%S", localtime())
def debug_print(*msg: Any, flag: bool):
'''
prints if the provided flag is true
'''
if flag:
print(msg)
def pid_from_emulator_port(emulator_port: str) -> int:
'''
:param emulator_port:
integer `emulator_port`
returns:
PID of provided `emulator_port`
'''
tcp_port = "tcp:" + str(emulator_port)
# lsof -sTcp:LISTEN -iTcp:5555
pid = subprocess.check_output(
['lsof', '-sTcp:LISTEN', '-i', tcp_port])
pid = pid.decode()
# COMMAND PID USER FD TYPE DEVICE SIZE/OFF NODE NAME
# qemu-syst 11803 amit 52u IPv4 1855210 0t0 TCP localhost:5555
# (LISTEN)
pid = pid.split('\n')[1:][0].split(' ')[1]
# 11803
return int(pid)
def ps_details_of_pid(pid: int) -> str:
'''
retuns:
device details from `pid`
'''
device_details = subprocess.check_output(['ps', str(pid)])
device_details = device_details.decode().strip()
return device_details
def change_file_permission(filename_with_full_path: str, permission: int):
'''
`permission` in 3 digit number
'''
check_file_directory_exists(filename_with_full_path, True)
subprocess.check_output(
['chmod', str(permission), filename_with_full_path])
def print_dual_list(list_one: List, list_two: List):
'''
prints two same length lists matching each other in the following format.
eg:
>>> "{}: {}".format(list_one[i], list_two[i])
'''
if not len(list_one) == len(list_two):
raise ValueError("List length mismatched")
for i in range(0, len(list_one) - 1):
print("{}: {}".format(list_one[i], list_two[i]))
| {"/run_monkey_only.py": ["/util.py", "/api_commands.py", "/emulator_manager.py", "/config_reader.py", "/apk.py", "/mobile_monkey.py", "/telnet_connector.py", "/adb_logcat.py", "/log_analyzer.py"], "/adb_monkey.py": ["/config_reader.py", "/api_commands.py", "/emulator.py", "/apk.py", "/adb_settings.py", "/emulator_manager.py", "/adb_logcat.py"], "/log_analyzer.py": ["/util.py"], "/kill_emulator.py": ["/emulator_manager.py"], "/fuzz_context.py": ["/adb_logcat.py", "/emulator.py", "/adb_settings.py", "/mutex.py", "/telnet_connector.py", "/config_reader.py", "/interval_event.py"], "/interval_event.py": ["/adb_settings.py", "/telnet_connector.py", "/util.py", "/config_reader.py"], "/apk.py": ["/util.py", "/config_reader.py"], "/adb_settings.py": ["/config_reader.py", "/api_commands.py", "/util.py"], "/config_reader.py": ["/util.py"], "/api_commands.py": ["/config_reader.py", "/util.py", "/emulator.py", "/apk.py"], "/monkey.py": ["/config_reader.py", "/adb_logcat.py", "/apk.py", "/emulator.py", "/fuzz_context.py", "/adb_settings.py", "/telnet_connector.py", "/interval_event.py"], "/mobile_monkey.py": ["/config_reader.py", "/emulator_manager.py", "/api_commands.py", "/telnet_connector.py", "/emulator.py", "/fuzz_context.py", "/adb_settings.py", "/util.py", "/adb_monkey.py", "/apk.py", "/adb_logcat.py", "/log_analyzer.py"], "/adb_logcat.py": ["/api_commands.py", "/config_reader.py", "/emulator.py", "/apk.py"], "/telnet_connector.py": ["/config_reader.py", "/util.py"], "/install_app.py": ["/config_reader.py", "/emulator_manager.py", "/api_commands.py", "/telnet_connector.py", "/emulator.py", "/fuzz_context.py", "/adb_settings.py", "/util.py", "/adb_monkey.py", "/apk.py", "/adb_logcat.py", "/log_analyzer.py"], "/mobicomonkey.py": ["/config_reader.py", "/emulator.py", "/api_commands.py", "/apk.py", "/emulator_manager.py", "/xml_element.py", "/adb_settings.py", "/telnet_connector.py", "/util.py", "/monkey.py", "/adb_logcat.py", "/mutex.py", "/adb_monkey.py"], "/contextConfig_reader.py": ["/config_reader.py"], "/emulator_manager.py": ["/emulator.py", "/config_reader.py", "/contextConfig_reader.py", "/api_commands.py", "/util.py"], "/test.py": ["/api_commands.py", "/emulator_manager.py", "/config_reader.py", "/apk.py", "/adb_logcat.py", "/telnet_connector.py", "/adb_monkey.py", "/emulator.py", "/fuzz_context.py", "/adb_settings.py", "/interval_event.py"]} |
78,667 | LordAmit/mobile-monkey | refs/heads/master | /contextConfig_reader.py | '''
context config reader for app
'''
import configparser as ConfigParser
import config_reader as config
class ContextConfigReader(object):
'''
reads the context config
'''
def __init__(self):
pass
@staticmethod
def context_config_reader(option, uid):
'''
reads the config file in the specified uid:
:param option: specifies the option to look for
:param uid: specifies the UID of the folder containing the contextConfigFile
'''
context_config = ConfigParser.ConfigParser()
context_config_file_location = config.TEMP + uid + '/contextConfigFile'
# context_config.read(
# "/home/amit/git/
# mobile_application_contextual_testing/emulator_manager/temp/contextConfigFile")
try:
context_config.read(context_config_file_location)
value = context_config.get('context', option)
return value
except ConfigParser.NoSectionError:
print("Error: section context not found")
exit()
except FileNotFoundError:
print(context_config_file_location + " not found: ")
exit()
| {"/run_monkey_only.py": ["/util.py", "/api_commands.py", "/emulator_manager.py", "/config_reader.py", "/apk.py", "/mobile_monkey.py", "/telnet_connector.py", "/adb_logcat.py", "/log_analyzer.py"], "/adb_monkey.py": ["/config_reader.py", "/api_commands.py", "/emulator.py", "/apk.py", "/adb_settings.py", "/emulator_manager.py", "/adb_logcat.py"], "/log_analyzer.py": ["/util.py"], "/kill_emulator.py": ["/emulator_manager.py"], "/fuzz_context.py": ["/adb_logcat.py", "/emulator.py", "/adb_settings.py", "/mutex.py", "/telnet_connector.py", "/config_reader.py", "/interval_event.py"], "/interval_event.py": ["/adb_settings.py", "/telnet_connector.py", "/util.py", "/config_reader.py"], "/apk.py": ["/util.py", "/config_reader.py"], "/adb_settings.py": ["/config_reader.py", "/api_commands.py", "/util.py"], "/config_reader.py": ["/util.py"], "/api_commands.py": ["/config_reader.py", "/util.py", "/emulator.py", "/apk.py"], "/monkey.py": ["/config_reader.py", "/adb_logcat.py", "/apk.py", "/emulator.py", "/fuzz_context.py", "/adb_settings.py", "/telnet_connector.py", "/interval_event.py"], "/mobile_monkey.py": ["/config_reader.py", "/emulator_manager.py", "/api_commands.py", "/telnet_connector.py", "/emulator.py", "/fuzz_context.py", "/adb_settings.py", "/util.py", "/adb_monkey.py", "/apk.py", "/adb_logcat.py", "/log_analyzer.py"], "/adb_logcat.py": ["/api_commands.py", "/config_reader.py", "/emulator.py", "/apk.py"], "/telnet_connector.py": ["/config_reader.py", "/util.py"], "/install_app.py": ["/config_reader.py", "/emulator_manager.py", "/api_commands.py", "/telnet_connector.py", "/emulator.py", "/fuzz_context.py", "/adb_settings.py", "/util.py", "/adb_monkey.py", "/apk.py", "/adb_logcat.py", "/log_analyzer.py"], "/mobicomonkey.py": ["/config_reader.py", "/emulator.py", "/api_commands.py", "/apk.py", "/emulator_manager.py", "/xml_element.py", "/adb_settings.py", "/telnet_connector.py", "/util.py", "/monkey.py", "/adb_logcat.py", "/mutex.py", "/adb_monkey.py"], "/contextConfig_reader.py": ["/config_reader.py"], "/emulator_manager.py": ["/emulator.py", "/config_reader.py", "/contextConfig_reader.py", "/api_commands.py", "/util.py"], "/test.py": ["/api_commands.py", "/emulator_manager.py", "/config_reader.py", "/apk.py", "/adb_logcat.py", "/telnet_connector.py", "/adb_monkey.py", "/emulator.py", "/fuzz_context.py", "/adb_settings.py", "/interval_event.py"]} |
78,668 | LordAmit/mobile-monkey | refs/heads/master | /emulator_manager.py | '''
Emulator Manager
'''
import subprocess
import shlex
import time
import os
from typing import List
from emulator import Emulator
import config_reader as config
from contextConfig_reader import ContextConfigReader as c_config
import api_commands
import util
emulator_processes: List = []
context_list = {}
PRINT_FLAG = False
def get_context(uid: str= "mostaque#1485838365"):
'''
gets the full contexts from contextConfigFile from specified project
'''
list1 = ['emulator_name', 'abi', 'android_version',
'net_speed', 'net_delay', 'cpu_delay', 'Screen_orientation']
i = 0
for items in list1:
command = c_config.context_config_reader(str(list1[i]), uid)
context_list.update({list1[i]: command})
i += 1
print(context_list)
return context_list
def create_emulator():
android = config.get('android')
target_id = 5
emulator_create = subprocess.Popen(
[android, 'create', 'avd', '-n', context_list['emulator_name'], '-t',
str(target_id), '-b',
context_list['abi']], stdin=subprocess.PIPE)
stri = str('n').encode('utf-8')
emulator_create.stdin.write(stri)
return emulator_create
def get_avd_list():
'''
returns a list of avds
'''
return api_commands.emulator_list_of_avds()
def get_running_avd_ports() -> List:
'''
returns a list containing ports of running avds
'''
return api_commands.adb_list_avd_ports()
def kill_emulator(port: int = config.EMULATOR_PORT):
# android = config.get('android')
# process = subprocess.Popen(
# [android, 'delete', 'avd', '-n', context_list['emulator_name']])
command = "{} -s emulator-{} emu kill".format(config.adb, port)
subprocess.check_output(shlex.split(command))
def check_avd_booted_completely(emulator_port) -> str:
"""
Checks if the AVD specified in ``port`` is booted completely
through a system call:
>>> adb -s emulator-5555 shell getprop sys.boot_completed
it returns 1 if boot is completed.
args:
emulator_port (int): The port of the emulator
returns:
if completed, returns 1. Otherwise, continues checking.
"""
port = "emulator-"
port = port + str(emulator_port)
adb = config.adb
print(port)
print("going to sleep")
time.sleep(20)
i = 0
while True:
check = subprocess.check_output(
[adb, '-s', port, 'shell', 'getprop', 'sys.boot_completed'])
check = check.decode().strip()
if check == "1":
print("completed")
return "1"
time.sleep(2)
i = i + 1
print("wait" + str(i))
# check = int(check)
# return check
# def check_running_avd():
# '''
# check if required avd in contextConfig in running avds
# '''
# list_avds = config.avd_file_reader()
# list_avds.pop(-1)
# emulator_instances = adb_instances_manager()
# running_emulator_model = []
# valid_model = []
# for instance in emulator_instances:
# running_emulator_model.append(instance.model)
# for avd in list_avds:
# if avd in running_emulator_model:
# pass
# else:
# valid_model.append(avd)
# print(valid_model)
# return valid_model
# def emulator_runner(contexts: List):
# '''
# runs emulator based on the settings provided in context
# '''
# util.show_step(1)
# print(contexts['emulator_name'])
# if not is_context_avd_in_system_avds(contexts['emulator_name']):
# print('Error: provided context_avd ' +
# contexts['emulator_name'] + ' is not present in list of avds')
# print('Possible list of Avds are: ')
# util.detail_print(get_avd_list())
# return
# api_commands.adb_start_server_safe()
# util.show_step(4)
# avds = check_running_avd()
# if avds:
# emulator_port = get_running_avd_ports()
# if emulator_port:
# emulator_port = int(emulator_port[-1]) + 2
# else:
# emulator_port = 5555
# print(emulator_port)
#
# The console port number must be an even integer between 5554 and 5584,
# inclusive. <port>+1 must also be free and will be reserved for ADB.
#
# for name in avds:
# print(name)
command = config.EMULATOR
# command_argument = " -avd " + name
# print(command_argument)
# print(command + command_argument)
subprocess.Popen([command,
'-port', str(emulator_port), '-avd',
context_list['emulator_name'], '-use-system-libs'],
stdout=subprocess.PIPE)
# print(current_process.pid, emulator_port)
check = check_avd_booted_completely(emulator_port)
if check == "1":
print(context_list['emulator_name'] + " has booted completely")
flag = True
return flag
else:
print(context_list['emulator_name'] + " has not booted completely")
flag = False
return flag
# emulator_port += 2
# emulator_processes.append(current_process)
# else:
# print ("all AVD is allready running")
def get_name(uid):
path = os.getcwd() + '/temp/' + uid + '/' + uid + '/context'
with open(path, 'r') as f:
first_line = f.readline()
return first_line
def adb_instances_manager() -> List[Emulator]:
'''
returns the List of emulators.
:returns `List[Emulator]`:
'''
emulators = []
api_commands.adb_start_server_safe()
adb_ports = api_commands.adb_list_avd_ports()
for adb_port in adb_ports:
pid = util.pid_from_emulator_port(adb_port)
model = api_commands.avd_model_from_pid(pid)
current_emulator = Emulator(int(adb_port), pid, model)
emulators.append(current_emulator)
util.detail_print(emulators)
return emulators
def get_list_emulators():
return adb_instances_manager()
def get_adb_instance_from_emulators(model: str) -> Emulator:
'''
returns the Emulator data type if specified model is matched.
example:
>>> get_adb_instances_from_emulators('Nexus6')
'''
emulators = adb_instances_manager()
for emulator in emulators:
if emulator.model == model:
return emulator
raise ValueError('No emulator found for ' + model)
def get_processid_of_adb_instance_by_model(emulators: List[Emulator],
model: str):
'''
returns the PID of running adb_instance when the model name is specified
'''
if emulators and model:
for emulator in emulators:
if emulator.model == model:
return emulator.pid
else:
return None
def get_device_emulator_model(output_raw):
# print(output_raw)
"""
PID TTY STAT TIME COMMAND
15522 tty2 Rl+ 128:13 /home/amit/Android/Sdk/tools/emulator64-x86 -port 5557 -avd nexus_s # noqa
"""
current_string = output_raw.split('\n')[1:][:1][0]
"""
15521 tty2 Rl+ 134:48 /home/amit/Android/Sdk/tools/emulator64-x86 -port 5555 -avd nexus_4# noqa
"""
index_of_avd = current_string.index('-avd')
"""
nexus_s
"""
return current_string[index_of_avd + 5:]
def is_context_avd_in_system_avds(context_avd: str) -> bool:
'''
returns boolean, if the provided `avd` name is in the list of System Avds
'''
if context_avd in get_avd_list():
return True
else:
return False
def emulator_wipe_data(emulator: Emulator):
'''
wipes data for the specified emulator by `port`
'''
subprocess.check_output(
[config.EMULATOR, '@' + emulator.model, '-wipe-data'])
def emulator_start_avd(port: int, emulator_name: str):
'''
starts emulator at the designated `port` specified by the `emulator_name`.# noqa
Internally, it observers headless flag from config file to start emulator in headless mode.# noqa
'''
if config.HEADLESS:
command = "{} -port {} -avd {} -no-skin -no-audio -no-window".format(
config.EMULATOR, str(port), emulator_name)
else:
command = "{} -port {} -avd {} -accel auto -use-system-libs".format(
config.EMULATOR, str(port), emulator_name)
subprocess.Popen(shlex.split(command),
stdout=subprocess.PIPE)
if __name__ == '__main__':
# emulator_runner()
adb_instances_manager()
| {"/run_monkey_only.py": ["/util.py", "/api_commands.py", "/emulator_manager.py", "/config_reader.py", "/apk.py", "/mobile_monkey.py", "/telnet_connector.py", "/adb_logcat.py", "/log_analyzer.py"], "/adb_monkey.py": ["/config_reader.py", "/api_commands.py", "/emulator.py", "/apk.py", "/adb_settings.py", "/emulator_manager.py", "/adb_logcat.py"], "/log_analyzer.py": ["/util.py"], "/kill_emulator.py": ["/emulator_manager.py"], "/fuzz_context.py": ["/adb_logcat.py", "/emulator.py", "/adb_settings.py", "/mutex.py", "/telnet_connector.py", "/config_reader.py", "/interval_event.py"], "/interval_event.py": ["/adb_settings.py", "/telnet_connector.py", "/util.py", "/config_reader.py"], "/apk.py": ["/util.py", "/config_reader.py"], "/adb_settings.py": ["/config_reader.py", "/api_commands.py", "/util.py"], "/config_reader.py": ["/util.py"], "/api_commands.py": ["/config_reader.py", "/util.py", "/emulator.py", "/apk.py"], "/monkey.py": ["/config_reader.py", "/adb_logcat.py", "/apk.py", "/emulator.py", "/fuzz_context.py", "/adb_settings.py", "/telnet_connector.py", "/interval_event.py"], "/mobile_monkey.py": ["/config_reader.py", "/emulator_manager.py", "/api_commands.py", "/telnet_connector.py", "/emulator.py", "/fuzz_context.py", "/adb_settings.py", "/util.py", "/adb_monkey.py", "/apk.py", "/adb_logcat.py", "/log_analyzer.py"], "/adb_logcat.py": ["/api_commands.py", "/config_reader.py", "/emulator.py", "/apk.py"], "/telnet_connector.py": ["/config_reader.py", "/util.py"], "/install_app.py": ["/config_reader.py", "/emulator_manager.py", "/api_commands.py", "/telnet_connector.py", "/emulator.py", "/fuzz_context.py", "/adb_settings.py", "/util.py", "/adb_monkey.py", "/apk.py", "/adb_logcat.py", "/log_analyzer.py"], "/mobicomonkey.py": ["/config_reader.py", "/emulator.py", "/api_commands.py", "/apk.py", "/emulator_manager.py", "/xml_element.py", "/adb_settings.py", "/telnet_connector.py", "/util.py", "/monkey.py", "/adb_logcat.py", "/mutex.py", "/adb_monkey.py"], "/contextConfig_reader.py": ["/config_reader.py"], "/emulator_manager.py": ["/emulator.py", "/config_reader.py", "/contextConfig_reader.py", "/api_commands.py", "/util.py"], "/test.py": ["/api_commands.py", "/emulator_manager.py", "/config_reader.py", "/apk.py", "/adb_logcat.py", "/telnet_connector.py", "/adb_monkey.py", "/emulator.py", "/fuzz_context.py", "/adb_settings.py", "/interval_event.py"]} |
78,669 | LordAmit/mobile-monkey | refs/heads/master | /test.py | import os
import api_commands
import emulator_manager
import config_reader as config
from apk import Apk
import api_commands
from adb_logcat import Logcat, TestType
activities = []
apk = Apk(config.APK_FULL_PATH)
emulator = emulator_manager.get_adb_instance_from_emulators(
config.EMULATOR_NAME)
# file = open("test/activity", "w")
# file.write(api_commands.adb_get_activity_list(emulator, apk))
# file.close()
# file = open('test/activity', 'r')
# file2 = open('test/activity_list', 'w')
# for l in file.readlines():
# if 'A: android:name' in l and 'Activity' in l:
# arr = l.split('"')
# activities.append(arr[1])
# file2.write(arr[1] + "\n")
# print(arr[1])
# file.close()
# file2.close()
# os.remove('test/activity')
from telnet_connector import TelnetAdb
import adb_monkey
from adb_logcat import Logcat
from threading import Thread
from typing import List
import os
import config_reader as config
from adb_logcat import FatalWatcher, Logcat
from apk import Apk
from emulator import Emulator
from fuzz_context import Fuzzer
from adb_settings import Airplane, UserRotation
from telnet_connector import GsmProfile, NetworkDelay, NetworkStatus
import interval_event
PRINT_FLAG = True
dir = os.path.dirname(__file__)
network_delay = os.path.join(dir, 'test/networkdelay.txt')
network_status = os.path.join(dir, 'test/networkstatus.txt')
gsm_profile = os.path.join(dir, 'test/gsmprofile.txt')
print(network_delay)
print(network_status)
threads = []
log = Logcat(emulator, apk, TestType.MobileMonkey)
fuzz = Fuzzer(config.MINIMUM_INTERVAL,
config.MAXIMUM_INTERVAL, config.SEED, config.DURATION,
FatalWatcher(log.file_address))
# if config.CONTEXT_FILE == 1:
# network_delay_interval_events =\
# interval_event.read_interval_event_from_file(
# network_delay, NetworkDelay)
# else:
# network_delay_interval_events = fuzz.generate_step_interval_event(
# NetworkDelay)
# threads.append(Thread(target=fuzz.random_network_delay, args=(
# config.LOCALHOST, emulator, network_delay_interval_events)))
tel = TelnetAdb()
tel.set_gsm_profile(GsmProfile.STRENGTH4)
# [thread.start() for thread in threads]
# [thread.join() for thread in threads]
# emulator_mana11ger.emulator_wipe_data(emulator)
| {"/run_monkey_only.py": ["/util.py", "/api_commands.py", "/emulator_manager.py", "/config_reader.py", "/apk.py", "/mobile_monkey.py", "/telnet_connector.py", "/adb_logcat.py", "/log_analyzer.py"], "/adb_monkey.py": ["/config_reader.py", "/api_commands.py", "/emulator.py", "/apk.py", "/adb_settings.py", "/emulator_manager.py", "/adb_logcat.py"], "/log_analyzer.py": ["/util.py"], "/kill_emulator.py": ["/emulator_manager.py"], "/fuzz_context.py": ["/adb_logcat.py", "/emulator.py", "/adb_settings.py", "/mutex.py", "/telnet_connector.py", "/config_reader.py", "/interval_event.py"], "/interval_event.py": ["/adb_settings.py", "/telnet_connector.py", "/util.py", "/config_reader.py"], "/apk.py": ["/util.py", "/config_reader.py"], "/adb_settings.py": ["/config_reader.py", "/api_commands.py", "/util.py"], "/config_reader.py": ["/util.py"], "/api_commands.py": ["/config_reader.py", "/util.py", "/emulator.py", "/apk.py"], "/monkey.py": ["/config_reader.py", "/adb_logcat.py", "/apk.py", "/emulator.py", "/fuzz_context.py", "/adb_settings.py", "/telnet_connector.py", "/interval_event.py"], "/mobile_monkey.py": ["/config_reader.py", "/emulator_manager.py", "/api_commands.py", "/telnet_connector.py", "/emulator.py", "/fuzz_context.py", "/adb_settings.py", "/util.py", "/adb_monkey.py", "/apk.py", "/adb_logcat.py", "/log_analyzer.py"], "/adb_logcat.py": ["/api_commands.py", "/config_reader.py", "/emulator.py", "/apk.py"], "/telnet_connector.py": ["/config_reader.py", "/util.py"], "/install_app.py": ["/config_reader.py", "/emulator_manager.py", "/api_commands.py", "/telnet_connector.py", "/emulator.py", "/fuzz_context.py", "/adb_settings.py", "/util.py", "/adb_monkey.py", "/apk.py", "/adb_logcat.py", "/log_analyzer.py"], "/mobicomonkey.py": ["/config_reader.py", "/emulator.py", "/api_commands.py", "/apk.py", "/emulator_manager.py", "/xml_element.py", "/adb_settings.py", "/telnet_connector.py", "/util.py", "/monkey.py", "/adb_logcat.py", "/mutex.py", "/adb_monkey.py"], "/contextConfig_reader.py": ["/config_reader.py"], "/emulator_manager.py": ["/emulator.py", "/config_reader.py", "/contextConfig_reader.py", "/api_commands.py", "/util.py"], "/test.py": ["/api_commands.py", "/emulator_manager.py", "/config_reader.py", "/apk.py", "/adb_logcat.py", "/telnet_connector.py", "/adb_monkey.py", "/emulator.py", "/fuzz_context.py", "/adb_settings.py", "/interval_event.py"]} |
78,671 | samuelcolvin/MonQL | refs/heads/master | /MonQL/controllers.py | from flask import render_template, jsonify, request
import json, traceback
from MonQL.Connections import app, connections, test_connection, tree_json
def jsonabort(e):
traceback.print_exc()
error = '%s: %s' % (e.__class__.__name__, str(e))
return jsonify(error = error), 400
def jsonifyany(ob):
if isinstance(ob, list):
return json.dumps(ob)
else:
return jsonify(**ob)
@app.route('/')
@app.route('/about')
@app.route('/addcon')
@app.route('/editcon/<_>')
@app.route('/con/<_>')
def index(_=None):
return render_template('main.html')
@app.route('/api/cons')
def conlist():
return jsonify(cons=connections())
@app.route('/api/condef/<conid>')
def condef(conid):
try:
return jsonify(con = connections.select(int(conid)))
except Exception, e: return jsonabort(e)
@app.route('/api/viewtree/<conid>')
def viewtree(conid):
node = None
if 'node' in request.args:
node = int(request.args.get('node'))
data = tree_json(int(conid), node)
# pprint(data)
return jsonifyany(data)
@app.route('/api/submitcon', methods=['POST'])
def submitcon():
try:
data = json.loads(request.data)
data = connections.update(data)
return jsonify(status='success', data=data)
except Exception, e: return jsonabort(e)
@app.route('/api/testcon/<conid>')
def test_connection_response(conid):
try:
return test_connection(conid)
except Exception, e: return jsonabort(e)
@app.route('/api/delete/<conid>')
def deletecon(conid):
try:
response = connections.delete(int(conid))
return jsonify(status='success', data = response)
except Exception, e: return jsonabort(e)
@app.errorhandler(404)
def page_not_found(_):
# return index()
return '404 - page not found', 404 | {"/MonQL/Inspect/__init__.py": ["/MonQL/Inspect/_sql.py", "/MonQL/Inspect/_mongo.py", "/MonQL/Inspect/_utils.py"], "/MonQL/__init__.py": ["/MonQL/controllers.py"], "/runserver.py": ["/MonQL/__init__.py"]} |
78,672 | samuelcolvin/MonQL | refs/heads/master | /test.py | from MonQL import Connections
from pprint import pprint
def con(conid = 0):
print '\n **testing con with connection id = %d**' % conid
response = Connections.test_connection(conid)
print response
def tree(conid = 0):
print '\n **testing tree with connection id = %d**' % conid
data = Connections.tree_json(conid)
pprint(data)
TEST_DB = 0
con(TEST_DB)
tree(TEST_DB) | {"/MonQL/Inspect/__init__.py": ["/MonQL/Inspect/_sql.py", "/MonQL/Inspect/_mongo.py", "/MonQL/Inspect/_utils.py"], "/MonQL/__init__.py": ["/MonQL/controllers.py"], "/runserver.py": ["/MonQL/__init__.py"]} |
78,673 | samuelcolvin/MonQL | refs/heads/master | /MonQL/Inspect/_sql.py | import MySQLdb as mdb
import sqlite3
import psycopg2
from MonQL.Inspect._utils import *
import traceback
class _SqlBase(db_comm):
_con=None
def __init__(self, con_sets):
self._con_sets = con_sets
self._setup_types()
self._con_cur()
self.db_name = con_sets.get('dbname', None)
def _con_cur(self):
if not self._con:
self._con = self._get_con()
self._cur = self._con.cursor()
def get_tables(self, dbname):
return self._get_tables(dbname)
def get_table_fields(self, dbname, t_name):
sql = 'SELECT * FROM %s.%s LIMIT 1' % (dbname, t_name)
return self.get_query_fields(sql)
def server_info(self):
return ''
def get_query_fields(self, sql, ex_type = None):
if 'limit' not in sql.lower():
sql += ' LIMIT 1'
cur, fields = self._execute_get_descrition(sql)
values = cur.fetchone()
if values:
for field, v in zip(fields, values):
if field[1] is None:
field[1] = type(v).__name__
self._close()
return fields
def get_values(self, dbname, t_name, limit = 20):
cur = self._execute('SELECT * FROM %s.%s LIMIT %d' % (dbname, t_name, limit))
return self._process_data(cur.fetchall())[0]
def execute(self, sql, ex_type = None):
try:
cur = self._execute(sql)
data = cur.fetchall()
except mdb.Error, e:
error = 'ERROR %s: %s' % (type(e).__name__, e.args[1])
return False, error, None
except Exception, e:
error = 'ERROR %s: %s' % (type(e).__name__, str(e))
return False, error, None
else:
result, fields = self._process_data(data)
print 'success %d results' % len(result)
return True, result, fields
finally:
self._close()
def _execute(self, command):
try:
self._con_cur()
self._cur.execute(command)
return self._cur
except Exception, e:
print "Error: %s" % str(e)
print 'SQL: %s' % command
self._close()
raise(e)
def _process_data(self, data):
fields = [col[0] for col in self._cur.description]
name_fields = [i for i, f in enumerate(fields) if 'dbname' in f]
i2 = 1
if len(name_fields) > 0:
i2 = name_fields[0]
data2 = []
i = 0
for row in data:
label = self._create_label(row[0], row[i2])
values = [self._smart_text(d) for d in row]
data2.append((values, label))
i += 1
if i > MAX_ROWS:
break
self._close()
return data2, fields
def _execute_get_descrition(self, sql):
cur = self._execute(sql)
fields = []
for col in cur.description:
self._process_column(col, fields)
return cur, fields
def _setup_types(self):
self._types = {}
for t in dir(mdb.constants.FIELD_TYPE):
if not t.startswith('_'):
v = getattr(mdb.constants.FIELD_TYPE, t)
self._types[v] = t
def _close(self):
try:
self._con.close()
self._con = None
except:
pass
class MySQL(_SqlBase):
def _get_con(self):
return mdb.connect(self._con_sets['host'], self._con_sets.get('user', None),
self._con_sets.get('pass', None), port=self._con_sets['port'])
def get_version(self):
cur = self._execute('SELECT VERSION()')
return cur.fetchone()
def get_databases(self):
cur = self._execute('SHOW DATABASES')
dbs = [info[0] for info in cur.fetchall()]
self._close()
return dbs
def _execute_get_descrition(self, sql):
cur = self._execute(sql)
fields = []
for col in cur.description:
self._process_column(col, fields)
return cur, fields
def _get_tables(self, dbname):
tables = []
cur, fields = self._execute_get_descrition('SHOW TABLE STATUS IN %s' % dbname)
field_names = [i[0] for i in fields]
for t_info in cur.fetchall():
tables.append((t_info[0], t_info))
self._close()
return tables, field_names
def _process_column(self, col, fields):
fields.append((col[0], self._types[col[1]]))
class PostgreSQL(_SqlBase):
def _get_con(self):
return psycopg2.connect('user=%(user)s host=%(host)s dbname = %(dbname)s' % self._con_sets)
def get_version(self):
info = self.server_info()
if ' on' in info:
return info[:info.index(' on')]
return info
def server_info(self):
cur = self._execute('SELECT VERSION()')
return cur.fetchone()[0]
def get_table_fields(self, dbname, t_name):
sql = 'SELECT * FROM %s LIMIT 1' % t_name
return self.get_query_fields(sql)
def get_databases(self):
cur = self._execute('SELECT datname FROM pg_database WHERE datistemplate = false')
dbs = [info[0] for info in cur.fetchall()]
self._close()
return dbs
def _get_tables(self, dbname):
tables = []
cur, fields = self._execute_get_descrition('SELECT * FROM information_schema.tables')
# tables = [': '.join(t) for t in cur.fetchall()]
field_names = [i[0] for i in fields]
for t_info in cur.fetchall():
tables.append((t_info[2], t_info))
self._close()
return tables, field_names
def _process_column(self, col, fields):
fields.append([col.name, self._types.get(col.type_code, None)])
class SQLite(_SqlBase):
def _get_con(self):
return sqlite3.connect(self._con_sets['path'])
def get_version(self):
return sqlite3.sqlite_version
def get_databases(self):
return []
def _get_tables(self, dbname):
tables = []
cur, fields = self._execute_get_descrition("SELECT * FROM sqlite_master WHERE type='table';")
field_names = [i[0] for i in fields]
for t_info in cur.fetchall():
tables.append((t_info[1], t_info))
self._close()
return tables, field_names
def _process_column(self, col, fields):
fields.append([col[0], None])
| {"/MonQL/Inspect/__init__.py": ["/MonQL/Inspect/_sql.py", "/MonQL/Inspect/_mongo.py", "/MonQL/Inspect/_utils.py"], "/MonQL/__init__.py": ["/MonQL/controllers.py"], "/runserver.py": ["/MonQL/__init__.py"]} |
78,674 | samuelcolvin/MonQL | refs/heads/master | /MonQL/Inspect/__init__.py | from MonQL.Inspect._sql import MySQL, SQLite, PostgreSQL
from MonQL.Inspect._mongo import MongoDB
from MonQL.Inspect._utils import ConnectionError | {"/MonQL/Inspect/__init__.py": ["/MonQL/Inspect/_sql.py", "/MonQL/Inspect/_mongo.py", "/MonQL/Inspect/_utils.py"], "/MonQL/__init__.py": ["/MonQL/controllers.py"], "/runserver.py": ["/MonQL/__init__.py"]} |
78,675 | samuelcolvin/MonQL | refs/heads/master | /MonQL/__init__.py | # Flask database viewer
from flask import Flask
__version__ = '0.0.1'
app = Flask(__name__)
app.config.from_object('MonQL.settings')
import MonQL.controllers | {"/MonQL/Inspect/__init__.py": ["/MonQL/Inspect/_sql.py", "/MonQL/Inspect/_mongo.py", "/MonQL/Inspect/_utils.py"], "/MonQL/__init__.py": ["/MonQL/controllers.py"], "/runserver.py": ["/MonQL/__init__.py"]} |
78,676 | samuelcolvin/MonQL | refs/heads/master | /MonQL/Connections.py | from datetime import datetime as dtdt
import traceback, json, os
from MonQL import app
import MonQL.Inspect
from pprint import pprint
class Connections(object):
_cons = None
def __call__(self):
return self.get_cons()
def get_cons(self):
if not self._cons:
self._cons = self._get_cons()
return self._cons
def _get_cons(self):
fn = app.config['CONNECTION_DEFS']
if os.path.exists(fn):
text = open(fn, 'r').read()
if len(text) > 0:
return json.loads(text)
return []
def select(self, conid):
return next((con for con in self.get_cons() if con['id'] == conid), None)
def update(self, con):
cons = self.get_cons()
if 'id' in con:
old = next((con2 for con2 in cons if con2['id'] == con['id']), None)
if old: cons.remove(old)
else:
if len(cons) == 0:
con['id'] = 0
else:
con['id'] = max(cons, key=lambda con2: con2['id'])['id'] + 1
cons.append(con)
self._save_cons(cons)
self._cons = None
return con
def delete(self, conid):
cons = self.get_cons()
print 'before:', len(cons)
cons = [con for con in cons if con['id'] != conid]
self._save_cons(cons)
self._cons = None
print 'after:', len(cons)
def _save_cons(self, cons):
json.dump(cons,
open(app.config['CONNECTION_DEFS'], 'w'),
indent=2,
separators=(',', ': '),
sort_keys = True)
connections = Connections()
def getcomms(con):
return getattr(MonQL.Inspect, con['dbtype'])(con)
def test_connection(conid):
con = connections.select(int(conid))
response = 'Connectiong to "%s"\n' % con['ref']
try:
comms = getcomms(con)
response += 'connecting with %s\n' % comms.__class__.__name__
response += 'Successfully connected\n'
response += 'Version: %s\n' % comms.get_version()
response += 'Server Info: %s\n' % comms.server_info()
if 'dbname' in con:
response += 'Connecting to db %s\n' % con['dbname']
tables, _ = comms.get_tables(con['dbname'])
response += '%d tables found\n' % len(tables)
else:
response += 'No database name entered, not connecting to db'
except Exception, e:
traceback.print_exc()
response += '\n** Error: %s %s **' % (e.__class__.__name__, str(e))
else:
response += '\n** Successfully Connected **'
return response
def tree_json(conid, node = None):
tree = TreeGenerater(conid)
if node:
return tree.get_values(node)
else:
return tree.data
class TreeGenerater(object):
_id = 0
comms = {}
def __init__(self, conid):
self.data = {'DATA': []}
self._con = connections()[conid]
self._comms = getcomms(self._con)
self._get_con()
def get_values(self, node_id):
node_id = int(node_id)
dbname, table = self._find_table(node_id)
table_name = table['table_name']
fields = [f[0] for f in table['fields']]
rows = self._get_rows(self._comms.get_values(dbname, table_name), fields)
table['children'] = rows
if 'load_on_demand' in table:
del table['load_on_demand']
return rows
@property
def json_data(self):
return self._2json(self.data)
def _2json(self, data):
return json.dumps(data, indent=2)
# def execute_query(self, query):
# comms = self._get_comms(m.Database.objects.get(id=query.db.id))
# success, result, fields = comms.execute(query.code, query.function)
# if success:
# rows = self._get_rows(result, fields)
# d = {'id': self._get_id(), 'label': 'QUERY: %s' % str(query), 'children': rows}
# d['info'] = [('Query Properties', [])]
# d['info'][0][1].append(('Results', len(rows)))
# d['info'][0][1].append(('Code', query.code))
# self.data['DATA'].append(d)
# self._generate_json()
# return None
# else:
# return result
def _get_rows(self, raw_rows, fields):
rows = []
for v, label in raw_rows:
row = {'id': self._get_id(), 'label': label}
row['info'] = [['', []]]
row['info'][0][1] = [(name, val) for name, val in zip(fields, v)]
rows.append(row)
return rows
def _find_table(self, node_id):
for con in self.data['DATA']:
for db in con['children']:
dbname = db['name']
for table in db['children']:
if table['id'] == node_id:
return dbname, table
raise Exception('Table %d not found' % node_id)
def _get_con(self):
try:
c = {'id': self._get_id(), 'label': 'CONNECTION: %s' % self._con['ref'], 'con_id': self._con['id']}
c['info'] = [('Database Properties', [])]
for name, value in self._con.items():
c['info'][0][1].append((name, value))
c['info'][0][1].append(('DB Version', self._comms.get_version()))
c['info'][0][1].append(('Server Info', self._comms.server_info()))
dbs = []
for name in self._comms.get_databases():
dbs.append(('', name))
if len(dbs) > 0:
c['info'].append(('Databases', dbs))
if 'dbname' in self._con:
dbs = [self._con['dbname']]
else:
dbs = self._comms.get_databases()
c['children'] = self._get_dbs(dbs)
except Exception, e:
traceback.print_exc()
self.data['ERROR'] = '%s: %s' % (e.__class__.__name__, str(e))
else:
self.data['DATA'].append(c)
def _get_dbs(self, dbs):
return [{'label': db,
'children': self._get_tables(db),
'id': self._get_id(),
'name': db} for db in dbs]
def _get_tables(self, dbname):
t_data = []
tables, prop_names = self._comms.get_tables(dbname)
for t_name, t_info in tables:
table = {'id': self._get_id(), 'label': t_name, 'table_name': t_name, 'load_on_demand': True}
table['info'] = [('Table Properties', []), ('Fields', [])]
for name, value in zip(prop_names, t_info):
if type(value) == dtdt:
value = value.strftime('%Y-%m-%d %H:%M:%S %Z')
table['info'][0][1].append((name, value))
try:
fields = self._comms.get_table_fields(dbname, t_name)
table['info'][0][1].append(('Field Count', len(fields)))
table['fields'] = fields
for name, field_type in fields:
table['info'][1][1].append((name, str(field_type)))
except: pass
t_data.append(table)
return t_data
def _get_id(self):
self._id += 1
return self._id
def _get_max_id(self):
if self._id != 0 or len(self.data['DATA']) == 0:
return self._id
return self._get_max_id_rec(self.data['DATA'][-1])
def _get_max_id_rec(self, ob):
if 'children' in ob and len(ob['children']) > 0:
return self._get_max_id_rec(ob['children'][-1])
elif 'id' in ob:
return ob['id']
return self._id
| {"/MonQL/Inspect/__init__.py": ["/MonQL/Inspect/_sql.py", "/MonQL/Inspect/_mongo.py", "/MonQL/Inspect/_utils.py"], "/MonQL/__init__.py": ["/MonQL/controllers.py"], "/runserver.py": ["/MonQL/__init__.py"]} |
78,677 | samuelcolvin/MonQL | refs/heads/master | /MonQL/Inspect/_mongo.py | import pymongo, re
from MonQL.Inspect._utils import *
from bson.code import Code as BsonCode
import json
import collections
import traceback
import StringIO
class MongoDB(db_comm):
def __init__(self, con):
try:
self._client = pymongo.MongoClient(con['host'], con['port'])
except ConnectionError, e:
msg = 'CONNECTION ERROR %s: %s' % (type(e).__name__, str(e))
print msg
raise Exception(msg)
def get_version(self):
try:
mongv = self._client.server_info()['version']
except:
mongv = 'unknown'
return 'PyMongo v%s, Mongo Server v%s' % (pymongo.version, mongv)
def server_info(self):
return json.dumps(self._client.server_info(), indent = 2)
def get_databases(self):
return self._client.database_names()
def get_database(self, dbname):
return self._client[dbname]
def get_tables(self, dbname):
db = self.get_database(dbname)
tables = []
for name in db.collection_names():
tables.append((name, (name, db[name].count())))
field_names = ('name', 'count')
return tables, field_names
def get_table_fields(self, dbname, t_name):
db = self.get_database(dbname)
f = db[t_name].find_one()
if f:
return [(k, type(v).__name__) for k, v in f.items()]
return []
def get_query_fields(self, code, ex_type = None):
cursor = self._execute(code, ex_type)
for row in cursor:
return [(k, type(v).__name__) for k, v in row.items()]
return []
def get_values(self, dbname, t_name, limit = SIMPLE_LIMIT):
db = self.get_database(dbname)
c = db[t_name].find(limit=limit)
data, _ = self._process_data(c)
return data
def execute(self, code, ex_type = None):
try:
cursor = self._execute(code, ex_type)
result, fields = self._process_data(cursor)
except Exception, e:
traceback.print_exc()
error = 'ERROR %s: %s' % (type(e).__name__, str(e))
return False, error, None
else:
return True, result, fields
def _execute(self, dbname, code, ex_type = None):
db = self.get_database(dbname)
self._code_lines = code.split('\n')
self._get_other_vars()
if self._source_col is None:
raise Exception('The souce collection must be defined in the top level of the code'+
' as "source = <collection_name>')
collection = db[self._source_col]
if ex_type == 'map_reduce':
if self._dest_col is None:
raise Exception('The destination collection must be defined in the top level of the code'+
' as "dest = <collection_name>')
functions = self._split_functions()
if 'map' not in functions.keys() or 'reduce' not in functions.keys():
raise Exception('Both "map" and "reduce" functions must be defined')
cursor = collection.map_reduce(functions['map'], functions['reduce'], self._dest_col)
cursor = cursor.find()
else:
json_text = '\n'.join(self._code_lines)
q_object = self._ordered_json(json_text)
if ex_type == 'aggregate':
cursor = collection.aggregate(q_object)
else:
cursor = collection.find(q_object)
if self._sort:
sort = self._ordered_json(self._sort)
cursor = cursor.sort(sort.items())
return cursor
def _ordered_json(self, text):
text = text.strip(' \t')
if text == '':
return None
return json.JSONDecoder(object_pairs_hook=collections.OrderedDict).decode(text)
def close(self):
pass
def _process_data(self, cursor):
data = []
i = 0
fields = []
for row in cursor:
if i == 0:
fields = row.keys()
i1 = fields[0]
if '_id' in fields: i1 = '_id'
i2 = fields[1]
if i1 == i2:
i2 = fields[0]
for k in fields:
if 'name' in k:
i2 = k
break
try:
label = self._create_label(row[i1], row[i2])
except KeyError:
l1 = '*'
l2 = '*'
try: l1 = row[i1]
except: pass
try: l2 = row[i2]
except: pass
label = self._create_label(l1, l2)
values = [self._smart_text(v) for v in row.values()]
data.append((values, label))
i += 1
if i > MAX_ROWS:
break
return data, fields
def _get_other_vars(self):
to_find = {'source': None, 'dest': None, 'sort': None}
lines = self._code_lines[:]
for line in lines:
for k, v in to_find.items():
if re.search(k + ' *=', line) and not v and not 'function' in line:
if k == 'sort':
to_find[k] = line[line.index('=') + 1:].replace(';', '')
self._code_lines.remove(line)
else:
to_find[k] = self._get_value_remove(line)
break
if None not in to_find.values():
break
self._source_col = to_find['source']
self._dest_col = to_find['dest']
self._sort = to_find['sort']
def _get_value_remove(self, line):
v = re.findall('\w+', line[line.index('='):])[0]
self._code_lines.remove(line)
return v
def _split_functions(self):
def process_func(lines):
name = re.findall('\w+', lines[0].replace('function', ''))[0]
brackets = 0
started = False
for ii, line in enumerate(lines):
for c in line:
if c == '{':
brackets +=1
started = True
if c == '}':
brackets -=1
if brackets == 0 and started:
code = '\n'.join(lines[:ii + 1])
return ii, name, code
i = 0
functions = {}
while True:
if i >= len(self._code_lines):
break
line = self._code_lines[i]
if 'function' in line:
endi, name, code = process_func(self._code_lines[i:])
functions[name] = code
i += endi
i += 1
return functions
| {"/MonQL/Inspect/__init__.py": ["/MonQL/Inspect/_sql.py", "/MonQL/Inspect/_mongo.py", "/MonQL/Inspect/_utils.py"], "/MonQL/__init__.py": ["/MonQL/controllers.py"], "/runserver.py": ["/MonQL/__init__.py"]} |
78,678 | samuelcolvin/MonQL | refs/heads/master | /runserver.py | import MonQL
if __name__ == '__main__':
MonQL.app.run() | {"/MonQL/Inspect/__init__.py": ["/MonQL/Inspect/_sql.py", "/MonQL/Inspect/_mongo.py", "/MonQL/Inspect/_utils.py"], "/MonQL/__init__.py": ["/MonQL/controllers.py"], "/runserver.py": ["/MonQL/__init__.py"]} |
78,679 | samuelcolvin/MonQL | refs/heads/master | /MonQL/Inspect/_utils.py | import re
import chardet
import StringIO
# import numpy
import json
MAX_ROWS = 1000
SIMPLE_LIMIT = 50
class ConnectionError(Exception):
pass
class db_comm(object):
def _smart_text(self, value):
try:
return smart_text(value)
except:
return 'unknown character'
def _create_label(self, v1, v2):
v2 = self._smart_text(v2)
label = '%s: %s' % (self._smart_text(v1)[:10], v2[:20])
if len(v2) > 20:
label = label[:-3] + '...'
return label
def _sanitize_df(self, dataframe):
for c in dataframe.columns:
if dataframe[c].dtype == object:
dataframe[c] = dataframe[c].apply(super_smart_text)
# this doesn't seem to work :-( :
# elif dataframe[c].dtype == numpy.int64:
# dataframe[c] = dataframe[c].astype(int)
return dataframe
def _to_string(self, dataframe, code, string_format='csv'):
fields = self.get_query_fields(code)
field_names = [f[0] for f in fields]
name_convert = {}
for c in dataframe.columns:
if c in field_names and string_format == 'csv':
i = field_names.index(c)
col_type = fields[i][1]
name_convert[c] = '%s (%s)' % (c, col_type)
if col_type == 'DATETIME':
dataframe[c] = dataframe[c].apply(lambda x: x.strftime('%s'))
dataframe.rename(columns=name_convert, inplace=True)
file_stream = StringIO.StringIO()
# , date_format = '%s' - not yet working in production pandas :-(
if string_format == 'csv':
dataframe.to_csv(file_stream, index=False)
elif string_format == 'json':
dataframe.to_json(file_stream, orient='records')
return file_stream.getvalue()
def smart_text(s, encoding='utf-8', errors='strict'):
if isinstance(s, dict):
return json.dumps(s, indent=2)
if isinstance(s, unicode):
return s
try:
if not isinstance(s, basestring):
if hasattr(s, '__unicode__'):
s = s.__unicode__()
else:
s = unicode(bytes(s), encoding, errors)
else:
s = s.decode(encoding, errors)
except UnicodeDecodeError as e:
if not isinstance(s, Exception):
print s
import pdb; pdb.set_trace()
raise e
else:
s = ' '.join([smart_text(arg, encoding, errors) for arg in s])
return s
ALLOWED_ENCODING = set(['ascii', 'ISO-8859-2', 'windows-1252', 'SHIFT_JIS', 'Big5', 'IBM855', 'windows-1251', 'ISO-8859-5', 'KOI8-R', 'ISO-8859-7', 'EUC-JP', 'ISO-8859-8', 'IBM866', 'MacCyrillic', 'windows-1255', 'GB2312', 'EUC-KR', 'TIS-620'])
ESC_BYTES = re.compile(r'\\x[0-9a-f][0-9a-f]')
def super_smart_text(text):
if text is None:
return ''
enc = chardet.detect(text)
if enc['encoding'] is not None and enc['encoding'] in ALLOWED_ENCODING:
text = unicode(text, enc['encoding'], errors='replace')
else:
text = ESC_BYTES.sub('', text.encode('string-escape'))
# text = text.encode('UTF8')
return text | {"/MonQL/Inspect/__init__.py": ["/MonQL/Inspect/_sql.py", "/MonQL/Inspect/_mongo.py", "/MonQL/Inspect/_utils.py"], "/MonQL/__init__.py": ["/MonQL/controllers.py"], "/runserver.py": ["/MonQL/__init__.py"]} |
78,680 | samuelcolvin/MonQL | refs/heads/master | /MonQL/settings.py | DEBUG = True
# file to store database definitions in
CONNECTION_DEFS = 'connections.json' | {"/MonQL/Inspect/__init__.py": ["/MonQL/Inspect/_sql.py", "/MonQL/Inspect/_mongo.py", "/MonQL/Inspect/_utils.py"], "/MonQL/__init__.py": ["/MonQL/controllers.py"], "/runserver.py": ["/MonQL/__init__.py"]} |
78,694 | JeffreyILipton/KillerSawBot | refs/heads/master | /jigsaw_robot/drive_module/drive_module.py | from jigsaw_robot.config import (
DRIVE_MODULE_PORT,
DRIVE_MODULE_ADDR,
DRIVE_TICKS_PER_LINEAR_MM
)
from jigsaw_robot.roboclaw.roboclaw import Roboclaw
drive = Roboclaw(DRIVE_MODULE_PORT, 115200)
opened = drive.Open()
if not opened:
raise IOError("Failed to connect to Roboclaw on port {}".format(DRIVE_MODULE_PORT))
"""
Set left motor to go at a certain speed.
"""
def set_left_velocity(velocity : float):
drive.SpeedM1(DRIVE_MODULE_ADDR, int(velocity * DRIVE_TICKS_PER_LINEAR_MM))
"""
Set right motor to go at a certain speed.
"""
def set_right_velocity(velocity : float):
drive.SpeedM2(DRIVE_MODULE_ADDR, int(velocity * DRIVE_TICKS_PER_LINEAR_MM))
"""
Gets left motor encoder value converted to mm
"""
def get_left_position():
valid, position, _ = drive.ReadEncM1(DRIVE_MODULE_ADDR)
if not valid:
raise IOError("Failed to read left motor encoder")
return position/DRIVE_TICKS_PER_LINEAR_MM
"""
Gets right motor encoder value converted to mm
"""
def get_right_position():
valid, position, _ = drive.ReadEncM2(DRIVE_MODULE_ADDR)
if not valid:
raise IOError("Failed to read right motor encoder")
return position/DRIVE_TICKS_PER_LINEAR_MM
"""
Resets left and right encoder positions.
"""
def reset_encoders():
drive.ResetEncoders(DRIVE_MODULE_ADDR)
"""
Shuts down both motors.
"""
def panic():
set_left_velocity(0)
set_right_velocity(0)
reset_encoders() | {"/jigsaw_robot/drive_module/drive_module.py": ["/jigsaw_robot/config.py"], "/jigsaw_robot/relay_module/__init__.py": ["/jigsaw_robot/relay_module/relay_module.py"], "/jigsaw_robot/slide_module/slide_module.py": ["/jigsaw_robot/config.py"], "/KillerInterface.py": ["/Logging.py"], "/jigsaw_robot/safety_module/__init__.py": ["/jigsaw_robot/safety_module/safety_module.py"], "/jigsaw_robot/drive_module/__init__.py": ["/jigsaw_robot/drive_module/drive_module.py"], "/joystick.py": ["/jigsaw_robot/__init__.py"], "/jigsaw_robot/__init__.py": ["/jigsaw_robot/jigsaw_robot.py"], "/jigsaw_robot/jigsaw_robot.py": ["/jigsaw_robot/drive_module/__init__.py", "/jigsaw_robot/relay_module/__init__.py"], "/jigsaw_robot/relay_module/relay_module.py": ["/jigsaw_robot/config.py"], "/TrajectoryTests.py": ["/Model.py"]} |
78,695 | JeffreyILipton/KillerSawBot | refs/heads/master | /jigsaw_robot/relay_module/__init__.py | from jigsaw_robot.relay_module.relay_module import * | {"/jigsaw_robot/drive_module/drive_module.py": ["/jigsaw_robot/config.py"], "/jigsaw_robot/relay_module/__init__.py": ["/jigsaw_robot/relay_module/relay_module.py"], "/jigsaw_robot/slide_module/slide_module.py": ["/jigsaw_robot/config.py"], "/KillerInterface.py": ["/Logging.py"], "/jigsaw_robot/safety_module/__init__.py": ["/jigsaw_robot/safety_module/safety_module.py"], "/jigsaw_robot/drive_module/__init__.py": ["/jigsaw_robot/drive_module/drive_module.py"], "/joystick.py": ["/jigsaw_robot/__init__.py"], "/jigsaw_robot/__init__.py": ["/jigsaw_robot/jigsaw_robot.py"], "/jigsaw_robot/jigsaw_robot.py": ["/jigsaw_robot/drive_module/__init__.py", "/jigsaw_robot/relay_module/__init__.py"], "/jigsaw_robot/relay_module/relay_module.py": ["/jigsaw_robot/config.py"], "/TrajectoryTests.py": ["/Model.py"]} |
78,696 | JeffreyILipton/KillerSawBot | refs/heads/master | /AnalyzeCharicterizations.py | import csv
import numpy as np
from numpy import genfromtxt
import matplotlib
import matplotlib.pyplot as plt
import sys
from CreateModel import minAngleDif
from scipy.stats import linregress
def AnalyseFile(file = 'Run.csv'):
data = genfromtxt(file,delimiter = ',')
print data.shape
headings = data[0,:]
data = np.delete(data,0,0)
print data.shape
# convert T from ms since epoch to seconds since start
#T = data[:,0]
#T = T-T[0]
#T = T/(1e6)
#data[:,0]=T
speeds = np.unique(data[:,1])
speeds = np.delete(speeds,0,0)
analysis = np.zeros((speeds.size,4))
for i in range(0,speeds.size):
speed = speeds[i]
analysis[i,:] = analyzeSpeed(speed,data,True)
Uslope, Uintercept, U_r_value, U_p_value, U_std_err = linregress(analysis[:,0],analysis[:,2])
calced = Uslope*analysis[:,0]+Uintercept
plt.figure(1)
plt.plot(analysis[:,0],analysis[:,1],'-')
plt.title("cmd vs delay")
quicker = analysis[np.where(analysis[:,1]<1.2)]
Mslope, Mintercept, M_r_value, M_p_value, M_std_err = linregress(quicker[:,0],quicker[:,1])
print "Mslope: ", Mslope,"\tr:", M_r_value,"\t stdErr: ",M_std_err
print "Mintercept: ", Mintercept
MCalced = Mslope*analysis[:,0]+Mintercept
plt.plot(analysis[:,0],MCalced,'--')
plt.figure(2)
plt.plot(analysis[:,0],analysis[:,2],'-')
plt.plot(analysis[:,0],calced,'--')
plt.title("cmd vs Actual speed")
print "Uslope: ", Uslope,"\tr:", U_r_value,"\t stdErr: ",U_std_err
print "Uintercept", Uintercept
plt.figure(3)
ro = 125#mm
Tslope, Tintercept, T_r,T_p,T_err = linregress(analysis[:,0],analysis[:,3])
Tcalc = Tslope*analysis[:,0]+Tintercept
plt.plot(analysis[:,0],analysis[:,3],'-')
plt.plot(analysis[:,0],Tcalc,'--')
plt.title("$\Theta% vs cmd speed")
print "Tslope: ", Tslope,"\tr:", T_r,"\t stdErr: ",T_err
print "Tintercept", Tintercept
S = np.mat([[Uslope],[Tslope]])
O = np.mat([[Uintercept],[Tintercept]])
alphaInv = np.mat([[1,ro],[1,-ro]])
G = alphaInv.dot(S)
V = alphaInv.dot(O)
print "G:"
print G
print "V:"
print V
plt.show()
def analyzeSpeed(speed,data,doplot = False):
section = data[np.where(data[:,1]==speed)]
To = section[0,0]
Xo = section[0,2]
Yo = section[0,3]
section[:,0] = (section[:,0]-To)/(1e6)
section[:,2] = section[:,2]-Xo
section[:,3] = section[:,3]-Yo
moving = section[np.where(section[:,2]>2.0)]
D = np.sqrt(np.square(moving[:,2])+np.square(moving[:,3]));
timeToStart = moving[0,0]
slope, intercept, r_value, p_value, std_err = linregress(moving[:,0],D)
ThetaRate, ThetaIntercept, Theta_r,Theta_p,Theta_err = linregress(moving[:,0],moving[:,4])
if doplot:
plt.figure(1)
plt.subplot(311)
plt.plot(moving[:,0],D,'-')
plt.title("D vs T")
plt.subplot(312)
plt.plot(moving[:,2],moving[:,3],'-')
plt.title("Y vs X")
plt.subplot(313)
plt.plot(moving[:,0],moving[:,4],'-')
plt.plot(moving[:,0],ThetaRate*moving[:,0]+ThetaIntercept,'--')
plt.title("Theta vs T")
plt.show()
print "cmd: ",speed, "\tactual:" , slope,"\tr:", r_value
return [speed,timeToStart,slope,ThetaRate]
def main():
AnalyseFile('unifiedtest.csv')
if __name__ == "__main__":
sys.exit(int(main() or 0)) | {"/jigsaw_robot/drive_module/drive_module.py": ["/jigsaw_robot/config.py"], "/jigsaw_robot/relay_module/__init__.py": ["/jigsaw_robot/relay_module/relay_module.py"], "/jigsaw_robot/slide_module/slide_module.py": ["/jigsaw_robot/config.py"], "/KillerInterface.py": ["/Logging.py"], "/jigsaw_robot/safety_module/__init__.py": ["/jigsaw_robot/safety_module/safety_module.py"], "/jigsaw_robot/drive_module/__init__.py": ["/jigsaw_robot/drive_module/drive_module.py"], "/joystick.py": ["/jigsaw_robot/__init__.py"], "/jigsaw_robot/__init__.py": ["/jigsaw_robot/jigsaw_robot.py"], "/jigsaw_robot/jigsaw_robot.py": ["/jigsaw_robot/drive_module/__init__.py", "/jigsaw_robot/relay_module/__init__.py"], "/jigsaw_robot/relay_module/relay_module.py": ["/jigsaw_robot/config.py"], "/TrajectoryTests.py": ["/Model.py"]} |
78,697 | JeffreyILipton/KillerSawBot | refs/heads/master | /jigsaw_robot/slide_module/slide_module.py | from jigsaw_robot.config import (
SLIDE_MODULE_PORT,
SLIDE_MODULE_ADDR,
SLIDE_TICKS_PER_LINEAR_MM,
DRILL_PLUNGE_DEPTH,
JIGSAW_PLUNGE_DEPTH
)
from jigsaw_robot.roboclaw.roboclaw import Roboclaw
slide = Roboclaw(SLIDE_MODULE_PORT, 115200)
slide.Open()
# home_axis()
"""
Gets drill motor encoder value converted to mm
"""
def get_drill_position():
valid, position, _ = slide.ReadEncM1(SLIDE_MODULE_ADDR)
if not valid:
raise IOError("Failed to read drill motor encoder")
return position/SLIDE_TICKS_PER_LINEAR_MM
"""
Gets jigsaw motor encoder value converted to mm
"""
def get_jigsaw_position():
valid, position, _ = slide.ReadEncM2(SLIDE_MODULE_ADDR)
if not valid:
raise IOError("Failed to read jigsaw motor encoder")
return position/SLIDE_TICKS_PER_LINEAR_MM
"""
Moves drill to top position
"""
def raise_drill(speed):
speed = int(speed * SLIDE_TICKS_PER_LINEAR_MM)
accel = int(5*speed)
deccel = accel
position = int(1 * SLIDE_TICKS_PER_LINEAR_MM)
if not slide.SpeedAccelDeccelPositionM1(SLIDE_MODULE_ADDR,accel,speed,deccel,position,1):
raise IOError("Failed to raise drill: CRC failure")
"""
Moves drill to bottom position
speed - The speed at which to move.
"""
def lower_drill(speed):
speed = int(speed * SLIDE_TICKS_PER_LINEAR_MM)
accel = int(5*speed)
deccel = accel
position = int(DRILL_PLUNGE_DEPTH * SLIDE_TICKS_PER_LINEAR_MM)
if not slide.SpeedAccelDeccelPositionM1(SLIDE_MODULE_ADDR,accel,speed,deccel,position,1):
raise IOError("Failed to lower drill: CRC failure")
"""
Moves jigsaw to top position
"""
def raise_jigsaw(speed):
speed = int(speed * SLIDE_TICKS_PER_LINEAR_MM)
accel = int(5*speed)
deccel = accel
position = int(1 * SLIDE_TICKS_PER_LINEAR_MM)
if not slide.SpeedAccelDeccelPositionM2(SLIDE_MODULE_ADDR,accel,speed,deccel,position,1):
raise IOError("Failed to raise jigsaw: CRC failure")
"""
Moves jigsaw to bottom position
"""
def lower_jigsaw(speed):
speed = int(speed * SLIDE_TICKS_PER_LINEAR_MM)
accel = int(5*speed)
deccel = accel
position = int(JIGSAW_PLUNGE_DEPTH * SLIDE_TICKS_PER_LINEAR_MM)
if not slide.SpeedAccelDeccelPositionM2(SLIDE_MODULE_ADDR,accel,speed,deccel,position,1):
raise IOError("Failed to lower jigsaw: CRC failure")
"""
Stops all motors
"""
def panic():
success = slide.SpeedM1(SLIDE_MODULE_ADDR, 0)
success = success and slide.SpeedM2(SLIDE_MODULE_ADDR, 0)
if not success:
raise IOError("Slide panic failed. Time to really panic!") | {"/jigsaw_robot/drive_module/drive_module.py": ["/jigsaw_robot/config.py"], "/jigsaw_robot/relay_module/__init__.py": ["/jigsaw_robot/relay_module/relay_module.py"], "/jigsaw_robot/slide_module/slide_module.py": ["/jigsaw_robot/config.py"], "/KillerInterface.py": ["/Logging.py"], "/jigsaw_robot/safety_module/__init__.py": ["/jigsaw_robot/safety_module/safety_module.py"], "/jigsaw_robot/drive_module/__init__.py": ["/jigsaw_robot/drive_module/drive_module.py"], "/joystick.py": ["/jigsaw_robot/__init__.py"], "/jigsaw_robot/__init__.py": ["/jigsaw_robot/jigsaw_robot.py"], "/jigsaw_robot/jigsaw_robot.py": ["/jigsaw_robot/drive_module/__init__.py", "/jigsaw_robot/relay_module/__init__.py"], "/jigsaw_robot/relay_module/relay_module.py": ["/jigsaw_robot/config.py"], "/TrajectoryTests.py": ["/Model.py"]} |
78,698 | JeffreyILipton/KillerSawBot | refs/heads/master | /CreateInterface.py | from enum import IntEnum
import serial
import struct
from math import *
import sys
import time
DEBUG = False#True
NO_SERIAL = False
class Create_OpMode(IntEnum):
Passive = 130
Safe = 131
Full = 132
class Create_DriveMode(IntEnum):
Drive = 137
Direct = 145
class Create_Commands(IntEnum):
Start = 128
def minMax(min_val,max_val,val):
return max(min_val,min(val,max_val))
class CreateRobotCmd(object):
def __init__(self,port,OpMode,DriveMode):
'''Opens Serial Port'''
# These are hard limits in the create which are hard coded in
self.rmin = -2000.0
self.rmax = 2000.0
self.vmin = -500.0
self.vmax = 500.0
# opp mode is either Pasisve, safe, or full. Always use full
self.opmode = OpMode
#information on drive mode is bellow and in documentation
self.drivemode = DriveMode
#Serial port baud is currently hard coded
if NO_SERIAL:
self.port = serial.Serial()
else:
self.port = serial.Serial(port,57600,parity = serial.PARITY_NONE, stopbits = serial.STOPBITS_ONE,xonxoff=False,timeout=10.0)
def start(self):
self._writeCommand(Create_Commands.Start)
self._writeCommand(self.opmode)
def stop(self):
'''Stops movement and sets the device to passive'''
self.directDrive(0,0)
self.opmode = Create_OpMode.Passive
self._writeCommand(Create_OpMode.Passive)
#self.port.close()
def _writeCommand(self,cmd):
'''the input type should be a string, int, or Create_ value
int is converted to a char string,
strings are passed through'''
if (type(cmd) == type(Create_Commands.Start) or
type(cmd) == type(Create_OpMode.Full) or
type(cmd) == type(Create_DriveMode.Direct) ):
cmd = int(cmd)
if type(cmd) == int:
cmd = str(chr(cmd))
elif type(cmd) == type(None):
print "huh"
return
nb = len(cmd)
if not NO_SERIAL:
nb_written = self.port.write(cmd)
if (nb != nb_written):print "Error only wrote %i not %i bytes"%(nb_written,nb)
if DEBUG:
int_form = []
for i in range(0,nb):
int_form.append(int(ord(cmd[i])))
print cmd
print int_form
def demo(self):
cmd = struct.pack('B',136)+struct.pack('B',2)
self._writeCommand(cmd)
def _makecmd(self,head,one,two):
return struct.pack('B',head)+struct.pack('>h',one)+struct.pack('>h',two)
def drive(self,Radius,Velocity):
'''This mode uses radii and velocity for turning
straight requires R=None
Clockwise and Counterclockwise in place are R=0
'''
if (self.drivemode != Create_DriveMode.Drive): self.self.drivemode =Create_DriveMode.Drive
Velocity = minMax(self.vmin,self.vmax,Velocity)
if Radius == None:
Radius = 32767
elif Radius ==0 and Velocity >0:
Radius =int('0xFFFF',0)
elif Radius ==0 and Velocity <0:
Radius =int('0x0001',0)
else:
Radius = minMax(self.rmin,self.rmax,Radius)
cmd = self._makecmd(int(self.drivemode),int(Velocity),int(Radius))
self._writeCommand(cmd)
def directDrive(self,V1,V2):
'''The direct drive mode allows control over right and left wheels directly. This uses v1 for R and V2 for L'''
if (self.drivemode != Create_DriveMode.Direct): self.drivemode = Create_DriveMode.Direct
V1 = minMax(self.vmin,self.vmax,V1)
V2 = minMax(self.vmin,self.vmax,V2)
cmd = self._makecmd(int(self.drivemode),int(V1),int(V2))
self._writeCommand(cmd)
def main():
CRC = CreateRobotCmd('/dev/ttyUSB0',Create_OpMode.Full,Create_DriveMode.Direct)
print CRC.port.isOpen()
if CRC.port.isOpen() or DEBUG:
print "starting"
CRC.start()
CRC.stop()
for i in range(0,2):
CRC.directDrive(50,50)
time.sleep(5)
CRC.directDrive(0,-50)
time.sleep(5)
CRC.directDrive(-50,0)
time.sleep(5)
CRC.directDrive(-50,-50)
# time.sleep(10)
#time.sleep(2)
#CRC.drive(5*pow(10,(i+1)),100)
time.sleep(5)
#CRC.drive(5,100)
CRC.stop()
#CRC.start()
print "Done"
return 0
if __name__ == "__main__":
sys.exit(int(main() or 0))
| {"/jigsaw_robot/drive_module/drive_module.py": ["/jigsaw_robot/config.py"], "/jigsaw_robot/relay_module/__init__.py": ["/jigsaw_robot/relay_module/relay_module.py"], "/jigsaw_robot/slide_module/slide_module.py": ["/jigsaw_robot/config.py"], "/KillerInterface.py": ["/Logging.py"], "/jigsaw_robot/safety_module/__init__.py": ["/jigsaw_robot/safety_module/safety_module.py"], "/jigsaw_robot/drive_module/__init__.py": ["/jigsaw_robot/drive_module/drive_module.py"], "/joystick.py": ["/jigsaw_robot/__init__.py"], "/jigsaw_robot/__init__.py": ["/jigsaw_robot/jigsaw_robot.py"], "/jigsaw_robot/jigsaw_robot.py": ["/jigsaw_robot/drive_module/__init__.py", "/jigsaw_robot/relay_module/__init__.py"], "/jigsaw_robot/relay_module/relay_module.py": ["/jigsaw_robot/config.py"], "/TrajectoryTests.py": ["/Model.py"]} |
78,699 | JeffreyILipton/KillerSawBot | refs/heads/master | /Simulator.py | from threading import Thread, Lock, Event
from StateEstimator import *
from CreateInterface import *
from Model import *
from Controller import *
from TrajectoryTests import *
from Logging import *
import sys
from KillerInterface import *
from plotRun import *
class TickTock():
def __init__(self):
self.SimI=0
self.ConI=0
self.lock = Lock()
def setSimI(self,I):
#self.lock.acquire()
self.SimI = I
#self.lock.release()
def setConI(self,I):
#self.lock.acquire()
self.ConI = I
#self.lock.release()
#print "set: ",state
def simTick(self):
return self.ConI>=self.SimI
def conTick(self):
return self.ConI<=self.SimI
class Simulator(Thread):
def __init__(self,stopper, CRC_sim, stateholder, XKs, ro, dt, Q, speedup = 10, timelock=None, NoNoise=False):
Thread.__init__(self)
self.stopper = stopper
self.CRC = CRC_sim
self.holder = stateholder
self.ro =ro
self.dt = dt
self.Q = Q
self.Xks = XKs
self.t0 = int(time.time()*1000)
self.index = 0
self.speedup=speedup
self.ticktock = timelock
self.no_noise = NoNoise
def run(self):
X_k = np.mat(np.zeros( (6,1) ) )
print "start sim"
while (not self.stopper.is_set() ) and self.index<( len(self.Xks) ):
time.sleep(self.dt/self.speedup)
Uc = self.CRC.LastU()
G,V = MotorGainAndOffset()
U = G.dot(Uc)+V
for i in range(0,2):
if fabs(U[i])<10:
U[i]=0
X_k = self.holder.GetConfig()
#if (self.index==0): Conf[0,0]+=20.0
n = [0.1,0.1,2*pi/360/4]
W = np.matrix([np.random.normal(0,n[i],1) for i in range(0,3)] )
#print W
K1 = B(X_k[2,0],self.ro).dot(U)
K2 = B(X_k[2,0]+self.dt*0.5*K1[2,0],self.ro).dot(U)
K3 = B(X_k[2,0]+self.dt*0.5*K2[2,0],self.ro).dot(U)
K4 = B(X_k[2,0]+self.dt*K3[2,0],self.ro).dot(U)
# B returns a 3x1 but X_k is 3x1
X_k_p1 = A(self.dt).dot(X_k) + self.dt/6*(K1+2*K2+2*K3+K4) +W
if self.no_noise:
X_k_p1 = A(self.dt).dot(X_k) + self.dt/6*(K1+2*K2+2*K3+K4)
#print A(self.dt)
#print X_k_p1[0:3]
X_k_p1[2,0] = X_k_p1[2,0]%(2.0*pi)
X_k = X_k_p1
#print "Sim:",self.index
t = self.t0+self.dt*1000*self.index
step = False
if self.ticktock == None: step=True
elif self.ticktock.simTick():
step = True
self.ticktock.setSimI(self.index+1)
if step:
self.holder.setState(X_k_p1[0:3],t)
self.index+=1
class CRC_Sim:
def __init__(self):
self.Us=[]
def start(self):
pass
def stop(self):
pass
def directDrive(self,V1,V2):
V1= max(min(V1,500),-500)
V2= max(min(V2,500),-500)
self.Us.append(np.matrix([V1,V2]).transpose())
def LastU(self):
if len(self.Us):
return self.Us[-1]
return np.matrix([0,0]).transpose()
class KillerSim(KillerRobotCmd):
def __init__(self,log_queue = None):
KillerRobotCmd.__init__(self,None,log_queue)
self.Us = []
def directDrive(self,V1,V2):
self.drive(V1,V2)
self.Us.append(np.matrix([V1,V2]).transpose())
def LastU(self):
if len(self.Us):
return self.Us[-1]
return np.matrix([0,0]).transpose()
def main():
channel = 'VICON_sawbot'
r_wheel = 125#mm
dt = 1.0/5.0
dt = 0.15
'''Q should be 1/distance deviation ^2
R should be 1/ speed deviation^2
'''
dist = 20.0 #mm
ang = 0.25 # radians
Q = np.diag([1.0/(dist*dist),
1.0/(dist*dist),
1.0/(ang*ang)])
R = np.eye(2)
command_variation = 20.0
R = np.diag([1/( command_variation * command_variation ),
1/( command_variation * command_variation )] )
maxUc = 20;
r_circle = 300#mm
speed = 25 #64
Xks = circle(r_circle,dt,speed)
#Xks = straight(1000,1.0/5.0,speed)
#Xks = loadTraj('../Media/card2-dist5.20-rcut130.00-trajs-0.npy')
Xks,Uks = TrajToUko(Xks,r_wheel,dt)
#Xks = Xks[:50]
lock = Lock()
start = np.matrix(Xks[0][0:3]).transpose()
print start
speedup = 100.0
sh = StateHolder(lock,start)
timelock = TickTock()
runNum = 8
#Setup the logging
LogQ = Queue(0)
Log_stopper = Event()
logname = "Run%i.csv"%runNum
Log = Logger(logname,Log_stopper,LogQ)
LogQ2 = Queue(0)
Log_stopper2 = Event()
logname2 = "time%i.csv"%runNum
Log2 = Logger(logname2,Log_stopper2,LogQ2)
LogQ3 = Queue(0)
Log_stopper3 = Event()
logname3 = "cmds%i.csv"%runNum
Log3 = Logger(logname3,Log_stopper3,LogQ3)
#setup the controller
T = 5 #horizon
RunControl = True
CC_stopper = Event()
CRC = KillerSim(LogQ3) # CRC_Sim()
CC = Controller(CC_stopper,CRC,sh,Xks,Uks,r_wheel,dt,Q,R,T,maxUc,LogQ,not RunControl,speedup,timelock,LogQ2)
VSim_stopper = Event()
#setup the simulator
VSim = Simulator(VSim_stopper,CRC,sh,Xks,r_wheel,dt,Q,speedup,timelock)
CRC.start()
VSim.start()
#time.sleep(0.005)
CC.start()
Log.start()
Log2.start()
Log3.start()
CC.join()
CRC.stop()
VSim_stopper.set()
Log_stopper.set()
Log_stopper2.set()
Log_stopper3.set()
VSim.join()
Log.join()
Log2.join()
Log3.join()
print 'Done'
time.sleep(0.05)
plotCSVRun(logname)
return 0
if __name__ == "__main__":
sys.exit(int(main() or 0)) | {"/jigsaw_robot/drive_module/drive_module.py": ["/jigsaw_robot/config.py"], "/jigsaw_robot/relay_module/__init__.py": ["/jigsaw_robot/relay_module/relay_module.py"], "/jigsaw_robot/slide_module/slide_module.py": ["/jigsaw_robot/config.py"], "/KillerInterface.py": ["/Logging.py"], "/jigsaw_robot/safety_module/__init__.py": ["/jigsaw_robot/safety_module/safety_module.py"], "/jigsaw_robot/drive_module/__init__.py": ["/jigsaw_robot/drive_module/drive_module.py"], "/joystick.py": ["/jigsaw_robot/__init__.py"], "/jigsaw_robot/__init__.py": ["/jigsaw_robot/jigsaw_robot.py"], "/jigsaw_robot/jigsaw_robot.py": ["/jigsaw_robot/drive_module/__init__.py", "/jigsaw_robot/relay_module/__init__.py"], "/jigsaw_robot/relay_module/relay_module.py": ["/jigsaw_robot/config.py"], "/TrajectoryTests.py": ["/Model.py"]} |
78,700 | JeffreyILipton/KillerSawBot | refs/heads/master | /Logging.py | from threading import Thread, Event
from Queue import Queue
import sys
import csv
class Logger(Thread):
def __init__(self,name,stopper,queue):
Thread.__init__(self)
self.stopper = stopper
self.queue = queue
self.csvFile = open(name,'wb')
self.writer = csv.writer(self.csvFile)
def run(self):
while not self.stopper.is_set():
if not self.queue.empty():
v = self.queue.get()
self.writer.writerow(v)
self.queue.task_done()
self.csvFile.close() | {"/jigsaw_robot/drive_module/drive_module.py": ["/jigsaw_robot/config.py"], "/jigsaw_robot/relay_module/__init__.py": ["/jigsaw_robot/relay_module/relay_module.py"], "/jigsaw_robot/slide_module/slide_module.py": ["/jigsaw_robot/config.py"], "/KillerInterface.py": ["/Logging.py"], "/jigsaw_robot/safety_module/__init__.py": ["/jigsaw_robot/safety_module/safety_module.py"], "/jigsaw_robot/drive_module/__init__.py": ["/jigsaw_robot/drive_module/drive_module.py"], "/joystick.py": ["/jigsaw_robot/__init__.py"], "/jigsaw_robot/__init__.py": ["/jigsaw_robot/jigsaw_robot.py"], "/jigsaw_robot/jigsaw_robot.py": ["/jigsaw_robot/drive_module/__init__.py", "/jigsaw_robot/relay_module/__init__.py"], "/jigsaw_robot/relay_module/relay_module.py": ["/jigsaw_robot/config.py"], "/TrajectoryTests.py": ["/Model.py"]} |
78,701 | JeffreyILipton/KillerSawBot | refs/heads/master | /KillerInterface.py | import serial
import pickle
from Logging import Queue
from enum import IntEnum
class KillerRobotProtocol(IntEnum):
Start = 0
LeftMotor = 1
RightMotor = 2
LeftAndRightMotor = 3
Drill = 4
JigsawLower = 5
JigsawRaise = 6
JigsawStart = 7
JigsawStop = 8
Status = 9
Stop = 10
class KillerRobotOutMessage(object):
def __init__(self, message_type , first_value = None, second_value = None):
self.message_type = message_type
self.first_value = first_value
self.second_value = second_value
def serialized(self):
return pickle.dump(self) + "\n".encode('utf-8')
def __str__(self):
return str(self.message_type) +","+ str(self.first_value) +","+ str(self.second_value)
class KillerRobotInMessage(object):
def __init__(self, ack , error_type = None):
self.ack = ack
self.error_type = error_type
def serialized(self):
return pickle.dump(self) + str(self.ack) + str(self.error_type)
def __str__(self):
return "InMsg" + "," + str(self.ack) + "," + str(self.error_type)
class KillerRobotCmd(object):
"""
Initializes Killer robot.
port - The port that the Xbee is connected to. Used for serial comms
debug - If set to a queue instance, this robot instance will redirect all serial commands to the queue file
"""
def __init__(self, port , log_queue = None):
# robot velocity limits for both wheels
self.velocity_min = -100 #mm/s
self.velocity_max = 100 #mm/s
self.is_logging = True if log_queue else False
self.logQueue = log_queue
self.is_debug = False if port else True
self.port = None
if not self.is_debug:
self.port = serial.Serial(port)
"""
Starts up robot; opens port and tells robot to wake up.
"""
def start(self):
if self.port: self.port.open()
start_message = KillerRobotOutMessage(KillerRobotProtocol.Start)
self._write_message(start_message)
"""
Stops robot; closes port and tells robot to shut down.
"""
def stop(self):
stop_message = KillerRobotOutMessage(KillerRobotProtocol.Stop)
self._write_message(stop_message)
if self.port: self.port.close()
"""
Tells robot to drive with wheels moving at requested velocity.
Command will FAIL if the robot is drilling or moving the jigsaw slide
"""
def drive(self, left_velocity, right_velocity):
left_velocity = max(self.velocity_min, min(self.velocity_max, left_velocity))
right_velocity = max(self.velocity_min, min(self.velocity_max, right_velocity))
drive_message = KillerRobotOutMessage(KillerRobotProtocol.LeftAndRightMotor,
first_value = left_velocity,
second_value = right_velocity)
self._write_message(drive_message)
"""
Tells robot to peck drill at the current location. Command will FAIL
if the robot is moving.
"""
def drill(self):
drill_message = KillerRobotOutMessage(KillerRobotProtocol.Drill)
self._write_message(drill_message)
"""
Tells the robot to lower the jigsaw
"""
def lower_jigsaw(self):
jigsaw_message = KillerRobotOutMessage(KillerRobotProtocol.JigsawLower)
self._write_message(jigsaw_message)
"""
Lowers jigsaw. Command will FAIL if the robot is moving
"""
def raise_jigsaw(self):
jigsaw_message = KillerRobotOutMessage(KillerRobotProtocol.JigsawRaise)
self._write_message(jigsaw_message)
"""
Starts jigsaw.
"""
def start_jigsaw(self):
jigsaw_message = KillerRobotOutMessage(KillerRobotProtocol.JigsawStart)
self._write_message(jigsaw_message)
"""
Stops jigsaw
"""
def stop_jigsaw(self):
jigsaw_message = KillerRobotOutMessage(KillerRobotProtocol.JigsawStop)
self._write_message(jigsaw_message)
def _write_message(self, message):
if self.is_logging:
self.logQueue.put(str(message).split(','))
response = None
if self.is_debug:
response = KillerRobotInMessage(True)
else:
self.port.write(message.serialized())
response = pickle.loads(self.port.read_until())
if self.is_logging:
self.logQueue.put(str(response).split(','))
if not response.ack:
raise IOError("Robot did not successfully parse command")
return response
| {"/jigsaw_robot/drive_module/drive_module.py": ["/jigsaw_robot/config.py"], "/jigsaw_robot/relay_module/__init__.py": ["/jigsaw_robot/relay_module/relay_module.py"], "/jigsaw_robot/slide_module/slide_module.py": ["/jigsaw_robot/config.py"], "/KillerInterface.py": ["/Logging.py"], "/jigsaw_robot/safety_module/__init__.py": ["/jigsaw_robot/safety_module/safety_module.py"], "/jigsaw_robot/drive_module/__init__.py": ["/jigsaw_robot/drive_module/drive_module.py"], "/joystick.py": ["/jigsaw_robot/__init__.py"], "/jigsaw_robot/__init__.py": ["/jigsaw_robot/jigsaw_robot.py"], "/jigsaw_robot/jigsaw_robot.py": ["/jigsaw_robot/drive_module/__init__.py", "/jigsaw_robot/relay_module/__init__.py"], "/jigsaw_robot/relay_module/relay_module.py": ["/jigsaw_robot/config.py"], "/TrajectoryTests.py": ["/Model.py"]} |
78,702 | JeffreyILipton/KillerSawBot | refs/heads/master | /Controller.py | from threading import Thread, Lock, Event
from StateEstimator import *
from CreateInterface import *
from Model import *
from Simulator import TickTock
import scipy
from scipy.optimize import minimize
import sys
#import csv
from math import fabs
def obj(Xbar,Xtraj,Qbar):
DX = diffXs(Xbar,Xtraj)
#DX = (Xbar.reshape((Xbar.size,1))-Xtraj)
J = 0.5*DX.T.dot(Qbar).dot(DX)
j = float(J[0,0])
return j
def jacobian(Xbar,Xtraj,Qbar):
DX = diffXs(Xbar,Xtraj)
jac = DX.T.dot(Qbar)
njac = np.squeeze(np.asarray(jac))
return njac
def dynamicConstraint(Xbar,Xnow,dt,ro,T):
G,V = MotorGainAndOffset()
C = np.zeros((3*(T),1))
U1 = Xbar[0:2].reshape((2,1))
X2 = Xbar[2:5].reshape((3,1))
Umod = G.dot(U1)+V
C[0:3] = X2-Xnow - dt*B(Xnow[2],ro).dot(Umod)
for i in range(1,T):
Xkm1 = Xbar[5*(i-1)+2 : 5*(i-1)+2+3].reshape((3,1))
Ukm1 = Xbar[5*(i-1)+3+2 : 5*(i-1)+4+3].reshape((2,1))
Xk = Xbar[5*(i ) +2 : 5*(i )+2+3].reshape((3,1))
Umod = G.dot(Ukm1)+V
diff = Xk - Xkm1 - dt*B(Xkm1[2],ro).dot(Umod)
C[3*i:3*i+3] = diff
Cturned = np.squeeze(np.asarray(C))
return Cturned
def subBlock(Xbar,dt,ro,i):
U1 = Xbar[5*(i) :5*(i)+2].reshape((2,1))
x1 = Xbar[5*(i)-3 :5*(i)].reshape((3,1))
G,V = MotorGainAndOffset()
Umod = G.dot(U1)+V
quack = dt*dBdtheta(x1[2]).dot(Umod)
crack = np.zeros((3,3))
crack[:,2] = np.squeeze(quack)
Bk = B(x1[2],ro)
dC1dx1 = -np.eye(3) - crack
dC1du1 = -dt*Bk.dot(G)
dC1dx2 = np.eye(3)
return np.asarray(np.bmat([dC1dx1,dC1du1,dC1dx2]))
def dynamicJacobian(Xbar,Xnow,dt,ro,T):
Cj = np.zeros((3*(T),5*T))
Bk = B(Xnow[2],ro)
G,V = MotorGainAndOffset()
U1 = Xbar[0:2].reshape((2,1))
Umod = G.dot(U1)+V
dC1du1 = -dt*Bk.dot(G)
dC1dx2 = np.eye(3)
Cj[0:3,0:5]=np.bmat([dC1du1,dC1dx2])
for i in range(1,T):
block = subBlock(Xbar,dt,ro,i)
Cj[3*i:3*i+3,5*i-3:5*i+5] = block
djacobian = np.squeeze(np.asarray(Cj))
return djacobian
def bounds(T,Uos,Umaxs):
b = []
for i in range(0,T):
b.append((None,None))
b.append((None,None))
b.append((None,None))
b.append((Uos[i,0]-Umax[0],Uos[i,0]+Umax[0]))
b.append((Uos[i,1]-Umax[1],Uos[i,1]+Umax[1]))
return b
def xtrajMaker(Xks,Uks,T,index):
xtraj = np.zeros((5*T,1))
for i in range(0,T):
xtraj[0+5*i:2+5*i] = Uks[index+i].transpose()
xtraj[2+5*i:5+5*i] = Xks[index+1+i].reshape((3,1))#.transpose()
return xtraj
def xGuess(Xguess,Xstar,ro,dt,T):
if T >= Xstar.size/5.0:
Xguess[0:-5] = Xstar[5:].reshape((Xstar.size-5,1))
ulast = Xstar[-5:-3]
xlast = Xstar[-3:]
xnew = xlast+dt*B(xlast[2],ro).dot(ulast)
Xguess[-5:-3] = ulast.reshape((2,1))
Xguess[-3:] = xnew.T
else:
Xguess = Xstar[5:5*T+5]
return Xguess
def MPC(dt,ro,T,Xtraj,Qbar,Xguess,X_m):
constrains = ({'type':'eq',
'fun':lambda x: dynamicConstraint(x,X_m,dt,ro,T),
'jac': lambda x: dynamicJacobian(x,X_m,dt,ro,T)})
#Set the objective function and its jacobian
targetobj = lambda x: obj(x,Xtraj,Qbar)
targetjac = lambda x: jacobian(x,Xtraj,Qbar)
XStar = minimize(targetobj,np.squeeze(np.asarray(Xguess)),method='SLSQP',
options = {'maxiter':10},
#bounds = self.bounds,
constraints = constrains,#)#,
jac = targetjac)
U = XStar.x[0:2]
return U,XStar.x
def thresholdU(U,Uc,maxU):
Udif = U-Uc
U_clean = np.array(U)
for i in range(0,2):
if fabs(Udif[i])>maxU:
U_clean[i] = maxU*Udif[i]/fabs(Udif[i])+Uc[i]
return U_clean
class Controller(Thread):
def __init__(self,stopper,CRC,stateholder,Xks,Uks,ro,dt,Q,R,T,maxU=100,StateQueue=None,NoControl=False,speedup = 1,ticktoc = None, SimQ = None):
Thread.__init__(self)
self.nocontrol = NoControl
self.speedup = speedup
self.ticktock = ticktoc
self.CRC = CRC
self.holder = stateholder
self.dt = dt
self.T =T
self.Q = Q
self.ro = ro
self.stopper = stopper
self.state_queue = StateQueue
self.simq = SimQ
self.Uos = Uks
self.Xks = Xks
self.maxU = maxU
self.index = 0
if type(self.state_queue)!=type(None):
row=['Time','X_target','Y_target','Angle_target','X_actual','Y_actual','Angle_actual','DX angle','U[0]','U[1]','Uc[0]','Uc[1]']
self.state_queue.put(row)
if type(SimQ) != type(None):
row = ["time","dt","speedup"]
self.simq.put(row)
def run(self):
waittime = 0
Qbar = makeSuperQ(self.Q,self.T)
while (self.index<( len(self.Uos)-2)) and (not self.stopper.is_set()) :
tic = time.time()
# the current State
X_m = self.holder.GetConfig()
t = self.holder.getTime()
Uc = np.squeeze(np.array(self.Uos[self.index]).transpose())
# This is where the control happens
if not self.nocontrol:
#Set the Horizon
T = min( (len(self.Uos) - self.index-1), self.T)
if self.index ==0:
Xguess = xtrajMaker(self.Xks,self.Uos,self.T,self.index)
else:
Xguess = xGuess(Xguess,XStar,self.ro,self.dt,T)
if (T!= self.T): Qbar = makeSuperQ(self.Q,T)
Xtraj = xtrajMaker(self.Xks,self.Uos,T,self.index)
# Run MPC
U_init, XStar = MPC(self.dt,self.ro,T,Xtraj,Qbar,Xguess,X_m)
# Threshold results
U = thresholdU(U_init,Uc,self.maxU)
else:
U=Uc
# Threshold difference between expected and actual
# blocking if using simulator
step = False
if self.ticktock == None: step=True
elif self.ticktock.conTick():
step = True
self.ticktock.setConI(self.index+1)
# wait for time needed
toc = time.time()
time_taken = toc-tic
print time_taken
waittime = self.dt-time_taken
waittime = max(waittime,0)
time.sleep(waittime/self.speedup)
if step:
self.CRC.directDrive(U[0],U[1])
if type(self.simq) != type(None):
row = [time_taken,self.dt,self.speedup]
self.simq.put(row)
if type(self.state_queue)!=type(None):
# add to log
Xk = np.matrix(self.Xks[self.index]).transpose()
DX = X_m- Xk
#look out for theta wrap around
DX[2,0] = minAngleDif(X_m[2,0],self.Xks[self.index][2])
row = [t]+[Xk[0,0], Xk[1,0], Xk[2,0] ]+[X_m[0,0], X_m[1,0], X_m[2,0] ]+[DX[2,0]]+[U[0],U[1]]+[Uc[0],Uc[1]]
self.state_queue.put(row)
print "I:",self.index
self.index +=1
print "Control Done"
def main():
#setup controller infor
channel = 'VICON_sawbot'
r_wheel = 125#mm
dt = 1.0/5.0
maxU = 15.0
'''Q should be 1/distance deviation ^2
R should be 1/ speed deviation^2
'''
dist = 20.0 #mm
ang = 0.5 # radians
Q = np.diag([1.0/(dist*dist),
1.0/(dist*dist),
1.0/(ang*ang)])
R = np.eye(2)
command_variation = 10.0
R = np.diag([1/( command_variation * command_variation ),
1/( command_variation * command_variation )] )
# Setup the Trajectory
#Xks = loadTraj('../Media/card4-dist5.20-rcut130.00-trajs-0.npy')
r_circle = 260#mm
speed = 20 #64
Xks = circle(r_circle,dt,speed)#loadTraj('../Media/card4-dist5.20-rcut130.00-trajs-0.npy')
Xks,Uks = TrajToUko(Xks,r_wheel,dt)
# Setup the Robot interface
CRC = CreateRobotCmd('/dev/ttyUSB0',Create_OpMode.Full,Create_DriveMode.Direct)
# setup the Vicon interface
lock = Lock()
sh = StateHolder(lock,np.matrix([0,0,0]).transpose())
VI_stopper = Event() # https://christopherdavis.me/blog/threading-basics.html
VI = ViconInterface(VI_stopper,channel,sh)
VI.start()
time.sleep(0.05)
# Get initial position
Xinitial = sh.GetConfig()
print 'X_initial:', Xinitial
# transform to start at robot current position.
Xtraj0 = Xks[0]
Xks = [transformToViconFrame(Xinitial,Xtraj0,Xtraj) for Xtraj in Xks]
# make the Controller for the trajectory
T = 5
CC_stopper = Event()
LogQ = Queue(0)
CC = Controller(CC_stopper,CRC,sh,Xks,Uks,r_wheel,dt,Q,R,T,maxU,LogQ,NoControl=False)
CRC.start() # this must come before CC.start()
#Setup the logging
Log_stopper = Event()
logname = "Run1.csv"
Log = Logger(logname,Log_stopper,LogQ)
# Start log and controll
CC.start()
Log.start()
# Wait for the control to be done and stop logging and vicon
CC.join()
Log_stopper.set()
Log.join()
VI_stopper.set()
VI.join()
print "Done"
# Make plots!
plotCSVRun(logname)
if __name__ == "__main__":
from plotRun import *
from Logging import *
from TrajectoryTests import *
from Trajectory import *
sys.exit(int(main() or 0))
| {"/jigsaw_robot/drive_module/drive_module.py": ["/jigsaw_robot/config.py"], "/jigsaw_robot/relay_module/__init__.py": ["/jigsaw_robot/relay_module/relay_module.py"], "/jigsaw_robot/slide_module/slide_module.py": ["/jigsaw_robot/config.py"], "/KillerInterface.py": ["/Logging.py"], "/jigsaw_robot/safety_module/__init__.py": ["/jigsaw_robot/safety_module/safety_module.py"], "/jigsaw_robot/drive_module/__init__.py": ["/jigsaw_robot/drive_module/drive_module.py"], "/joystick.py": ["/jigsaw_robot/__init__.py"], "/jigsaw_robot/__init__.py": ["/jigsaw_robot/jigsaw_robot.py"], "/jigsaw_robot/jigsaw_robot.py": ["/jigsaw_robot/drive_module/__init__.py", "/jigsaw_robot/relay_module/__init__.py"], "/jigsaw_robot/relay_module/relay_module.py": ["/jigsaw_robot/config.py"], "/TrajectoryTests.py": ["/Model.py"]} |
78,703 | JeffreyILipton/KillerSawBot | refs/heads/master | /Model.py | from math import *
import numpy as np
import scipy
'''
let the vehicle have two wheels with speeds U1 and U2. lets U1 be the one on the left and U2 the one on the right when looking form above with the front of hte vehicle
X_car
/ \
|
|
------|<----o---->|-------> Y_car
U1 | U2
|
|
\ /
V_cm = 0.5*(U1+U2) = sqrt( X_dot^2 + Y_dot^2 )
Theta_dot = 1/ro * 1/2 * (U2-U1)
X_dot = BU
_ _ _ _ _ _
| X_dot | | 1/2*cos(theta), 1/2*cos(theta) | * | U1 |
| Y_dot | = | 1/2*sin(theta), 1/2*sin(theta) | |_U2_|
|_Theta_dot_| |_-1/(2*ro) , 1/(2*ro) _|
X_k+1 = I+Bu
Inverting V_cm and theta_dot eq we get
U1 = V-R*theta_dot
U2 = V+R*theta_dot
'''
def minAngleDif(x,y):
a = atan2(sin(x-y), cos(x-y))
#if(a<0):a = 2*pi-a
return a
def V(Xk,Xkp1,dt):
vm = [ (Xkp1[0]-Xk[0])/dt , ((Xkp1[1]-Xk[1])/dt) ]
return vm
def UkFromXkandXkplusone(Xk,Xkp1,ro,dt):
#V = sqrt( ((Xkp1[0]-Xk[0])/dt)**2 + ((Xkp1[1]-Xk[1])/dt)**2 )
#http://stackoverflow.com/questions/1878907/the-smallest-difference-between-2-angles
#d_theta = minAngleDif(Xkp1[2],Xk[2])
#thetadot = d_theta/dt
DX = Xkp1-Xk
DX[2] = minAngleDif(Xkp1[2],Xk[2])
Binv = 1.0/dt*PseudoBInv(Xk[2],ro)
#Uk = [(V-ro*thetadot),(V+ro*thetadot)]
#Uk = np.array(Uk)
#Uk = np.array([[(V+ro*thetadot)],
# [(V-ro*thetadot)]])
Uk = Binv.dot(DX)
G,Mo = MotorGainAndOffset()
GI = np.linalg.inv(G)
Uc = GI.dot(Uk.transpose()-Mo)
return Uc.transpose()
def sameSign(a,b):
if (a==0 or b==0) and (a!=0 or b!=0): return False
return ((a<0) == (b<0))
def dotProduct(v1,v2):
return v1[0]*v2[0]+v1[1]*v2[1]
def TrajToUko(Xks,ro,dt,):
Ukos = []
prev_v = [0,0]
new_xks = []
for i in range(0,len(Xks)-1):
Xk = Xks[i]
Xkp1 = Xks[i+1]
v = V(Xk,Xkp1,dt)
Uko = np.array(UkFromXkandXkplusone(Xk,Xkp1,ro,dt))
npts=1
if (dotProduct(prev_v,v) <= 0):
delay = DelayModel(sqrt(dotProduct(v,v)))
npts = int(delay/dt)
for j in range(0,npts):
new_xks.append(Xk)
Ukos.append(Uko)
prev_v = v
return new_xks,Ukos
def B(th,r0):
'''returns the B matrix
this expects a 1d array for X
'''
#g = 0.7964
B = np.matrix([[.5*cos(th), .5*cos(th)],[.5*sin(th), .5*sin(th)],[1.0/(2.0*r0), -1.0/(2.0*r0)]])
return B
def PseudoBInv(th,ro):
Binv = np.matrix([[cos(th), sin(th),ro],[cos(th), sin(th),-ro]])
return Binv
def A(dt):
Ia = np.mat(np.eye(3))
#Dt = dt*Ia
#Za = np.mat(np.zeros((3,3)))
#A = np.bmat([[Ia,Dt],[Za,Za]])
return Ia
def dBdtheta(th):
B = np.matrix([[-0.5*sin(th), -0.5*sin(th)],
[ 0.5*cos(th), 0.5*cos(th)],
[ 0, 0]])
return B
def diffXs(Xbar,Xtraj):
DX = (Xbar.reshape((Xbar.size,1))-Xtraj)
for i in range(4,Xbar.size,5):
DX[i] = minAngleDif(Xbar[i],Xtraj[i])
return DX
def makeSuperQ(Q,T):
diag=[]
for i in range(0,T):
diag.append(np.zeros((2,2)))
diag.append(Q)
qbar = scipy.sparse.block_diag(diag).todense()
return qbar
def DelayModel(speed):
if speed < 17.5: return 2.0
Mslope = -0.021
MIntercept = 1.377
delay = Mslope*speed+MIntercept
return delay
def MotorGainAndOffset():
G = np.diag([0.855,0.7337])
V = np.mat([[-1.8889],[-0.6113]])
return G,V | {"/jigsaw_robot/drive_module/drive_module.py": ["/jigsaw_robot/config.py"], "/jigsaw_robot/relay_module/__init__.py": ["/jigsaw_robot/relay_module/relay_module.py"], "/jigsaw_robot/slide_module/slide_module.py": ["/jigsaw_robot/config.py"], "/KillerInterface.py": ["/Logging.py"], "/jigsaw_robot/safety_module/__init__.py": ["/jigsaw_robot/safety_module/safety_module.py"], "/jigsaw_robot/drive_module/__init__.py": ["/jigsaw_robot/drive_module/drive_module.py"], "/joystick.py": ["/jigsaw_robot/__init__.py"], "/jigsaw_robot/__init__.py": ["/jigsaw_robot/jigsaw_robot.py"], "/jigsaw_robot/jigsaw_robot.py": ["/jigsaw_robot/drive_module/__init__.py", "/jigsaw_robot/relay_module/__init__.py"], "/jigsaw_robot/relay_module/relay_module.py": ["/jigsaw_robot/config.py"], "/TrajectoryTests.py": ["/Model.py"]} |
78,704 | JeffreyILipton/KillerSawBot | refs/heads/master | /jigsaw_robot/safety_module/__init__.py | from jigsaw_robot.safety_module.safety_module import * | {"/jigsaw_robot/drive_module/drive_module.py": ["/jigsaw_robot/config.py"], "/jigsaw_robot/relay_module/__init__.py": ["/jigsaw_robot/relay_module/relay_module.py"], "/jigsaw_robot/slide_module/slide_module.py": ["/jigsaw_robot/config.py"], "/KillerInterface.py": ["/Logging.py"], "/jigsaw_robot/safety_module/__init__.py": ["/jigsaw_robot/safety_module/safety_module.py"], "/jigsaw_robot/drive_module/__init__.py": ["/jigsaw_robot/drive_module/drive_module.py"], "/joystick.py": ["/jigsaw_robot/__init__.py"], "/jigsaw_robot/__init__.py": ["/jigsaw_robot/jigsaw_robot.py"], "/jigsaw_robot/jigsaw_robot.py": ["/jigsaw_robot/drive_module/__init__.py", "/jigsaw_robot/relay_module/__init__.py"], "/jigsaw_robot/relay_module/relay_module.py": ["/jigsaw_robot/config.py"], "/TrajectoryTests.py": ["/Model.py"]} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.