branch_name
stringclasses
149 values
text
stringlengths
23
89.3M
directory_id
stringlengths
40
40
languages
listlengths
1
19
num_files
int64
1
11.8k
repo_language
stringclasses
38 values
repo_name
stringlengths
6
114
revision_id
stringlengths
40
40
snapshot_id
stringlengths
40
40
refs/heads/master
<file_sep># pdns Command line tool to add and and delete dns records and domains from powerdns postgresql database. ## Installation Copy pdnscmd.conf.sample to /etc/pdnscmd.conf and edit as needed. Create group pdnscmd and add your user(s) to this group. Set /etc/pdnscmd.conf filesystem permissions to for example 0750 and change group to pdnscmd cp pdnscmd.conf.sample /etc/pdnscmd.conf vi /etc/pdnscmd.conf groupadd -r pdnscmd usermod -aG pdnscmd youruser chmod 750 /etc/pdnscmd.conf chgrp pdnscmd /etc/pdnscmd.conf ## Usage Example usage. $ pdns.py > domain example.com example.com> add test A 127.0.0.1 example.com> show ADD record name=test.example.com and type=A and content=127.0.0.1 and ttl=360 example.com> commit example.com> list ... testi.example.com 360 A - 127.0.0.1 ... example.com> delete test.example.com A 127.0.0.1 example.com> show DELETE record name=test.example.com and type=A and content=127.0.0.1 example.com> revert <file_sep>#!/usr/bin/env python3 # encoding: utf-8 import cmd import sys import os import psycopg2 from datetime import datetime import configparser from ipaddress import IPv6Address, IPv6Network, IPv4Address, IPv4Network, AddressValueError import subprocess import requests import logging logger = logging.getLogger() logger.setLevel(logging.DEBUG) logging.basicConfig() CONFIG_FILE = os.environ.get("CONFIG_FILE", '/etc/pdnscmd.conf') config = configparser.ConfigParser() config.read(CONFIG_FILE) try: MASTER_DNS = config.get('global', 'master_dns') except configparser.NoOptionError: MASTER_DNS = 'example.com' try: SLAVES = [x.strip() for x in config.get('global', 'slaves').split(',')] except configparser.NoOptionError: SLAVES = ['ns2.example.com'] try: ADMIN_CONTACT = config.get('global', 'admin_contact') except configparser.NoOptionError: ADMIN_CONTACT = 'hostmaster.example.com' try: dbname = config.get('postgres', 'database') except configparser.NoOptionError: dbname = 'postgres' try: dbuser = config.get('postgres', 'user') except configparser.NoOptionError: dbuser = 'powerdns' try: dbhost = config.get('postgres', 'host') except configparser.NoOptionError: dbhost = '127.0.0.1' try: password = config.get('postgres', 'password') except configparser.NoOptionError: password = None f = open("/etc/powerdns/pdns.d/pdns.local.gpgsql", 'r') for line in f.readlines(): if line.startswith('gpgsql-password='): password = line.split('=', 1)[1] f.close() if not password: print("Cannot find postgres password") sys.exit(1) DEFAULT_TTL=360 DEBUG = False dbconn = conn = psycopg2.connect("dbname=%s user=%s password=%s host=%s" % (dbname, dbuser, password, dbhost)) db = conn.cursor() def notify_domain(domain): p = subprocess.call(['pdns_control', 'notify', domain], timeout=5) class CommandException(Exception): pass class Task(object): def validate(self): return True def execute(self): return True def show(self): return "" class RecordActions(object): DELETE=1 UPDATE=2 ADD=2 class Record(Task): def __init__(self, key, rtype, value, domain, ttl=None, priority=None, action=RecordActions.ADD): if key == '@' or key == '': self.key = domain.domain else: self.key = "%s.%s" % (key, domain.domain) self.rtype = rtype self.value = value self.ttl = ttl if ttl is None and action == RecordActions.ADD: self.ttl = DEFAULT_TTL self.priority = priority self.domain = domain self.action = action def execute(self): args = ['name', 'type', 'content', 'domain_id'] values = [self.key, self.rtype, self.value, self.domain.zone_id] self.domain.clear_records() for k, v in (('ttl', self.ttl), ('prio', self.priority),): if v is not None: args.append(k) values.append(v) if self.action == RecordActions.DELETE: db.execute("DELETE FROM records WHERE " + ' and '.join(["%s=%%s" % k for k in args]) + " RETURNING id", values) elif self.action == RecordActions.ADD: db.execute("INSERT INTO records (" + ', '.join(args) + ") VALUES (" + ','.join(['%s']*len(values)) + ") RETURNING id", values) else: raise NotImplemented("Update not implemented") if db.fetchone(): return True return False def show(self): args = [('name', self.key), ('type', self.rtype), ('content', self.value)] for k, v in (('ttl', self.ttl), ('prio', self.priority)): if v is not None: args.append((k,v)) record = ' and '.join([ "%s=%s" % (k,v) for k,v in args]) if self.action == RecordActions.DELETE: return "DELETE record %s" % record else: return "ADD record %s" % record class Domain(Task): def __init__(self, domain): self.domain = domain.rstrip('.') self._records = [] self.zone_id = None self.exists() self.to_delete = False def validate(self): if ' ' in self.domain or '.' not in self.domain: raise CommandException("Invalid domain %s" % self.domain) return True def exists(self): db.execute("SELECT name, id from domains where name = %s", (self.domain,)) res = db.fetchone() if res: self.zone_id = int(res[1]) return True else: return False def show(self): if not self.exists(): return "ADD domain %s" % self.domain if self.to_delete: return "DELETE domain %s" % self.domain return "" def clear_records(self): self._records = [] def _format_record(self, row): return { 'key': row[0], 'type': row[1] or '-', 'ttl': row[2] or '-', 'priority': row[3] or '-', 'value': row[4] or '-' } def update_records(self): db.execute("SELECT name, type, ttl, coalesce(prio::text,''), content FROM records WHERE domain_id = %s ORDER BY name, type, content", (self.zone_id,)) self._records = [{'key': x[0], 'type': x[1] or '-', 'ttl': x[2] or '-', 'priority': x[3] or '-', 'value': x[4] or '-'} for x in db.fetchall()] def records(self): if not self._records: self.update_records() return self._records def fqdn(self, key): key = key.strip('.') if key == '@': key = self.domain elif not key.endswith(self.domain): key = '%s.%s' % (key, self.domain) return key.lower() def exists_record(self, key, rtype, value, priority=None): key = self.fqdn(key) query = "SELECT id from records WHERE domain_id = %s and name = %s and type = %s and content = %s" args = [self.zone_id, key, rtype, value] if priority is not None: args.append("%s" % (priority,)) query = query + " and prio = %s" if DEBUG: print(query) db.execute(query, args) if db.fetchone() is None: return False return True def get_records(self, key, rtype=None, value=None): key = self.fqdn(key) args = [self.zone_id, key] query = "SELECT name, type, ttl, coalesce(prio::text,''), content FROM records " \ "WHERE domain_id = %s and name = %s" if rtype is not None: query += " type = %s" args.append(rtype) if value is not None: query += " content = %s" args.append(value) if DEBUG: print(query) db.execute(query, args) return [self._format_record(x) for x in db.fetchall()] """ Column | Type | Modifiers | Storage | Stats target | Description -----------------+------------------------+------------------------------------------------------+----------+--------------+------------- id | integer | not null default nextval('domains_id_seq'::regclass) | plain | | name | character varying(255) | not null | extended | | master | character varying(128) | default NULL::character varying | extended | | last_check | integer | | plain | | type | character varying(6) | not null | extended | | notified_serial | integer | | plain | | account | character varying(40) | default NULL::character varying | extended | | """ """ Column | Type | Modifiers | Storage | Stats target | Description --------------+--------------------------+------------------------------------------------------+----------+--------------+------------- id | integer | not null default nextval('records_id_seq'::regclass) | plain | | domain_id | integer | | plain | | name | character varying(255) | default NULL::character varying | extended | | type | character varying(10) | default NULL::character varying | extended | | content | character varying(65535) | default NULL::character varying | extended | | ttl | integer | | plain | | prio | integer | | plain | | change_date | integer | | plain | | disabled | boolean | default false | plain | | ordername | character varying(255) | | extended | | auth | boolean | default true | plain | | """ def create(self): if self.exists(): return db.execute("INSERT INTO domains (name, last_check, notified_serial, type, master, account) VALUES (%s, NULL, 0, 'MASTER', %s, '') RETURNING id", (self.domain, MASTER_DNS)) res = db.fetchone() self.zone_id = int(res[0]) db.execute("INSERT INTO records (name, type, ttl, content, prio, domain_id) VALUES (%s, 'SOA', %s, %s, %s, %s)" , (self.domain, DEFAULT_TTL, '%s %s %s01 3600 900 1209600 86400' % (MASTER_DNS, ADMIN_CONTACT, datetime.now().strftime("%Y%m%d")), '0', self.zone_id)) for i in [MASTER_DNS] + SLAVES: db.execute("INSERT INTO records (name, type, ttl, content, prio, domain_id) VALUES (%s, 'NS', %s, %s, 0, %s)" , (self.domain, DEFAULT_TTL, i, self.zone_id)) def inc_serial(self): db.execute("SELECT id, content FROM records WHERE type = 'SOA' and domain_id = %s", (self.zone_id,)) res = db.fetchone() cur = res[1] serial = int(cur.split()[2])+1 alt = int(datetime.now().strftime('%Y%m%d01')) if alt > serial: serial = alt soa = "%s %s %s %s %s %s %s" % tuple(cur.split()[:2] + [serial] + cur.split()[3:]) db.execute("UPDATE records SET content = %s WHERE id = %s", (soa, res[0])) def delete(self): if not self.exists(): return db.execute("DELETE from records where domain_id = %s", (self.zone_id,)) db.execute("DELETE from domains WHERE name = %s", (self.domain,)) def execute(self): if self.to_delete: self.delete() else: self.create() class DNSCommander(cmd.Cmd): prompt = '> ' todoqueue = [] current_domain = None update_serial = False def do_domain(self, line): """Select and add new domain""" line = line.rstrip('.') d = Domain(line) d.validate() if not d.exists(): self.todoqueue.append(d) print("Domain: %s" % line) self.current_domain = d self.prompt = '%s> ' % line def complete_domain(self, line, text, begidx, endidx): completions = [] db.execute("SELECT name from domains WHERE name LIKE %s", ('%s%%' % line.strip(),)) for res in db.fetchall(): if res[0].startswith(line.strip()): completions.append(res[0]) if len(completions) > 20: return [] return completions def generate_reverse(self, ip, name, domain=None): name = name.rstrip('.') + '.' if ':' in ip: try: ipobject = IPv6Address(ip) except AddressValueError as e: raise CommandException("Invalid IPv6 address: %s" % e) reverse = '.'.join(ipobject.exploded[::-1].replace(':', '')) + '.ip6.arpa' else: try: ipobject = IPv4Address(ip) except AddressValueError as e: raise CommandException("Invalid IPv4 address: %s" % e) reverse = '.'.join(ipobject.exploded.split('.')[::-1]) + '.in-addr.arpa' if not domain: for d in self.get_domains(): if reverse.endswith(d[0]): domain = Domain(d[0]) break if not domain: raise CommandException("No such domain for %s" % reverse) for r in domain.records(): if r['key'] == reverse: raise CommandException("Reverse record for key %s already exists with value %s" % (reverse, r['value'])) if not reverse.endswith(domain.domain): raise CommandException("Wrong zone for this record!") reverse = reverse[:len(reverse) - len(domain.domain) - 1] if domain.exists_record(reverse, "PTR", name): raise CommandException("Record already exists!") r = Record(reverse, "PTR", name, domain=domain) self.todoqueue.append(r) self.update_serial = True def delete_reverse(self, ip, name, domain=None): name = name.rstrip('.') + '.' if ':' in ip: try: ipobject = IPv6Address(ip) except AddressValueError as e: raise CommandException("Invalid IPv6 address: %s" % e) reverse = '.'.join(ipobject.exploded[::-1].replace(':', '')) + '.ip6.arpa' else: try: ipobject = IPv4Address(ip) except AddressValueError as e: raise CommandException("Invalid IPv4 address: %s" % e) reverse = '.'.join(ipobject.exploded.split('.')[::-1]) + '.in-addr.arpa' if not domain: for d in self.get_domains(): if reverse.endswith(d[0]): domain = Domain(d[0]) break if not domain: raise CommandException("No such domain for %s" % reverse) for r in domain.records(): if r['key'] == reverse and r['value'].rstrip('.') == name.rstrip('.'): print("Removing reverse record %s PTR %s" % (r['key'], r['value'])) r = Record(reverse[:len(reverse) - len(domain.domain) - 1], "PTR", r['value'], ttl=r['ttl'], domain=domain, action=RecordActions.DELETE) self.todoqueue.append(r) self.update_serial = True return def reset_prompt(self): self.update_serial = False self.current_domain = None self.prompt = '> ' def do_commit(self, line): """Commit changes""" domains = [] for t in self.todoqueue: t.execute() if t.domain not in domains and isinstance(t.domain, Domain): domains.append(t.domain) self.todoqueue = [] if self.update_serial: for d in domains: d.inc_serial() dbconn.commit() #self.reset_prompt() if self.update_serial: for d in domains: notify_domain(d.domain) def do_revert(self, line): """Revert changes""" self.todoqueue = [] dbconn.rollback() #self.reset_prompt() def parse_ttl(self, ttl): try: ttl = int(ttl) if ttl > 0 and ttl < 65535: return ttl except ValueError: pass raise CommandException("Invalid ttl %s" % ttl) def parse_weight(self, weight): try: weight = int(weight) if weight > 0 and weight < 65535: return weight except ValueError: pass raise CommandException("Invalid weight %s" % weight) def parse_priority(self, t): try: t = int(t) if t >= 0 and t <= 65535: return t except ValueError: pass raise CommandException("Invalid priority %s" % t) def parse_port(self, t): try: t = int(t) if t > 0 and t < 65535: return t except ValueError: pass raise CommandException("Invalid port %s" % t) def parse_record(self, line): ttl = None priority = None parts = line.split(None, 6) if len(parts) < 3: raise CommandException("Cannot parse %s" % line) key = parts[0].strip().lower() record_type = parts[1].strip().upper() if record_type in ['TXT', 'A', 'AAAA', 'NS', 'CNAME', 'SPF']: parts = line.split(None, 3) if len(parts) == 4: ttl = self.parse_ttl(parts[2]) value = parts[3] elif len(parts) == 3: value = parts[2] else: raise CommandException("Cannot parse %s" % line) if record_type in ['CAA']: # CAA is a little special parts = line.split(None, 3) if len(parts) == 4: ttl = self.parse_ttl(parts[2]) value = parts[3] elif len(parts) == 3: value = parts[2] else: raise CommandException("Cannot parse %s" % line) if value.split(None, 2) != 3: raise CommandException("Cannot parse %s, CAA record format flag type \"value\"" % line) caa_flag, caa_type, caa_value = value.split(None, 2) try: int(caa_flag) except ValueError: raise CommandException("Cannot parse %s, flag should be integer" % line) if caa_type.strip() not in ['issue', 'issuewild', 'iodef']: raise CommandException("Cannot parse %s, invalid CAA tag, choices issue, issuewild, iodef" % line) if not caa_value.endswith('"') or not caa_value.startswith('"'): raise CommandException("Cannot parse %s, CAA record third argument should be quoted" % line) elif record_type in ['MX', 'SRV', 'TLSA']: parts = line.split(None, 4) if len(parts) == 5: ttl = self.parse_ttl(parts[2]) priority = self.parse_priority(parts[3]) value = parts[4] elif len(parts) == 4: priority = self.parse_priority(parts[2]) value = parts[3] else: raise CommandException("Cannot parse %s" % line) elif record_type in ['PTR']: parts = line.split(None, 3) if len(parts) == 4: ttl = self.parse_ttl(parts[2]) value = parts[3] elif len(parts) == 3: value = parts[2] else: raise CommandException("Cannot parse %s" % line) if not value.endswith('.'): value = "%s." % value else: raise CommandException("Cannot parse %s" % line) if not self.current_domain: raise CommandException("Select domain first!") if record_type == "A": try: ipobject = IPv4Address(value) except AddressValueError as e: raise CommandException("Invalid IPv4 address: %s" % e) if record_type == "AAAA": try: ipobject = IPv6Address(value) except AddressValueError as e: raise CommandException("Invalid IPv6 address: %s" % e) return (key, record_type, value.lower(), ttl, priority) def do_add(self, line): """ Add new dns record to zone: add key type [ttl] [priority] [weight] [port] value Key is for example www type is record type, one of A, AAAA, CNAME, TXT, NS, MX, SRV, PTR, CAA, TLSA ttl is opional time to live value priority is used with MX, CAA, TLSA and SRV records weight and port are SRV specific values """ key, record_type, value, ttl, priority = self.parse_record(line) key = key.rstrip(".") if key.endswith(self.current_domain.domain): key = key[:-len(self.current_domain.domain)-1] if self.current_domain.exists_record(key, record_type, value, priority=priority): raise CommandException("Record already exists!") r = Record(key, record_type, value, ttl=ttl, priority=priority, domain=self.current_domain) self.todoqueue.append(r) self.update_serial = True # Generate reverse if record_type in ['A', 'AAAA']: if self.current_domain.domain not in key: key = '%s.%s' % (key, self.current_domain.domain) self.generate_reverse(value, key) print("Generating reverse record also") def do_addrev(self, line): """ Add new reverse dns record to zone addrev ip name """ if not self.current_domain: raise CommandException("Select domain first") if len(line.split()) != 2: raise CommandException("Invalid arguments") ip, name = line.split(None, 1) self.update_serial = True self.generate_reverse(ip, name, self.current_domain) def do_genrev(self, line): """ Generate reverse records for name genrev name """ if not self.current_domain: raise CommandException("Select domain first") if not line: raise CommandException("Name required!") for record in self.current_domain.records(): if record['key'] != line: continue if record['type'] in ['A', 'AAAA']: try: self.generate_reverse(record['value'], record['key']) self.update_serial = True except CommandException as e: print("Not doing reverse for %s: %s" % (record['value'], e)) def do_delete(self, line): """Delete dns record: delete key type [ttl] [priority] [weight] [port] value """ if len(line.split()) < 3: print("Use deleteall to delete multiple records") return key, record_type, value, ttl, priority = self.parse_record(line) key = key.rstrip(".").lower() if key.endswith(self.current_domain.domain): key = key[:-len(self.current_domain.domain)-1].strip() if key == '': key = '@' if not self.current_domain.exists_record(key, record_type, value, priority=priority): print("key: '%s' type: '%s' value: '%s' priority: '%s'" % (key, record_type, value, priority)) if not self.current_domain.exists_record(key, record_type, "%s %s" % (priority, value), priority=None): raise CommandException("Record does not exists!") value = "%s %s" % (priority, value) priority = None r = Record(key, record_type, value, ttl=ttl, priority=priority, domain=self.current_domain, action=RecordActions.DELETE) self.todoqueue.append(r) self.update_serial = True if record_type in ['A', 'AAAA']: if self.current_domain.domain not in key: key = '%s.%s' % (key, self.current_domain.domain) self.delete_reverse(value, key) def do_deleteall(self, line): """Delete all dns records matching key: deleteall key [type] """ type = None if len(line.split()) == 1: key = line.strip() else: key, type = line.split(None, 1) type = type.upper() key = key.rstrip(".").lower() if key.endswith(self.current_domain.domain): key = key[:-len(self.current_domain.domain) - 1].strip() if key == '' or key == '@': raise CommandException("Removing all from root level is not allowed.") for row in self.current_domain.get_records(key=key, rtype=type): if row["type"].upper() in ["SOA"]: print("Skipping SOA record") continue row_key = row['key'] if row_key.endswith(self.current_domain.domain): row_key = row_key[:-len(self.current_domain.domain) - 1].strip() r = Record(row_key, row["type"], row["value"], ttl=row["ttl"], priority=None if row["priority"] == '-' else row["priority"], domain=self.current_domain, action=RecordActions.DELETE) self.todoqueue.append(r) if row["type"] in ['A', 'AAAA']: if self.current_domain.domain not in row["key"]: rev_key = '%s.%s' % (row["key"], self.current_domain.domain) else: rev_key = row["key"] self.delete_reverse(row["value"], rev_key) self.update_serial = True def complete_delete(self, text, line, beginidx, endidx): records = self.current_domain.records() l = len(line.split()) if l == 1 or (l == 2 and text): if text: full_text = line.split()[-1] else: full_text = text diff = len(full_text) - len(text) if full_text == '@': return [self.current_domain.domain] record_set = [y['key'][diff:] for y in records if y['key'].startswith(full_text)] # Make list unique return list(set(record_set)) elif l == 2 or (l == 3 and text): key = line.split()[1].strip() #print("B: %s" % key) types = [] for y in records: #print("%s %s %s" % (y['key'], y['key'] == key, key)) if y['key'] == key: #print("%s type: %s value: %s" % (y['key'], y['type'], y['value'])) if y['type'] not in types: types.append(y['type']) return [x for x in types if x.startswith(text)] elif l == 3 or (l == 4 and text): key, key_type = line.split()[1:3] if text: full_text = line.split()[-1] else: full_text = text diff = len(full_text) - len(text) return list(set([x['value'][diff:] for x in records if x['key'] == key and x['type'] == key_type and x['value'].startswith(text)])) return [] def do_deletedomain(self, line): if self.current_domain: print("Get out of domain context first") return False if self.todoqueue: print("Commit or revert first") return False d = Domain(line) if not d.exists(): print("Domain %s does not exist" % domain) return False d.to_delete = True self.todoqueue.append(d) def complete_deletedomain(self, *args, **kwargs): return self.complete_domain(*args, **kwargs) def do_EOF(self, line): if self.todoqueue: print("Revert first") return False if self.current_domain: self.current_domain = None print("") self.prompt = '> ' else: print("") return True def onecmd(self, str): try: return cmd.Cmd.onecmd(self, str) except CommandException as e: print('Error: %s' % e) def do_show(self, line): """Show changes to do """ if not self.todoqueue: print("Nothing changed, did you mean list?") return for thing in self.todoqueue: print(thing.show()) def do_list(self, line): """list [filter] List Domains/records """ keys = ["key", "type", "value"] if line: keywords = line.strip().split() else: keywords = [] if self.current_domain: print("\033[1m{0:<40} {1:<6} {2:<5} {3:>4} {4}\033[0m".format("key", "ttl", "type", "priority", "value")) for row in self.current_domain.records(): if keywords: found = False for x in keys: for k in keywords: if k in row[x]: found = True continue if not found: continue print("{key:<40} {ttl:<6} {type:<5} {priority:>4} {value}".format(**row)) else: print("\033[1m{0:<40} {1:<10} {2:>12}\033[0m".format("name", "type", "notified serial")) for row in self.get_domains(): print("{0:<40} {1:<10} {2:>12}".format(*row)) print("") def do_ls(self, line): return self.do_list(line) def do_toggle_debug(self, line): global DEBUG DEBUG = not DEBUG def get_domains(self): db.execute("SELECT name, type, notified_serial FROM domains ORDER BY name") return [[a, b, '%s' % c] for a,b,c in db.fetchall()] if __name__ == '__main__': DNSCommander().cmdloop()
5f57236a1d56f20d78a2358ce23e0cc06691562e
[ "Markdown", "Python" ]
2
Markdown
eranii/pdnscmd
0c15fd57347f777bc0b29ca6854da6e5247e88cb
5cc4fa8e6de1f815dfd82bed1de3311ca881b615
refs/heads/master
<repo_name>eco-systems/eclearance<file_sep>/protected/modules/main/views/clearance/view.php <?php /* @var $this ClearanceController */ /* @var $model Clearance */ $this->breadcrumbs=array( 'Clearances'=>array('index'), $model->id, ); $this->menu=array( array('label'=>'List Clearance', 'url'=>array('index')), array('label'=>'Create Clearance', 'url'=>array('create')), array('label'=>'Update Clearance', 'url'=>array('update', 'id'=>$model->id)), array('label'=>'Delete Clearance', 'url'=>'#', 'linkOptions'=>array('submit'=>array('delete','id'=>$model->id),'confirm'=>'Are you sure you want to delete this item?')), array('label'=>'Manage Clearance', 'url'=>array('admin')), ); ?> <h1>View Clearance #<?php echo $model->id; ?></h1> <?php $this->widget('zii.widgets.CDetailView', array( 'data'=>$model, 'attributes'=>array( 'id', 'station_id', 'applicant_id', 'clearance_no', 'purpose', 'or_number', 'investigator_id', 'officer_id', 'findings', 'residentcertnumber', 'amount', 'datefiled', ), )); ?> <file_sep>/README.md # E-Police MIS <file_sep>/protected/modules/main/models/Clearance.php <?php /** * This is the model class for table "clearance". * * The followings are the available columns in table 'clearance': * @property integer $id * @property integer $station_id * @property integer $applicant_id * @property string $clearance_no * @property string $purpose * @property string $or_number * @property integer $investigator_id * @property integer $officer_id * @property string $findings * @property string $residentcertnumber * @property string $amount * @property integer $datefiled */ class Clearance extends CActiveRecord { /** * @return string the associated database table name */ public function tableName() { return 'clearance'; } /** * @return array validation rules for model attributes. */ public function rules() { // NOTE: you should only define rules for those attributes that // will receive user inputs. return array( array('station_id, applicant_id, clearance_no, purpose, or_number, investigator_id, officer_id, findings, residentcertnumber, amount, datefiled', 'required'), array('station_id, applicant_id, investigator_id, officer_id, datefiled', 'numerical', 'integerOnly'=>true), array('clearance_no, purpose, or_number, findings, residentcertnumber', 'length', 'max'=>200), array('amount', 'length', 'max'=>20), // The following rule is used by search(). // @todo Please remove those attributes that should not be searched. array('id, station_id, applicant_id, clearance_no, purpose, or_number, investigator_id, officer_id, findings, residentcertnumber, amount, datefiled', 'safe', 'on'=>'search'), ); } /** * @return array relational rules. */ public function relations() { // NOTE: you may need to adjust the relation name and the related // class name for the relations automatically generated below. return array( ); } /** * @return array customized attribute labels (name=>label) */ public function attributeLabels() { return array( 'id' => 'ID', 'station_id' => 'Station', 'applicant_id' => 'Applicant', 'clearance_no' => 'Clearance No', 'purpose' => 'Purpose', 'or_number' => 'Or Number', 'investigator_id' => 'Investigator', 'officer_id' => 'Officer', 'findings' => 'Findings', 'residentcertnumber' => 'Residentcertnumber', 'amount' => 'Amount', 'datefiled' => 'Datefiled', ); } /** * Retrieves a list of models based on the current search/filter conditions. * * Typical usecase: * - Initialize the model fields with values from filter form. * - Execute this method to get CActiveDataProvider instance which will filter * models according to data in model fields. * - Pass data provider to CGridView, CListView or any similar widget. * * @return CActiveDataProvider the data provider that can return the models * based on the search/filter conditions. */ public function search() { // @todo Please modify the following code to remove attributes that should not be searched. $criteria=new CDbCriteria; $criteria->compare('id',$this->id); $criteria->compare('station_id',$this->station_id); $criteria->compare('applicant_id',$this->applicant_id); $criteria->compare('clearance_no',$this->clearance_no,true); $criteria->compare('purpose',$this->purpose,true); $criteria->compare('or_number',$this->or_number,true); $criteria->compare('investigator_id',$this->investigator_id); $criteria->compare('officer_id',$this->officer_id); $criteria->compare('findings',$this->findings,true); $criteria->compare('residentcertnumber',$this->residentcertnumber,true); $criteria->compare('amount',$this->amount,true); $criteria->compare('datefiled',$this->datefiled); return new CActiveDataProvider($this, array( 'criteria'=>$criteria, )); } /** * Returns the static model of the specified AR class. * Please note that you should have this exact method in all your CActiveRecord descendants! * @param string $className active record class name. * @return Clearance the static model class */ public static function model($className=__CLASS__) { return parent::model($className); } } <file_sep>/protected/modules/main/views/clearance/_form.php <?php /* @var $this ClearanceController */ /* @var $model Clearance */ /* @var $form CActiveForm */ ?> <div class="form"> <?php $form=$this->beginWidget('CActiveForm', array( 'id'=>'clearance-form', // Please note: When you enable ajax validation, make sure the corresponding // controller action is handling ajax validation correctly. // There is a call to performAjaxValidation() commented in generated controller code. // See class documentation of CActiveForm for details on this. 'enableAjaxValidation'=>false, )); ?> <p class="note">Fields with <span class="required">*</span> are required.</p> <?php echo $form->errorSummary($model); ?> <div class="row"> <?php echo $form->labelEx($model,'station_id'); ?> <?php echo $form->textField($model,'station_id'); ?> <?php echo $form->error($model,'station_id'); ?> </div> <div class="row"> <?php echo $form->labelEx($model,'applicant_id'); ?> <?php echo $form->textField($model,'applicant_id'); ?> <?php echo $form->error($model,'applicant_id'); ?> </div> <div class="row"> <?php echo $form->labelEx($model,'clearance_no'); ?> <?php echo $form->textField($model,'clearance_no',array('size'=>60,'maxlength'=>200)); ?> <?php echo $form->error($model,'clearance_no'); ?> </div> <div class="row"> <?php echo $form->labelEx($model,'purpose'); ?> <?php echo $form->textField($model,'purpose',array('size'=>60,'maxlength'=>200)); ?> <?php echo $form->error($model,'purpose'); ?> </div> <div class="row"> <?php echo $form->labelEx($model,'or_number'); ?> <?php echo $form->textField($model,'or_number',array('size'=>60,'maxlength'=>200)); ?> <?php echo $form->error($model,'or_number'); ?> </div> <div class="row"> <?php echo $form->labelEx($model,'investigator_id'); ?> <?php echo $form->textField($model,'investigator_id'); ?> <?php echo $form->error($model,'investigator_id'); ?> </div> <div class="row"> <?php echo $form->labelEx($model,'officer_id'); ?> <?php echo $form->textField($model,'officer_id'); ?> <?php echo $form->error($model,'officer_id'); ?> </div> <div class="row"> <?php echo $form->labelEx($model,'findings'); ?> <?php echo $form->textField($model,'findings',array('size'=>60,'maxlength'=>200)); ?> <?php echo $form->error($model,'findings'); ?> </div> <div class="row"> <?php echo $form->labelEx($model,'residentcertnumber'); ?> <?php echo $form->textField($model,'residentcertnumber',array('size'=>60,'maxlength'=>200)); ?> <?php echo $form->error($model,'residentcertnumber'); ?> </div> <div class="row"> <?php echo $form->labelEx($model,'amount'); ?> <?php echo $form->textField($model,'amount',array('size'=>20,'maxlength'=>20)); ?> <?php echo $form->error($model,'amount'); ?> </div> <div class="row"> <?php echo $form->labelEx($model,'datefiled'); ?> <?php echo $form->textField($model,'datefiled'); ?> <?php echo $form->error($model,'datefiled'); ?> </div> <div class="row buttons"> <?php echo CHtml::submitButton($model->isNewRecord ? 'Create' : 'Save'); ?> </div> <?php $this->endWidget(); ?> </div><!-- form -->
1f8ff7074addf12b716ed708180e256cfb53730c
[ "Markdown", "PHP" ]
4
PHP
eco-systems/eclearance
35e15b4aed19dedc8af0ded79050afacc28c92a5
65221fb462783fa9e53d6f63dcaf349f7e6a5dd5
refs/heads/master
<file_sep><p align="center"> <img src="logo.png" alt="Go-Web"> </p> A simple MVC web framework for Golang lovers!. # Warning!! This project is still under development. Feel free to play with it but it's not ready for production. # Why another framework? Go-Web adopts a “convention over configuration” approach similarly to frameworks like Laravel ,Symfony and Rails. By following this principle, Go-Web reduces the need for “repetitive” tasks like explicitly binding routes, actions and middleware; while not problematic per se, programmers may want to adopt “ready-to-use” solutions, for instances if they want easily build complex services, aiming at a reduced “productive lag”. Programmers may want to use existing frameworks like Gin-Gonic and Go Buffalo, but Go-Web differs from them because of the aforementioned “convention over configuration” approach. [See full documentation](https://goweb.ikdev.it/) ## Translator wanted! We'd like to translate Go-Web documentation in several languages. If you want to help to reach this goal please contact me at <EMAIL>. Languages: - [x] English - [ ] Italian - [ ] Chinese - [ ] French - [ ] Spanish <file_sep>module github.com/RobyFerro/go-web go 1.16 // Only for development environment //replace github.com/RobyFerro/go-web-framework => custom path require ( github.com/RobyFerro/go-web-framework v0.9.0-beta github.com/auth0/go-jwt-middleware v0.0.0-20200810150920-a32d7af194d1 github.com/brianvoe/gofakeit/v4 v4.3.0 github.com/denisenkom/go-mssqldb v0.10.0 // indirect github.com/dgrijalva/jwt-go v3.2.0+incompatible github.com/elastic/go-elasticsearch/v8 v8.0.0-20200819071622-59b6a186f8dd github.com/go-redis/redis/v7 v7.4.0 github.com/gorilla/sessions v1.2.1 github.com/jinzhu/gorm v1.9.16 github.com/jinzhu/now v1.1.1 // indirect github.com/joho/godotenv v1.3.0 github.com/klauspost/compress v1.10.11 // indirect github.com/labstack/gommon v0.3.0 github.com/lib/pq v1.3.0 // indirect github.com/mattn/go-runewidth v0.0.13 // indirect github.com/mattn/go-sqlite3 v2.0.3+incompatible // indirect github.com/onsi/ginkgo v1.12.0 // indirect github.com/onsi/gomega v1.9.0 // indirect github.com/tidwall/pretty v1.0.1 // indirect go.mongodb.org/mongo-driver v1.5.1 golang.org/x/crypto v0.0.0-20210506145944-38f3c27a63bf golang.org/x/lint v0.0.0-20200302205851-738671d3881b // indirect golang.org/x/time v0.0.0-20200630173020-3af7569d3a1e golang.org/x/tools v0.0.0-20200827010519-17fd2f27a9e3 // indirect gopkg.in/yaml.v2 v2.3.0 // indirect ) <file_sep>package register import ( "github.com/RobyFerro/go-web-framework" "github.com/RobyFerro/go-web-framework/register" "github.com/RobyFerro/go-web/app/console" "github.com/RobyFerro/go-web/app/http/controller" "github.com/RobyFerro/go-web/database/model" "github.com/RobyFerro/go-web/router" "github.com/RobyFerro/go-web/service" ) // BaseEntities returns a struct that contains Go-Web base entities func BaseEntities() foundation.BaseEntities { return foundation.BaseEntities{ // Commands configuration represent all Go-Web application conf // Every command needs to be registered in the following list Commands: console.Commands, // Controllers will handle all Go-Web controller // Here is where you've to register your custom controller // If you create a new controller with Alfred it will be auto-registered Controllers: register.ControllerRegister{ &controller.UserController{}, &controller.AuthController{}, &controller.HomeController{}, }, // Services will handle all app IOC services // Every service needs to be registered in the following list Services: register.ServiceRegister{ service.ConnectDB, service.ConnectElastic, service.ConnectMongo, service.ConnectRedis, }, // SingletonServices represent all IOC services that have to be initialized only once. // Every service needs to be registered in the following list SingletonServices: register.ServiceRegister{}, // CommandServices represent all console services. CommandServices: console.Services, // Models will handle all application models // Here is where you've to register your custom models // If you create a new model with Alfred it will be auto-registered Models: register.ModelRegister{ model.User{}, }, // Router contains all application routes Router: []register.HTTPRouter{ router.AppRouter, router.AuthRouter, }, } } <file_sep>package middleware import ( "github.com/RobyFerro/go-web-framework" "log" "net/http" ) type BasicAuthMiddleware struct { Name string Description string } // Handle used to check if the basic auth session is present. // Use this middleware to protect resources with the basic authentication. func (BasicAuthMiddleware) Handle(next http.Handler) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { store := foundation.RetrieveCookieStore() session, err := store.Get(r, "basic-auth") if err != nil { log.Fatal(err) } if session.Values["user"] == nil { http.Error(w, "Forbidden", http.StatusForbidden) } else { next.ServeHTTP(w, r) } next.ServeHTTP(w, r) }) } // GetName returns the middleware name func (m BasicAuthMiddleware) GetName() string { return m.Name } // GetDescription returns the middleware description func (m BasicAuthMiddleware) GetDescription() string { return m.Description } func NewBasicAuthMiddleware() BasicAuthMiddleware { return BasicAuthMiddleware{ Name: "BasicAuth", Description: "Provides basic authentication", } } <file_sep>import React, {Component} from 'react' class Logo extends Component { render() { return ( <div className="container"> <h1>Welcome to Go-Web framework!</h1> <img className="logo" src="public/img/logo.png" alt="Go-Web Framework"/> </div> ) } } export default Logo<file_sep>import {applyMiddleware, combineReducers, createStore} from 'redux'; import mainReducer from "./reducers/mainReducer"; import thunk from 'redux-thunk'; const store = applyMiddleware(thunk)(createStore)(combineReducers({ main: mainReducer }), { main: {} }); export default store;<file_sep>const mainReducer = (state = {}, action) => { // Here you can put your mainReducer switch statement /* switch (action.type) { state = { ...state, // custom action ] } } */ return state }; export default mainReducer<file_sep># Change Log All notable changes to the "Go-web" will be documented in this file. ## [Unreleased] ## [v0.9.0-beta] - 2021-09-19 ### Changed - Changed AuthController with new kernel.Request payload - Updated new gwf version ## [v0.8.1-beta] - 2021-09-03 ### Removed - Logging middleware. Now logs are handled by the global gfw handler. ### Changed - Updated new gwf version - Ignores .exe files - Middleware architecture ### Removed - Middleware register cause now are registered directly in http routers. ## [v0.8.0-beta] - 2021-09-02 ### Changed - Implement adaptation to new GWF version ## [v0.7.2-beta] - 2021-09-02 ### Changed - Removed pointers in route middlewares ### Added - Support for request validation in routing ## [v0.7.1-beta] - 2021-08-30 ### Changed - Moved command service register in "command" module - Changed .yml routing system in favour of the router module. Now every route/group have to be registered directly in go structure. - Changed .yml configuration. Now system and custom configuration are located into the new config module. ## [v0.7.0-beta] - 2021-08-30 ### Removed - Removed async jobs ### Changed - Console command register in "kernel.go" ## [v0.6.2-beta] - 2021-08-27 ### Changed - Updated gwf version - Now evey middleware consists in an isolated struct. ## [v0.6.1-beta] - 2021-08-25 ### Changed - Improved makefile ## [v0.6.0-beta] - 2021-08-25 ### Changed - Split command line interfaces and http server ## [v0.5.3-beta] - 2021-08-20 ### Changed - Updated GWF version ## [v0.5.2-beta] - 2021-08-19 ### Changed - Implemented CLI service container ## [v0.5.1-beta] - 2021-08-19 ### Changed - Updated GWF version ## [v0.5.0-beta] - 2021-08-19 ### Changed - Implemented IOC container with a 'request lifecycle' - Implemented SingletonContainer - Updated GWF version ## [v0.4.7-beta] - 2021-06-21 ### Changed - GWF version that contains old helpers in tool package. - Documentation style and content ## [v0.4.6-beta] - 2021-06-16 ### Changed - Fix go.mod dependencies. ### Removed - Helper package ## [v0.4.5-beta] - 2021-06-16 ### Changed - Removed install, http_loader, show route, daemon run cli commands ## [v0.4.3-beta] - 2021-06-14 ### Fixed - Installation procedure in documentation ### Removed - Install command from `alfred` ### Added - Updated `go-web-framework` version ## [v0.4.2-beta] - 2020-08-28 ### Added - Make file command to run and compile Go-Web ### Changed - Project documentation - Remove duplicated element form README.md ## [v0.4.1-beta] - 2020-08-28 ### Added - Auto-register generated component ### Changed - Component registration location (register.go) ## [v0.4.0-beta] - 2020-08-27 ### Added - Alfred CLI tool ### Removed - Some commands from project build ## [v0.3.2-beta] - 2020-07-09 ### Changed - Updated GWF version ### Fixed - Default JWT auth duration ## [v0.3.1-beta] - 2020-03-21 ### Added - Project documentation - Fix basic auth middleware - Add *.test.json to .gitignore - Add gob structure for basic auth in goweb.go ## [v0.3.0-beta] - 2020-02-24 ### Added - Custom app configuration - Returns user information by calling /admin/test route ### Changed - Moved HTTP kernel from Go-Web to Go-web framework ## [v0.2.1-beta] - 2020-02-19 ### Added - Insert changelog file ### Changed - Update Go-Web framework version ## [v0.2-beta] - 2020-02-19 ### Added - Updated base Go-Web Framework version ### Changed - Insert placeholder in config.yml.example for app.key node ## [v0.1-beta] - 2020-02-17 ### Added - First Go-Web release <file_sep>package controller import ( "github.com/RobyFerro/go-web-framework/kernel" "github.com/RobyFerro/go-web-framework/tool" ) type HomeController struct { kernel.BaseController } // Main returns the Go-Web welcome page. This is just an example of Go-Web controller. With the "c" parameter you've access to // the method/properties declared in BaseController (controller.go). // Of course you can edit this method with a custom logic. func (c *HomeController) Main() { tool.View("index.html", c.Response, nil) } <file_sep>import React, {Component} from 'react' import Logo from "../components/logo"; import {connect} from "react-redux"; class Main extends Component { render() { return ( <div> <Logo/> </div> ) } } const mapSateToProps = state => { return { main: state.main } }; export default connect(mapSateToProps)(Main)
7aaef9c12472029d88072ad97d63cf15f9caee80
[ "Markdown", "JavaScript", "Go Module", "Go" ]
10
Markdown
workspaceking/go-web
3495a09563746d10c2d31cfca2df8a7394c88951
0b64da681293fc9c825b7226f3ca388bf0195949
refs/heads/master
<file_sep>#include <glut.h> #include<math.h> #include<stdio.h> static double x1 = 0, rotX = 0.0, rotY = 0.0, rot = 0; int wire = 0, panaroma = 0, open = 0, walk = 0; float xpos = 0, ypos = 0, zpos = 0, xrot = 0, yrot = 0, angle = 0.0; static void SpecialKey(int key, int x, int y) { switch (key) { case GLUT_KEY_UP: rotX -= 0.1; glutPostRedisplay(); break; case GLUT_KEY_DOWN: rotX += 0.1; glutPostRedisplay(); break; case GLUT_KEY_LEFT: rotY -= 0.1; glutPostRedisplay(); break; case GLUT_KEY_RIGHT: rotY += 0.1; glutPostRedisplay(); break; } } void flag() { glPushMatrix(); glTranslated(3, 14, -4.3); glScaled(12, 7, 0.5); if (wire) glutWireCube(0.1); else glutSolidCube(0.1); glPopMatrix(); } void box() { glPushMatrix(); glScaled(2, 0.5, 2); if (wire) glutWireCube(1); else glutSolidCube(1); glPopMatrix(); glPushMatrix(); glTranslated(0.75, 0.5, 0.75); if (wire) glutWireCube(0.5); else glutSolidCube(0.5); glPopMatrix(); glPushMatrix(); glTranslated(0.75, 0.5, 0.75); if (wire) glutWireCube(0.5); else glutSolidCube(0.5); glPopMatrix(); glPushMatrix(); glTranslated(-0.75, 0.5, 0.75); if (wire) glutWireCube(0.5); else glutSolidCube(0.5); glPopMatrix(); glPushMatrix(); glTranslated(0.75, 0.5, -0.75); if (wire) glutWireCube(0.5); else glutSolidCube(0.5); glPopMatrix(); glPushMatrix(); glTranslated(-0.75, 0.5, -0.75); if (wire) glutWireCube(0.5); else glutSolidCube(0.5); glPopMatrix(); } void renderCylinder(float x1, float y1, float z1, float x2, float y2, float z2, float radius, int subdivisions, GLUquadricObj* quadric) { float vx = x2 - x1; float vy = y2 - y1; float vz = z2 - z1; //handle the degenerate case of z1 == z2 with an approximation if (vz == 0) vz = .0001; float v = sqrt(vx * vx + vy * vy + vz * vz); float ax = 57.2957795 * acos(vz / v); if (vz < 0.0) ax = -ax; float rx = -vy * vz; float ry = vx * vz; glPushMatrix(); //draw the cylinder body glTranslatef(x1, y1, z1); glRotatef(ax, rx, ry, 0.0); gluQuadricOrientation(quadric, GLU_OUTSIDE); gluCylinder(quadric, radius, radius, v, subdivisions, 1); //draw the first cap gluQuadricOrientation(quadric, GLU_INSIDE); gluDisk(quadric, 0.0, radius, subdivisions, 1); glTranslatef(0, 0, v); //draw the second cap gluQuadricOrientation(quadric, GLU_OUTSIDE); gluDisk(quadric, 0.0, radius, subdivisions, 1); glPopMatrix(); } void renderCylinder_convenient(float x1, float y1, float z1, float x2, float y2, float z2, float radius, int subdivisions) { //the same quadric can be re-used for drawing many cylinders GLUquadricObj* quadric = gluNewQuadric(); gluQuadricNormals(quadric, GLU_SMOOTH); renderCylinder(x1, y1, z1, x2, y2, z2, radius, subdivisions, quadric); gluDeleteQuadric(quadric); } void fort(double rang) { glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); glLoadIdentity(); if (walk) { glRotatef(xrot, 1.0, 0.0, 0.0); //rotate our camera on glRotatef(yrot, 0.0, 1.0, 0.0); //rotate our camera on the glTranslated(-xpos, -ypos, -zpos); } else if (panaroma) gluLookAt(0.5, 15, 1, 0, 9, -7, 0, 1, 0); if (!walk) glTranslatef(0.0f, -5.0f, -48.0f); else { glTranslatef(0, 1, -75); glScaled(2, 2, 2.5); } glRotatef(rang, 0.0f, 1.0f, 0.0f); glPushMatrix(); glTranslated(0, 0, -10); glScaled(1, 1, 1.3); glColor3f(250 / 255.0, 220 / 255.0, 50 / 255.0); //Draw fleft cylinder glPushMatrix(); glTranslatef(-22.5, -3.0, 23); renderCylinder_convenient(0, 0, 0, 0, 5, 0, 1.4, 20); glPopMatrix(); //Draw fright cylinder glPushMatrix(); glTranslatef(22.5, -3.0, 23); renderCylinder_convenient(0, 0, 0, 0, 5, 0, 1.4, 20); glPopMatrix(); //Draw bleft cylinder glPushMatrix(); glTranslatef(-22.5, -3.0, -8.0); renderCylinder_convenient(0, 0, 0, 0, 5, 0, 1.4, 20); glPopMatrix(); //Draw bright cylinder glPushMatrix(); glTranslatef(22.5, -3.0, -8.0); renderCylinder_convenient(0, 0, 0, 0, 5, 0, 1.4, 20); glPopMatrix(); // Draw the left Wall glPushMatrix(); glScaled(0.3, 1.5, 15); glTranslatef(0.0, 0.0, -0.5); glTranslatef(-75, -1, 1.0); if (wire) glutWireCube(2); else glutSolidCube(2); glPopMatrix(); // Draw right wall glPushMatrix(); glScaled(0.3, 1.5, 15); glTranslatef(0.0, 0.0, -0.5); glTranslatef(75, -1, 1.0); if (wire) glutWireCube(2); else glutSolidCube(2); glPopMatrix(); // Draw rear wall glPushMatrix(); glRotatef(90, 0, 1, 0); glScaled(0.3, 1.5, 23); glTranslatef(0.0, 0.0, -0.5); glTranslatef(26.5, -1.0, 0.5); if (wire) glutWireCube(2); else glutSolidCube(2); glPopMatrix(); //Draw bottom glColor3f(0 / 255.0, 250 / 255.0, 0 / 255.0); glPushMatrix(); glTranslated(0, -5, 8); glScaled(70, 1, 55); if (wire) glutWireCube(1); else glutSolidCube(1); glPopMatrix(); //Draw bottom glColor3f(200 / 255.0, 180 / 255.0, 50 / 255.0); glPushMatrix(); glTranslated(0, -3.5, 10); glScaled(50, 0.5, 39); if (wire) glutWireCube(1); else glutSolidCube(1); glPopMatrix(); glColor3f(250 / 255.0, 220 / 255.0, 50 / 255.0); //Gate wall 1 glPushMatrix(); glScaled(9, 1.5, 0.5); glTranslatef(-1.5, -1, 47.0); if (wire) glutWireCube(2); else glutSolidCube(2); glPopMatrix(); //Gate wall 2 glPushMatrix(); glScaled(9, 1.5, 0.5); glTranslatef(1.5, -1, 47.0); if (wire) glutWireCube(2); else glutSolidCube(2); glPopMatrix(); //Entrance l glPushMatrix(); glScaled(1.2, 2.6, 0.9); glTranslatef(-4.6, -0.2, 26); if (wire) glutWireCube(2); else glutSolidCube(2); glPopMatrix(); //Entrance r glPushMatrix(); glScaled(1.2, 2.6, 0.9); glTranslatef(4.6, -0.2, 26); if (wire) glutWireCube(2); else glutSolidCube(2); glPopMatrix(); //Entrance t glPushMatrix(); glScaled(4.4, 1, 0.9); glTranslatef(0, 2, 26); if (wire) glutWireCube(2); else glutSolidCube(2); glPopMatrix(); //Entrance t1 glPushMatrix(); glScaled(4.4, 1, 0.9); glTranslatef(0, 3, 26); if (wire) glutWireCube(1.5); else glutSolidCube(1.5); glPopMatrix(); //Entrance t2 glPushMatrix(); glScaled(4.4, 1, 0.9); glTranslatef(0, 4, 26); if (wire) glutWireCube(1.0); else glutSolidCube(1.0); glPopMatrix(); glColor3d(230, 232, 250); //Audi 1 glPushMatrix(); glTranslated(0, 4.78, 23.5); if (wire) glutWireTorus(0.08, 0.3, 10, 20); else glutSolidTorus(0.08, 0.3, 10, 20); glPopMatrix(); //Audi 2 glPushMatrix(); glTranslated(0.5, 4.78, 23.5); if (wire) glutWireTorus(0.08, 0.3, 10, 20); else glutSolidTorus(0.08, 0.3, 10, 20); glPopMatrix(); //Audi 3 glPushMatrix(); glTranslated(-0.5, 4.78, 23.5); if (wire) glutWireTorus(0.08, 0.3, 10, 20); else glutSolidTorus(0.08, 0.3, 10, 20); glPopMatrix(); glColor3f(139 / 255.0, 69 / 255.0, 19 / 255.0); //Gate1 glPushMatrix(); if (open) glRotatef(-10, 0, 1, 0); glScaled(4.2, 5, 0.5); glTranslatef(-0.5, -0.2, 46); if (wire) glutWireCube(1.0); else glutSolidCube(1.0); glPopMatrix(); //Gate2 glPushMatrix(); if (open) glRotatef(10, 0, 1, 0); glScaled(4.2, 5, 0.5); glTranslatef(0.5, -0.2, 46); if (wire) glutWireCube(1.0); else glutSolidCube(1.0); glPopMatrix(); glPopMatrix(); glTranslated(0.5, -1.5, -6); glPopMatrix(); //Draw the main cube //Draw front wall glColor3f(200 / 255.0, 150 / 255.0, 150 / 255.0); glPushMatrix(); glTranslated(-7, -1, 17); glScaled(18, 8, 0.8); if (wire) glutWireCube(1.0); else glutSolidCube(1.0); glPopMatrix(); //Draw sidewall glPushMatrix(); glRotated(-90, 0, 1, 0); glTranslated(7, -1, 16); glScaled(21, 8, 0.8); if (wire) glutWireCube(1.0); else glutSolidCube(1.0); glPopMatrix(); //Draw back wall glPushMatrix(); glTranslated(-9.75, -1, -3.6); glScaled(13.25, 8, 0.8); if (wire) glutWireCube(1.0); else glutSolidCube(1.0); glPopMatrix(); glColor3f(150 / 255.0, 100 / 255.0, 50 / 255.0); //Draw big cylinder glPushMatrix(); glTranslated(-10.3, -2.5, -2.2); renderCylinder_convenient(0, 0, 0, 0, 8, 0, 4, 20); glPopMatrix(); glColor3f(255 / 255.0, 0 / 255.0, 0 / 255.0); //Draw big cone glPushMatrix(); glRotatef(-90, 1, 0, 0); glTranslated(-10.3, 2, 5); if (wire) glutWireCone(7, 6, 15, 15); else glutSolidCone(7, 6, 15, 15); glPopMatrix(); //Draw cube glColor3f(200 / 255.0, 150 / 255.0, 150 / 255.0); glPushMatrix(); glTranslated(7.6, -1, 4); glScaled(3, 2.5, 7); if (wire) glutWireCube(4.0); else glutSolidCube(4.0); glPopMatrix(); glColor3f(238 / 255.0, 44 / 255.0, 44 / 255.0); //Draw sphere glPushMatrix(); glTranslated(8, 4, 7); if (wire) glutWireSphere(5, 25, 25); else glutSolidSphere(5, 25, 25); glPopMatrix(); glColor3f(200 / 255.0, 150 / 255.0, 150 / 255.0); glPushMatrix(); glTranslatef(0.0, 0.0, -0.5); glScaled(1.6, 3, 2); if (wire) glutWireCube(4); else glutSolidCube(4); glPopMatrix(); glColor3f(150 / 255.0, 100 / 255.0, 75 / 255.0); //Draw fr cylinder glPushMatrix(); glTranslated(.5, 6, 1.0); renderCylinder_convenient(0, 0, 0, 0, 4, 0, 0.7, 20); glPopMatrix(); //Draw fl cylinder glPushMatrix(); glTranslated(-9, -2.4, 9.0); renderCylinder_convenient(0, 0, 0, 0, 12, 0, 1.3, 20); glPopMatrix(); //Draw br cylinder glPushMatrix(); glTranslated(2.9, -2.4, -5.0); renderCylinder_convenient(0, 0, 0, 0, 20, 0, 2, 20); glPopMatrix(); //Draw bm cylinder glPushMatrix(); glTranslated(-1.2, -2.45, -4.1); renderCylinder_convenient(0, 0, 0, 0, 16, 0, 1.5, 50); glPopMatrix(); glPushMatrix(); glTranslated(7, -2.45, -4.1); renderCylinder_convenient(0, 0, 0, 0, 13, 0, 1.5, 50); glPopMatrix(); glColor3f(1, 0, 0); //Draw cone1 glPushMatrix(); glRotatef(-90, 1, 0, 0); glTranslated(-1.2, 4.1, 13); if (wire) glutWireCone(2.2, 3.5, 15, 15); else glutSolidCone(2.2, 3.5, 15, 15); glPopMatrix(); //Draw cone2 glPushMatrix(); glRotatef(-90, 1, 0, 0); glTranslated(2.8, 4.8, 17); if (wire) glutWireCone(3, 5, 15, 15); else glutSolidCone(3, 5, 15, 15); glPopMatrix(); //Draw cone3 glPushMatrix(); glRotatef(-90, 1, 0, 0); glTranslated(7, 4.1, 10); if (wire) glutWireCone(2.2, 3.5, 15, 15); else glutSolidCone(2.2, 3.5, 15, 15); glPopMatrix(); glScaled(1.8, 1.6, 1.8); glTranslated(-5, 6, 5); glColor3f(150 / 255.0, 100 / 255.0, 100 / 255.0); //Draw box box(); glColor3d(255, 215, 0); glPushMatrix(); glTranslated(5.3, 1, -4.35); glRotated(rot, 1, 1, 1); if (wire) glutWireTorus(0.15, 0.4, 10, 20); else glutSolidTorus(0.15, 0.4, 10, 20); glPopMatrix(); glPushMatrix(); glColor3d(230, 232, 250); glTranslated(5.3, 1.2, -4.35); glRotated(rot, 0, 0, 0); if (wire) glutWireTorus(0.05, 0.5, 10, 20); else glutSolidTorus(0.05, 0.5, 5, 20); glPopMatrix(); glColor3f(0.439216, 0.858824, 0.576471); glPushMatrix(); // fLAG post glTranslated(6.5, 7.5, -7.7); renderCylinder_convenient(0, 0, 0, 0, 3, 0, 0.03, 20); glPopMatrix(); glTranslated(3, -4, -3.35); glColor3f(200 / 255.0, 150 / 255.0, 30 / 255.0); glPushMatrix(); glTranslated(-11, 0.4, -9.6); box(); glPopMatrix(); glPushMatrix(); glTranslated(14.2, 0.4, 12.75); box(); glPopMatrix(); glPushMatrix(); glTranslated(-11, 0.4, 12.75); box(); glPopMatrix(); glPushMatrix(); glTranslated(14.2, 0.4, -9.6); box(); glPopMatrix(); glColor3f(1, 157 / 255, 50); flag(); glTranslated(-3.2, -10, 17.5); glColor3f(1, 157 / 255, 50); flag(); glPushMatrix(); // fLAG post glColor3f(0, 0, 0); glTranslated(3.5, 11, -4.32); renderCylinder_convenient(0, 0, 0, 0, 3.5, 0, 0.03, 20); glPopMatrix(); rot += 1; glFlush(); glutSwapBuffers(); } void rotater() { x1 += 0.05; fort(x1); } void init() { glClearColor(0.690196078, 0.87843137, 0.90196078, 1.0); glViewport(0, 0, 1050, 680); glMatrixMode(GL_PROJECTION); glLoadIdentity(); gluPerspective(60.0f, (GLfloat)1050 / (GLfloat)680, 0.2f, 200.0f); glMatrixMode(GL_MODELVIEW); glLoadIdentity(); glClearDepth(2.0f); glEnable(GL_DEPTH_TEST); glDepthFunc(GL_LEQUAL); } void Display() { GLfloat mat_ambient[] = { 0.7f,0.7f,0.7f,1.0f }; GLfloat mat_diffuse[] = { 0.5f,0.5f,.5f,1.0f }; GLfloat mat_specular[] = { 1.0f,1.0f,1.0f,1.0f }; GLfloat mat_shininess[] = { 100.0f }; glMaterialfv(GL_FRONT, GL_AMBIENT, mat_ambient); glMaterialfv(GL_FRONT, GL_DIFFUSE, mat_diffuse); glMaterialfv(GL_FRONT, GL_SPECULAR, mat_specular); glMaterialfv(GL_FRONT, GL_SHININESS, mat_shininess); GLfloat lightIntensity[] = { 0.3f,0.3f,0.3f,1.0f }; GLfloat light_position[] = { 2.0f,5.0f,6.0f,0.0f }; glLightfv(GL_LIGHT0, GL_POSITION, light_position); glLightfv(GL_LIGHT0, GL_DIFFUSE, lightIntensity); glFlush(); glutSwapBuffers(); fort(x1); } void keyboard(unsigned char key, int x, int y) { if (key == '+')//going up { xrot += 1; if (xrot > 360) xrot -= 360; } if (key == '-')//going down { xrot -= 1; if (xrot < -360) xrot += 360; } if (key == '8')//going front { float xrotrad, yrotrad; yrotrad = (yrot / 180 * 3.141592654f); xrotrad = (xrot / 180 * 3.141592654f); xpos += float(sin(yrotrad)); zpos -= float(cos(yrotrad)); ypos -= float(sin(xrotrad)); } if (key == '2')//going back { float xrotrad, yrotrad; yrotrad = (yrot / 180 * 3.141592654f); xrotrad = (xrot / 180 * 3.141592654f); xpos -= float(sin(yrotrad)); zpos += float(cos(yrotrad)); ypos += float(sin(xrotrad)); } if (key == '6')//going right { yrot += 1; if (yrot > 360) yrot -= 360; } if (key == '4')//going left { yrot -= 1; if (yrot < -360)yrot += 360; } if (key == 27) exit(0); if (key == '5')open = !open; Display(); } void menu(int id) { switch (id) { case 1:glutIdleFunc(rotater); break; case 2:panaroma = 0; break; case 3:panaroma = 1; break; case 4:wire = 1; break; case 5:wire = 0; break; case 6: walk = !walk; break; case 7: exit(0); break; } glFlush(); glutSwapBuffers(); glutPostRedisplay(); } int main(int argc, char* argv[]) { glutInit(&argc, argv); printf("\n\n\t\t\t\tGLOBAL ACADEMY OF TECHNOLOGY\n\n\t\t\tDEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING\n"); printf("\n\n\t\t\t\t CG MINI PROJECT ON \" CASTLE\"\n\n"); printf("\n\n\n\n\n\n\n\n\n\t\t\t\t NAME: <NAME> \n "); printf("\t\t\t USN: 1GA17CS181 \n"); printf("\n\t\t\t\t UNDER THE GUIDANCE OF:\n\t\t\t Mrs. <NAME>, Assistant Professor \n"); glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGB); glutInitWindowSize(950, 700); glutInitWindowPosition(50, 0); glutCreateWindow("Castle"); glutDisplayFunc(Display); glutKeyboardFunc(keyboard); glutSpecialFunc(SpecialKey); glEnable(GL_LIGHTING); glEnable(GL_LIGHT0); glShadeModel(GL_SMOOTH); glEnable(GL_DEPTH_TEST); glEnable(GL_NORMALIZE); glEnable(GL_COLOR_MATERIAL); glutCreateMenu(menu); glutAddMenuEntry("Rotate", 1); glutAddMenuEntry("Normal view", 2); glutAddMenuEntry("Bird Eye view", 3); glutAddMenuEntry("Wired structure", 4); glutAddMenuEntry("Solid Structure", 5); glutAddMenuEntry("Walk Mode", 6); glutAddMenuEntry("Exit", 7); glutAttachMenu(GLUT_RIGHT_BUTTON); init(); glutMainLoop(); return 0; } <file_sep># 3D-Castle-CG-project This is 3D structure of the castle built using opengl libraries It also consist of mouse and keyboard driven event that performs following a)rotate the castle b)bird eye view c)normal view d)gives wired structure e)goes to walk mode f)give solid structure g)open/close the gate h)exit
ba46a8bbe670927ae27c2077187e4744c0a6656f
[ "Markdown", "C++" ]
2
C++
Yuvaraj-P/3D-Castle-opengl-project
066154eca92231688223abfcf9bf4653e018b68f
9b00b0cc9240137c9933408a487acde584a65f6f
refs/heads/main
<file_sep>const express = require('express') const mongoose = require('mongoose') port = process.env.PORT || 9000; const url = 'mongodb+srv://testUser:<EMAIL>/sample_airbnb?retryWrites=true&w=majority' const app = express() mongoose.connect(url, {useNewUrlParser:true}) const con = mongoose.connection con.on('open', () => { console.log('connected...') }) app.use(express.json()) const contactRouter = require('./routes/contacts') app.use('/contacts',contactRouter) app.listen(port, () => { console.log('Server started') })<file_sep># contactApp-node-mongo-atlas contact app with node, express, mongo cloud git init git remote add origin https://github.com/CrashTechIndia/contactApp-node-mongo-atlas.git
314416ff959073881221a6a3bc8cb956c8ae4b84
[ "JavaScript", "Markdown" ]
2
JavaScript
CrashTechIndia/contactApp-node-mongo-atlas
a56a7c0e7e236a44f68badae215cf01273fe7a4f
b19a2fc10b947166b78d9057619f17190717c437
refs/heads/master
<file_sep>package org.egovernments.egoverp.models; public class ProfileUpdateFailedEvent { } <file_sep> package org.egovernments.egoverp.models; import com.google.gson.annotations.Expose; import com.google.gson.annotations.SerializedName; import java.util.ArrayList; import java.util.List; /** * POJO class, initial response to getComplaints API calls **/ public class GrievanceAPIResponse { @SerializedName("status") @Expose private GrievanceAPIStatus status; @SerializedName("result") @Expose private List<Grievance> result = new ArrayList<>(); public GrievanceAPIStatus getStatus() { return status; } public List<Grievance> getResult() { return result; } } <file_sep>package org.egovernments.egoverp.models; /** * POJO class, used by register user API calls **/ public class RegisterRequest { private String emailId; private String mobileNumber; private String name; private String password; private String deviceId; private String deviceType; private String OSVersion; public RegisterRequest(String emailId, String mobileNumber, String name, String password, String deviceId, String deviceType, String OSVersion) { this.emailId = emailId; this.mobileNumber = mobileNumber; this.name = name; this.password = <PASSWORD>; this.deviceId = deviceId; this.deviceType = deviceType; this.OSVersion = OSVersion; } public String getEmailId() { return emailId; } public String getMobileNumber() { return mobileNumber; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getPassword() { return <PASSWORD>; } public String getDeviceId() { return deviceId; } public String getDeviceType() { return deviceType; } public String getOSVersion() { return OSVersion; } } <file_sep>package org.egovernments.egoverp.activities; import android.content.Intent; import android.os.Build; import android.os.Bundle; import android.support.design.widget.FloatingActionButton; import android.support.v4.widget.SwipeRefreshLayout; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.view.View; import android.widget.ProgressBar; import org.egovernments.egoverp.R; import org.egovernments.egoverp.adapters.GrievanceAdapter; import org.egovernments.egoverp.events.GrievanceUpdateFailedEvent; import org.egovernments.egoverp.events.GrievancesUpdatedEvent; import org.egovernments.egoverp.helper.CardViewOnClickListener; import org.egovernments.egoverp.models.Grievance; import org.egovernments.egoverp.network.UpdateService; import java.util.ArrayList; import java.util.List; import de.greenrobot.event.EventBus; /** * The activity containing grievance list **/ //TODO pagination not working on first list load public class GrievanceActivity extends BaseActivity { public static List<Grievance> grievanceList; private CardViewOnClickListener.OnItemClickCallback onItemClickCallback; private RecyclerView recyclerView; private ProgressBar progressBar; public static GrievanceAdapter grievanceAdapter; private android.support.v4.widget.SwipeRefreshLayout swipeRefreshLayout; //The currently visible page no. private int pageNo = 1; //The number of pages which have been loaded public static int pageLoaded = 0; private int previousTotal = 0; private int visibleThreshold = 5; private final int ACTION_UPDATE_REQUIRED = 111; private boolean loading = true; public static boolean isUpdateFailed = false; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_grievance); progressBar = (ProgressBar) findViewById(R.id.grievance_recylerview_placeholder); recyclerView = (RecyclerView) findViewById(R.id.recylerview); recyclerView.setHasFixedSize(true); recyclerView.setClickable(true); final LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this); linearLayoutManager.setOrientation(LinearLayoutManager.VERTICAL); recyclerView.setLayoutManager(linearLayoutManager); //Enables infinite scrolling (pagination) recyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() { int firstVisibleItem, visibleItemCount, totalItemCount; @Override public void onScrolled(RecyclerView recyclerView, int dx, int dy) { super.onScrolled(recyclerView, dx, dy); visibleItemCount = recyclerView.getChildCount(); totalItemCount = linearLayoutManager.getItemCount(); firstVisibleItem = linearLayoutManager.findFirstVisibleItemPosition(); if (loading) { if (totalItemCount > previousTotal) { loading = false; previousTotal = totalItemCount; } } // End has been reached if (!loading && (totalItemCount - visibleItemCount) <= (firstVisibleItem + visibleThreshold)) { // Fetch further complaints if (pageNo >= pageLoaded) { pageNo++; Intent intent = new Intent(GrievanceActivity.this, UpdateService.class); intent.putExtra(UpdateService.KEY_METHOD, UpdateService.UPDATE_COMPLAINTS); intent.putExtra(UpdateService.COMPLAINTS_PAGE, String.valueOf(pageNo)); startService(intent); loading = true; } } } }); //Enables pull to refresh swipeRefreshLayout = (SwipeRefreshLayout) findViewById(R.id.recylerview_refreshlayout); swipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() { @Override public void onRefresh() { progressBar.setVisibility(View.GONE); Intent intent = new Intent(GrievanceActivity.this, UpdateService.class).putExtra(UpdateService.KEY_METHOD, UpdateService.UPDATE_COMPLAINTS); intent.putExtra(UpdateService.COMPLAINTS_PAGE, "1"); startService(intent); } }); //CardView on click listener onItemClickCallback = new CardViewOnClickListener.OnItemClickCallback() { @Override public void onItemClicked(View view, int position) { Intent intent = new Intent(GrievanceActivity.this, GrievanceDetailsActivity.class); intent.putExtra(GrievanceDetailsActivity.GRIEVANCE_ITEM, grievanceList.get(position)); startActivityForResult(intent, ACTION_UPDATE_REQUIRED); } }; //Checks if the update service has fetched complaints before setting up list if (grievanceList != null) { pageLoaded++; progressBar.setVisibility(View.GONE); grievanceAdapter = new GrievanceAdapter(GrievanceActivity.this, grievanceList, onItemClickCallback); recyclerView.setAdapter(grievanceAdapter); } else { grievanceList = new ArrayList<>(); grievanceAdapter = new GrievanceAdapter(GrievanceActivity.this, grievanceList, onItemClickCallback); recyclerView.setAdapter(grievanceAdapter); grievanceList = null; } FloatingActionButton newComplaintButton = (FloatingActionButton) findViewById(R.id.list_fab); com.melnykov.fab.FloatingActionButton newComplaintButtonCompat = (com.melnykov.fab.FloatingActionButton) findViewById(R.id.list_fabcompat); View.OnClickListener onClickListener = new View.OnClickListener() { @Override public void onClick(View v) { //Activity refreshes if NewGrievanceActivity finishes with success startActivityForResult(new Intent(GrievanceActivity.this, NewGrievanceActivity.class), ACTION_UPDATE_REQUIRED); } }; if (Build.VERSION.SDK_INT >= 21) { newComplaintButton.setOnClickListener(onClickListener); } else { newComplaintButton.setVisibility(View.GONE); newComplaintButtonCompat.setVisibility(View.VISIBLE); newComplaintButtonCompat.setOnClickListener(onClickListener); } if (isUpdateFailed) { progressBar.setVisibility(View.GONE); isUpdateFailed = false; } } //Handles result when NewGrievanceActivity finishes @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); if (requestCode == ACTION_UPDATE_REQUIRED && resultCode == RESULT_OK) { progressBar.setVisibility(View.GONE); pageNo = 1; Intent intent = new Intent(GrievanceActivity.this, UpdateService.class).putExtra(UpdateService.KEY_METHOD, UpdateService.UPDATE_COMPLAINTS); intent.putExtra(UpdateService.COMPLAINTS_PAGE, "1"); startService(intent); grievanceAdapter = null; } } //Subscribes the activity to events @Override protected void onStart() { EventBus.getDefault().register(this); super.onStart(); } //Unsubscribes the activity to events @Override public void onStop() { EventBus.getDefault().unregister(this); super.onStop(); } //Updates the complaint list when subscribed and a GrievancesUpdatedEvent is posted by the UpdateService @SuppressWarnings("unused") public void onEvent(GrievancesUpdatedEvent grievancesUpdatedEvent) { //If a refresh action has been taken, reinitialize the list if (grievanceAdapter == null) { pageLoaded = 1; pageNo = 1; previousTotal = 0; progressBar.setVisibility(View.GONE); grievanceAdapter = new GrievanceAdapter(GrievanceActivity.this, grievanceList, onItemClickCallback); recyclerView.setAdapter(grievanceAdapter); swipeRefreshLayout.setRefreshing(false); } else { pageLoaded++; grievanceAdapter.notifyDataSetChanged(); } progressBar.setVisibility(View.GONE); } @SuppressWarnings("unused") public void onEvent(GrievanceUpdateFailedEvent grievanceUpdateFailedEvent) { swipeRefreshLayout.setRefreshing(false); progressBar.setVisibility(View.GONE); grievanceList = new ArrayList<>(); grievanceAdapter = new GrievanceAdapter(GrievanceActivity.this, grievanceList, onItemClickCallback); recyclerView.setAdapter(grievanceAdapter); grievanceList = null; } } <file_sep> package org.egovernments.egoverp.models; import com.google.gson.annotations.Expose; import com.google.gson.annotations.SerializedName; import java.util.ArrayList; import java.util.List; public class PropertyTaxCallback { @SerializedName("assessmentNo") @Expose private String assessmentNo; @SerializedName("propertyAddress") @Expose private String propertyAddress; @SerializedName("localityName") @Expose private String localityName; @SerializedName("ownerDetails") @Expose private List<TaxOwnerDetail> taxOwnerDetails = new ArrayList<>(); @SerializedName("taxDetails") @Expose private List<TaxDetail> taxDetails = new ArrayList<>(); @SerializedName("errorDetails") @Expose private TaxErrorDetails taxErrorDetails; /** * @return The assessmentNo */ public String getAssessmentNo() { return assessmentNo; } /** * @return The propertyAddress */ public String getPropertyAddress() { return propertyAddress; } /** * @return The localityName */ public String getLocalityName() { return localityName; } /** * @return The ownerDetails */ public List<TaxOwnerDetail> getTaxOwnerDetails() { return taxOwnerDetails; } /** * @return The taxDetails */ public List<TaxDetail> getTaxDetails() { return taxDetails; } /** * @return The taxErrorDetails */ public TaxErrorDetails getTaxErrorDetails() { return taxErrorDetails; } } <file_sep>package org.egovernments.egoverp.activities; import android.app.ProgressDialog; import android.content.Intent; import android.graphics.Color; import android.graphics.drawable.ColorDrawable; import android.os.AsyncTask; import android.os.Build; import android.os.Bundle; import android.os.Handler; import android.provider.Settings; import android.support.design.widget.TextInputLayout; import android.support.v7.app.AppCompatActivity; import android.text.TextUtils; import android.view.Gravity; import android.view.KeyEvent; import android.view.View; import android.view.inputmethod.EditorInfo; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.Button; import android.widget.EditText; import android.widget.Spinner; import android.widget.TextView; import android.widget.Toast; import org.egovernments.egoverp.R; import org.egovernments.egoverp.helper.ConfigManager; import org.egovernments.egoverp.helper.CustomAutoCompleteTextView; import org.egovernments.egoverp.helper.NothingSelectedSpinnerAdapter; import org.egovernments.egoverp.models.City; import org.egovernments.egoverp.models.RegisterRequest; import org.egovernments.egoverp.network.ApiController; import org.egovernments.egoverp.network.SessionManager; import com.google.gson.JsonObject; import java.io.IOException; import java.io.InputStream; import java.util.ArrayList; import java.util.List; import java.util.regex.Matcher; import java.util.regex.Pattern; import retrofit.Callback; import retrofit.RetrofitError; import retrofit.client.Response; public class RegisterActivity extends AppCompatActivity { private String name; private String phoneno; private String email; private String password; private String confirmpassword; private String deviceID; private String deviceOS; private String deviceType; private TextView municipalityInfo; private TextInputLayout nameInputLayout; private String url; private String cityName; private ProgressDialog progressDialog; private ConfigManager configManager; private Handler handler; private Spinner spinner; private SessionManager sessionManager; private CustomAutoCompleteTextView autoCompleteTextView; private int check = 0; private int code; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_register); android.support.v7.widget.Toolbar toolbar = (android.support.v7.widget.Toolbar) findViewById(R.id.toolbar); setSupportActionBar(toolbar); android.support.v7.app.ActionBar actionBar = getSupportActionBar(); if (actionBar != null) { actionBar.setBackgroundDrawable(new ColorDrawable(Color.parseColor("#00000000"))); actionBar.setDisplayHomeAsUpEnabled(true); } spinner = (Spinner) findViewById(R.id.signup_city); progressDialog = new ProgressDialog(this, ProgressDialog.STYLE_SPINNER); progressDialog.setIndeterminate(true); progressDialog.setMessage("Processing request"); progressDialog.setCancelable(false); sessionManager = new SessionManager(this); municipalityInfo = (TextView) findViewById(R.id.municipality_change_info); nameInputLayout = (TextInputLayout) findViewById(R.id.signup_name_inputlayout); final EditText name_edittext = (EditText) findViewById(R.id.signup_name); final EditText email_edittext = (EditText) findViewById(R.id.signup_email); final EditText phoneno_edittext = (EditText) findViewById(R.id.signup_phoneno); final EditText password_edittext = (EditText) findViewById(R.id.signup_password); final EditText confirmpassword_edittext = (EditText) findViewById(R.id.signup_confirmpassword); autoCompleteTextView = (CustomAutoCompleteTextView) findViewById(R.id.register_spinner_autocomplete); autoCompleteTextView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Toast toast = Toast.makeText(RegisterActivity.this, "Fetching municipality list, please wait", Toast.LENGTH_SHORT); toast.setGravity(Gravity.CENTER | Gravity.CENTER_HORIZONTAL, 0, 0); toast.show(); } }); deviceID = Settings.Secure.getString(this.getContentResolver(), Settings.Secure.ANDROID_ID); deviceOS = Integer.toString(Build.VERSION.SDK_INT); deviceType = "mobile"; Button register = (Button) findViewById(R.id.signup_register); register.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { progressDialog.show(); name = name_edittext.getText().toString().trim(); email = email_edittext.getText().toString().trim(); phoneno = phoneno_edittext.getText().toString().trim(); password = password_edittext.getText().toString().trim(); confirmpassword = <PASSWORD>irmpassword_edittext.getText().toString().trim(); submit(name, email, phoneno, password, confirmpassword); } }); confirmpassword_edittext.setOnEditorActionListener(new TextView.OnEditorActionListener() { @Override public boolean onEditorAction(TextView v, int actionId, KeyEvent event) { if (actionId == EditorInfo.IME_ACTION_DONE) { progressDialog.show(); name = name_edittext.getText().toString().trim(); email = email_edittext.getText().toString().trim(); phoneno = phoneno_edittext.getText().toString().trim(); password = password_edittext.getText().toString().trim(); confirmpassword = confirmpassword_edittext.getText().toString().trim(); submit(name, email, phoneno, password, confirmpassword); return true; } return false; } }); handler = new Handler(); try { InputStream inputStream = getAssets().open("egov.conf"); configManager = new ConfigManager(inputStream, RegisterActivity.this); inputStream.close(); } catch (IOException e) { e.printStackTrace(); } new GetAllCitiesTask().execute(); } private boolean isValidEmail(String email) { String expression = "^[\\w\\.-]+@([\\w\\-]+\\.)+[A-Z]{2,4}$"; Pattern pattern = Pattern.compile(expression, Pattern.CASE_INSENSITIVE); Matcher matcher = pattern.matcher(email); return matcher.matches(); } private boolean isValidPassword(String password) { String expression = "((?=.*\\d)(?=.*[a-z])(?=.*[A-Z])(?=.*[@$;:+=-_?()!]).{8,32})"; Pattern pattern = Pattern.compile(expression); Matcher matcher = pattern.matcher(password); return matcher.matches(); } private void submit(final String name, final String email, final String phoneno, final String password, final String confirmpassword) { if (url == null || TextUtils.isEmpty(name) || TextUtils.isEmpty(email) || TextUtils.isEmpty(phoneno) || TextUtils.isEmpty(password) || TextUtils.isEmpty(confirmpassword)) { Toast toast = Toast.makeText(RegisterActivity.this, "Please fill all the fields", Toast.LENGTH_SHORT); toast.setGravity(Gravity.CENTER | Gravity.CENTER_HORIZONTAL, 0, 0); toast.show(); progressDialog.dismiss(); } else if (phoneno.length() != 10) { Toast toast = Toast.makeText(RegisterActivity.this, "Phone no. must be 10 digits", Toast.LENGTH_SHORT); toast.setGravity(Gravity.CENTER | Gravity.CENTER_HORIZONTAL, 0, 0); toast.show(); progressDialog.dismiss(); } else if (!isValidEmail(email)) { Toast toast = Toast.makeText(RegisterActivity.this, "Please enter a valid email ID", Toast.LENGTH_SHORT); toast.setGravity(Gravity.CENTER | Gravity.CENTER_HORIZONTAL, 0, 0); toast.show(); progressDialog.dismiss(); } else if (!isValidPassword(password)) { Toast toast = Toast.makeText(RegisterActivity.this, "Password must be 8-32 characters long, containing at least one uppercase letter, one lowercase letter, and one number or special character excluding '& < > # % \" ' / \\' and space", Toast.LENGTH_LONG); toast.setGravity(Gravity.CENTER | Gravity.CENTER_HORIZONTAL, 0, 0); toast.show(); progressDialog.dismiss(); } else if (!password.equals(confirmpassword)) { Toast toast = Toast.makeText(RegisterActivity.this, "Passwords do not match", Toast.LENGTH_SHORT); toast.setGravity(Gravity.CENTER | Gravity.CENTER_HORIZONTAL, 0, 0); toast.show(); progressDialog.dismiss(); } else { sessionManager.setBaseURL(url, cityName, code); RegisterRequest registerRequest = new RegisterRequest(email, phoneno, name, password, deviceID, deviceType, deviceOS); ApiController.getAPI(RegisterActivity.this).registerUser(registerRequest, new Callback<JsonObject>() { @Override public void success(JsonObject jsonObject, Response response) { handler.post(new Runnable() { @Override public void run() { Toast toast = Toast.makeText(RegisterActivity.this, "Account created", Toast.LENGTH_SHORT); toast.setGravity(Gravity.CENTER | Gravity.CENTER_HORIZONTAL, 0, 0); toast.show(); progressDialog.dismiss(); } }); ApiController.getAPI(RegisterActivity.this).sendOTP(phoneno, new Callback<JsonObject>() { @Override public void success(JsonObject jsonObject, Response response) { } @Override public void failure(RetrofitError error) { } }); Intent intent = new Intent(RegisterActivity.this, AccountActivationActivity.class); intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); intent.putExtra("username", phoneno); intent.putExtra("password", <PASSWORD>); startActivity(intent); finish(); } @Override public void failure(final RetrofitError error) { handler.post(new Runnable() { @Override public void run() { JsonObject jsonObject = null; progressDialog.dismiss(); if (error != null) { if (error.getLocalizedMessage() != null && !error.getLocalizedMessage().contains("400")) { Toast toast = Toast.makeText(RegisterActivity.this, error.getLocalizedMessage(), Toast.LENGTH_SHORT); toast.setGravity(Gravity.CENTER | Gravity.CENTER_HORIZONTAL, 0, 0); toast.show(); } else { try { jsonObject = (JsonObject) error.getBody(); } catch (Exception e) { e.printStackTrace(); } if (jsonObject != null) { Toast toast = Toast.makeText(RegisterActivity.this, "An account already exists with that email ID or mobile no.", Toast.LENGTH_SHORT); toast.setGravity(Gravity.CENTER | Gravity.CENTER_HORIZONTAL, 0, 0); toast.show(); } else { Toast toast = Toast.makeText(RegisterActivity.this, "An unexpected error occurred while accessing the network", Toast.LENGTH_SHORT); toast.setGravity(Gravity.CENTER | Gravity.CENTER_HORIZONTAL, 0, 0); toast.show(); } } } else { Toast toast = Toast.makeText(RegisterActivity.this, "An unexpected error occurred while accessing the network", Toast.LENGTH_SHORT); toast.setGravity(Gravity.CENTER | Gravity.CENTER_HORIZONTAL, 0, 0); toast.show(); } } }); } }); } } class GetAllCitiesTask extends AsyncTask<String, Integer, Object> { @Override protected Object doInBackground(String... params) { try { if (configManager.getString("api.multicities").equals("false")) { handler.post(new Runnable() { @Override public void run() { municipalityInfo.setVisibility(View.GONE); spinner.setVisibility(View.GONE); autoCompleteTextView.setVisibility(View.GONE); nameInputLayout.setBackgroundResource(R.drawable.top_edittext); } }); } else { final List<City> cityList = ApiController.getAllCitiesURLs(configManager.getString("api.multipleCitiesUrl")); if (cityList != null) { final List<String> cities = new ArrayList<>(); for (int i = 0; i < cityList.size(); i++) { cities.add(cityList.get(i).getCityName()); } handler.post(new Runnable() { @Override public void run() { ArrayAdapter<String> dropdownAdapter = new ArrayAdapter<>(RegisterActivity.this, android.R.layout.simple_spinner_dropdown_item, cities); dropdownAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); spinner.setAdapter(new NothingSelectedSpinnerAdapter(dropdownAdapter, android.R.layout.simple_spinner_dropdown_item, RegisterActivity.this)); spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() { @Override public void onItemSelected(AdapterView<?> parent, View view, int position, long id) { check = check + 1; if (check > 1) { url = cityList.get(position - 1).getUrl(); cityName = cityList.get(position - 1).getCityName(); code = cityList.get(position - 1).getCityCode(); autoCompleteTextView.setText(cityList.get(position - 1).getCityName()); autoCompleteTextView.dismissDropDown(); } } @Override public void onNothingSelected(AdapterView<?> parent) { } }); ArrayAdapter<String> autoCompleteAdapter = new ArrayAdapter<>(RegisterActivity.this, android.R.layout.simple_spinner_dropdown_item, cities); autoCompleteTextView.setHint("Municipality"); autoCompleteTextView.setCompoundDrawablesWithIntrinsicBounds(R.drawable.ic_location_city_black_24dp, 0, R.drawable.ic_keyboard_arrow_down_black_24dp, 0); autoCompleteTextView.setOnClickListener(null); autoCompleteTextView.setAdapter(autoCompleteAdapter); autoCompleteTextView.setThreshold(1); autoCompleteTextView.setDrawableClickListener(new CustomAutoCompleteTextView.DrawableClickListener() { @Override public void onClick(DrawablePosition target) { if (target == DrawablePosition.RIGHT) { spinner.performClick(); } } }); autoCompleteTextView.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { String s = autoCompleteTextView.getText().toString(); for (City city : cityList) { if (s.equals(city.getCityName())) { url = city.getUrl(); cityName = city.getCityName(); code = city.getCityCode(); } } } }); } }); } else { handler.post(new Runnable() { @Override public void run() { autoCompleteTextView.setOnClickListener(null); autoCompleteTextView.setHint("Loading failed"); autoCompleteTextView.setCompoundDrawablesWithIntrinsicBounds(R.drawable.ic_location_city_black_24dp, 0, R.drawable.ic_refresh_black_24dp, 0); autoCompleteTextView.setDrawableClickListener(new CustomAutoCompleteTextView.DrawableClickListener() { @Override public void onClick(DrawablePosition target) { if (target == DrawablePosition.RIGHT) { autoCompleteTextView.setCompoundDrawablesWithIntrinsicBounds(R.drawable.ic_location_city_black_24dp, 0, 0, 0); autoCompleteTextView.setDrawableClickListener(null); autoCompleteTextView.setHint(getString(R.string.loading_label)); new GetAllCitiesTask().execute(); } } }); Toast toast = Toast.makeText(RegisterActivity.this, "An unexpected error occurred while retrieving the list of available municipalities", Toast.LENGTH_SHORT); toast.setGravity(Gravity.CENTER | Gravity.CENTER_HORIZONTAL, 0, 0); toast.show(); autoCompleteTextView.setCompoundDrawablesWithIntrinsicBounds(R.drawable.ic_location_city_black_24dp, 0, R.drawable.ic_refresh_black_24dp, 0); autoCompleteTextView.setDrawableClickListener(new CustomAutoCompleteTextView.DrawableClickListener() { @Override public void onClick(DrawablePosition target) { if (target == DrawablePosition.RIGHT) { autoCompleteTextView.setCompoundDrawablesWithIntrinsicBounds(R.drawable.ic_location_city_black_24dp, 0, 0, 0); autoCompleteTextView.setDrawableClickListener(null); autoCompleteTextView.setHint(getString(R.string.loading_label)); new GetAllCitiesTask().execute(); } } }); } }); } } } catch (IOException e) { e.printStackTrace(); handler.post(new Runnable() { @Override public void run() { autoCompleteTextView.setOnClickListener(null); autoCompleteTextView.setHint("Loading failed"); autoCompleteTextView.setCompoundDrawablesWithIntrinsicBounds(R.drawable.ic_location_city_black_24dp, 0, R.drawable.ic_refresh_black_24dp, 0); autoCompleteTextView.setDrawableClickListener(new CustomAutoCompleteTextView.DrawableClickListener() { @Override public void onClick(DrawablePosition target) { if (target == DrawablePosition.RIGHT) { autoCompleteTextView.setCompoundDrawablesWithIntrinsicBounds(R.drawable.ic_location_city_black_24dp, 0, 0, 0); autoCompleteTextView.setDrawableClickListener(null); autoCompleteTextView.setHint(getString(R.string.loading_label)); new GetAllCitiesTask().execute(); } } }); Toast toast = Toast.makeText(RegisterActivity.this, "An unexpected error occurred while retrieving the list of available municipalities", Toast.LENGTH_SHORT); toast.setGravity(Gravity.CENTER | Gravity.CENTER_HORIZONTAL, 0, 0); toast.show(); autoCompleteTextView.setCompoundDrawablesWithIntrinsicBounds(R.drawable.ic_location_city_black_24dp, 0, R.drawable.ic_refresh_black_24dp, 0); autoCompleteTextView.setDrawableClickListener(new CustomAutoCompleteTextView.DrawableClickListener() { @Override public void onClick(DrawablePosition target) { if (target == DrawablePosition.RIGHT) { autoCompleteTextView.setCompoundDrawablesWithIntrinsicBounds(R.drawable.ic_location_city_black_24dp, 0, 0, 0); autoCompleteTextView.setDrawableClickListener(null); autoCompleteTextView.setHint(getString(R.string.loading_label)); new GetAllCitiesTask().execute(); } } }); } }); } return null; } } } <file_sep>package org.egovernments.egoverp.network; import android.app.IntentService; import android.content.Intent; import android.location.Address; import android.location.Geocoder; import android.text.TextUtils; import android.util.Log; import org.egovernments.egoverp.events.AddressReadyEvent; import java.io.IOException; import java.util.ArrayList; import java.util.List; import de.greenrobot.event.EventBus; /** * Service resolves lat/lng data to address in background when **/ public class AddressService extends IntentService { public static final String LAT = "LAT"; public static final String LNG = "LNG"; public static String addressResult = ""; /** * Creates an IntentService. Invoked by your subclass's constructor. */ public AddressService() { super("Default"); } @Override protected void onHandleIntent(Intent intent) { // Get the location passed to this service through an extra. Double lat = intent.getDoubleExtra(LAT, 0); Double lng = intent.getDoubleExtra(LNG, 0); List<Address> addresses = null; Geocoder geocoder = new Geocoder(getApplicationContext()); try { addresses = geocoder.getFromLocation(lat, lng, 1); } catch (IOException | IllegalArgumentException ioException) { // Catch network or other I/O problems. ioException.printStackTrace(); } // Handle case where no address was found. if (addresses == null || addresses.size() == 0) { Log.e("Address null", ""); } else { Address address = addresses.get(0); ArrayList<String> addressFragments = new ArrayList<>(); // Fetch the address lines using getAddressLine, // join them, and send them to the thread. for (int i = 0; i < address.getMaxAddressLineIndex(); i++) { addressFragments.add(address.getAddressLine(i)); } addressResult = TextUtils.join(System.getProperty("line.separator"), addressFragments); //Post event on success so that all relevant subscribers can react EventBus.getDefault().post(new AddressReadyEvent()); } } } <file_sep> package org.egovernments.egoverp.models; import com.google.gson.annotations.Expose; import com.google.gson.annotations.SerializedName; import java.util.ArrayList; import java.util.List; public class WaterTaxCallback { @SerializedName("consumerNo") @Expose private String consumerNo; @SerializedName("ownerName") @Expose private String ownerName; @SerializedName("mobileNo") @Expose private String mobileNo; @SerializedName("propertyAddress") @Expose private String propertyAddress; @SerializedName("localityName") @Expose private String localityName; @SerializedName("taxDetails") @Expose private List<TaxDetail> taxDetails = new ArrayList<>(); @SerializedName("errorDetails") @Expose private TaxErrorDetails errorDetails; /** * @return The consumerNo */ public String getConsumerNo() { return consumerNo; } /** * @return The ownerName */ public String getOwnerName() { return ownerName; } /** * @return The mobileNo */ public String getMobileNo() { return mobileNo; } /** * @return The propertyAddress */ public String getPropertyAddress() { return propertyAddress; } /** * @return The localityName */ public String getLocalityName() { return localityName; } /** * @return The taxDetails */ public List<TaxDetail> getTaxDetails() { return taxDetails; } /** * @return The errorDetails */ public TaxErrorDetails getTaxErrorDetails() { return errorDetails; } } <file_sep>package org.egovernments.egoverp.application; import android.app.Application; import org.egovernments.egoverp.network.SSLTrustManager; import com.squareup.okhttp.Cache; import com.squareup.okhttp.Interceptor; import com.squareup.okhttp.OkHttpClient; import com.squareup.okhttp.Protocol; import com.squareup.okhttp.Response; import com.squareup.picasso.OkHttpDownloader; import com.squareup.picasso.Picasso; import java.io.File; import java.io.IOException; import java.util.Collections; /** * Performs setup for some frequently used functions of the app **/ public class EgovAppConfig extends Application { private final OkHttpClient client = SSLTrustManager.createClient(); @Override public void onCreate() { super.onCreate(); //Creates an interceptor to force image caching no matter the server instructions Interceptor REWRITE_CACHE_CONTROL_INTERCEPTOR = new Interceptor() { @Override public Response intercept(Chain chain) throws IOException { Response originalResponse = chain.proceed(chain.request()); return originalResponse.newBuilder() .header("Cache-Control", "max-age=60") .build(); } }; //Retrieves the app cache directory and sets up a cache for the OkHttpClient File cacheDir = this.getExternalCacheDir(); if (cacheDir == null) { // Fall back to using the internal cache directory cacheDir = this.getCacheDir(); } client.setCache(new Cache(cacheDir, 100 * 1024 * 1024)); client.setProtocols(Collections.singletonList(Protocol.HTTP_1_1)); client.networkInterceptors().add(REWRITE_CACHE_CONTROL_INTERCEPTOR); //Sets up the picasso global singleton instance Picasso.Builder builder = new Picasso.Builder(this); Picasso picasso = builder .downloader(new OkHttpDownloader(client)) .build(); Picasso.setSingletonInstance(picasso); } }<file_sep> package org.egovernments.egoverp.models.errors; /** * POJO class to parse server error messages. Cannot parse all error messages as they are inconsistent **/ import com.google.gson.annotations.Expose; import com.google.gson.annotations.SerializedName; public class ErrorResponse { @SerializedName("status") @Expose private ErrorMessage errorStatus; @SerializedName("result") @Expose private String result; /** * @return The errorStatus */ public ErrorMessage getErrorStatus() { return errorStatus; } /** * @return The result */ public String getResult() { return result; } } <file_sep>package org.egovernments.egoverp.adapters; import android.content.Context; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.BaseAdapter; import android.widget.TextView; import org.egovernments.egoverp.R; import org.egovernments.egoverp.models.TaxDetail; import java.lang.ref.WeakReference; import java.util.List; public class TaxAdapter extends BaseAdapter { private WeakReference<Context> contextWeakReference; private List<TaxDetail> taxDetails; public TaxAdapter(List<TaxDetail> taxDetails, Context context) { this.taxDetails = taxDetails; this.contextWeakReference = new WeakReference<>(context); } @Override public int getCount() { return taxDetails.size(); } @Override public Object getItem(int position) { return taxDetails.get(position); } @Override public long getItemId(int position) { return position; } @Override public View getView(int position, View convertView, ViewGroup parent) { TaxViewHolder taxViewHolder = null; View view = convertView; if (convertView == null) { view = LayoutInflater.from(contextWeakReference.get()).inflate(R.layout.item_tax, parent, false); taxViewHolder = new TaxViewHolder(); taxViewHolder.taxAmount = (TextView) view.findViewById(R.id.propertytax_taxamount); taxViewHolder.taxChequePenalty = (TextView) view.findViewById(R.id.propertytax_chequepenalty); taxViewHolder.taxPenalty = (TextView) view.findViewById(R.id.propertytax_penalty); taxViewHolder.taxInstallment = (TextView) view.findViewById(R.id.propertytax_installment); taxViewHolder.taxRebate = (TextView) view.findViewById(R.id.propertytax_rebate); taxViewHolder.taxTotal = (TextView) view.findViewById(R.id.propertytax_total); view.setTag(taxViewHolder); } if (taxViewHolder == null) { taxViewHolder = (TaxViewHolder) view.getTag(); } TaxDetail taxDetail = (TaxDetail) getItem(position); taxViewHolder.taxInstallment.setText("Installment: " + taxDetail.getInstallment()); taxViewHolder.taxAmount.setText("Amount: Rs. " + taxDetail.getTaxAmount()); taxViewHolder.taxChequePenalty.setText("Cheque Bounce Penalty: Rs. " + taxDetail.getChqBouncePenalty()); taxViewHolder.taxPenalty.setText("Penalty: Rs. " + taxDetail.getPenalty()); taxViewHolder.taxRebate.setText("Rebate: Rs. " + taxDetail.getRebate()); taxViewHolder.taxTotal.setText("Total: Rs. " + taxDetail.getTotalAmount()); return view; } public static class TaxViewHolder { private TextView taxAmount; private TextView taxChequePenalty; private TextView taxPenalty; private TextView taxInstallment; private TextView taxRebate; private TextView taxTotal; } } <file_sep>package org.egovernments.egoverp.activities; import android.app.ProgressDialog; import android.content.Intent; import android.graphics.Color; import android.os.Bundle; import android.os.Handler; import android.support.v4.widget.DrawerLayout; import android.support.v7.app.ActionBarDrawerToggle; import android.support.v7.app.AppCompatActivity; import android.view.Gravity; import android.view.View; import android.view.ViewGroup; import android.widget.AdapterView; import android.widget.BaseAdapter; import android.widget.FrameLayout; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.ListView; import android.widget.RelativeLayout; import android.widget.TextView; import org.egovernments.egoverp.R; import org.egovernments.egoverp.network.ApiController; import org.egovernments.egoverp.network.SessionManager; import com.google.gson.JsonObject; import java.util.ArrayList; import java.util.List; import retrofit.Callback; import retrofit.RetrofitError; import retrofit.client.Response; /** * The activity sets up common features of layout for other activities **/ public class BaseActivity extends AppCompatActivity { protected LinearLayout fullLayout; protected FrameLayout activityContent; protected ArrayList<NavigationItem> arrayList; protected DrawerLayout drawerLayout; protected ActionBarDrawerToggle actionBarDrawerToggle; protected CharSequence mActionBarTitle; protected SessionManager sessionManager; protected ProgressDialog progressDialog; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.baselayout); } //Overridden method will intercept layout passed and inflate it into baselayout.xml @Override public void setContentView(final int layoutResID) { fullLayout = (LinearLayout) getLayoutInflater().inflate(R.layout.baselayout, null); activityContent = (FrameLayout) fullLayout.findViewById(R.id.drawer_content); getLayoutInflater().inflate(layoutResID, activityContent, true); super.setContentView(fullLayout); sessionManager = new SessionManager(getApplicationContext()); progressDialog = new ProgressDialog(this, ProgressDialog.STYLE_SPINNER); progressDialog.setIndeterminate(true); progressDialog.setMessage(getString(R.string.processing_msg)); progressDialog.setCancelable(false); android.support.v7.widget.Toolbar toolbar = (android.support.v7.widget.Toolbar) findViewById(R.id.toolbar); setSupportActionBar(toolbar); final android.support.v7.app.ActionBar actionBar = getSupportActionBar(); assert actionBar != null; mActionBarTitle = actionBar.getTitle(); toolbar.setNavigationIcon(R.drawable.ic_menu_white_24dp); drawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout); actionBarDrawerToggle = new ActionBarDrawerToggle(this, drawerLayout, toolbar, R.string.app_name, R.string.app_name) { public void onDrawerClosed(View view) { actionBar.setTitle(mActionBarTitle); } public void onDrawerOpened(View drawerView) { actionBar.setTitle(R.string.menu_label); } }; drawerLayout.setDrawerListener(actionBarDrawerToggle); ListView listView = (ListView) findViewById(R.id.drawer); arrayList = new ArrayList<>(); fillList(); BaseAdapter navAdapter = new NavAdapter(arrayList); listView.setAdapter(navAdapter); listView.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { Intent intent; Handler drawerClose = new Handler(); Runnable runnable = new Runnable() { @Override public void run() { drawerLayout.closeDrawer(Gravity.LEFT); } }; switch (position) { case 0: if (!getTitle().toString().equals(getString(R.string.home_label))) finish(); else drawerClose.postDelayed(runnable, 1000); break; case 1: if (!getTitle().toString().equals(getString(R.string.grievances_label))) { intent = new Intent(BaseActivity.this, GrievanceActivity.class); intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); startActivity(intent); if (!getTitle().toString().equals(getString(R.string.home_label))) finish(); } else drawerLayout.closeDrawer(Gravity.LEFT); break; case 2: if (!getTitle().toString().equals(getString(R.string.propertytax_label))) { intent = new Intent(BaseActivity.this, PropertyTaxSearchActivity.class); intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); startActivity(intent); if (!getTitle().toString().equals(getString(R.string.home_label))) finish(); } else drawerLayout.closeDrawer(Gravity.LEFT); break; case 3: if (!getTitle().toString().equals(getString(R.string.watertax_label))) { intent = new Intent(BaseActivity.this, WaterTaxSearchActivity.class); intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); startActivity(intent); if (!getTitle().toString().equals(getString(R.string.home_label))) finish(); } else drawerLayout.closeDrawer(Gravity.LEFT); break; case 4: if (!getTitle().toString().equals(getString(R.string.profile_label))) { intent = new Intent(BaseActivity.this, ProfileActivity.class); intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); startActivity(intent); if (!getTitle().toString().equals(getString(R.string.home_label))) finish(); } else drawerLayout.closeDrawer(Gravity.LEFT); break; case 5: progressDialog.show(); ApiController.getAPI(BaseActivity.this).logout(sessionManager.getAccessToken(), new Callback<JsonObject>() { @Override public void success(JsonObject jsonObject, Response response) { sessionManager.logoutUser(); ApiController.apiInterface = null; Intent intent = new Intent(BaseActivity.this, LoginActivity.class).setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); startActivity(intent); progressDialog.dismiss(); finish(); } @Override public void failure(RetrofitError error) { sessionManager.logoutUser(); ApiController.apiInterface = null; Intent intent = new Intent(BaseActivity.this, LoginActivity.class).setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); startActivity(intent); progressDialog.dismiss(); finish(); } }); break; } } }); } //Method fills the nav drawer's ArrayList private void fillList() { arrayList.add(new NavigationItem(R.drawable.ic_home_black_24dp, getString(R.string.home_label))); arrayList.add(new NavigationItem(R.drawable.ic_feedback_black_24dp, getString(R.string.grievances_label))); arrayList.add(new NavigationItem(R.drawable.ic_business_black_24dp, getString(R.string.propertytax_label))); arrayList.add(new NavigationItem(R.drawable.ic_water_black_24dp, getString(R.string.watertax_label))); arrayList.add(new NavigationItem(R.drawable.ic_person_black_24dp, getString(R.string.profile_label))); arrayList.add(new NavigationItem(R.drawable.ic_backspace_black_24dp, getString(R.string.logout_label))); } //POJO class for nav drawer items private class NavigationItem { private final int NavIcon; private final String NavTitle; public NavigationItem(int navIcon, String navTitle) { NavIcon = navIcon; NavTitle = navTitle; } public int getNavIcon() { return NavIcon; } public String getNavTitle() { return NavTitle; } } private class NavigationViewHolder { private ImageView nav_item_icon; private TextView nav_item_text; private RelativeLayout nav_drawer_row; } //Custom adapter for nav drawer public class NavAdapter extends BaseAdapter { List<NavigationItem> navigationItems; public NavAdapter(List<NavigationItem> navigationItems) { this.navigationItems = navigationItems; } @Override public int getCount() { return navigationItems.size(); } @Override public NavigationItem getItem(int position) { return navigationItems.get(position); } @Override public long getItemId(int position) { return position; } @Override public View getView(int position, View convertView, ViewGroup parent) { NavigationViewHolder navigationViewHolder = null; View view = convertView; if (convertView == null) { view = getLayoutInflater().inflate(R.layout.item_navdrawer, parent, false); navigationViewHolder = new NavigationViewHolder(); navigationViewHolder.nav_item_text = (TextView) view.findViewById(R.id.title); navigationViewHolder.nav_item_icon = (ImageView) view.findViewById(R.id.icon); navigationViewHolder.nav_drawer_row = (RelativeLayout) view.findViewById(R.id.navdrawer_row); view.setTag(navigationViewHolder); } if (navigationViewHolder == null) { navigationViewHolder = (NavigationViewHolder) view.getTag(); } NavigationItem navigationItem = getItem(position); navigationViewHolder.nav_item_text.setText(navigationItem.getNavTitle()); if (mActionBarTitle.equals(navigationItem.getNavTitle())) navigationViewHolder.nav_drawer_row.setBackgroundColor(Color.parseColor("#90CAF9")); navigationViewHolder.nav_item_icon.setImageResource(navigationItem.getNavIcon()); return view; } } }<file_sep> package org.egovernments.egoverp.models; import com.google.gson.annotations.Expose; import com.google.gson.annotations.SerializedName; import java.util.ArrayList; import java.util.List; /** * POJO class, response to getComplaintLocation in autocompleteTextview of NewGrievanceActivity **/ public class GrievanceLocationAPIResponse { @SerializedName("result") @Expose private List<GrievanceLocation> grievanceLocation = new ArrayList<>(); /** * @return The grievanceLocation */ public List<GrievanceLocation> getGrievanceLocation() { return grievanceLocation; } } <file_sep> package org.egovernments.egoverp.models; import com.google.gson.annotations.Expose; import com.google.gson.annotations.SerializedName; public class TaxDetail { @SerializedName("installment") @Expose private String installment; @SerializedName("taxAmount") @Expose private Integer taxAmount; @SerializedName("chqBouncePenalty") @Expose private Integer chqBouncePenalty; @SerializedName("penalty") @Expose private Integer penalty; @SerializedName("rebate") @Expose private Integer rebate; @SerializedName("totalAmount") @Expose private Integer totalAmount; /** * @return The installment */ public String getInstallment() { return installment; } /** * @return The taxAmount */ public Integer getTaxAmount() { return taxAmount; } /** * @return The chqBouncePenalty */ public Integer getChqBouncePenalty() { return chqBouncePenalty; } /** * @return The penalty */ public Integer getPenalty() { return penalty; } /** * @return The totalAmount */ public Integer getTotalAmount() { return totalAmount; } public Integer getRebate() { return rebate; } } <file_sep>package org.egovernments.egoverp.network; import android.content.Context; import android.content.SharedPreferences; import java.util.Calendar; /** * Stores session data to enable persistent logged in status and to enable seamless renewal of session in background without user input **/ public class SessionManager { private SharedPreferences pref; private SharedPreferences.Editor editor; private static final String BASE_URL = "Base URL"; private static final String URL_CREATED_TIME = "Url timeout"; private static final String URL_LOCATION = "Url location"; private static final String URL_LOCATION_CODE = "Url location code"; private static final String PREF_NAME = "CredentialsPref"; public static final String IS_LOGGED_IN = "IsLoggedIn"; public static final String KEY_PASSWORD = "<PASSWORD>"; public static final String KEY_USERNAME = "username"; public static final String KEY_ACCESS_TOKEN = "access_token"; public SessionManager(Context context) { pref = context.getSharedPreferences(PREF_NAME, 0); } //When the user is logged in, store data in shared preferences to be used across sessions public void loginUser(String password, String email, String accessToken) { editor = pref.edit(); editor.putBoolean(IS_LOGGED_IN, true); editor.putString(KEY_PASSWORD, <PASSWORD>); editor.putString(KEY_USERNAME, email); editor.putString(KEY_ACCESS_TOKEN, accessToken); editor.apply(); } //Only when user explicitly logs out, clear all data from storage public void logoutUser() { editor = pref.edit(); editor.remove(KEY_PASSWORD); editor.remove(KEY_USERNAME); editor.remove(KEY_ACCESS_TOKEN); editor.putBoolean(IS_LOGGED_IN, false); editor.apply(); } public boolean isLoggedIn() { return pref.getBoolean(IS_LOGGED_IN, false); } public String getPassword() { return pref.getString(KEY_PASSWORD, null); } public String getUsername() { return pref.getString(KEY_USERNAME, null); } public String getAccessToken() { String access_token = pref.getString(KEY_ACCESS_TOKEN, null); if (access_token != null) //To remove quotes from string return access_token.substring(1, access_token.length() - 1); return null; } public void invalidateAccessToken() { editor = pref.edit(); editor.putString(KEY_ACCESS_TOKEN, null); editor.apply(); } public void setBaseURL(String url, String location, int code) { editor = pref.edit(); if (url.substring(url.length() - 1).equals("/")) editor.putString(BASE_URL, url.substring(0, url.length() - 1)); else editor.putString(BASE_URL, url); editor.putInt(URL_CREATED_TIME, Calendar.getInstance().get(Calendar.DAY_OF_YEAR)); editor.putString(URL_LOCATION, location); editor.putInt(URL_LOCATION_CODE, code); editor.apply(); } public String getBaseURL() { return pref.getString(BASE_URL, null); } public int getUrlAge() { return Math.abs(Calendar.getInstance().get(Calendar.DAY_OF_YEAR) - pref.getInt(URL_CREATED_TIME, 100)); } public String getUrlLocation() { return pref.getString(URL_LOCATION, null); } public int getUrlLocationCode() { return pref.getInt(URL_LOCATION_CODE, 0); } } <file_sep> package org.egovernments.egoverp.models; import com.google.gson.annotations.Expose; import com.google.gson.annotations.SerializedName; import java.util.ArrayList; import java.util.List; /** * POJO class, needed to resolve the list returned by getComplaintHistory **/ public class GrievanceCommentAPIResult { @SerializedName("comments") @Expose private List<GrievanceComment> grievanceComments = new ArrayList<>(); /** * @return The grievanceComments */ public List<GrievanceComment> getGrievanceComments() { return grievanceComments; } } <file_sep>package org.egovernments.egoverp.activities; import android.graphics.Color; import android.graphics.drawable.ColorDrawable; import android.os.Build; import android.os.Bundle; import android.support.design.widget.FloatingActionButton; import android.support.v7.app.AppCompatActivity; import android.text.TextUtils; import android.view.Gravity; import android.view.KeyEvent; import android.view.View; import android.view.inputmethod.EditorInfo; import android.widget.EditText; import android.widget.ProgressBar; import android.widget.TextView; import android.widget.Toast; import org.egovernments.egoverp.R; import org.egovernments.egoverp.network.ApiController; import org.egovernments.egoverp.network.SessionManager; import com.google.gson.JsonObject; import retrofit.Callback; import retrofit.RetrofitError; import retrofit.client.Response; /** * The password recovery screen activity **/ public class ForgotPasswordActivity extends AppCompatActivity { private String phone; private ProgressBar progressBar; private FloatingActionButton sendButton; private com.melnykov.fab.FloatingActionButton sendButtonCompat; private SessionManager sessionManager; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_forgotpassword); progressBar = (ProgressBar) findViewById(R.id.forgotprogressBar); android.support.v7.widget.Toolbar toolbar = (android.support.v7.widget.Toolbar) findViewById(R.id.toolbar); setSupportActionBar(toolbar); android.support.v7.app.ActionBar actionBar = getSupportActionBar(); if (actionBar != null) { actionBar.setBackgroundDrawable(new ColorDrawable(Color.parseColor("#00000000"))); actionBar.setDisplayHomeAsUpEnabled(true); } sessionManager = new SessionManager(this); sendButton = (FloatingActionButton) findViewById(R.id.forgotpassword_send); sendButtonCompat = (com.melnykov.fab.FloatingActionButton) findViewById(R.id.forgotpassword_sendcompat); final EditText phone_edittext = (EditText) findViewById(R.id.forgotpassword_edittext); phone_edittext.setOnEditorActionListener(new TextView.OnEditorActionListener() { @Override public boolean onEditorAction(TextView v, int actionId, KeyEvent event) { if (actionId == EditorInfo.IME_ACTION_DONE) { phone = phone_edittext.getText().toString().trim(); progressBar.setVisibility(View.VISIBLE); sendButton.setVisibility(View.GONE); sendButtonCompat.setVisibility(View.GONE); submit(phone); return true; } return false; } }); View.OnClickListener onClickListener = new View.OnClickListener() { @Override public void onClick(View v) { phone = phone_edittext.getText().toString().trim(); progressBar.setVisibility(View.VISIBLE); sendButton.setVisibility(View.GONE); sendButtonCompat.setVisibility(View.GONE); submit(phone); } }; if (Build.VERSION.SDK_INT >= 21) { sendButton.setOnClickListener(onClickListener); } else { sendButtonCompat.setVisibility(View.VISIBLE); sendButton.setVisibility(View.GONE); sendButtonCompat.setOnClickListener(onClickListener); } } //Invokes call to API private void submit(String phone) { if (TextUtils.isEmpty(phone)) { Toast toast = Toast.makeText(ForgotPasswordActivity.this, R.string.forgot_password_prompt, Toast.LENGTH_SHORT); toast.setGravity(Gravity.CENTER | Gravity.CENTER_HORIZONTAL, 0, 0); toast.show(); progressBar.setVisibility(View.GONE); if (Build.VERSION.SDK_INT >= 21) { sendButton.setVisibility(View.VISIBLE); } else { sendButtonCompat.setVisibility(View.VISIBLE); } } else if (phone.length() != 10) { Toast toast = Toast.makeText(ForgotPasswordActivity.this, R.string.mobilenumber_length_prompt, Toast.LENGTH_SHORT); toast.setGravity(Gravity.CENTER | Gravity.CENTER_HORIZONTAL, 0, 0); toast.show(); progressBar.setVisibility(View.GONE); if (Build.VERSION.SDK_INT >= 21) { sendButton.setVisibility(View.VISIBLE); } else { sendButtonCompat.setVisibility(View.VISIBLE); } } else { ApiController.getAPI(ForgotPasswordActivity.this).recoverPassword(phone, sessionManager.getBaseURL(), new Callback<JsonObject>() { @Override public void success(JsonObject resp, Response response) { Toast toast = Toast.makeText(ForgotPasswordActivity.this, R.string.recoverymessage_msg, Toast.LENGTH_SHORT); toast.setGravity(Gravity.CENTER | Gravity.CENTER_HORIZONTAL, 0, 0); toast.show(); progressBar.setVisibility(View.GONE); if (Build.VERSION.SDK_INT >= 21) { sendButton.setVisibility(View.VISIBLE); } else { sendButtonCompat.setVisibility(View.VISIBLE); } finish(); } @Override public void failure(RetrofitError error) { if (error.getLocalizedMessage() != null && !error.getLocalizedMessage().contains("400")) { if (error.getLocalizedMessage() != null) { Toast toast = Toast.makeText(ForgotPasswordActivity.this, error.getLocalizedMessage(), Toast.LENGTH_SHORT); toast.setGravity(Gravity.CENTER | Gravity.CENTER_HORIZONTAL, 0, 0); toast.show(); } else { JsonObject jsonObject = (JsonObject) error.getBody(); if (jsonObject != null) { Toast toast = Toast.makeText(ForgotPasswordActivity.this, R.string.noaccount_msg, Toast.LENGTH_SHORT); toast.setGravity(Gravity.CENTER | Gravity.CENTER_HORIZONTAL, 0, 0); toast.show(); } } } else { Toast toast = Toast.makeText(ForgotPasswordActivity.this, "An unexpected error occurred while accessing the network", Toast.LENGTH_SHORT); toast.setGravity(Gravity.CENTER | Gravity.CENTER_HORIZONTAL, 0, 0); toast.show(); } progressBar.setVisibility(View.GONE); if (Build.VERSION.SDK_INT >= 21) { sendButton.setVisibility(View.VISIBLE); } else { sendButtonCompat.setVisibility(View.VISIBLE); } } }); } } } <file_sep> package org.egovernments.egoverp.models; import com.google.gson.annotations.Expose; import com.google.gson.annotations.SerializedName; /** * POJO class, the status response of getComplaints. Used only for hasNextPage value in pagination of grievance activity recyclerview **/ public class GrievanceAPIStatus { @SerializedName("hasNextPage") @Expose private String hasNextPage; @SerializedName("type") @Expose private String type; @SerializedName("message") @Expose private String message; /** * @return The hasNextPage */ public String getHasNextPage() { return hasNextPage; } /** * @return The type */ public String getType() { return type; } /** * @return The message */ public String getMessage() { return message; } } <file_sep>package org.egovernments.egoverp.activities; import android.content.Intent; import android.os.Bundle; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.view.View; import org.egovernments.egoverp.R; import org.egovernments.egoverp.adapters.HomeAdapter; import org.egovernments.egoverp.helper.CardViewOnClickListener; import org.egovernments.egoverp.models.HomeItem; import java.util.ArrayList; import java.util.List; public class HomeActivity extends BaseActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_home); List<HomeItem> homeItemList = new ArrayList<>(); RecyclerView recyclerView = (RecyclerView) findViewById(R.id.home_recyclerview); recyclerView.setHasFixedSize(true); LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this); linearLayoutManager.setOrientation(LinearLayoutManager.VERTICAL); recyclerView.setLayoutManager(linearLayoutManager); CardViewOnClickListener.OnItemClickCallback onItemClickCallback = new CardViewOnClickListener.OnItemClickCallback() { @Override public void onItemClicked(View view, int position) { switch (position) { case 0: startActivity(new Intent(HomeActivity.this, GrievanceActivity.class)); break; case 1: startActivity(new Intent(HomeActivity.this, PropertyTaxSearchActivity.class)); break; case 2: startActivity(new Intent(HomeActivity.this, WaterTaxSearchActivity.class)); break; case 3: startActivity(new Intent(HomeActivity.this, ProfileActivity.class)); break; } } }; homeItemList.add(new HomeItem("Grievances", R.drawable.ic_feedback_black_24dp, "File grievances or review and update previously filed grievances")); homeItemList.add(new HomeItem("Property tax", R.drawable.ic_business_black_24dp, "View property tax details for an assessment number")); homeItemList.add(new HomeItem("Water tax", R.drawable.ic_water_black_24dp, "View water tax details for a consumer code")); homeItemList.add(new HomeItem("Profile", R.drawable.ic_person_black_24dp, "Update or review your profile details.")); HomeAdapter homeAdapter = new HomeAdapter(homeItemList, onItemClickCallback); recyclerView.setAdapter(homeAdapter); } } <file_sep>package org.egovernments.egoverp.helper; import android.view.View; /** * Functions as an OnItemClickListener for recylcerview with cardviews **/ public class CardViewOnClickListener implements View.OnClickListener { private int position; private OnItemClickCallback onItemClickCallback; public CardViewOnClickListener(int position, OnItemClickCallback onItemClickCallback) { this.position = position; this.onItemClickCallback = onItemClickCallback; } @Override public void onClick(View view) { if (onItemClickCallback != null) { onItemClickCallback.onItemClicked(view, position); } } public interface OnItemClickCallback { void onItemClicked(View view, int position); } }<file_sep>package org.egovernments.egoverp.activities; import android.app.ProgressDialog; import android.content.Intent; import android.os.Bundle; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentManager; import android.support.v4.app.FragmentPagerAdapter; import android.support.v4.view.ViewPager; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.Toolbar; import android.text.TextUtils; import android.view.Gravity; import android.view.MotionEvent; import android.view.View; import android.widget.ArrayAdapter; import android.widget.Button; import android.widget.EditText; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.ListView; import android.widget.ProgressBar; import android.widget.RelativeLayout; import android.widget.Spinner; import android.widget.TextView; import android.widget.Toast; import org.egovernments.egoverp.R; import org.egovernments.egoverp.adapters.GrievanceCommentAdapter; import org.egovernments.egoverp.events.AddressReadyEvent; import org.egovernments.egoverp.fragments.GrievanceImageFragment; import org.egovernments.egoverp.helper.NothingSelectedSpinnerAdapter; import org.egovernments.egoverp.models.Grievance; import org.egovernments.egoverp.models.GrievanceCommentAPIResponse; import org.egovernments.egoverp.models.GrievanceCommentAPIResult; import org.egovernments.egoverp.models.GrievanceUpdate; import org.egovernments.egoverp.network.AddressService; import org.egovernments.egoverp.network.ApiController; import org.egovernments.egoverp.network.SessionManager; import org.egovernments.egoverp.network.UpdateService; import com.google.gson.JsonObject; import com.viewpagerindicator.LinePageIndicator; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Arrays; import java.util.Locale; import de.greenrobot.event.EventBus; import retrofit.Callback; import retrofit.RetrofitError; import retrofit.client.Response; /** * Displays the details of a complaint when clicked in GrievanceActivity recycler view **/ public class GrievanceDetailsActivity extends AppCompatActivity { public static final String GRIEVANCE_ITEM = "GrievanceItem"; private static Grievance grievance; private ListView listView; private EditText updateComment; private ProgressDialog progressDialog; private TextView complaintLocation; private String action; private SessionManager sessionManager; private boolean isComment = false; private ProgressBar progressBar; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_grievance_details); grievance = (Grievance) getIntent().getSerializableExtra(GRIEVANCE_ITEM); sessionManager = new SessionManager(GrievanceDetailsActivity.this); Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar); setSupportActionBar(toolbar); if (getSupportActionBar() != null) getSupportActionBar().setDisplayHomeAsUpEnabled(true); TextView complaintDate = (TextView) findViewById(R.id.details_complaint_date); TextView complaintType = (TextView) findViewById(R.id.details_complaint_type); TextView complaintDetails = (TextView) findViewById(R.id.details_complaint_details); TextView complaintStatus = (TextView) findViewById(R.id.details_complaint_status); TextView complaintLandmark = (TextView) findViewById(R.id.details_complaint_landmark); TextView complaintNo = (TextView) findViewById(R.id.details_complaintNo); TextView commentBoxLabel = (TextView) findViewById(R.id.commentbox_label); complaintLocation = (TextView) findViewById(R.id.details_complaint_location); final LinearLayout feedbackLayout = (LinearLayout) findViewById(R.id.feedback_layout); Button updateButton = (Button) findViewById(R.id.grievance_update_button); updateComment = (EditText) findViewById(R.id.update_comment); progressBar = (ProgressBar) findViewById(R.id.grievance_history_placeholder); listView = (ListView) findViewById(R.id.grievance_comments); final Spinner actionsSpinner = (Spinner) findViewById(R.id.update_action); final Spinner feedbackSpinner = (Spinner) findViewById(R.id.update_feedback); ArrayList<String> actions_open = new ArrayList<>(Arrays.asList("Comment", "Withdraw")); ArrayList<String> actions_closed = new ArrayList<>(Arrays.asList("Comment", "Re-open")); ArrayList<String> feedbackOptions = new ArrayList<>(Arrays.asList("Unspecified", "Satisfactory", "Unsatisfactory")); progressDialog = new ProgressDialog(this, ProgressDialog.STYLE_SPINNER); progressDialog.setIndeterminate(true); progressDialog.setMessage("Processing request"); progressDialog.setCancelable(false); //The default image when complaint has no uploaded images ImageView default_image = (ImageView) findViewById(R.id.details_defaultimage); //The layout for uploaded images RelativeLayout imageLayout = (RelativeLayout) findViewById(R.id.details_imageslayout); //If no uploaded images if (grievance.getSupportDocsSize() == 0) { default_image.setVisibility(View.VISIBLE); imageLayout.setVisibility(View.GONE); } else { ViewPager viewPager = (ViewPager) findViewById(R.id.details_complaint_image); viewPager.setAdapter(new GrievanceImagePagerAdapter(getSupportFragmentManager())); LinePageIndicator linePageIndicator = (LinePageIndicator) findViewById(R.id.indicator); linePageIndicator.setViewPager(viewPager); } //Parses complaint date into a more readable format try { //noinspection SpellCheckingInspection complaintDate.setText(new SimpleDateFormat("EEEE, d MMMM, yyyy", Locale.ENGLISH) .format(new SimpleDateFormat("yyyy-MM-dd hh:mm:ss.SSS", Locale.ENGLISH) .parse(grievance.getCreatedDate()))); } catch (ParseException e) { e.printStackTrace(); } complaintType.setText(grievance.getComplaintTypeName()); complaintDetails.setText(grievance.getDetail()); if (TextUtils.isEmpty(grievance.getLandmarkDetails())) { findViewById(R.id.details_complaint_landmark_label).setVisibility(View.GONE); complaintLandmark.setVisibility(View.GONE); } else complaintLandmark.setText(grievance.getLandmarkDetails()); //If grievance has lat/lng values, location name is null if (grievance.getLat() == null) complaintLocation.setText(grievance.getChildLocationName() + " - " + grievance.getLocationName()); else { getAddress(grievance.getLat(), grievance.getLng()); } complaintNo.setText(grievance.getCrn()); complaintStatus.setText(resolveStatus(grievance.getStatus())); //Display feedback spinner if (grievance.getStatus().equals("COMPLETED") || grievance.getStatus().equals("REJECTED") || grievance.getStatus().equals("WITHDRAWN")) { ArrayAdapter<String> adapter = new ArrayAdapter<>(GrievanceDetailsActivity.this, R.layout.view_grievanceupdate_spinner, actions_closed); adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); actionsSpinner.setAdapter(new NothingSelectedSpinnerAdapter(adapter, R.layout.view_grievanceupdate_spinner, GrievanceDetailsActivity.this)); commentBoxLabel.setText("Feedback"); feedbackLayout.setVisibility(View.VISIBLE); ArrayAdapter<String> feedbackAdapter = new ArrayAdapter<>(GrievanceDetailsActivity.this, R.layout.view_grievancefeedback_spinner, feedbackOptions); feedbackAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); feedbackSpinner.setAdapter(new NothingSelectedSpinnerAdapter(feedbackAdapter, R.layout.view_grievancefeedback_spinner, GrievanceDetailsActivity.this)); } //Display default spinners else { ArrayAdapter<String> adapter = new ArrayAdapter<>(GrievanceDetailsActivity.this, R.layout.view_grievanceupdate_spinner, actions_open); adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); actionsSpinner.setAdapter(new NothingSelectedSpinnerAdapter(adapter, R.layout.view_grievanceupdate_spinner, GrievanceDetailsActivity.this)); commentBoxLabel.setText("Update grievance"); } listView.setOnTouchListener(new View.OnTouchListener() { // Setting on Touch Listener for handling the touch inside ScrollView @Override public boolean onTouch(View v, MotionEvent event) { // Disallow the touch request for parent scroll on touch of child view v.getParent().requestDisallowInterceptTouchEvent(true); return false; } }); ApiController.getAPI(GrievanceDetailsActivity.this).getComplaintHistory(grievance.getCrn(), sessionManager.getAccessToken(), new Callback<GrievanceCommentAPIResponse>() { @Override public void success(GrievanceCommentAPIResponse grievanceCommentAPIResponse, Response response) { GrievanceCommentAPIResult grievanceCommentAPIResult = grievanceCommentAPIResponse.getGrievanceCommentAPIResult(); progressBar.setVisibility(View.GONE); listView.setVisibility(View.VISIBLE); listView.setAdapter(new GrievanceCommentAdapter(grievanceCommentAPIResult.getGrievanceComments(), GrievanceDetailsActivity.this)); } @Override public void failure(RetrofitError error) { if (error.getLocalizedMessage() != null) if (error.getLocalizedMessage().equals("Invalid access token")) { Toast toast = Toast.makeText(GrievanceDetailsActivity.this, "Session expired", Toast.LENGTH_SHORT); toast.setGravity(Gravity.CENTER | Gravity.CENTER_HORIZONTAL, 0, 0); toast.show(); sessionManager.logoutUser(); startActivity(new Intent(GrievanceDetailsActivity.this, LoginActivity.class)); } else { Toast toast = Toast.makeText(GrievanceDetailsActivity.this, error.getLocalizedMessage(), Toast.LENGTH_SHORT); toast.setGravity(Gravity.CENTER | Gravity.CENTER_HORIZONTAL, 0, 0); toast.show(); } else { Toast toast = Toast.makeText(GrievanceDetailsActivity.this, "An unexpected error occurred while retrieving comments", Toast.LENGTH_SHORT); toast.setGravity(Gravity.CENTER | Gravity.CENTER_HORIZONTAL, 0, 0); toast.show(); } progressBar.setVisibility(View.GONE); } }); updateButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { action = (String) actionsSpinner.getSelectedItem(); String comment = updateComment.getText().toString().trim(); String feedback = ""; if (feedbackLayout.getVisibility() == View.VISIBLE) { feedback = (String) feedbackSpinner.getSelectedItem(); } if (action == null) { Toast toast = Toast.makeText(GrievanceDetailsActivity.this, "Please select an action", Toast.LENGTH_SHORT); toast.setGravity(Gravity.CENTER | Gravity.CENTER_HORIZONTAL, 0, 0); toast.show(); } else { if ((action.equals("Comment") || action.equals("Re-open")) && TextUtils.isEmpty(comment)) { Toast.makeText(GrievanceDetailsActivity.this, "Comment is necessary for this action", Toast.LENGTH_SHORT).show(); } else if (feedback == null) { { Toast toast = Toast.makeText(GrievanceDetailsActivity.this, "Please select a feedback option", Toast.LENGTH_SHORT); toast.setGravity(Gravity.CENTER | Gravity.CENTER_HORIZONTAL, 0, 0); toast.show(); } } else { switch (action) { case "Comment": isComment = true; action = grievance.getStatus(); break; case "Withdraw": isComment = false; action = "WITHDRAWN"; break; case "Re-open": isComment = false; action = "REOPENED"; break; } progressDialog.show(); ApiController.getAPI(GrievanceDetailsActivity.this).updateGrievance(grievance.getCrn(), new GrievanceUpdate(action, feedback.toUpperCase(), comment), sessionManager.getAccessToken(), new Callback<JsonObject>() { @Override public void success(JsonObject jsonObject, Response response) { Toast toast = Toast.makeText(GrievanceDetailsActivity.this, R.string.grievanceupdated_msg, Toast.LENGTH_SHORT); toast.setGravity(Gravity.CENTER | Gravity.CENTER_HORIZONTAL, 0, 0); toast.show(); progressDialog.dismiss(); ApiController.getAPI(GrievanceDetailsActivity.this).getComplaintHistory(grievance.getCrn(), sessionManager.getAccessToken(), new Callback<GrievanceCommentAPIResponse>() { @Override public void success(GrievanceCommentAPIResponse grievanceCommentAPIResponse, Response response) { GrievanceCommentAPIResult grievanceCommentAPIResult = grievanceCommentAPIResponse.getGrievanceCommentAPIResult(); listView.setAdapter(new GrievanceCommentAdapter(grievanceCommentAPIResult.getGrievanceComments(), GrievanceDetailsActivity.this)); actionsSpinner.setSelection(0); feedbackSpinner.setSelection(0); updateComment.getText().clear(); if (!isComment) { Intent intent = new Intent(GrievanceDetailsActivity.this, UpdateService.class).putExtra(UpdateService.KEY_METHOD, UpdateService.UPDATE_COMPLAINTS); intent.putExtra(UpdateService.COMPLAINTS_PAGE, "1"); startService(intent); finish(); } } @Override public void failure(RetrofitError error) { if (error.getLocalizedMessage() != null) if (error.getLocalizedMessage().equals("Invalid access token")) { Toast toast = Toast.makeText(GrievanceDetailsActivity.this, "Session expired", Toast.LENGTH_SHORT); toast.setGravity(Gravity.CENTER | Gravity.CENTER_HORIZONTAL, 0, 0); toast.show(); sessionManager.logoutUser(); startActivity(new Intent(GrievanceDetailsActivity.this, LoginActivity.class)); } else { Toast toast = Toast.makeText(GrievanceDetailsActivity.this, error.getLocalizedMessage(), Toast.LENGTH_SHORT); toast.setGravity(Gravity.CENTER | Gravity.CENTER_HORIZONTAL, 0, 0); toast.show(); } else { Toast toast = Toast.makeText(GrievanceDetailsActivity.this, "An unexpected error occurred while retrieving comments", Toast.LENGTH_SHORT); toast.setGravity(Gravity.CENTER | Gravity.CENTER_HORIZONTAL, 0, 0); toast.show(); } } }); } @Override public void failure(RetrofitError error) { if (error.getLocalizedMessage() != null) if (error.getLocalizedMessage().equals("Invalid access token")) { Toast toast = Toast.makeText(GrievanceDetailsActivity.this, "Session expired", Toast.LENGTH_SHORT); toast.setGravity(Gravity.CENTER | Gravity.CENTER_HORIZONTAL, 0, 0); toast.show(); sessionManager.logoutUser(); startActivity(new Intent(GrievanceDetailsActivity.this, LoginActivity.class)); } else { Toast toast = Toast.makeText(GrievanceDetailsActivity.this, error.getLocalizedMessage(), Toast.LENGTH_SHORT); toast.setGravity(Gravity.CENTER | Gravity.CENTER_HORIZONTAL, 0, 0); toast.show(); } else { Toast toast = Toast.makeText(GrievanceDetailsActivity.this, "An unexpected error occurred while accessing the network", Toast.LENGTH_SHORT); toast.setGravity(Gravity.CENTER | Gravity.CENTER_HORIZONTAL, 0, 0); toast.show(); } progressDialog.dismiss(); } }); } } } }); } //Converts status parameters from server to a more readable form. Probably unnecessary but whatevs private int resolveStatus(String s) { if (s.equals("REGISTERED")) return R.string.registered_info; if (s.equals("PROCESSING")) return R.string.processing_label; if (s.equals("COMPLETED")) return R.string.completed_label; if (s.equals("FORWARDED")) return R.string.forwarded_label; if (s.equals("WITHDRAWN")) return R.string.withdrawn_label; if (s.equals("REJECTED")) return R.string.rejected_label; if (s.equals("REOPENED")) return R.string.reopend_label; return 0; } public static Grievance getGrievance() { return grievance; } //The viewpager custom adapter private class GrievanceImagePagerAdapter extends FragmentPagerAdapter { public GrievanceImagePagerAdapter(FragmentManager fm) { super(fm); } @Override public Fragment getItem(int position) { if (grievance.getSupportDocsSize() != 0) return GrievanceImageFragment.instantiateItem(position, sessionManager.getAccessToken(), grievance.getCrn(), String.valueOf(grievance.getSupportDocsSize() - position)); return null; } @Override public int getCount() { return grievance.getSupportDocsSize(); } } //If lat/lng is available attempt to resolve it to an address private void getAddress(Double lat, Double lng) { Intent intent = new Intent(this, AddressService.class); intent.putExtra(AddressService.LAT, lat); intent.putExtra(AddressService.LNG, lng); startService(intent); } //Handles AddressReadyEvent posted by AddressService on success @SuppressWarnings("unused") public void onEvent(AddressReadyEvent addressReadyEvent) { runOnUiThread(new Runnable() { @Override public void run() { complaintLocation.setText(AddressService.addressResult); } }); } //Subscribes the activity to events @Override protected void onStart() { EventBus.getDefault().register(this); super.onStart(); } //Unsubscribes the activity to events @Override protected void onStop() { EventBus.getDefault().unregister(this); super.onStop(); } } <file_sep>package org.egovernments.egoverp.network; /** * The API endpoints **/ public class ApiUrl { public final static String REFERRER_URL = "172.16.17.32"; public final static String AUTHORIZATION = "Basic ZWdvdi1hcGk6ZWdvd i1hcGk="; /** * Grievances */ public final static String COMPLAINT_GET_TYPES = "/api/v1.0/complaint/getAllTypes"; public final static String COMPLAINT_GET_FREQUENTLY_FILED_TYPES = "/api/v1.0/complaint/getFrequentlyFiledTypes"; public final static String COMPLAINT_CREATE = "/api/v1.0/complaint/create"; public final static String COMPLAINT_DOWNLOAD_SUPPORT_DOCUMENT = "/api/v1.0/complaint/{complaintNo}/downloadSupportDocument"; public final static String COMPLAINT_GET_LOCATION_BY_NAME = "/api/v1.0/complaint/getLocation"; public final static String COMPLAINT_LATEST = "/api/v1.0/complaint/latest/{page}/{pageSize}"; public final static String COMPLAINT_NEARBY = "/api/v1.0/complaint/nearby/{page}/{pageSize}"; public final static String COMPLAINT_SEARCH = "/api/v1.0/complaint/search"; public final static String COMPLAINT_DETAIL = "/api/v1.0/complaint/{complaintNo}/detail"; public final static String COMPLAINT_HISTORY = "/api/v1.0/complaint/{complaintNo}/complaintHistory"; public final static String COMPLAINT_STATUS = "/api/v1.0/complaint/{complaintNo}/status"; public final static String COMPLAINT_UPDATE_STATUS = "/api/v1.0/complaint/{complaintNo}/updateStatus"; /** * Citizen */ public final static String CITIZEN_REGISTER = "/api/v1.0/createCitizen"; public final static String CITIZEN_ACTIVATE = "/api/v1.0/activateCitizen"; public final static String CITIZEN_LOGIN = "/api/oauth/token"; public final static String CITIZEN_PASSWORD_RECOVER = "/api/v1.0/recoverPassword"; public final static String CITIZEN_GET_PROFILE = "/api/v1.0/citizen/getProfile"; public final static String CITIZEN_UPDATE_PROFILE = "/api/v1.0/citizen/updateProfile"; public final static String CITIZEN_LOGOUT = "/api/v1.0/citizen/logout"; public final static String CITIZEN_GET_MY_COMPLAINT = "/api/v1.0/citizen/getMyComplaint/{page}/{pageSize}"; public final static String CITIZEN_SEND_OTP = "/api/v1.0/sendOTP"; /** * Property Tax */ public final static String PROPERTY_TAX_DETAILS = "/restapi/property/propertytaxdetails"; /** * Water Tax */ public final static String WATER_TAX_DETAILS = "/restapi/watercharges/getwatertaxdetails"; } <file_sep>package org.egovernments.egoverp.helper; import android.content.Context; import android.database.Cursor; import android.net.Uri; import android.provider.MediaStore; /** * Returns the absolute path of a file referred to by a uri **/ public class UriPathHelper { public static String getRealPathFromURI(Uri contentUri, Context context) { try { String[] strings = {MediaStore.Images.Media.DATA}; String s = null; Cursor cursor = context.getContentResolver().query(contentUri, strings, null, null, null); int column_index; if (cursor != null) { column_index = cursor .getColumnIndexOrThrow(MediaStore.Images.Media.DATA); cursor.moveToFirst(); s = cursor.getString(column_index); cursor.close(); } if (s != null) { return s; } } catch (Exception e) { return contentUri.getPath(); } return contentUri.getPath(); } }
b86441e8bf984455b8d4c24b18bfb6f9393c8880
[ "Java" ]
23
Java
visheshreddy/EgovApp
21351940f721917f7bbddc1e8500b17f0e969c19
a2737a59b374322c7c5c62c59231bb2d155f03f1
refs/heads/master
<file_sep>Global.include('dev/js/Application/ElementListePoi.js'); class SousMenuListePoi extends DivObject { constructor(parent, id, json, scale, couleur) { super(parent, id); this.clickSignal = new signals.Signal(); this.addClass('sousMenuListePoi'); var b; // l'élément aura une hauteur qui dépend du nombre d'éléments switch (json.length) { case 1: b = 4; break; case 2: b = 3; break; default: b = 2.5; break; } this._balise.css({ 'max-height': 6.5 * scale + 'px', width: 7.5 * scale + 'px', bottom: b * scale + 'px' }); var divListePoi = new DivObject(this._balise, 'listePoi'); divListePoi.addClass('divListePoi'); divListePoi._balise.css({ width: 7 * scale + 'px', 'margin-right': 0.2 * scale + 'px' }); var menu = this; for (let i = 0; i < json.length; i++) { if (json[i] !== undefined) { // certains POIs donnent undefined ??? var e = new ElementListePoi(divListePoi._balise, i + 'elementListePoi', json[i], scale); if (i % 2 == 0) { e.css('background', '#EEE'); } e._balise.click(function () { menu.clickSignal.dispatch(i); // signal pour trigger l'ouverture de la fiche correspondante }); e.tweenAnimate({ opacity: 1, 'margin-left': 0 }, 0.4 + 0.1 * i, 0.2); // animation à l'ouverture } } var s = $('<style></style>') .html(".divListePoi::-webkit-scrollbar-thumb {\ background: "+ couleur + "; \ }"); divListePoi._balise.after(s); } }<file_sep>class Poi extends DivObject { constructor(div, id, json, viewer) { super(div, id + json.id); // parent and id this._json = json; this._viewer = viewer; this._id = id + json.id; this._title = json.title; this._subtitle = json.subtitle; this._text = json.text; this._site= json.site; this._galerie = json.galerie; this._address = json.mainAddress; this._thumbnail = json.thumbnail; this._subcontent = json.subContent; this.addClass("poi"); } }<file_sep>Global.include('dev/librairies/Signal.js'); Global.include('dev/librairies/SignalBinding.js'); Global.include('dev/js/Application.js'); var langue; var textesJSON; var textesJsonFR; var textesJsonDE; var textesJsonEN; var paramsJSON; var poisJSON; var poisJsonFR; var poisJsonDE; var poisJsonEN; var perennesJSON; var perennesJsonFR; var perennesJsonDE; var perennesJsonEN; var jeuxJSON; var jeuxJsonFR; var jeuxJsonDE; var jeuxJsonEN; var favPOIS; var favPoisFR; var favPoisDE; var favPoisEN; var body; var StageWidth; var StageHeight; // lieu de téléchargement des photos pour les POIs var loc = window.location.pathname; var mainFolder = loc.substring(1, loc.lastIndexOf('/')) + '/'; var s = loc.split('/'); var folderImgs = s[1] + '/' + s[2] + '/' + s[3] + '/Documents/MediaBallonDesVosges/'; var t; var application; function initApplication() { // mise en place d'un buffer var img = document.createElement('IMG'); img.setAttribute("src", "datas/buffer.gif"); img.setAttribute("id", "bufferContent"); document.body.appendChild(img); //Chargement du fichier de params $.when($.getJSON("datas/params.json", finChargementParams), $.getJSON("datas/texteFR.json", finChargementTexteFR), $.getJSON("datas/texteDE.json", finChargementTexteDE), $.getJSON("datas/texteEN.json", finChargementTexteEN), $.getJSON("datas/jeuFR.json", finChargementJeuFR), $.getJSON("datas/jeuDE.json", finChargementJeuDE), $.getJSON("datas/jeuEN.json", finChargementJeuEN), $.getJSON("datas/perenneFR.json", finChargementPerenneFR), $.getJSON("datas/perenneDE.json", finChargementPerenneDE), $.getJSON("datas/perenneEN.json", finChargementPerenneEN) ).then(chargementJsonPoiFR); }; function createApplication() { console.log("createApplication"); $('#bufferContent').remove(); body = $("body"); StageWidth = body.width(); StageHeight = body.height(); console.log(StageWidth + " - " + StageHeight); newApplication(); }; function newApplication(lg) { // fr au démarrage if (lg === undefined) lg = 'fr'; $('#Application').remove(); console.log(lg); langue = lg; switch (lg) { case 'fr': textesJSON = textesJsonFR; jeuxJSON = jeuxJsonFR; poisJSON = poisJsonFR; perennesJSON = perennesJsonFR; favPOIS = favPoisFR; break; case 'en': textesJSON = textesJsonEN; jeuxJSON = jeuxJsonEN; poisJSON = poisJsonEN; perennesJSON = perennesJsonEN; favPOIS = favPoisEN; break; case 'de': textesJSON = textesJsonDE; jeuxJSON = jeuxJsonDE; poisJSON = poisJsonDE; perennesJSON = perennesJsonDE; favPOIS = favPoisDE; break; default: break; } application = new Application(); application.lgSignal.add(function (lg) { newApplication(lg); }); } function finChargementParams(data) { //Récupération des données de params paramsJSON = data; langue = paramsJSON.langueParDefault; console.log("langue : " + langue); } function finChargementTexteFR(data) { textesJsonFR = data; } function finChargementTexteDE(data) { textesJsonDE = data; } function finChargementTexteEN(data) { textesJsonEN = data; } function finChargementJeuFR(data) { jeuxJsonFR = data; } function finChargementJeuDE(data) { jeuxJsonDE = data; } function finChargementJeuEN(data) { jeuxJsonEN = data; } function finChargementPerenneFR(data) { perennesJsonFR = data; } function finChargementPerenneDE(data) { perennesJsonDE = data; } function finChargementPerenneEN(data) { perennesJsonEN = data; } // récupération des json des POIs sur l'export du parc // dans le cas d'un échec, on reprend l'ancien fichier qui est sauvegardé function chargementJsonPoiFR() { var token = '<PASSWORD>'; var url = 'https://parc-ballons-vosges.fr/wp-json/wp/v2/exportjson/fr'; fetch(url, { method: 'GET', headers: new Headers({ 'password': <PASSWORD>, 'Content-Type': 'application/json' }) }) .then(response => { return response.json(); }) .then(data => { require('fs').writeFile(mainFolder + 'datas/poiFR.json', JSON.stringify(data), (err) => { if (err) { console.error(err.message); $.when($.getJSON(mainFolder + "datas/poiFR.json", function (data) { poisJsonFR = data; })).then(chargementJsonPoiEN); } else { poisJsonFR = data; chargementJsonPoiEN(); } }); }) .catch((error) => { console.error(error); $.when($.getJSON(mainFolder + "datas/poiFR.json", function (data) { poisJsonFR = data; })).then(chargementJsonPoiEN); }); } function chargementJsonPoiEN() { var token = '<PASSWORD>'; var url = 'https://parc-ballons-vosges.fr/wp-json/wp/v2/exportjson/en'; fetch(url, { method: 'GET', headers: new Headers({ 'password': token, 'Content-Type': 'application/json' }) }) .then(response => { return response.json(); }) .then(data => { require('fs').writeFile(mainFolder + 'datas/poiEN.json', JSON.stringify(data), (err) => { if (err) { console.error(err.message); $.when($.getJSON(mainFolder + "datas/poiEN.json", function (data) { poisJsonEN = data; })).then(chargementJsonPoiDE); } else { poisJsonEN = data; chargementJsonPoiDE(); } }); }) .catch((error) => { console.error(error); $.when($.getJSON(mainFolder + "datas/poiEN.json", function (data) { poisJsonEN = data; })).then(chargementJsonPoiDE); }); } function chargementJsonPoiDE() { var token = '<PASSWORD>'; var url = 'https://parc-ballons-vosges.fr/wp-json/wp/v2/exportjson/de'; fetch(url, { method: 'GET', headers: new Headers({ 'password': token, 'Content-Type': 'application/json' }) }) .then(response => { return response.json(); }) .then(data => { require('fs').writeFile(mainFolder + 'datas/poiDE.json', JSON.stringify(data), (err) => { if (err) { console.error(err.message); $.when($.getJSON(mainFolder + "datas/poiDE.json", function (data) { poisJsonDE = data; })).then(downloadImages); } else { poisJsonDE = data; downloadImages(); } }); }) .catch((error) => { console.error(error); $.when($.getJSON(mainFolder + "datas/poiDE.json", function (data) { poisJsonDE = data; })).then(downloadImages); }); } // téléchargement des images pour les POIs function downloadImages() { // récupération de tous les liens amenant vers une image var imgs = extractPicFileLinks(poisJsonFR); // une photo ayant le même nom qu'un élément déjà dans le dossier ne sera pas à nouveau téléchargé require("electron").remote.require("electron-download-manager").bulkDownload({ urls: imgs }, function (error, finished, errors) { if (error) { console.log("finished: " + finished); console.log("errors: " + errors); getFavouritePOIs(); return; } console.log("all finished"); getFavouritePOIs(); }); } // extraction des POIs "coup de coeur" function getFavouritePOIs() { favPoisFR = extractCoeurPois(poisJsonFR); favPoisEN = extractCoeurPois(poisJsonEN); favPoisDE = extractCoeurPois(poisJsonDE); createApplication(); } /*************************************************/ /**************** UTILS ***********************/ /*************************************************/ function shuffle(a) { var j, x, i; for (i = a.length - 1; i > 0; i--) { j = Math.floor(Math.random() * (i + 1)); x = a[i]; a[i] = a[j]; a[j] = x; } return a; } function somme(int) { var somme = 0; for (let i = 1; i < int; i++) { somme += i; } return somme; } function extractPicFileLinks(obj, imgs) { if (imgs === undefined) imgs = [] for (const i in obj) { if (Array.isArray(obj[i]) || typeof obj[i] === 'object') { imgs.concat(extractPicFileLinks(obj[i], imgs)); } else { if (i == 'thumbnail' || i == 'src') { if (obj[i] != false) { // console.log(obj[i]); imgs.push(obj[i]); } } } } return imgs; } function extractCoeurPois(obj, coeurs) { if (coeurs === undefined) coeurs = [] for (const i in obj) { if (Array.isArray(obj[i]) || typeof obj[i] === 'object') { // console.log('OBJECT'); coeurs.concat(extractCoeurPois(obj[i], coeurs)); } else { if (i == 'favorite') { if (obj[i] != false) { coeurs.push(obj); } } } } return coeurs; }<file_sep>class Global { static getLangue(){ return langue; } static include(file, mod = "text/javascript") { console.log("Je veux ajouter : " + file); // console.log($("head")[0].children); for(var i = 0; i < $("head")[0].children.length; i++){ var n = String($($("head")[0].children[i])[0].src).search(file); // console.log(n); if(n != -1){ console.log("Il existe déjà je return"); return; } } var oScript = document.createElement("script"); oScript.src = file; oScript.type = mod; document.head.appendChild(oScript); } static includeCSS(file){ var oScript = document.createElement("link"); oScript.href = file; oScript.rel = "stylesheet"; document.head.appendChild(oScript); } }<file_sep>Global.include('dev/js/Application/SliderDiaporama.js'); Global.include('dev/js/utils/qrcode.js'); Global.includeCSS('dev/css/Application/Fiche.css'); class Fiche extends DivObject { // constructor(div, poi, id) { constructor(poi, id, couleur) { super(poi._balise, id); this.signaux = { fermer: new signals.Signal() }; this._id = id; this._poi = poi; this._couleur = couleur; // this._langue = paramsJSON.langueParDefault; // mise en place de cette variable car les pois pour les communes seront différents // = pas de contenu dans la fiche // on ne l'affiche pas, mais on a besoin d'une fiche associée afin de récupérer le poi et du coup les coordonnées var isCommune = poi._subtitle === undefined; if (!isCommune) { this.addClass('elementFiche'); //permet la suppression de toutes les fiches avec $('.elementFiche').remove() var divFiche = new DivObject(this._balise, 'divFiche_' + this._id); divFiche.addClass("fiche"); this._divTexte = new DivObject(divFiche._balise, "divtxt_" + this._id); this._divTexte.addClass('divTexte'); this._titre = new BaliseObject(this._divTexte._balise, "h1"); this._titre.css('color', couleur); this._titre.html(poi._title); this._sousTitre = new BaliseObject(this._divTexte._balise, "h3"); this._sousTitre.html(poi._subtitle); this._texte = new BaliseObject(this._divTexte._balise, "p"); this._texte.addClass('paraScroll'); // div pour l'adresse et le bouton de partage de la fiche var bottom = new DivObject(this._divTexte._balise, "divBottom_" + id); bottom.addClass('divBottom'); bottom.css('background', couleur.split(')')[0] + ', 0.85)'); var ad = poi._address; var adressContent = ""; if (ad.name === undefined) adressContent = 'Unknown Adress'; else { if (ad.name != null && ad.name != "") { adressContent += ad.name.toUpperCase(); } if (ad.address != null && ad.address != "") { adressContent += '<br>' + ad.address; } if (ad.mail != null && ad.mail != "") { adressContent += "<br>" + ad.mail; } if (ad.tel != null && ad.tel != "") { adressContent += "<br>" + ad.tel; } } var divAdress = new DivObject(bottom._balise, 'divAdress_' + this._id); divAdress.addClass('divAdress'); divAdress.html(adressContent); var divPartage = new DivObject(bottom._balise, 'partage_' + this._id); divPartage.addClass('divPartage'); divPartage.css('background', couleur); var partage = '<img src="datas/imgs/carte/partage.svg">'; divPartage.html(partage + '<div>PARTAGER LA FICHE</div>'); divPartage._balise.click({ fiche: this }, this.clickPartage); var galerie = []; poi._galerie.forEach(element => { var t = folderImgs; var split = element.src.split('/'); t += split[split.length - 1]; galerie.push(t); }); var subContent = poi._subcontent; // voir la structure de l'export pour comprendre // un poi a un attribut galerie mais a aussi un attribut subcontent qui lui peut aussi avoir un attribut galerie var txtContent = ""; subContent.forEach(element => { txtContent += "<h3>" + element.title + "</h3>"; txtContent += element.text; element.galerie.forEach(pic => { var t = folderImgs; var split = pic.src.split('/'); t += split[split.length - 1]; galerie.push(t); }); }); this._texte.html(poi._text + txtContent); var s = $('<style></style>') .html(".fiche .paraScroll::-webkit-scrollbar-thumb {background: "+ couleur + "; }"); this._texte._balise.after(s); if (poi._thumbnail != false) { var t = folderImgs; var split = poi._thumbnail.split('/'); t += split[split.length - 1]; galerie.push(t); } if (galerie.length == 0) galerie.push('datas/imgs/menu/diaporama/logo.png'); this._btFermer = new DivObject(this._divTexte._balise, this._id + "_BtFermer"); this._btFermer.addClass("ficheBt"); this._btFermer.addClass("ficheBtFermer"); this._btFermer.css('background', couleur); this._btFermer.append('<div class="ficheBtFermerTexte">+</div>'); this._btFermer.x = 500 - this._btFermer.width / 2; this._btFermer.y = - this._btFermer.height / 2; // fermeture de l'élément gérer dans utilsOpenseadragon.js -> removeOverlay() var divSlider = new DivObject(divFiche._balise, 'divSlider_' + this._id); divSlider.addClass('divSlider'); new SliderDiaporama(divSlider._balise, 'slider_' + this._id, galerie, couleur, { height: 540, width: 500 }, 3, 0.5); this._overlay = ficheToOverlay(this); this._balise.toggle(); this._divSlider = divSlider; } // if(commune) } clickPartage(e) { var f = e.data.fiche; var site = f._poi._site $('.slidePartage').remove(); var slidePartage = new DivObject(f._divSlider._balise, 'slidePartage_' + f._id); slidePartage.addClass('slidePartage'); slidePartage.css('background', f._couleur); var enTete = new BaliseObject(slidePartage._balise, 'h3'); enTete.html('RECEVOIR LA FICHE'); var champTel = new DivObject(slidePartage._balise, 'champTel_' + f._id); champTel.addClass('champTel'); champTel.html('+'); var ind = new DivObject(slidePartage._balise, 'indication_' + f._id); ind.addClass('indicationTel'); ind.html(paramsJSON.indicationTel); var captionQR = new BaliseObject(slidePartage._balise, 'span', 'captionQR_' + f._id); captionQR.addClass('captionQR'); captionQR.html('EN FLASHANT LE CODE'); var divQR = new DivObject(slidePartage._balise, 'img_qrCode_' + f._id); divQR.addClass('divQR'); var qr = new QRCode('img_qrCode_' + f._id); qr.makeCode(site); var captionTEL = new BaliseObject(slidePartage._balise, 'span', 'captionTEL_' + f._id); captionTEL.addClass('captionTEL'); captionTEL.html('EN ENTRANT VOTRE NUMÉRO DE PORTABLE'); var divPave = new DivObject(slidePartage._balise, 'divPave_' + f._id); divPave.addClass('paveNum'); divPave.css('color', f._couleur); var captionFeedBack = new BaliseObject(slidePartage._balise, 'span', 'captionFeedBack' + f._id); captionFeedBack.addClass('captionFeedBack'); $('.captionFeedBack').css('display', 'none'); var feedBack = new Img(slidePartage._balise, 'feedBack' + f._id, ''); feedBack.addClass('feedBack'); $('.feedBack').css('display', 'none'); for (var i = 1; i < 13; i++) { var chiffre = new DivObject(divPave._balise, i + 'chiffre_' + f._id); chiffre.addClass('chiffre'); chiffre.attr('num', i); chiffre._balise.css({ left: ((i - 1) % 3) * 45 + 'px', top: Math.trunc((i - 1) / 3) * 60 + 'px' }); if (i == 10) { chiffre.html('<'); chiffre.css('color', 'red'); } else if (i == 11) chiffre.html(0); else if (i == 12) { chiffre.html('✓'); chiffre.css('color', 'white'); chiffre.css('background', 'green'); } else chiffre.html(i); chiffre._balise.click(function (e) { e.stopPropagation(); var num = $(this).attr('num'); var tel = champTel._balise.html(); if (num == 10) { if (tel.length > 1) tel = tel.slice(0, -1); } else if (num == 11) tel += '0'; else if (num == 12) { $('.captionQR').remove(); $('.captionTEL').remove(); $('.indicationTel').remove(); $('.divQR').remove(); $('.paveNum').remove(); $('.captionFeedBack').css('display', ''); $('.feedBack').css('display', ''); var content = 'Bonjour,%20veuillez%20trouver%20la%20fiche%20sur%20le%20lien%20suivant%20:%20' + site; var num = '00' + tel.slice(1); var url = 'https://www.ovh.com/cgi-bin/sms/http2sms.cgi?&account=sms-ss271992-1&contentType=text/json&login=pnrbv&password=<PASSWORD>&from=Anamnesia&to=' + num + '&message=' + content; console.log(url); fetch(url, { method: 'GET' }) .then(response => { return response.json(); }) .then(data => { console.log(data); if (data.status == 100) { // succès envoi captionFeedBack.html('MESSAGE ENVOYÉ AVEC SUCCÈS'); feedBack.attr('src', 'datas/imgs/carte/feedBackPositif.png'); } else { // echec var message = data.message captionFeedBack.html('ERREUR : ' + message); feedBack.attr('src', 'datas/imgs/carte/feedBackNegatif.png'); } }) .catch((error) => { console.error(error); captionFeedBack.html('ERREUR : ' + error); feedBack.attr('src', 'datas/imgs/carte/feedBackNegatif.png'); }); } else tel += num; champTel.html(tel); }); } var btnFermer = new DivObject(slidePartage._balise, f._id + "_btnFermer"); btnFermer.html('<div>+</div>'); btnFermer.addClass('btnFermerPartage'); btnFermer._balise.click(function () { slidePartage._balise.remove(); }); slidePartage.tweenAnimate({ opacity: 1 }); } get fermerSignal() { return this.signaux.fermer; } }<file_sep>class ElementSousMenu extends BlocMenu { constructor(parent, json, params, scale) { var x = params.x; var y = params.y; var taille = params.taille; var couleur = params.couleur; // params: parent, id, x, y, taille, couleur, nom du menu auquel il appartient super(parent, 'sousMenuElement_' + json.id, x * scale, y * scale, taille * scale, couleur); this._json = json; this._scale = scale; this._lien = json.lien; this._type = json.type; this._params = params; this.addClass('elementSousMenu'); var titre = new BaliseObject(this._balise, 'h2', 'titre_' + this._id) titre.html(this._json.titre.toUpperCase()); } init() { this._balise.css({ "width": this._taille, "height": this._taille, "left": this._x, "bottom": this._y, "background": this._couleur, "opacity": 0 }); this.tweenAnimate({ opacity: this._params.opacity }, 0.6 + this._params.num * 0.1, 0.5); } }<file_sep>Global.includeCSS('dev/css/Application/FichePerenne.css'); Global.include('dev/js/Application/SliderDiaporama.js'); class FichePerenne extends DivObject { constructor(parent, id, json, couleur) { super(parent, id); this.addClass('pagePerenne'); this.addClass('page'); $('#elementsDeco').css('display', 'none'); console.log(json); this._id = id; this._json = json; this._couleur = couleur; this.signaux = { finFermer: new signals.Signal() } this.clickSignal = new signals.Signal(); var fp = this; this._balise.click(function () { fp.clickSignal.dispatch(); }); //////////////// // TOP var divTop = new DivObject(this._balise, 'divTop_' + this._id); divTop.addClass('divTop'); var link = (json.imgTop == "") ? "datas/imgs/perenne/test/top.jpg" : json.imgTop; // var imageTop = new Img(divTop._balise, 'imageTop_' + this._id, link); var imageTop = new DivObject(divTop._balise, 'imageTop_' + this._id); imageTop.addClass('topImage'); imageTop._balise.css({ background: 'url('+link+')', 'background-size': 'cover', 'background-position': 'center' }); var s = $('<style>\ .pagePerenne h1, .pagePerenne h2, .pagePerenne h3 {\ color : ' + couleur + ';\ }\ </style>'); divTop._balise.after(s); var titre = new BaliseObject(divTop._balise, 'h1'); titre.addClass('topTitre'); // titre.html(loremTitre.toUpperCase()); titre.html(json.titre.toUpperCase()); // TOP ////////////////// var divContain = new DivObject(this._balise, 'divContain_' + this._id); divContain.addClass('divContain'); ////////////////// // GAUCHE var divLeft = new DivObject(divContain._balise, 'divLeft_' + this._id); divLeft.addClass('flex'); var introLeft = new BaliseObject(divLeft._balise, 'b', 'introLeft_' + this._id); introLeft.html(json.soustitre); var paraLeft = new BaliseObject(divLeft._balise, 'p', 'paraLeft_' + this._id); paraLeft.html(json.blocGauche1); paraLeft.css('margin-top', '30px'); // image var divImage = new DivObject(divLeft._balise, 'divImage_' + this._id); divImage.addClass('divImage'); var img = new Img(divImage._balise, 'imgLeft_' + this._id, json.imgGauche); var divTextImage = new DivObject(divImage._balise, 'divTextImage_' + this._id); divTextImage.css('background', couleur); divTextImage.html(json.desImgGauche); //TEXTE var text = new DivObject(divLeft._balise, 'textLeft_' + this._id); text.css('margin-top', '100px'); text.html(json.blocGauche2); // GAUCHE ////////////////////// ///////////////////////////// // DROITE var divRight = new DivObject(divContain._balise, 'divRight' + this._id); divRight.addClass('flex'); ////////// premier slider var divSliderComm = new DivObject(divRight._balise, 'divSliderComm_' + this._id); divSliderComm.addClass('sliderComm'); if (json.imgSlider1.length != 0) { new SliderDiaporama(divSliderComm._balise, 'slider1_' + this._id, json.imgSlider1, couleur, 400, 3, 0.5); } ///////////////////// var squareRight = new DivObject(divSliderComm._balise, 'squareRight_' + this._id); squareRight.addClass('squareRight'); squareRight.css('background', couleur); squareRight.html(json.blocSlider1); var textRight = new DivObject(divRight._balise, 'textRight_' + this._id); textRight.addClass('textRight'); textRight.html(json.blocDroit1); ////////// deuxième slider if (json.imgSlider2.length != 0) { var divSliderComm2 = new DivObject(divRight._balise, 'divSliderComm2_' + this._id); divSliderComm2.addClass('sliderComm'); new SliderDiaporama(divSliderComm2._balise, 'slider2_' + this._id, json.imgSlider2, couleur, 700, 4, 0.5); divSliderComm2.css('margin-top', '70px'); } ///////////////////// var divBottom = new DivObject(divRight._balise, 'divBottom_' + this._id); divBottom.addClass('divBottom'); divBottom.css('background', couleur); // divBottom.html(titreH2 + lorem); divBottom.html(json.blocDroit2); // DROITE ///////////////////////// this.css('opacity', 0); } init() { TweenLite.to(this._balise, 1, { opacity: 1 }); } supprimerFiche(fiche) { fiche._balise.remove(); } // GETTERS get finFermerSignal() { return this.signaux.finFermer; } }<file_sep>Global.include('dev/js/Application/ElementSousMenu.js'); Global.includeCSS('dev/css/Application/SousMenu.css'); Global.include('dev/js/Application/SousMenuListePoi.js'); class SousMenu extends DivObject { constructor(parent, json, titreElement, couleur, scale, lien) { super(parent, 'sousmenu'); this.addClass('sousmenu'); this._json = json; this._scale = scale; this._couleur = couleur; this._titreElement = titreElement; // enregistrement de tous les liens successifs dans un tableau pour pouvoir faire un retour en arrière this._lien = [lien]; this._jsonPoi = poisJSON[lien]; this._jsonPerenne = perennesJSON[lien]; // console.log(poisJSON); // console.log(lien); // console.log(this._jsonPoi); // console.log(this._jsonPerenne); this._carte = new Carte( $('#Application'), textesJSON.Application.Carte, couleur); this.signalFermer = new signals.Signal(); this.closeCarteSignal = new signals.Signal(); this.stopBackSignal = new signals.Signal(); // pour arrêter le défilement des images en background this.clickPerenne = new signals.Signal(); this.css('bottom', 1 * scale); var tailleEltTxt = 5.5; ///////////////////////////////// // element avec titre et texte this._divText = new DivObject(this._balise, "divText_" + this._id); this._divText.addClass('text_sousmenu'); this._divText._balise.css({ bottom: 4 * scale, left: -tailleEltTxt * scale, height: (tailleEltTxt - 2) * scale, width: (tailleEltTxt - 1) * scale, padding: scale + 'px ' + scale / 2 + 'px' }); var titre = new BaliseObject(this._divText._balise, 'h1', 'titre_' + this._id); var s = titreElement.toUpperCase(); var size = 840 / s.length; if (size > 65) { size = 65; } if (size < 37) { size = 37; } titre.html(s); titre._balise.css({ color: couleur, 'font-size': size + 'px', 'margin-top': '-20px' }); this._titre = titre; var texte = new BaliseObject(this._divText._balise, 'p', 'txt_' + this._id); texte.html(json.texte); texte._balise.css({ 'max-height': 1.8 * scale, 'margin-top': 0.3 * scale }); // scroll couleur var st = $('<style></style>') .html('#txt_' + this._id + "::-webkit-scrollbar-thumb {\ background: "+ couleur + "; \ }"); texte._balise.after(st); this._texte = texte; this._btnFermer = new DivObject(this._divText._balise, 'btnFermer_' + this._id); this._btnFermer.addClass('btnFermerSousMenu'); this._btnFermer._balise.css({ bottom: 4.5 * scale, height: scale, width: scale, background: couleur }); this._btnFermer.html('<span>+</span>'); var ssMenu = this; this.btnShouldClose = true; // click on btn while close sous menu // if false -> come back to previous menu this._btnFermer._balise.click(function () { $('#filterBackground').css('display', ''); $('#overlayPerenne').css('display', 'none'); if (ssMenu.btnShouldClose) { // fermer le sous menu, revenir au menu principal ssMenu.close(); ssMenu.signalFermer.dispatch(); } else { // revenir au menu précédent $('#jeu').remove(); $('.sousMenuListePoi').remove(); $('.divBtnCarteElement').remove(); ssMenu._btnFermer.html('<span>+</span>'); ssMenu._divssSousMenu.html(""); titre.html(s); titre.css('font-size', size + 'px'); texte.html(json.texte); ssMenu.btnShouldClose = true; ssMenu.reinitializeContent(); ssMenu.oldLienJson(ssMenu); ssMenu._sousMenuElements = []; ssMenu.affichageMenuElements(json.sousmenu); ssMenu.initSousMenuElement(); ssMenu._lien = [lien]; ssMenu._jsonPoi = poisJSON[lien]; ssMenu._jsonPerenne = perennesJSON[lien]; ssMenu._divText.tweenAnimate({ bottom: 4 * scale + 'px' }); ssMenu._divssSousMenu.tweenAnimate({ bottom: 4 * scale + 'px' }); } }); // sous elements this._sousMenuElements = []; this.affichageMenuElements(json.sousmenu); this._divssSousMenu = new DivObject(this._balise, 'ssSousMenu_' + this._id); this._divssSousMenu.addClass('ssSousMenu'); this._divssSousMenu._balise.css({ bottom: 4 * scale, left: -3 * scale, width: 1.5 * scale, height: (tailleEltTxt - 0.5) * scale, padding: 0.25 * scale, background: couleur }); this._inSousMenu = false; // pour savoir s'il faudra retirer ou non un étage dans _lien lorsque que l'on clique sur un élément 'carte' ou 'menu' dans le menu de gauche } reinitializeContent() { this._carte.removeAllOverlays(); $('.poi').remove(); $('.pagePerenne').remove(); this._fichePerenne = null; } init() { this._divText.tweenAnimate({ left: 2 * this._scale }, 0, 0.6); this._btnFermer.tweenAnimate({ bottom: 5.5 * this._scale }, 0.6, 0.3); this.initSousMenuElement(); this._divssSousMenu.tweenAnimate({ left: 0 }); if (this._lien[0] == 'coeur') { console.log('coup de coeur'); this._carte.init(); this.displayPoiOnMap(favPOIS); } } initSousMenuElement() { this._sousMenuElements.forEach(element => { element.init(); }); } // animation de fermeture du sous menu close() { $('#filterBackground').css('display', ''); $('#elementsDeco').css('display', ''); this._btnFermer.tweenAnimate({ bottom: 5.5 * this._scale }, 0, 0.3); this._divText.tweenAnimate({ left: -2 * this._scale, opacity: 0 }); this._sousMenuElements.forEach(element => { element.tweenAnimate({ opacity: 0 }); }); this._divssSousMenu.tweenAnimate({ left: - 2 * this._scale }); } // gestion de l'affichage du petit menu à gauche affichageMenuGauche(sMenu, json, num, type, couleur) { sMenu._btnFermer.html('<span class="noRotation">⤺</span>'); sMenu.btnShouldClose = false; var s = json[num].titre.toUpperCase(); var size = 840 / s.length; if (size > 65) { size = 65; } if (size < 37) { size = 37; } sMenu._titre.html(s); sMenu._titre.css('font-size', size + 'px'); if (json[num].texte !== undefined) { sMenu._texte.html(json[num].texte); } $('#divLeft').remove(); var divLeft = new DivObject(sMenu._divssSousMenu._balise, 'divLeft'); var ssTitre = new BaliseObject(divLeft._balise, 'h1'); ssTitre.html(sMenu._titreElement.toUpperCase()); divLeft.append('<hr>'); for (var i = 0; i < json.length; i++) { var span = new BaliseObject(divLeft._balise, 'span', 'spanSSMenu_' + i); span.html(json[i].titre.toUpperCase()); span.attr('num', i); // pour pouvoir récupérer le numéro lorsque l'on clique dessus if (i == num) { span.addClass('selected'); } span._balise.click(function () { sMenu.clickMenuGauche(sMenu, $(this).attr('num'), json, couleur); }); divLeft.append('<hr>'); } if (type != 'jeu' && type != 'poi') { var jsonElements = json[num].sousmenu; console.log(jsonElements); if (type == 'carte') { $('#filterBackground').css('display', 'none'); sMenu.sousElementsPOI(jsonElements); } else { sMenu.affichageMenuElements(jsonElements); } } } // gestion d'un clic sur un élément du menu de gauche clickMenuGauche(sMenu, num, json, couleur) { var type = json[num].type; var lien = json[num].lien; sMenu._carte.removeAllOverlays(); $('.selected').removeClass('selected'); $('#spanSSMenu_' + num).addClass('selected'); var s = json[num].titre.toUpperCase(); var size = 840 / s.length; if (size > 65) { size = 65; } if (size < 37) { size = 37; } sMenu._titre.html(s); sMenu._titre.css('font-size', size + 'px'); if (json[num].texte !== undefined) { sMenu._texte.html(json[num].texte); } switch (type) { case 'perenne': sMenu.reinitializeContent(); $('.divBtnCarteElement').remove(); $('.sousMenuListePoi').remove(); $('.elementSousMenu').remove(); $('#overlayPerenne').css('display', ''); sMenu._divText.tweenAnimate({ bottom: 4 * sMenu._scale + 'px' }); sMenu._divssSousMenu.tweenAnimate({ bottom: 4 * sMenu._scale + 'px' }); // fermeture et animations de tout ce qui est déjà à l'écran // check si besoin de descendre dans l'arborescence des éléments if (sMenu._inSousMenu) { sMenu.oldLienJson(sMenu); sMenu._inSousMenu = false; } var fp = new FichePerenne($('#Application'), 'fichePerenne', sMenu.getJsonPerenne(sMenu, lien), couleur); fp.clickSignal.add(function () { sMenu.clickPerenne.dispatch(); // pour la veille }); fp.init(); break; case 'poi': sMenu.reinitializeContent(); $('.elementSousMenu').remove(); $('.divBtnCarteElement').remove(); $('#overlayPerenne').css('display', 'none'); if (sMenu._inSousMenu) { sMenu.oldLienJson(sMenu); sMenu._inSousMenu = false; } var toDisp; switch (lien) { case "communes": case "sommets": case "cols": json.forEach(j => { if (j.lien == lien) toDisp = j.points; }); break; default: toDisp = sMenu.getJsonPoi(sMenu, lien); break; } sMenu.displayPoiOnMap(toDisp); sMenu.affichageMenuGauche(sMenu, json, num, type, couleur); break; case 'carte': sMenu.reinitializeContent(); $('#filterBackground').css('display', 'none'); $('.elementSousMenu').remove(); $('#overlayPerenne').css('display', 'none'); var jsonElements = json[num].sousmenu; if (sMenu._inSousMenu) sMenu.oldLienJson(sMenu); else sMenu._inSousMenu = true; sMenu._lien.push(lien); sMenu.sousElementsPOI(jsonElements); break; case 'jeu': var jeu = new Jeu($('#Application'), lien, couleur, sMenu._scale); jeu.clickSignal.add(function () { sMenu.clickPerenne.dispatch(); // veille }); jeu.init(); sMenu.affichageMenuGauche(sMenu, json, num, type, couleur); break; default: // type sous menu if (sMenu._inSousMenu) { sMenu.oldLienJson(sMenu); } if (lien !== undefined) sMenu._lien.push(lien); $('.sousMenuListePoi').remove(); $('.divBtnCarteElement').remove(); sMenu._divText.tweenAnimate({ bottom: 4 * sMenu._scale + 'px' }); sMenu._divssSousMenu.tweenAnimate({ bottom: 4 * sMenu._scale + 'px' }); sMenu._inSousMenu = true; var jsonElements = json[num].sousmenu; sMenu.affichageMenuElements(jsonElements); break; } } // récupération des éléments json pour les éléments des pérennes et des POIs // on repère notre emplacement dans l'aborescence grace au tableau this._lien getJsonPoi(sMenu, lien) { console.log(sMenu._lien); console.log(lien); var json = poisJSON; sMenu._lien.forEach(element => { if (json !== undefined && json[element] !== undefined) json = json[element]; }); return json[lien]; } getJsonPerenne(sMenu, lien) { console.log(sMenu._lien); console.log(lien); var json = perennesJSON; sMenu._lien.forEach(element => { if (json !== undefined && json[element] !== undefined) json = json[element]; }); return json[lien]; } // reculer d'un noeud dans l'arborescence + maj des variable contenant les éléments de pérenne et pois correspondant oldLienJson(sMenu) { sMenu._lien.pop(); var newJsonPoi = poisJSON; var newJsonPerenne = perennesJSON; sMenu._lien.forEach(key => { newJsonPoi = newJsonPoi[key]; newJsonPerenne = newJsonPerenne[key]; }); sMenu._jsonPoi = newJsonPoi; sMenu._jsonPerenne = newJsonPerenne; } displayPoiOnMap(json) { $('#filterBackground').css('display', 'none'); var b; switch (json.length) { case 1: b = 4; break; case 2: b = 4; break; default: b = 1.5 + json.length; break; } if (b > 8) { b = 8; } this._divText.tweenAnimate({ bottom: b * this._scale + 'px' }); this._divssSousMenu.tweenAnimate({ bottom: b * this._scale + 'px' }); $('#sousMenuListePOI').remove(); var sMenu = this; var smlp = new SousMenuListePoi(sMenu._parent, 'sousMenuListePOI', json, sMenu._scale, sMenu._couleur); smlp.clickSignal.add(function (num) { console.log(num); sMenu._carte.clickOnPoi(sMenu._carte._fiches[num], sMenu._carte); // ouverture de la fiche correspondante lors d'un clic sur un élément de la liste }); setTimeout(function () { sMenu._carte.initPOIsandFiches(json); sMenu._carte.init(); }, 1000); // timer pour performances au niveau graphisme } // AFFICHAGE DE SOUS ELEMENTS DE MENU NORMAUX ( = les carrés) // LIENS VERS UNE <NAME>, UNE CARTE, OU UN AUTRE SOUS MENU affichageMenuElements(json) { this.sousMenuElements = json; var i = 0; var sMenu = this; this._sousMenuElements.forEach(element => { var num = i; var lien = element._lien; var type = element._type; element._balise.click(function () { console.log('click lien : ' + lien); console.log('click type : ' + type); switch (type) { case 'perenne': sMenu.reinitializeContent(); $('#overlayPerenne').css('display', ''); var fp = new FichePerenne($('#Application'), 'fichePerenne', sMenu.getJsonPerenne(sMenu, lien), element._params.couleur); fp.clickSignal.add(function () { sMenu.clickPerenne.dispatch(); }); fp.init(); break; case 'carte': $('#overlayPerenne').css('display', 'none'); sMenu.reinitializeContent(); $('.elementSousMenu').remove(); sMenu._inSousMenu = true; sMenu._lien.push(lien); sMenu.affichageMenuGauche(sMenu, json, num, type, element._params.couleur); break; case 'poi': $('#overlayPerenne').css('display', 'none'); sMenu.reinitializeContent(); $('.elementSousMenu').remove(); var toDisp; switch (lien) { case "communes": case "sommets": case "cols": json.forEach(j => { if (j.lien == lien) toDisp = j.points; }); break; default: toDisp = sMenu.getJsonPoi(sMenu, lien); break; } sMenu.displayPoiOnMap(toDisp); sMenu.affichageMenuGauche(sMenu, json, num, type, element._params.couleur); break; case 'jeu': var jeu = new Jeu($('#Application'), lien, element._params.couleur, sMenu._scale); jeu.clickSignal.add(function () { sMenu.clickPerenne.dispatch(); // remet le compteur pour la veille à 0 }); jeu.init(); sMenu.affichageMenuGauche(sMenu, json, num, type, element._params.couleur); break; default: if (lien !== undefined) sMenu._lien.push(lien); sMenu._inSousMenu = true; sMenu.affichageMenuGauche(sMenu, json, num, type, element._params.couleur); break; } }); i++; }); sMenu.initSousMenuElement(); } // remove old elements and display the new ones // buttons are filters for poi overlays // sous menu pour les POIs avec des filtres sousElementsPOI(json) { var sMenu = this; sMenu.sousMenuElements = []; $('.divBtnCarteElement').remove(); var divBtn = new DivObject(sMenu._divText._balise, 'divBtnFiltre_' + sMenu._id); divBtn.addClass('divBtnCarteElement'); var divs = []; var allPOIs = []; // suppression des anciens elements for (let i = 0; i < json.length; i++) { var jsonElt = json[i]; var div = new DivObject(divBtn._balise, i + 'btnsFiltre_' + sMenu._id); div.addClass('btnsFiltre'); div.css('top', Math.trunc(i / 2) * 70 + 'px'); div.css(i % 2 == 0 ? 'left' : 'right', 0); var text = jsonElt.titre; var span = new BaliseObject(div._balise, 'span'); span.html(text.toUpperCase()); var sw = new DivObject(div._balise, i + 'sw_' + sMenu._id); sw.addClass('iconCarteElement'); var label = new BaliseObject(sw._balise, 'label', i + 'labelSwitch' + sMenu._id); label.addClass('switch'); label.attr('for', i + 'cbSwitch_' + sMenu._id); label._balise.after('<input type="checkbox" id="' + i + 'cbSwitch_' + sMenu._id + '" checked><span class="sliderSwitch"></span>'); div.isOpen = true; div.jsonPOIs = sMenu.getJsonPoi(sMenu, jsonElt.lien); allPOIs = allPOIs.concat(div.jsonPOIs); $('#' + i + 'labelSwitch' + sMenu._id).click(function () { sMenu.reinitializeContent(); sMenu._carte.removeAllOverlays(); divs[i].isOpen = !divs[i].isOpen; var toDisp = []; divs.forEach(d => { if (d.isOpen) { toDisp = toDisp.concat(d.jsonPOIs); console.log(d.jsonPOIs); } }); sMenu.displayPoiOnMap(toDisp); }); div.css('color', sMenu._couleur); divs.push(div); } var style = new BaliseObject(divBtn._balise, 'style'); style.html('input:checked + .sliderSwitch:before {\ background-color: '+ sMenu._couleur + ';\ }'); sMenu.displayPoiOnMap(allPOIs); } // affichage des éléments sous menu set sousMenuElements(jsonElements) { $('.elementSousMenu').remove(); this._sousMenuElements = []; var emplacements = [ { x: 9.5, y: 1.5 }, { x: 7.5, y: 3.5 }, { x: 9.5, y: 5.5 }, { x: 7.5, y: 7.5 }, { x: 9.5, y: 9.5 }, { x: 6.5, y: 9.5 }, { x: 4.5, y: 10 }, { x: 2.5, y: 11 }, { x: 6, y: 12 }, { x: 5.5, y: 2 }, { x: 3.5, y: 1.5 } ]; var taille = 2; for (let i = 0; i < jsonElements.length; i++) { var jsonElt = jsonElements[i]; var params = { x: emplacements[i].x, y: emplacements[i].y, taille: taille, couleur: this._couleur, num: i, opacity: (Math.floor(Math.random() * 2) == 0) ? 1 : 0.9 } var eltSsMenu = new ElementSousMenu(this._balise, jsonElt, params, this._scale); this._sousMenuElements.push(eltSsMenu); } } }<file_sep>Global.include('dev/js/utils/zSlider.js'); Global.includeCSS('dev/css/utils/zSlider.css'); class SliderDiaporama extends DivObject { constructor(parent, id, jsonImages, couleur, size, interval, duration) { super(parent, id); this._json = jsonImages; // NE PAS CHANGER LES NOMS DE CLASSE var divSlider = new DivObject(this._balise, 'divSlider_' + this._id); divSlider.addClass('divSlider'); var carousselRight = new DivObject(divSlider._balise, 'caroussel_' + this._id); carousselRight.addClass('z-slide-wrap'); carousselRight.addClass('top'); var ul = new BaliseObject(carousselRight._balise, 'ul'); ul.addClass('z-slide-content'); var length; if (jsonImages.length == 2 && jsonImages[1] == undefined) // bugs dans ce cas là length = 1; else if (jsonImages.length == 3 && jsonImages[2] == undefined) // idem length = 2; else length = jsonImages.length; if (length == 2) { // idem, plantage avec seulement 2 images. On en met donc au minimum 3 var first = jsonImages[0]; jsonImages.push(first); length = 3; } for (let i = 0; i < length; i++) { var li = new BaliseObject(ul._balise, 'li', 'li_' + i); li.css('background', 'url(' + jsonImages[i] + ')'); li.css('background-size', 'cover'); li.css('background-position', 'center'); li.addClass('z-slide-item'); } // size peut être de 2 type : soit size = 20px ou size = {height: 20px, width: 20px} $('#divSlider_' + this._id + ' .z-slide-wrap').css({ height: size.height ? size.height : size + 'px', width: size.width ? size.width : size + 'px' }); // API zSlider new Slider('#caroussel_' + this._id, '.z-slide-item', { interval: interval, duration: duration }); $('#divSlider_' + this._id + ' .z-slide-indicator').css('background', couleur); } }<file_sep>var R = 6371; function degreesToRadians(degrees) { return degrees * Math.PI / 180; } function pow(base, exposant) { return Math.pow(base, exposant); } // distance entre deux points avec coordonnées connues function distanceBtw2Coord(lat1, lon1, lat2, lon2) { dLat = degreesToRadians(lat2 - lat1); dLon = degreesToRadians(lon2 - lon1); l1 = degreesToRadians(lat1); l2 = degreesToRadians(lat2); a = pow(Math.sin(dLat / 2), 2) + pow(Math.sin(dLon / 2), 2) * Math.cos(l1) * Math.cos(l2); c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a)); return c * R; } // renvoi le json overlay (nécessaire pour openseadragon) correspondant aux paramètres du poi function poiToOverlay(p) { var origineCarte = textesJSON.Application.Carte.origineCarte; var finCarte = textesJSON.Application.Carte.finCarte; height = 8000; width = 8000; var lat = p._address.lat; var long = p._address.long; var dPixel = Math.sqrt(pow(height, 2) + pow(width, 2)); var dDistance = distanceBtw2Coord(finCarte.lat, finCarte.long, origineCarte.lat, origineCarte.long); var echelle = dDistance / dPixel; // en km/Pixel var coefXLat = pow(Math.cos((lat - origineCarte.lat) * 0.25), 2); var coefXLatPixel = (1 - coefXLat) * width * echelle; var coefYLong = pow(Math.cos((long - origineCarte.long) * 0.22), 2); var coefYLongPixel = (1 - coefYLong) * height * echelle; var x = distanceBtw2Coord(lat, long, lat, origineCarte.long); var y = distanceBtw2Coord(lat, long, origineCarte.lat, long); var x = x + coefXLatPixel; var y = y - coefYLongPixel; x = x / echelle; y = y / echelle; pourcentageX = x / width; pourcentageY = y / height; var overlay = { element: p._balise[0], // balise html de l'élément poi: p, // pour pouvoir le récupérer si besoin id: p._id, x: pourcentageX, y: pourcentageY, placement: 'CENTER' } return overlay; } // param : Img.class function layerToOverlay(l) { var overlay = { element: l._balise[0], layer: l, id: l._id, x: 0, y: 0, width: 1, height: 1 } l.css('display', 'none'); return overlay; } function ficheToOverlay(f) { var p = f._poi; var overlay = poiToOverlay(p); var over = { element: f._balise[0], id: f._id, x: overlay.x, y: overlay.y, placement: 'CENTER' } return over; } <file_sep>class ElementListePoi extends DivObject { constructor(parent, id, json, scale) { super(parent, id + json.id); this.addClass('elementListePoi'); var divImg = new DivObject(this._balise, 'image_' + this._id); divImg.addClass('divImgEltLiPoi'); var divTexte = new DivObject(this._balise, 'texte_' + this._id); var txt = new DivObject(divTexte._balise, 'txtLiPoiElt_' + this._id); txt.addClass('poiLiEltTexte'); var ad = json.mainAddress; if (ad !== undefined) { // si vrai = commune if (ad.name !== undefined) { var contact = ad.address; txt.html('<b>' + ad.name.toUpperCase() + '</b><br><p style="font-size:16px">' + contact + '</p>'); } else txt.html('<b>' + json.title.toUpperCase() + '</b><br><p style="font-size:16px">Unknown</p>') } else txt.html('<b>' + json.title.toUpperCase() + '</b>') this._balise.css({ height: scale - 5 + 'px' }); // margin bottom : 5px var thumbnail = json.thumbnail; if (!thumbnail) { thumbnail = 'datas/imgs/carte/poi/img_manquant.jpg'; } else { var t = folderImgs; var split = thumbnail.split('/'); t += split[split.length - 1]; thumbnail = t; } divImg._balise.css({ width: 2 * scale + 'px', height: scale - 5 + 'px', background: 'url(' + thumbnail + ')', 'background-size': 'cover', 'background-position': 'center' }); } }<file_sep>Global.include('dev/js/Application/ElementMenu.js'); Global.include('dev/js/Application/ElementDecoMenu.js'); Global.include('dev/js/Application/SousMenu.js'); Global.include('dev/js/Application/Jeu.js'); Global.includeCSS('dev/css/Application/Menu.css'); class Menu extends DivObject { constructor(parent, json) { super(parent, "menu"); this.addClass('page'); this._json = json; this._fondImgs = []; this._couleursAssociees = []; this.langueSignal = new signals.Signal(); this.backgroundDiaporama = json.diaporama; var overlay = new Img(this._balise, 'filterBackground', 'datas/imgs/menu/diaporama/overlay_img.png'); overlay.addClass('page'); overlay.css('z-index', 1); var overlayPerenne = new Img(this._balise, 'overlayPerenne', 'datas/imgs/perenne/texture_fiche.png'); overlayPerenne.addClass('page'); overlayPerenne.css('z-index', 1); overlayPerenne.css('display', 'none'); this.backPause = false; this._setIntervalFonction = 0; // id of the setInterval founction used to switch between background images var scale = 140; // unité en pixels pour la taille d'un élément. Beaucoup d'éléments repose sur ce chiffre // le changer modifiera donc tous ces éléments de la bonne manière // cependant, comme ce n'est pas accessible dans le css, tout n'est pas lié à ce chiffre this._scale = scale; this._sousMenu = null; // VEILLE this._tempsInactivite = 0; var tempsInactifMax = paramsJSON.tempsInactivity; var menu = this; var veille = setInterval(function () { if (menu._sousMenu != null && menu._tempsInactivite == tempsInactifMax) { menu._sousMenu.close(); menu._sousMenu.signalFermer.dispatch(); // clearInterval(veille); menu._sousMenu = null; } menu._tempsInactivite++; }, 1000); this._balise.click(function () { menu._tempsInactivite = 0; }); this._divEltsMenu = new DivObject(this._parent, "elementsMenu"); var bandeauLangues = new DivObject(this._divEltsMenu._balise, "bandeauLangues"); bandeauLangues.css('height', scale + 'px'); this._btnLangues = []; for (var i = 0; i < paramsJSON.langues.length; i++) { var langue = paramsJSON.langues[i].langue; var bt = new DivObject(bandeauLangues._balise, this._id + "_BtLang_" + langue); bt.addClass("menuBtn"); bt.addClass("menuBtnLangue"); if (langue == Global.getLangue()) bt.addClass('menuBtnLangueSelect') var right = 40 + 120 * i; bt.css('right', right + 'px'); bt.append('<div class="menuBtnLangueTexte">' + String(langue).toUpperCase() + '</div>'); this._btnLangues.push(bt); bt._balise.on("click touchstart", null, { instance: this }, this.clickElementMenuLang); } var maxHeight = 0; // pour la taille des divs. On va récupérer l'élément le plus haut pour avoir la taille max this._menuElements = []; for (let i = 0; i < json.element.length; i++) { var element = new ElementMenu(this._divEltsMenu._balise, json.element[i], scale); var bas = element._y + element._taille; if (bas > maxHeight) { maxHeight = bas; } this._menuElements.push(element); } this._decoMenuElements = []; this._divEltsDeco = new DivObject(this._balise, "elementsDeco"); for (let i = 0; i < json.deco.menu.length; i++) { var eltDeco = new ElementDecoMenu(this._divEltsDeco._balise, this._json.deco.menu[i], this._couleursAssociees[0], scale); var bas = eltDeco._y + 1; if (bas > maxHeight) { maxHeight = bas; } this._decoMenuElements.push(eltDeco); } var tailleDiv = maxHeight * scale; this._divEltsMenu.css('height', tailleDiv + 'px'); this._divEltsDeco.css('height', tailleDiv + 'px'); var i = 0; this._menuElements.forEach(element => { element._balise.click({ menu: this }, this.clickElementMenu); i++; }); } init() { this.displayBackground(); var menu = this; setTimeout(function () { menu._menuElements.forEach(menuElement => { menuElement.init(); }); menu._decoMenuElements.forEach(decoElement => { decoElement.init(); }); }, 2000); } clickElementMenu(e) { console.log('click Element in menu'); var menu = e.data.menu; menu._tempsInactivite = 0; menu.tidyElements(menu, $(this).attr('id')); menu.supprimerCarte(); menu.supprimerPerenne(); menu.supprimerJeu(); $('.sousMenuListePoi').remove(); $('#overlayPerenne').css('display', 'none'); $('#filterBackground').css('display', ''); menu.showSousMenu($(this)); } supprimerCarte() { $('#Carte').remove(); $(body).find('.elementFiche').remove(); this.playBackground(); } supprimerPerenne() { $('.pagePerenne').remove(); } supprimerJeu() { $('#jeu').remove(); } supprimerSousMenu() { $('.sousmenu').remove(); $('.sousMenuListePoi').remove(); this._sousMenu = null; } clickElementMenuLang(e) { console.log('click langue'); var instance = e.data.instance; var s = String($(this).attr('id')); s = s.replace(instance._id + "_BtLang_", ''); instance.langueSignal.dispatch(s); // redemarrage de l'interface avec changement des fichiers json } // fond d'écran changeant displayBackground() { var images = this._fondImgs; var nbImgs = images.length; var i = 0; var menu = this; var duree = paramsJSON.dureeFadeFond; clearInterval(this._setIntervalFonction); if (nbImgs == 0) { this._setIntervalFonction = 0; } else { TweenLite.to(images[i]._balise, duree, { opacity: 1 }); this._setIntervalFonction = setInterval(function () { if (!menu.backPause) { var current = i % nbImgs; var next = (i + 1) % nbImgs; TweenLite.to(images[current]._balise, duree, { opacity: 0 }); TweenLite.to(images[next]._balise, duree, { opacity: 1 }); var newColor = menu._couleursAssociees[next]; menu._decoMenuElements.forEach(e => { e.changeColor(newColor); }); i++; } }, paramsJSON.dureeFond * 1000); // temps entre chaque execution de la fonction } } pauseBackground() { this.backPause = true; } playBackground() { this.backPause = false; } toggleMenu(menu) { menu._balise.toggle(); } // "rangement" de tous les éléments en bas de l'écran // celui qui a été séléctionné reste plus grand tidyElements(menu, id) { var left = 0; var tailleSelect = 2.5; menu._menuElements.forEach(element => { if (element._id == id) { element.tweenAnimate({ height: tailleSelect * menu._scale, width: tailleSelect * menu._scale, top: '', bottom: 0, left: left * menu._scale, 'line-height': '', 'font-size': '25px' }); element._front.tweenAnimate({ background: element._src_fond != '#' ? element._couleur + 'A5' : element._couleur }); left += tailleSelect; } else { element.tweenAnimate({ height: menu._scale, width: menu._scale, top: '', bottom: 0, left: left * menu._scale, 'line-height': '20px', 'font-size': '10px' }); element._front.tweenAnimate({ background: element._couleur }) left++; } }); } moveDecoElements(menu) { menu._divEltsDeco.tweenAnimate({ bottom: menu._scale + 'px' }); for (let i = 0; i < menu._decoMenuElements.length; i++) { var element = menu._decoMenuElements[i]; var jsonElt = menu._json.deco.sousmenu[i]; element.tweenAnimate({ left: jsonElt.x * menu._scale, bottom: jsonElt.y * menu._scale, opacity: 0 }, 0, 0); element.tweenAnimate({ opacity: jsonElt.a }); } } showSousMenu(menuElt) { var menu = this; var lien = menuElt.attr('lien'); console.log('lien : ' + lien); var couleur = menuElt.children().css('background-color'); couleur = couleur.split(/[()]/); couleur = couleur[1].split(','); couleur = 'rgb(' + couleur[0] + ',' + couleur[1] + ',' + couleur[2] + ')'; var json = menu._json.SousMenu[lien]; $('.sousmenu').remove(); var titre = menuElt.find('.elementMenu_titre').html(); if (lien == 'local') { $('#overlayPerenne').css('display', ''); $('#filterBackground').css('display', 'none'); var fp = new FichePerenne($('#Application'), 'fichePerenne', perennesJSON['autour de moi'], couleur); fp.clickSignal.add(function () { sMenu.clickPerenne.dispatch(); }); fp.init(); } else { var sm = new SousMenu(menu._balise, json, titre, couleur, menu._scale, lien); sm._carte.carteOpenSignal.add(function () { menu.pauseBackground() }); sm._carte.clickSignal.add(function () { menu._tempsInactivite = 0; }); sm.closeCarteSignal.add(menu.playBackground); sm.clickPerenne.add(function () { menu._tempsInactivite = 0; }); sm.signalFermer.add(function () { menu.fermerSousMenu(menu); }); sm.stopBackSignal.add(function () { menu.pauseBackground(); $('.backgroundImage').css('display', 'none'); }); menu._sousMenu = sm; sm.init(); menu.moveDecoElements(menu); setTimeout(function () { menu.backgroundDiaporama = json.diaporama; menu.displayBackground(); }, 2050); } } // animation de fermeture du sous menu fermerSousMenu(menu) { $('.backgroundImage').css('display', 'block'); menu.supprimerCarte(); menu.supprimerPerenne(); menu.supprimerJeu(); menu._divEltsDeco.tweenAnimate({ bottom: 0, onComplete: function () { menu.supprimerSousMenu(); } }); menu._menuElements.forEach(menuElement => { menuElement.init(); }); menu._decoMenuElements.forEach(decoElement => { decoElement.init(); }); setTimeout(function () { menu.backgroundDiaporama = menu._json.diaporama; menu.displayBackground(); }, 3050); } // GETTERS // mets à jour les photos de fond set backgroundDiaporama(imagesJson) { for (let i = 0; i < this._fondImgs.length; i++) { this._fondImgs[i]._balise.remove(); } this._fondImgs = []; this._couleursAssociees = []; if (imagesJson.length != 0) { for (let i = 0; i < imagesJson.length; i++) { console.log("new back image : " + i); var img = imagesJson[i]; var image = new Img(this._balise, "fond_img_" + img.id, img.src); image.addClass('page'); image.addClass('backgroundImage'); image.css('opacity', 0); this._fondImgs.push(image); this._couleursAssociees.push(img.color); } } } }<file_sep># vosgesAnamnesia Application de bureau avec Electron pour un musée des Vosges <file_sep>/** * @name zSlider * @version 0.0.1 * @author creeperyang<<EMAIL>> * @description A pure JavaScript Carousel/Slider plugin that works well at Mobile/PC. */ 'use strict'; (function(root, factory) { if(typeof define === 'function' && define.amd) { // amd define([], factory); } else if(typeof exports === 'object') { // cmd module.exports = factory(); } else { // global. In browser, root will be window root.Slider = factory(); } })(this, function() { /** * defaults: Slider默认配置项 */ var defaults = { 'current': 0, // 初始化时显示项index 'duration': 0.8, // 单位:秒 'minPercentToSlide': null, // swipe至少多少距离时触发slide 'autoplay': true, // 是否自动轮播 'direction': 'left', // 自动轮播方向 'interval': 5 // 单位:秒,最好大于2(尤其开启自动轮播时) }; var nextTick = function(fn) { setTimeout(fn, 0); }; var capitalizeFirstLetter = function(text) { return text.charAt(0).toUpperCase() + text.slice(1); }; var setCompatibleStyle = (function(style) { var prefixes = ['moz', 'webkit', 'o', 'ms']; var len = prefixes.length; function getGoodPropName(prop) { var tmp; var i; if(prop in style) { return prop; } else { prop = capitalizeFirstLetter(prop); for(i = 0; i < len; i++) { tmp = prefixes[i] + prop; if(tmp in style) { break; } } return tmp; } } return function(el, prop, value) { el.style[getGoodPropName(prop)] = value; }; })(document.body.style); // old way to create event var createEvent = function(type, bubbles, cancelable) { var e; e = document.createEvent('Event'); e.initEvent(type, bubbles, cancelable); return e; }; var setTransition = function(pre, cur, next, preTransition, curTransition, nextTransition) { if(typeof preTransition === 'undefined') { preTransition = ''; } if(typeof curTransition === 'undefined') { curTransition = preTransition; } if(typeof nextTransition === 'undefined') { nextTransition = curTransition; } setCompatibleStyle(pre, 'transition', preTransition); setCompatibleStyle(cur, 'transition', curTransition); setCompatibleStyle(next, 'transition', nextTransition); }; var move = function(pre, cur, next, distance, width) { setCompatibleStyle(cur, 'transform', 'translate3d(' + distance + 'px, 0, 0)' ); setCompatibleStyle(pre, 'transform', 'translate3d(' + (distance - width) + 'px, 0, 0)' ); setCompatibleStyle(next, 'transform', 'translate3d(' + (distance + width) + 'px, 0, 0)' ); }; var prepareSlideItem = function(slider, container, list, count, index, width) { var realCount = count; var lastIndex; var item; var clone; var i; if(count === 2) { // clone and insert to dom clone = list[0].cloneNode(true); container.appendChild(clone); list.push(clone); clone = list[1].cloneNode(true); container.appendChild(clone); list.push(clone); count = 4; } lastIndex = count - 1; if(index > lastIndex || index < 0) { index = 0; } if(index !== 0) { list = list.splice(index, count - index).concat(list); } list[0].uuid = 0; list[lastIndex].uuid = lastIndex; setCompatibleStyle(list[0], 'transform', 'translate3d(0, 0, 0)'); setCompatibleStyle(list[lastIndex], 'transform', 'translate3d(-' + width + 'px, 0, 0)'); for (i = 1; i < lastIndex; i++) { item = list[i]; item.uuid = i; setCompatibleStyle(item, 'transform', 'translate3d(' + width + 'px, 0, 0)'); } slider.container = container; slider.list = list; slider.realCount = realCount; slider.count = count; slider.current = index; }; // create and layout indicators // http://jsperf.com/createnode-vs-clonenode, use clone instead create var prepareIndicator = function(slider, wrapClassName, className, howMany, activeIndex, activeClass) { var item = document.createElement('span'); var indicatorWrap = document.createElement('div'); var indicators = []; var i; indicatorWrap.className = wrapClassName || 'z-slide-indicator'; item.className = className || 'z-slide-dot'; for(i = 1; i < howMany; i++) { indicators.push(indicatorWrap.appendChild(item.cloneNode(false))); } indicators.push(indicatorWrap.appendChild(item)); indicators[activeIndex].className = 'z-slide-dot ' + activeClass; slider.indicatorWrap = indicatorWrap; slider.indicators = indicators; slider.container.appendChild(indicatorWrap); nextTick(function() { indicatorWrap.style.left = (slider.width - getComputedStyle(indicatorWrap).width.replace('px', '')) / 2 + 'px'; }); }; // update indicator style var updateIndicator = function(indicators, pre, cur) { indicators[pre].className = 'z-slide-dot'; indicators[cur].className = 'z-slide-dot active'; }; // invocated when resize var resetStyle = function(slider) { var lastIndex = slider.count - 1; var width = slider.width; var list = slider.list; var i; var indicatorWrap = slider.indicatorWrap; setCompatibleStyle(list[lastIndex], 'transform', 'translate3d(-' + width + 'px, 0, 0)'); for (i = 1; i < lastIndex; i++) { setCompatibleStyle(list[i], 'transform', 'translate3d(' + width + 'px, 0, 0)'); } indicatorWrap.style.left = (width - getComputedStyle(indicatorWrap).width.replace('px', '')) / 2 + 'px'; }; // swipestart handler var startHandler = function(ev, slider) { if(slider.options.autoplay) { clearTimeout(slider.timeId); } }; // swipemove handler var moveHandler = function(ev, slider, diffX) { var list = slider.list; var cur = list[0]; var pre = list[list.length - 1]; var next = list[1]; setTransition(pre, cur, next, ''); move(pre, cur, next, diffX, slider.width); }; // swipeend handler var endHandler = function(ev, slider, diffX) { var direction; if(Math.abs(diffX) < slider.compareDistance) { direction = 'restore'; } else { direction = diffX < 0 ? 'left' : 'right'; } slider.slide(direction, diffX); if(slider.options.autoplay) { slider.autoplay(); } }; // æŽ§ä»¶è¡Œä¸ºæ·»åŠ (Interact with user's touch/mousedown) // Bind events compatible with pc and Generate custom events like 'swipe','tap', ... // refer to http://blog.mobiscroll.com/working-with-touch-events/ var bindEvents = function(slider, startHandler, moveHandler, endHandler) { var container = slider.container; var startX, startY; var endX, endY; var diffX, diffY; var touch; var action; var scroll; var sort; var swipe; var sortTimer; function getCoord(e, c) { return /touch/.test(e.type) ? (e.originalEvent || e).changedTouches[0]['page' + c] : e['page' + c]; } function testTouch(e) { if (e.type === 'touchstart') { touch = true; } else if (touch) { touch = false; return false; } return true; } function onStart(ev) { if(action || !testTouch(ev)) { return; } action = true; startX = getCoord(ev, 'X'); startY = getCoord(ev, 'Y'); diffX = 0; diffY = 0; sortTimer = setTimeout(function() { sort = true; }, 200); startHandler(ev, slider); // swipestart this.dispatchEvent(createEvent('swipestart', true, true)); if (ev.type === 'mousedown') { ev.preventDefault(); document.addEventListener('mousemove', onMove, false); document.addEventListener('mouseup', onEnd, false); } } function onMove(ev) { var customEvent; if(!action) { return; } endX = getCoord(ev, 'X'); endY = getCoord(ev, 'Y'); diffX = endX - startX; diffY = endY - startY; if (!sort && !swipe && !scroll) { if (Math.abs(diffY) > 10) { // It's a scroll scroll = true; // Android 4.0(maybe more?) will not fire touchend event customEvent = createEvent('touchend', true, true); this.dispatchEvent(customEvent); } else if (Math.abs(diffX) > 7) { // It's a swipe swipe = true; } } if (swipe) { ev.preventDefault(); // Kill page scroll ev.stopPropagation(); moveHandler(ev, slider, diffX); // Handle swipe customEvent = createEvent('swipe', true, true); customEvent.movement = { diffX: diffX, diffY: diffY }; container.dispatchEvent(customEvent); } if(sort) { ev.preventDefault(); customEvent = createEvent('sort', true, true); container.dispatchEvent(customEvent); } if (Math.abs(diffX) > 5 || Math.abs(diffY) > 5) { clearTimeout(sortTimer); } } function onEnd(ev) { var customEvent; if(!action) { return; } action = false; if (swipe) { // Handle swipe end endHandler(ev, slider, diffX); // trigger 'swipeend' customEvent = createEvent('swipeend', true, true); customEvent.customData = { diffX: diffX, diffY: diffY }; container.dispatchEvent(customEvent); } else if (sort) { // trigger 'sortend' customEvent = createEvent('sortend', true, true); container.dispatchEvent(customEvent); } else if (!scroll && Math.abs(diffX) < 5 && Math.abs(diffY) < 5) { // Tap if (ev.type === 'touchend') { // Prevent phantom clicks // ev.preventDefault(); // let elements like `a` do default behavior } // trigger 'tap' customEvent = createEvent('tap', true, true); container.dispatchEvent(customEvent); } swipe = false; sort = false; scroll = false; clearTimeout(sortTimer); if (ev.type === 'mouseup') { document.removeEventListener('mousemove', onMove); document.removeEventListener('mouseup', onEnd); } } container.addEventListener('mousedown', onStart, false); container.addEventListener('touchstart', onStart, false); container.addEventListener('touchmove', onMove, false); container.addEventListener('touchend', onEnd, false); container.addEventListener('touchcancel', onEnd, false); }; var resizeHandler = function(slider) { if(slider.options.autoplay && slider.timeId !== null) { clearTimeout(slider.timeId); slider.timeId = null; } if(slider.resizeTimeId) { clearTimeout(slider.resizeTimeId); } slider.resizeTimeId = setTimeout(function() { slider.width = slider.container.clientWidth; if(slider.options.minPercentToSlide) { slider.compareDistance = slider.width * slider.options.minPercentToSlide; } resetStyle(slider); if(slider.options.autoplay) { slider.autoplay(); } }, 200); }; /** * @name Slider 轮播 * @param {String/DOM} containerSelector container选择器,或DOMå…ƒç´ ã€‚ * @param {String/Array} itemSelector item选择器,或DOMå…ƒç´ æ•°ç»„ã€‚ * @param {Object} 配置项,可选。 * @return {Object} Slider实例 */ function Slider(containerSelector, itemSelector, options) { var container; var list; var count; var width; var self; // console.log(containerSelector); if(!containerSelector || !itemSelector) { console.error('Slider: arguments error.'); return this; } container = typeof containerSelector === 'string' ? document.querySelector(containerSelector) : containerSelector; if(!container) { console.error('Slider: cannot find container.'); return this; } list = typeof itemSelector === 'string' ? container.querySelectorAll(itemSelector) : itemSelector; if(!list || !list.length) { console.error('Slider: no item inside container.'); return this; } self = this; // extend options options = options || {}; for (var name in defaults) { if (options[name] === undefined) { options[name] = defaults[name]; } } // list is a StaticNodeList rather than a real array, convert it. list = Array.prototype.slice.call(list); count = list.length; if(count === 1) { return; } // container width width = container.clientWidth; this.options = options; this.compareDistance = 0; this.timeId = null; this.width = width; if(options.minPercentToSlide) { this.compareDistance = width * options.minPercentToSlide; } // setup slider prepareSlideItem(this, container, list, count, options.current, width); prepareIndicator(this, 'z-slide-indicator', 'z-slide-dot', this.realCount || count, this.current, 'active'); bindEvents(this, startHandler, moveHandler, endHandler); // resize window.addEventListener('resize', function() { resizeHandler(self); }, false); // auto play if(options.autoplay) { this.interval = Math.max(2000, options.interval * 1000); this.autoplay(); } } Slider.version = '0.0.1'; Slider.defaults = defaults; Slider.prototype.autoplay = function() { var interval = this.interval; var self = this; this.timeId = setTimeout(function() { self.slide(); self.autoplay(); }, interval); }; Slider.prototype.slide = function(direction, diffX) { var list = this.list; var current = this.current; var count = this.count; var width = this.width; var duration = this.options.duration; var transitionText; var cur, pre, next, customEvent; direction = direction || this.options.direction; diffX = diffX || 0; if(direction === 'left') { list.push(list.shift()); this.current = (current + 1) % count; duration *= 1 - Math.abs(diffX) / width; } else if(direction === 'right'){ list.unshift(list.pop()); this.current = (current - 1 + count) % count; duration *= 1 - Math.abs(diffX) / width; } else { duration *= Math.abs(diffX) / width; } cur = list[0]; pre = list[count - 1]; next = list[1]; transitionText = 'transform ' + duration + 's linear'; if(direction === 'left' || (direction === 'restore' && diffX > 0)) { setTransition(pre, cur, next, transitionText, transitionText, ''); } else if(direction === 'right' || (direction === 'restore' && diffX < 0)) { setTransition(pre, cur, next, '', transitionText, transitionText); } move(pre, cur, next, 0, width); if(this.realCount === 2) { this.current = this.current % 2; updateIndicator(this.indicators, current % 2 , this.current); } else { updateIndicator(this.indicators, current, this.current); } customEvent = createEvent('slideend', true, true); customEvent.slider = this; customEvent.currentItem = cur; this.container.dispatchEvent(customEvent); }; return Slider; });<file_sep>Global.includeCSS('dev/css/Application/ElementMenu.css'); class ElementDecoMenu extends BlocMenu { constructor(parent, json, couleur, scale) { // params: parent, id, x, y, taille, couleur super(parent, "decoElement_" + json.id, json.x, json.y, scale, couleur); this._json = json; this._alpha = this._json.a; this._scale = scale; this.addClass('elementDecoMenu'); } init() { this.tweenAnimate({ "width": this._taille, "height": this._taille, "left": this._x * this._scale, "bottom": this._y * this._scale, "background": this._couleur, "opacity": 0 }, 0, 0); this.tweenAnimate({ opacity: this._alpha }, 1, 1); } }
3f6fd753c0fa2ba5cf54250149655a97a1011d78
[ "JavaScript", "Markdown" ]
15
JavaScript
maximefuchs/vosgesAnamnesia
1be8c482b1dbccf74a9a946241d1c67bd810dc05
434462a2d6f0e6a847ecc13a566c16cbc502378f
refs/heads/master
<file_sep>var pharmaTracker = artifacts.require("pharmaTracker.sol"); module.exports = function(deployer) { deployer.deploy(pharmaTracker); };<file_sep># Blockchain-Buildathon 2019 Blockchain Buildathon Competition
9afd63dfdb1c4e24a9b0139689d525d873176ee4
[ "JavaScript", "Markdown" ]
2
JavaScript
ethansachse/Blockchain-Buildathon
696af7d0841a5e0b590d4aec2fe5ede7985c7437
ba7b0af7bd6f7d1bac9bc8b03aa319ba9e8b03fd
refs/heads/main
<file_sep>from scapy.all import ARP, Ether, srp import socket import argparse import socket import threading from queue import Queue s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) s.connect(("8.8.8.8", 80)) ran = (s.getsockname()[0]) my = ran[0:11]+"1/24" s.close() target = my # make the ARP packet arp = ARP(pdst=target) # ether packet ether = Ether(dst="ff:ff:ff:ff:ff:ff") # the packet packet = ether/arp result = srp(packet, timeout=4, verbose=0)[0] hosts = [] for sent, received in result: # for each response, append ip and mac address to `clients` list hosts.append(received.psrc) for host in hosts: # print(host) q = Queue() open_ports = [] def port_scan(port): try: s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.settimeout(0.5) s.connect((host, port)) return True except: return False def filling(p_list): for port in p_list: q.put(port) def chandler(): while not q.empty(): port = q.get() if port_scan(port): # print(port) open_ports.append(port) p_list = range(1, 1024) filling(p_list) t_list = [] for th in range(100): thread = threading.Thread(target=chandler) t_list.append(thread) for thread in t_list: thread.start() for thread in t_list: thread.join() comb = [host] for ha in open_ports: comb.append(ha) print(comb) <file_sep># ice blablabla <file_sep>from scapy.all import ARP, Ether, srp import socket import argparse import socket import threading from queue import Queue s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) s.connect(("8.8.8.8", 80)) ran = (s.getsockname()[0]) my = ran[0:11]+"1/24" s.close() target = my # make the ARP packet arp = ARP(pdst=target) # ether packet ether = Ether(dst="ff:ff:ff:ff:ff:ff") # the packet packet = ether/arp result = srp(packet, timeout=4, verbose=0)[0] hosts = [] for sent, received in result: # for each response, append ip and mac address to `clients` list hosts.append(received.psrc) print(hosts)
e463deb484112ec5316fd03b8b16e890734b2310
[ "Markdown", "Python" ]
3
Python
myname36/ice
702a79e2c00e99bd5d37fbc3aa36a689d0028645
1b8dc5aebe1bbbf60eb652c6bfdc5c349cc1f032
refs/heads/master
<file_sep>using System.Collections; using System.Collections.Generic; using UnityEngine; public class MapController : MonoBehaviour { [SerializeField] public int width = 16; [SerializeField] public int height = 12; [SerializeField] public GameObject mapTilePrefab; [SerializeField] public Color wallColor; [SerializeField] public Color pathColor; [SerializeField] public int smoothIterations = 5; MapUnit[,] gameMap; /// <summary> /// Create the map of tiles on start /// </summary> void Start () { InitializeGameMap(); LinkMap(); GenerateMap(1, 1); SmoothMap(smoothIterations); } /// <summary> /// Link the map units together so they know their neighbors for quick calculating. /// </summary> void LinkMap() { for (int col = 0; col < width; col++) { for (int row = 0; row < height; row++) { var tileInfo = gameMap[col, row]; if (row - 1 >= 0) { tileInfo.neighbors[0] = gameMap[col, row - 1]; } if (row + 1 < height) { tileInfo.neighbors[1] = gameMap[col, row + 1]; } if (col - 1 >= 0) { tileInfo.neighbors[2] = gameMap[col - 1, row]; } if (col + 1 < width) { tileInfo.neighbors[3] = gameMap[col + 1, row]; } } } } /// <summary> /// Resets the numbers shown on the map representing move distances. /// </summary> public void ResetMap() { MapUnit[] allChildren = GetComponentsInChildren<MapUnit>(); foreach (MapUnit m in allChildren) { m.ResetDistance(); } } /// <summary> /// Reset the highlight color of all map units /// </summary> public void ResetHighlights() { MapUnit[] allChildren = GetComponentsInChildren<MapUnit>(); foreach (MapUnit m in allChildren) { m.ResetHighlight(); } } /// <summary> /// Initializes the game map. /// </summary> void InitializeGameMap() { gameMap = new MapUnit[width, height]; for (int col = 0; col < width; col++) { for (int row = 0; row < height; row++) { GameObject tile = Instantiate(mapTilePrefab) as GameObject; tile.transform.position = new Vector3(col, row, 0); tile.GetComponent<SpriteRenderer>().color = wallColor; tile.transform.SetParent(transform); gameMap[col, row] = tile.GetComponent<MapUnit>(); } } } /// <summary> /// Run a smoothing passes on the map after it is generated to /// give it an airier feel. /// </summary> void SmoothMap(int iterations) { for (int i = 0; i < iterations; i++) { for (int col = 0; col < width; col++) { for (int row = 0; row < height; row++) { if (gameMap[col, row].wall) { if (GetWallNeighbors(col, row) == 1) { gameMap[col, row].wall = false; gameMap[col, row].GetComponent<SpriteRenderer>().color = pathColor; } } } } } } /// <summary> /// Count number of neighbors that are walls. This version does not count where the map meets the outside world as a wall. /// </summary> /// <returns>The wall neighbors.</returns> /// <param name="locCol">Location col.</param> /// <param name="locRow">Location row.</param> int GetWallNeighbors(int locCol, int locRow) { int total = 0; for (int col = (locCol - 1 >= 0) ? locCol - 1 : 0; (col < locCol + 2) && (col < width); col++) { for (int row = (locRow - 1 >= 0) ? locRow - 1 : 0; (row < locRow + 2) && (row < height); row++) { if (row == locRow && col == locCol) { continue; } if (gameMap[col, row].wall) { total++; } } } return total; } /// <summary> /// Let's carve out a random maze map for the demo. /// </summary> /// <param name="col">Col.</param> /// <param name="row">Row.</param> void GenerateMap(int col, int row) { var tileInfo = gameMap[col, row]; gameMap[col, row].GetComponent<SpriteRenderer>().color = pathColor; tileInfo.visited = true; tileInfo.wall = false; List<int[]> validDirs = GetValidDirs(col, row); while (validDirs.Count > 0) { int[] chosenDir = validDirs[Random.Range(0, validDirs.Count)]; int nextCol = (int)((chosenDir[0] + col) * 0.5); int nextRow = (int)((chosenDir[1] + row) * 0.5); gameMap[nextCol, nextRow].wall = false; gameMap[nextCol, nextRow].GetComponent<SpriteRenderer>().color = pathColor; GenerateMap(chosenDir[0], chosenDir[1]); validDirs = GetValidDirs(col, row); } } /// <summary> /// find current valid dirs for maze generation. /// </summary> /// <returns>The valid dirs.</returns> /// <param name="col">Col.</param> /// <param name="row">Row.</param> List<int[]> GetValidDirs(int col, int row) { List<int[]> validDirs = new List<int[]>(); if ((col - 2 >= 0) && !gameMap[col - 2, row].visited) { validDirs.Add(new int[] { col - 2, row }); } if ((col + 2 < width) && !gameMap[col + 2, row].visited) { validDirs.Add(new int[] { col + 2, row }); } if ((row - 2 >= 0) && !gameMap[col, row - 2].visited) { validDirs.Add(new int[] { col, row - 2 }); } if ((row + 2 < height) && !gameMap[col, row + 2].visited) { validDirs.Add(new int[] { col, row + 2 }); } return validDirs; } } <file_sep>using UnityEngine; /// <summary> /// MapUnits assume that their parent is a map controller. /// </summary> public class MapUnit : MonoBehaviour { [SerializeField] public SpriteRenderer spriteHighlight; [SerializeField] public Color startHighlightColor; [SerializeField] public Color destinationHighlightColor; [SerializeField] public int startingMoves = 7; private const int INFINITY_DISTANCE = 100; public MapUnit[] neighbors = new MapUnit[4]; public bool visited = false; public bool wall = true; public int currentDistance = INFINITY_DISTANCE; /// <summary> /// when mouse button press happens, if this tile is not part of an /// existing distance interaction, then we start a new distance /// interaction. /// </summary> public void OnMouseDown() { if (currentDistance == INFINITY_DISTANCE) { GetComponentInParent<MapController>().ResetMap(); Propagate(startingMoves); } } /// <summary> /// when mouse enters this tile, we either set a mouse over highlight /// if the user has not selected a starting tile yet or we highlight the /// path from this tile if they do have a starting tile in range. /// </summary> public void OnMouseEnter() { GetComponentInParent<MapController>().ResetHighlights(); if (currentDistance == INFINITY_DISTANCE) { spriteHighlight.color = startHighlightColor; } else { HighlightPath(); } } /// <summary> /// Sets a highlight color on each tile involved in pathing to this one. /// </summary> public void HighlightPath() { if (wall == true || currentDistance == INFINITY_DISTANCE) { return; } spriteHighlight.color = destinationHighlightColor; foreach (MapUnit neighbor in neighbors) { if (neighbor == null) { continue; } if (neighbor.currentDistance == (currentDistance - 1)) { neighbor.HighlightPath(); break; } } } /// <summary> /// clear the number representing distance from most recently clicked tile /// </summary> public void ResetDistance() { currentDistance = INFINITY_DISTANCE; gameObject.GetComponentInChildren<TextMesh>().text = ""; } /// <summary> /// Resets the highlight. /// </summary> public void ResetHighlight() { spriteHighlight.color = Color.clear; } /// <summary> /// when an initial tile is selected, we show the number of moves to each tile in range. /// I opted to show all the moves in range right away as a prompt to help user know where /// to move the mouse, but if we wanted to only show the moves numbers for the active path /// we could just wait and not set the text mesh until the highlights are applied. /// </summary> /// <param name="movesLeft">Moves left.</param> public void Propagate(int movesLeft) { if (wall == true) { return; } if (currentDistance < (startingMoves - movesLeft)) { return; } if (movesLeft > 0) { currentDistance = startingMoves - movesLeft; gameObject.GetComponentInChildren<TextMesh>().text = " " + currentDistance.ToString(); foreach (MapUnit neighbor in neighbors) { if (neighbor != null) { neighbor.Propagate(movesLeft - 1); } } } } }
678f9d867fa32fe8f9689e26f0c7df57f4be1985
[ "C#" ]
2
C#
cutopia/GridMap
fe11c24b257654391635ec95a22135c1dee5b677
2153f6b60c61f92ed6c57c6a6c20bfb99b09e908
refs/heads/master
<file_sep>#!/bin/bash echo "changing all eps to png for file $1" cat $1 | sed -e s/\\.eps/\\.png/g > $1.tmp cat $1.tmp | sed -e s/eps\}/png\}/g > $1 rm -f $1.tmp
b440005948c443b6605f64bf862f447860c68b42
[ "Shell" ]
1
Shell
yantailee/ipsysctl-tutorial
0dda94cf007a68cd70d6c886de3e1acb6449d91d
fd582bc0bdfc5a173c5d2609a5fb4661dd7b3415
refs/heads/master
<file_sep>#include "creature.h" #include "world.h" #include "species.h" #include "RandomInt.h" #include <cassert> #include <iostream> #include <cstdlib> #include <ctime> RandomInt r; Creature::Creature(Species * s, unsigned x, unsigned y, World * w):canfly(false),rest(false){ mySpot =new Location(x,y); myNextMove = 1; myWorld = w; mySpecies = s; if (w != NULL){ //if there is a board, put it on the board in the //right spot if it is unoccupied if (w->emptyCreature(x,y)) w->at(x).at(y) = this; } } Creature::Creature(Species * s, unsigned x, unsigned y, World * w, bool condition1, bool condition2){ mySpot =new Location(x,y); myNextMove = 1; myWorld = w; mySpecies = s; canfly = condition1; rest = condition2; speCreAct = 0; if (w != NULL){ //if there is a board, put it on the board in the //right spot if it is unoccupied if (w->emptyCreature(x,y)) w->at(x).at(y) = this; } } char Creature::getSymbol() const { return mySpecies->symbol(); } void Creature::act(){ // Special Creature can fly after 5 general moves // Special Creature can hop along with changing // direction after 3 general moves after it flies if ((checkFly()) && (checkRest())) { if ((speCreActed() == 5) || (speCreActed() == 13) || (speCreActed() == 21) || (speCreActed() == 29)) { fly(); } else if (speCreActed() == 8) { hop(); mySpot->turnLeft(); } else if (speCreActed() == 16) { hop(); mySpot->turnRight(); } else if (speCreActed() == 24) { mySpot->turnLeft(); hop(); } else if (speCreActed() == 32) { mySpot->turnRight(); hop(); assignSpeCreActed(0); } else { act_1(); } assignSpeCreActed(speCreActed()+1); } else if ((checkFly()) && (!checkRest())) { if (speCreActed() == 5) { fly(); assignSpeCreActed(0); } else { act_1(); } assignSpeCreActed(speCreActed()+1); } else { act_1(); } } void Creature::act_1() { char action = mySpecies->execute(myNextMove, this); //returns 'h' for hop, 'i' for infect, 'l' for turn left and //'r' for turn right. //next the method determines whether the move is possible and if it is //the creature does the thing. switch (action) { case 'h':hop(); break; case 'i':infect(); break; case 'l':mySpot->turnLeft(); break; case 'r':mySpot->turnRight(); break; } return; } void Creature::hop(){ // if the space ahead is on the board and empty then change my location // and update the board with my new location. Location * l = mySpot->getAhead(myWorld->getWidth(), myWorld->getHeight()); if (l != Location::offBoard){ //l is on the board unsigned x = l->getX(); unsigned y = l->getY(); if (myWorld->emptyCreature(x,y)){ // and l is empty //reflect the move in the world myWorld->at(x).at(y) = this; myWorld->at(mySpot->getX()).at(mySpot->getY()) = myWorld->getEmpty(); //update my record of where I am delete mySpot; mySpot = l; } } } void Creature::fly(){ // if the space ahead is on the board and empty then change my location // and update the board with my new location. unsigned a = r.Generate(0,myWorld->getHeight()-1); unsigned b = r.Generate(0,myWorld->getWidth()-1); if (myWorld->emptyCreature(a,b)){ // and l is empty cout << "Fly from " << mySpot->getX() << "," << mySpot->getY() << " to " << a << "," << b <<endl; //reflect the move in the world myWorld->at(a).at(b) = this; myWorld->at(mySpot->getX()).at(mySpot->getY()) = myWorld->getEmpty(); //update my record of where I am delete mySpot; mySpot = new Location(a,b,mySpot->getDirection()); } } void Creature::infect(){ // if the space ahead is on the board and contains a creature // then give it a new species Location * l = mySpot->getAhead(myWorld->getWidth(), myWorld->getHeight()); if (l != Location::offBoard){ //l is on the board unsigned x = l->getX(); unsigned y = l->getY(); if (!myWorld->emptyCreature(x,y)){ // there is something to infect myWorld->at(x).at(y)->mySpecies = mySpecies; myWorld->at(x).at(y)->myNextMove = 1; } } } bool Creature::facingWall() const{ return mySpot->getAhead(myWorld->getWidth(), myWorld->getHeight()) == Location::offBoard; } bool Creature::facingEnemy() const{ Location * l = mySpot->getAhead(myWorld->getWidth(), myWorld->getHeight()); if (l != Location::offBoard){ //l is on the board unsigned x = l->getX(); unsigned y = l->getY(); return (!myWorld->emptyCreature(x,y) && myWorld->at(x).at(y)->mySpecies != mySpecies); } return false; } bool Creature::facingSame() const{ Location * l = mySpot->getAhead(myWorld->getWidth(), myWorld->getHeight()); if (l != Location::offBoard){ //l is on the board unsigned x = l->getX(); unsigned y = l->getY(); return (!myWorld->emptyCreature(x,y) && myWorld->at(x).at(y)->mySpecies == mySpecies); } return false; } bool Creature::facingEmpty() const{ Location * l = mySpot->getAhead(myWorld->getWidth(), myWorld->getHeight()); if (l != Location::offBoard){ //l is on the board unsigned x = l->getX(); unsigned y = l->getY(); return myWorld->emptyCreature(x,y); } return false; } bool Creature::checkFly() { if(canfly)return true; else return false; } bool Creature::checkRest() { if(rest)return true; else return false; } unsigned Creature::speCreActed() { return speCreAct; } void Creature::assignSpeCreActed(unsigned i) { speCreAct = i; } Creature::~Creature(){ delete mySpot; } <file_sep>#include "species.h" #include "RandomInt.h" #include<iostream> #include<cstdlib> #include<sstream> #include<string> #include <ctime> using namespace std; bool trim(string &); bool valid(const string &); Species::Species(istream & ist){ char temp[90]; string nextInstruction; ist.getline(temp, 80, '\n'); if (! ist.good()){ cerr<< "Problem reading species file\n"; exit(2); } behavior.push_back(temp); //used to keep numbering consistent //with instruction files. while ( ! ist.eof() ){ ist.getline(temp, 80, '\n'); // cerr<< "read line: " << temp << endl; nextInstruction = temp; if ( trim(nextInstruction)) { behavior.push_back(nextInstruction); } else { break; //once we hit a bad instruction, we quit } } } string Species::getName() const { return behavior[0]; } bool trim(string & s){ //trim does all of the error checking in the input instruction. It must //be one of hop, infect, left, right, ifenemy, ifwall, ifsame, ifrandom, //empty or go and have an address when appropriate. //if the string is not a valid instruction, false is returned string digits ="0123456789"; if (s.length() < 3){ return false; } if(s.find("hop") == 0){ s = "hop"; } else if (s.find("infect")==0){ s = "infect"; } else if (s.find("left")==0){ s = "left"; } else if (s.find("right")==0){ s = "right"; } else if ((s.find("go") == 0) || (s.find("if") == 0)){ string t(s.substr(0,2)); unsigned i = 2; while (s[i] != ' '){ // get the rest of the if word t += s[i++]; } if ( !valid(t) ){ return false; } while (s[i] == ' '){ i++;} //skip over blanks t += ' '; //we need exactly one blank while (digits.find(s[i]) != string::npos){ //now add the address t += s[i++]; } s = t; } return true; } bool valid(const string & s ){ if( s == "ifenemy") return true; if( s == "ifempty") return true; if( s == "ifwall") return true; if( s == "ifsame") return true; if( s == "ifrandom") return true; if( s == "go") return true; return false; } char Species::execute(unsigned & moveNumber, Creature * cp) const { //determines the next move depending on the current moveNumber and //location returns 'h' for hop, 'i' for infect, 'l' for turn left and //'r' for turn right. string command; unsigned address; while (true){ istringstream s(behavior[moveNumber++]); s >> command >> address; //The address extraction may fail. This //doesn't matter since all commands without //addresses cause the method to return. //std::cerr<< "command:"<<command<<": address:"<<address<<":\n"; if (command == "hop") return 'h'; else if (command == "infect") return 'i'; else if (command == "left") return 'l'; else if (command == "right") return 'r'; else if (command == "fly") return 'f'; else if (command == "!hopright") return '!'; else if (command == "-hopleft") return '-'; else if (command == "_lefthop") return '_'; else if (command == "~righthop") return '~'; else if (command == "go") moveNumber = address; else if (command == "ifwall"){ if (cp->facingWall()){ moveNumber = address; } } else if (command == "ifenemy"){ if (cp->facingEnemy()){ moveNumber = address; } } else if (command == "ifsame"){ if (cp->facingSame()){ moveNumber = address; } } else if (command == "ifempty"){ if (cp->facingEmpty()){ moveNumber = address; } } else if (command == "ifrandom"){ RandomInt r; if (r.Generate(1,2) == 1){ moveNumber = address; } } } } <file_sep>/* RandomInt.cpp defines the non-trivial RandomInt operations. * Written by: <NAME>, Spring, 1993, at Calvin College. * Written for: C++: An Introduction To Computing. * Revised: Spring 1997, for C++: An Introduction To Computing 2e. * * See RandomInt.h for the class declaration, ******************************************************************/ #include "RandomInt.h" bool RandomInt::generatorInitialized = false; RandomInt::RandomInt() { Initialize(0, RAND_MAX); } RandomInt::RandomInt(int low, int high) { assert(0 <= low); assert(low < high); Initialize(low, high); } RandomInt::RandomInt(int seedValue) { assert(seedValue >= 0); SeededInitialize(seedValue, 0, RAND_MAX); } RandomInt::RandomInt(int seedValue, int low, int high) { assert(seedValue >= 0); assert(0 <= low); assert(low < high); SeededInitialize(seedValue, low, high); } void RandomInt::Print(std::ostream & out) const { out << myRandomValue; } std::ostream & operator<< (std::ostream & out, const RandomInt & randInt) { randInt.Print(out); return out; } int RandomInt::NextRandomInt() { return myLowerBound + rand() % (myUpperBound - myLowerBound + 1); } RandomInt RandomInt::Generate() { myRandomValue = NextRandomInt(); return *this; } RandomInt::operator int() { return myRandomValue; } void RandomInt::Initialize(int low, int high) { myLowerBound = low; myUpperBound = high; if (!generatorInitialized) // call srand() first time only { srand(long(time(0))); // use clock for seed generatorInitialized = true; } myRandomValue = NextRandomInt(); } void RandomInt::SeededInitialize(int seedValue, int low, int high) { myLowerBound = low; myUpperBound = high; srand(seedValue); generatorInitialized = true; myRandomValue = NextRandomInt(); } RandomInt RandomInt::Generate(int low, int high) { assert(0 <= low); assert(low < high); myLowerBound = low; myUpperBound = high; myRandomValue = NextRandomInt(); return *this; } <file_sep>all:evo evo: location.o species.o world.o creature.o RandomInt.o evo.cpp g++ -o evo RandomInt.o location.o species.o world.o creature.o evo.cpp RandomInt.o: RandomInt.cpp RandomInt.h g++ -c RandomInt.cpp location.o: location.cpp location.h g++ -c location.cpp species.o: species.cpp species.h g++ -c species.cpp world.o: world.cpp world.h g++ -c world.cpp creature.o: creature.cpp creature.h g++ -c creature.cpp clean: rm -f evo *.o core.[0-9]* *~ *# <file_sep>#include<fstream> #include<iostream> #include<string> #include<cassert> #include<cstdlib> #include<queue> #include <ctime> #include "species.h" #include "creature.h" #include "world.h" #include "RandomInt.h" using namespace std; int main(){ int abc; RandomInt r; unsigned worldSize = 20; World w(worldSize, worldSize); vector<Creature *> cq; vector<Species *> species; ifstream s1; s1.open("Food.txt"); assert(s1); species.push_back(new Species(s1)); s1.close(); s1.open("Rover.txt"); assert(s1); species.push_back(new Species(s1)); s1.close(); s1.open("Landmine.txt"); assert(s1); species.push_back(new Species(s1)); s1.close(); s1.open("Flytrap.txt"); assert(s1); species.push_back(new Species(s1)); s1.close(); s1.open("Hop.txt"); assert(s1); species.push_back(new Species(s1)); s1.close(); s1.open("CreepingDeath.txt"); assert(s1); species.push_back(new Species(s1)); s1.close(); while (cq.size() < 2 * worldSize){ unsigned row = rand()%worldSize; unsigned col = rand()%worldSize; if (w.emptyCreature(row,col)) cq.push_back(new Creature(species[rand()%species.size()], //r.Generate(0,species.size()-1)], row, col, &w)); } // Start inserting Special Creatures species.clear(); // Three species having special characters s1.open("Rover.txt"); assert(s1); species.push_back(new Species(s1)); s1.close(); s1.open("CreepingDeath.txt"); assert(s1); species.push_back(new Species(s1)); s1.close(); s1.open("Flytrap.txt"); assert(s1); species.push_back(new Species(s1)); s1.close(); int a; int b; cout << endl <<endl; cout << "There are only few special creatures in this game." << endl; cout << endl << "The creature that gets infected remains same" <<endl<<"i.e. special if it's special and general if it's general." << endl << endl; // Maximum 30 percent creatures in the world can be Special Creatures a = r.Generate(0,((30*worldSize)/100)); for (int i = 0; i <= a ; ++i) { unsigned row = r.Generate(0,worldSize-1); unsigned col = r.Generate(0,worldSize-1); if (w.emptyCreature(row,col)) { b = r.Generate(0,2); if (b==2) // Special Flytrap can fly but cannot hop along with changing directions { cq.push_back(new Creature(species[b],row, col, &w,true,false)); } else // Special Creeping Death and Special Rover can both fly and hop along with changing directions { cq.push_back(new Creature(species[b],row, col, &w,true,true)); } cout << "Special Creature at row " << row << ", column " <<col << endl<<endl; } } cout << w; for(unsigned count = 0; count < 2000*worldSize; ++count){ for(unsigned i = 0; i < cq.size(); ++i){ cq[i]->act(); } system("sleep 1"); cout << "Generation " << count << endl << w; } } <file_sep>#ifndef SPIECES_H #define SPIECES_H #include <string> #include <vector> #include <istream> #include "creature.h" using namespace std; class Species{ private: vector<string> behavior; // behavior[0] holds the species name // behaviors start at 1 and contains the program for // the species public: Species(istream &); string getName() const; char symbol() const {return behavior[0][0];} char execute(unsigned &, Creature *) const; }; #endif <file_sep>#include <iostream> #include "location.h" #include "RandomInt.h" using namespace std; Location * Location::offBoard = new Location(0,0,0); Location::Location(unsigned x, unsigned y): xCoor(x), yCoor(y){ RandomInt r; direction = r.Generate(0,NUMBER_OF_DIRECTIONS -1); } Location::Location(unsigned x, unsigned y, unsigned d): xCoor(x), yCoor(y), direction(d){} unsigned Location::getX() const { return xCoor; } unsigned Location::getY() const { return yCoor; } void Location::turnLeft(){ direction = (direction + NUMBER_OF_DIRECTIONS - 1) % NUMBER_OF_DIRECTIONS; } void Location::turnRight(){ direction = (direction + 1) % NUMBER_OF_DIRECTIONS; } Location * Location::getAhead(unsigned boardWidth, unsigned boardHeight) const{ // returns a pointer to a Location object with a valid spot on the board // if one exists otherwise returns NULL switch (direction) { case 0: //North if (xCoor > 0) return new Location(xCoor -1, yCoor, direction); break; case 1: //East if (yCoor < boardWidth-1) return new Location(xCoor, yCoor + 1, direction); break; case 2: //South if (xCoor < boardHeight-1) return new Location(xCoor + 1, yCoor, direction); break; case 3: //West if (yCoor > 0) return new Location(xCoor, yCoor - 1, direction); break; } return offBoard; } <file_sep>#ifndef LOCATION_H #define LOCATION_H const unsigned NUMBER_OF_DIRECTIONS = 8; // 0:North // 1:East // 2:South // 3:West class Location{ private: unsigned xCoor, yCoor; unsigned direction; // each location has a direction as well public: static Location * offBoard; Location(unsigned x=0, unsigned y=0); Location(unsigned x, unsigned y, unsigned d); unsigned getX() const; unsigned getY() const; unsigned getDirection() const{return direction;}; void turnLeft(); void turnRight(); void fly(); Location * getAhead(unsigned boardWidth, unsigned boardHeight) const; }; #endif <file_sep>#ifndef WORLD_H #define WORLD_H #include <string> #include <vector> #include <istream> #include "creature.h" #include "location.h" using namespace std; class World: public vector< vector < Creature * > >{ private: Creature * stdEmptyCreature; public: World(unsigned w = 80, unsigned h= 80); bool emptyCreature(unsigned, unsigned) const; unsigned getWidth() const {return at(0).size();} unsigned getHeight() const {return size();} void display(ostream &) const; Creature * getEmpty() const {return stdEmptyCreature;} ~World(); }; ostream & operator<<(ostream &, const World &); #endif <file_sep>/* RandomInt.h declares RandomInt, pseudo-random integer class. * * Written by: <NAME>, Spring, 1993, at Calvin College. * Written for: C++: An Introduction To Computing. * Revised: Spring 1997, for C++: An Introduction To Computing 2e. * * See RandomInt.doc for class documentation, ******************************************************************/ #ifndef RANDOMINT #define RANDOMINT #include <iostream> #include <cstdlib> #include <cassert> #include <ctime> class RandomInt { public: RandomInt(); RandomInt(int low, int high); RandomInt(int seedValue); RandomInt(int seedValue, int low, int high); void Print(std::ostream & out) const; RandomInt Generate(); RandomInt Generate(int low, int high); operator int(); private: void Initialize(int low, int high); void SeededInitialize(int seedValue, int low, int high); int NextRandomInt(); int myLowerBound, myUpperBound, myRandomValue; static bool generatorInitialized; }; std::ostream & operator<< (std::ostream & out, const RandomInt & randInt); #endif <file_sep>#include "world.h" World::World(unsigned w, unsigned h){ stdEmptyCreature = new Creature(NULL, 0, 0, NULL); vector<Creature *> temp (w, stdEmptyCreature); for (unsigned i = 0; i < h; ++i){ push_back(temp); } } bool World::emptyCreature(unsigned row, unsigned col) const{ return at(row).at(col) == stdEmptyCreature; } void World::display(ostream & ost) const { for (unsigned i = 0 ; i < size(); ++i){ for (unsigned j = 0; j < at(0).size(); ++j){ if (!emptyCreature(i,j)){ ost << at(i).at(j)->getSymbol() << " "; } else{ ost << '_' << " "; } } ost << endl; } } ostream & operator<<(ostream & ost, const World & w){ w.display(ost); return ost; } World::~World(){ for (unsigned i = 0 ; i < size(); ++i){ for (unsigned j = 0; j < at(0).size(); ++j){ if (!emptyCreature(i,j)){ delete at(i).at(j); } } } delete stdEmptyCreature; } <file_sep>#ifndef CREATURE_H #define CREATURE_H #include "location.h" class World; class Species; class Creature{ private: Species * mySpecies; Location * mySpot; World * myWorld; unsigned myNextMove; void hop(); void infect(); bool canfly; bool rest; unsigned speCreAct; public: Creature(Species * s, unsigned x, unsigned y, World * w); Creature(Species * s, unsigned x, unsigned y, World * w, bool condition1, bool condition2); Location * getLocation() const {return mySpot;} void act_1(); char getSymbol() const ; void act(); //method carries out action for the turn void fly(); bool facingWall() const; bool facingEnemy() const; bool facingEmpty() const; bool facingSame() const; bool checkFly(); bool checkRest(); unsigned speCreActed(); void assignSpeCreActed(unsigned i); ~Creature(); }; #endif
5d29041b4661ed68dacaa79f1edd8e4febb39e72
[ "Makefile", "C++" ]
12
C++
ashadhik/CPPCreatureSurvival
e895656b31634d72b65dd523e59b16b7bde56d8a
505cb1c48b642d1ddb1a91079b83ce9f972b82f7
refs/heads/master
<repo_name>gallardolopezmiguel/connections<file_sep>/MONGODB/app/controllers/userController.js const userModel = require('../models/userModel'); const bcrypt = require('bcrypt'); const createUser = (req, res) => { userModel.create({ name: req.body.name, email: req.body.email, password: req.body.password, hasPet: req.body.hasPet }, function(err, result){ if(err) { res.status(401).json({ sucess: false, message: 'Cannot create this user Yet, try another one', error: err }); } else { res.status(200).json({ sucess: true, message: result }); } }); }; const getUsers = (req, res) => { userModel.find((err, data) => { if (err){ res.status(404).json({ success: false, message: err }); } else { res.status(200).json({ success: true, message: data }); } }); }; const login = (req, res, next) => { const user = { email: req.body.email, password: <PASSWORD> }; // find user userModel.findOne({email: user.email}, function(err, userData){ if(err || !userData) { const error = { success: false, error_msg: err, message: 'User not Found' }; res.status(404).json(error); } else { // compare password if(bcrypt.compareSync(user.password, userData.password)) { res.status(200).json({ sucess: true, message: 'Logged', data: userData }); } else { res.status(401).json({ sucess: false, message: 'Incorrect Password' }); } } }); }; module.exports = { createUser, getUsers, login }<file_sep>/MONGODB/app/models/userModel.js const mongoose = require('mongoose'); const bcrypt = require('bcrypt'); const saltRounds = 10; const Schema = mongoose.Schema; // create user schema const UserSchema = new Schema({ name: { type: String, required:true }, email: { type: String, required:true }, password: { type: String, required: true } }); UserSchema.pre('save', function(next) { this.password = bcrypt.hashSync(this.password, saltRounds); next(); }); const newUserSchema = new Schema(); // modify a schema newUserSchema.add(UserSchema).add({ hasPet: { type: Boolean } }); module.exports = mongoose.model('User', newUserSchema);<file_sep>/routes/commentsRoute.js const express = require('express'); const router = express.Router(); const commentsController = require('../app/controllers/commentsController'); router.get('/', commentsController.getComments); router.post('/add', commentsController.addComment); module.exports = router;<file_sep>/MONGODB/app/controllers/commentsController.js const Comment = require('../models/commentsModel'); const User = require('../models/userModel'); const addComment = (req, res) => { const saveComment = new Comment(req.body); saveComment.save() .then(comment => { User.populate(comment, {path: 'user'}, (err, data) => { if (err) { res.status(500).json({ success: false, message: 'We found some issues with the user stuff', error: err }); } else { res.status(200).json({ success: true, message: 'Comment, Created!', extraInfo: data }); } }); }).catch(err => { res.status(500).json({ success: false, message: 'Something is not working', extraInfo: err }); }); }; const getComments = (req, res) => { Comment.find((err, data) =>{ if(err) { const error = { success: false, message: err }; res.status(404).json(error); } else { User.populate(data, {path: 'user'}, (err, newData) => { if(err) { res.status.json({ success: false, error: err }); } else { res.status(200).json({ success:true, message: newData }); } }); } }); }; module.exports = { addComment, getComments }
5db3ae2bb17a2b220831b058e551c407912cefec
[ "JavaScript" ]
4
JavaScript
gallardolopezmiguel/connections
5fb081f189163b8fe1878ebfe682e4b6479b8164
31ea031aea488819873e81f15ba79efa4d93d24d
refs/heads/master
<file_sep>#!/bin/bash # converts farenheit to celcius or celcius to farenheit echo "Please enter a temparture in (C) or (F). Ex: 35F" read temp1 len=${#temp1} unit=`echo "$temp1" | tail -c +$len` len2=$[$len-1] rawTemp1=`echo "$temp1" | head -c +$len2` if [ "$unit" == "F" ] then rawTemp2=$[$rawTemp1-32] rawTemp2=$[$rawTemp2*5] rawTemp2=$[$rawTemp2/9] unit2="C" elif [ "$unit" == "C" ] then rawTemp2=$[$rawTemp1*9] rawTemp2=$[$rawTemp2/5] rawTemp2=$[$rawTemp2+32] unit2="F" else echo "Please use capital letters and no spaces when entering temperature" >2& fi echo "The temperature " $temp1 " is converted to " $rawTemp2$unit2 <file_sep>#!/bin/bash echo "Please enter a number to be converted from decimal to hexadecimal" read decim remainder=$decim hex="" while [ $decim -gt 0 ] do remainder=$[$decim % 16] if [ $remainder == 10 ] then hex="A"$hex elif [ $remainder == 11 ] then hex="B"$hex elif [ $remainder == 12 ] then hex="C"$hex elif [ $remainder == 13 ] then hex="D"$hex elif [ $remainder == 14 ] then hex="E"$hex elif [ $remainder == 15 ] then hex="F"$hex else hex=$remainder$hex fi decim=$[$decim / 16] done echo "hexidecimal representation is " $hex <file_sep>#!/bin/bash str="This program adds two numbers entered from the command line. Please" echo "Enter first number" read num1 echo "Enter second number" read num2 if [ -z "$num1" ] then echo $str "enter a first number" >&2 elif [ -z "$num2" ] then echo $str "enter a second number" >&2 else echo $num1 " + " $num2 " = " $(($num1+$num2)) >&1 fi <file_sep>#!/bin/bash str="This program finds the maximum of three numbers entered from the command line. Please" echo "Enter first number" read num1 echo "Enter second number" read num2 echo "Enter third number" read num3 if [ -z "$num1" ] then echo $str "enter a first number" >&2 elif [ -z "$num2" ] then echo $str "enter a second number" >&2 elif [ -z "$num3" ] then echo $str "enter a third number" >&2 else max=$num1 # max = num1 if [ $num1 -lt $num2 ] # test if num2 > num1 then max=$num2 # max = $num2 if [ $num2 -lt $num3 ] # test if num3 > num2 then max=$num3 # max = num3 fi elif [ $num1 -lt $num3 ] # test if num3 > num1 then max=$num3 # then max = num3 fi echo "The maximum of the three numbers you entered is" $max fi <file_sep>#!/bin/bash # Computes the factorial of entered number echo "Please enter a number greater than zero" read num fact=1 counter=$num if [ $num -lt 1 ] then echo "Th number must be greater than zero" >&2 else while [ $counter -gt 1 ] do fact=`expr $counter \* $fact` counter=`expr $counter - 1` done fi echo $num"! = " $fact <file_sep># Bash Scripts A collection of Bash scripts.<file_sep>#!/bin/bash # prints a pyramid! cols=`tput cols` rows=5 start=$((cols/2)) char=* tput clear for ((i = 0; i <= 5; i++)) do temp=$((start-i)) tput cup $i $temp for ((j = 1; j <= i; j++)) do printf "$i " done done tput clear for ((i = 0; i <= 5; i++)) do temp=$((start-i)) tput cup $i $temp for ((j = 1; j <= i; j++)) do printf "* " done done printf "\n"
b874ce6b5310ac1818e525c8c73aa26f8786bda1
[ "Markdown", "Shell" ]
7
Shell
mdh266/BashScripts
96511a54733c522e44e6f33b0498af3b18f15fe3
590cb92191c2b2c8851b9a220071130cdf2cca6b
refs/heads/master
<file_sep>print("Pozdrav iz aplikacije od <NAME> s brojem indeksa R3760!")
e4afc7e2efc8c0c877b13dc66dc87d4a07026849
[ "Python" ]
1
Python
fcuic/RUAP-Projekt
d9934eea863d747a49e4ba1b339b3adef426f12f
976966b528d59f182a62c96c28f48b3a9e716a6e
refs/heads/master
<file_sep>import pygame import numpy as np import os.path import window MapSpriteX=16 MapSpriteY=16 MultiplyScale=4 SpriteSizeX=MapSpriteX*MultiplyScale SpriteSizeY=MapSpriteY*MultiplyScale #creating a numpy array to store the map information MapArray=np.array([ [1,1,1,2,1,1,1,1,1,2,3,3,2,1,1,1,1,1,2,1], [2,2,2,2,2,2,2,2,2,2,3,3,2,2,2,2,2,2,2,2], [2,1,4,0,4,0,4,0,4,0,4,0,4,0,4,0,4,0,1,2], [2,0,0,0,0,2,0,0,0,0,0,1,1,1,1,1,1,1,1,2], [2,0,2,0,0,2,0,0,0,0,1,1,1,1,1,1,1,1,1,2], [2,0,0,0,0,2,0,0,5,0,0,5,5,1,1,1,1,1,1,2], [2,0,2,0,0,2,0,0,5,0,1,1,1,1,1,1,1,1,1,2], [2,0,0,0,0,2,0,0,5,0,0,1,5,1,1,1,1,1,1,2], [1,0,2,0,0,2,0,0,0,0,1,1,1,1,1,1,1,1,1,2], [1,0,0,0,0,2,0,5,0,0,0,1,1,1,1,1,1,1,1,2], [1,0,2,0,0,2,0,5,0,0,1,1,1,1,1,1,1,1,1,2], [1,0,0,0,0,2,0,0,5,5,5,5,5,1,1,1,1,1,1,2], [1,0,2,0,0,2,0,0,0,0,1,1,1,1,1,1,1,1,1,2], [1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,2] ]) # -OR- #MapArray=np.ones((64,48)) #Figure the size of the map in pixels MapSize=pygame.Rect(0,0,MapArray.shape[1]*SpriteSizeX,MapArray.shape[0]*SpriteSizeY) #loads the tileset image into system memory tilemap_image=pygame.image.load(os.path.join("images","pokemonSprites.png")).convert() #defining the locations within the tilemap image: [x,y] #Technically this isn't necessary; I could take the lists here and place them directly into the dictionary below. I don't do this because I want it to be human-readable. #I'll remove this step once I code a parser for the Tiled .TMX format. blank=[112,0] flower=[64,64] gravel=[192,0] CosmeticGrassFull=[256,0] CosmeticGrassSparse=[256,48] barrier=[224,64,"Solid"] realgrass=[272,0] fence=[240,64] bouncy=[256,64,"bouncy"] TileDict={ 0:blank, 1:gravel, 2:barrier, 3:realgrass, 4:CosmeticGrassSparse, 5:bouncy } #This class holds a tile image and rect in memory. class ImageBlock(pygame.sprite.Sprite): def __init__(self,imageFile,tilemapx,tilemapy): # Call the parent class (Sprite) constructor pygame.sprite.Sprite.__init__(self) #Load image from disk and create a subsurface of the specified location within the tilemap self.image = imageFile.subsurface(tilemapx,tilemapy,MapSpriteX,MapSpriteY) #scales the images to the expected tile size self.image=pygame.transform.scale(self.image,(SpriteSizeX, SpriteSizeY)) # Fetch the rectangle object that has the dimensions of the image with the command self.image.get_rect() # Use the retrieved rect to update the position of the ImageBlock object by setting the values of rect.x and rect.y self.rect = self.image.get_rect() def generate_map_tiles(): map_tiles_group=pygame.sprite.Group() #for each x,y coordinate and the associated array value: for index, x in np.ndenumerate(MapArray): #Create a block based on the x,y coordinates given at the appropriate place in the tile dictionary. # new block object = block class (where to pull the image from, the first value in the array in the appropriate place in the tile dictionary, the second value in same) block = ImageBlock(tilemap_image,TileDict[x][0],TileDict[x][1]) if "Solid" in TileDict[x]: block.walkable=False if "bouncy" in TileDict[x]: block.bouncy=True # Draw the block at the location on-screen equivalent to its location in the array block.rect.x = index[1]*SpriteSizeX block.rect.y = index[0]*SpriteSizeY # Add the block to the list of background sprites map_tiles_group.add(block) return map_tiles_group map_group=generate_map_tiles()<file_sep>import pygame import window import player import map pygame.init() WindowX=640 WindowY=576 #Create the main window screen=pygame.display.set_mode([WindowX,WindowY]) running=True # -------- Main Program Loop ----------- while running: # ALL EVENT PROCESSING SHOULD GO BELOW THIS COMMENT for event in pygame.event.get(): # User did something if event.type == pygame.QUIT: # If user clicked close running=False # Flag that we are done so we exit this loop if event.type == pygame.KEYDOWN: if event.key == pygame.K_SPACE: #Cycles through the existing pokemon, using code and variables from the player module player.pokemonList,player.activePokemon=player.pokemonBump(player.pokemonList,player.activePokemon) #gets player input: Left, Right, Up, Down player.player_input(player.activePokemon) #Centers the camera on the player window.camera_update(player.activePokemon) #draws the group made up of map tiles window.draw_group(map.map_group) #draws the player window.draw_single(player.activePokemon) #does miscellaneous window stuff window.remainder_window_update() # Close the window and quit. pygame.quit () <file_sep>Zeldamon is a game that draws inspiration from the old-school Game Boy games Pokemon Red and Blue, and Legend of Zelda: Link's Awakening. My goal is to create a game where you can switch between the pokemon trainer and his pokemon, explore dungeons, and fight other pokemon on the overworld without switching to a battle screen. As the pokemon you will be able to use attacks and techniques, and as the trainer you will be able to use tools that have similar effects. You will even be able to fight pokemon as the trainer, but if the trainer loses all of his health your pokemon won't be able to continue without you. The game itself is still early in development and is currently missing most of its planned features. Zeldamon is written for Python 3 and uses the Pygame and NumPy libraries. The world maps are XML files created with the Tiled Map Editor. Contact Information: Name: <NAME> Email: <EMAIL><file_sep>import pygame WindowX=640 WindowY=576 pygame.init() #Create the main window screen=pygame.display.set_mode([WindowX,WindowY]) #I placed "import map" here because some of map's functions require an active display #and an initialized pygame. import map #Create a Rect the same size as the screen to use as a camera. VirtualWindow=pygame.Surface.get_rect(screen) # Used to manage how fast the screen updates clock=pygame.time.Clock() pygame.display.set_caption("ZeldaMon") #Create a Rect the same size as the screen to use as a camera. VirtualWindow=pygame.Surface.get_rect(screen) def camera_update(activePokemon): """Update the camera to center over the player.""" #Place the center of the screen at the center of the player VirtualWindow.center=activePokemon.rect.center #If the window is further out than the edge of the map, set the window edge to the edge of the map. if VirtualWindow.top<map.MapSize.top: VirtualWindow.top=map.MapSize.top if VirtualWindow.bottom>map.MapSize.bottom: VirtualWindow.bottom=map.MapSize.bottom if VirtualWindow.left<map.MapSize.left: VirtualWindow.left=map.MapSize.left if VirtualWindow.right>map.MapSize.right: VirtualWindow.right=map.MapSize.right def draw_group(sprite_group): #Sets screen to white, then blits all sprites to the display screen surface. screen.fill((255,255,255)) for a in sprite_group: #If the tile collides with the camera rect; in other words, if the tile is at all on-screen: if a.rect.colliderect(VirtualWindow): #blit the image of the tile sprite (a.image) to the coordinates listed in the sprite minus the x/y coordinates of the virtual window. screen.blit (a.image, [(a.rect.x-VirtualWindow.x),(a.rect.y-VirtualWindow.y)]) def draw_single(sprite): screen.blit (sprite.image, [(sprite.rect.x-VirtualWindow.x),(sprite.rect.y-VirtualWindow.y)]) def remainder_window_update(): #Updates the physical screen with what's been blitted to the screen surface. pygame.display.flip() # Limit to 80 frames per second clock.tick(80) # Display FPS on the title bar instead of "zeldamon" pygame.display.set_caption(str(clock.get_fps()))<file_sep>import pygame import os.path #import map to get access to the MultiplyScale variable import map PlayerMove=3 #This class represents the player class class playerClass(pygame.sprite.Sprite): def __init__(self,pokemonfile): # Call the parent class (Sprite) constructor pygame.sprite.Sprite.__init__(self) player_image=pygame.image.load(os.path.join("images","PokemonSprites",pokemonfile)).convert_alpha() #Create a image subsurface from the player spritesheet. #Player numbers. Need to add the code to crop transparency. That, or just use the existing code and put the trainer on a pokemon-style sheet. I dunno. #self.FacingDown=player_image.subsurface(0,0,16,16) #self.FacingUp=player_image.subsurface(32,0,16,16) #self.FacingLeft=player_image.subsurface(0,16,16,16) #self.FacingRight=pygame.transform.flip(self.FacingLeft,True,False) # -OR- #Pokemon sheet #Facing down #Create a temporary subsurface from the player spritesheet TempSubsurface=player_image.subsurface(0,64,32,32) #Get the a rectangle that crops out empty alpha space. TempRect=TempSubsurface.get_bounding_rect() #Create the Surface FacingDown that's the width and height of the cropped rectangle, and make sure it can handle per-pixel transparency. self.FacingDown=pygame.Surface((TempRect.width,TempRect.height), flags=pygame.SRCALPHA) #Take the original image, move it left and up by the difference between the original rectangle and the cropped rectangle #As an example, of the original x is 0 and the cropped x is 40, the command will move the image left by 40 to place it right on the FacingDown Surface. self.FacingDown.blit(TempSubsurface, (-TempRect.x,-TempRect.y)) #Facing Up #Create a temporary subsurface from the player spritesheet TempSubsurface=player_image.subsurface(0,0,32,32) #Get the a rectangle that crops out empty alpha space. TempRect=TempSubsurface.get_bounding_rect() #Create the Surface FacingDown that's the width and height of the cropped rectangle, and make sure it can handle per-pixel transparency. self.FacingUp=pygame.Surface((TempRect.width,TempRect.height), flags=pygame.SRCALPHA) #Take the original image, move it left and up by the difference between the original rectangle and the cropped rectangle #As an example, of the original x is 0 and the cropped x is 40, the command will move the image left by 40 to place it right on the FacingDown Surface. self.FacingUp.blit(TempSubsurface, (-TempRect.x,-TempRect.y)) #Facing Left #Create a temporary subsurface from the player spritesheet TempSubsurface=player_image.subsurface(32,0,32,32) #Get the a rectangle that crops out empty alpha space. TempRect=TempSubsurface.get_bounding_rect() #Create the Surface FacingDown that's the width and height of the cropped rectangle, and make sure it can handle per-pixel transparency. self.FacingLeft=pygame.Surface((TempRect.width,TempRect.height), flags=pygame.SRCALPHA) #Take the original image, move it left and up by the difference between the original rectangle and the cropped rectangle #As an example, of the original x is 0 and the cropped x is 40, the command will move the image left by 40 to place it right on the FacingDown Surface. self.FacingLeft.blit(TempSubsurface, (-TempRect.x,-TempRect.y)) #Facing Right self.FacingRight=pygame.transform.flip(self.FacingLeft,True,False) #Create a temporary rectangle based on the image taken from the player spritesheet. # Use that information to scale the subsurface of the image by the amount specified in the variable MultiplyScale. TempRect=self.FacingDown.get_rect() self.FacingDown=pygame.transform.scale(self.FacingDown, (int(TempRect.width*map.MultiplyScale),int(TempRect.height*map.MultiplyScale))) TempRect=self.FacingUp.get_rect() self.FacingUp=pygame.transform.scale(self.FacingUp, (int(TempRect.width*map.MultiplyScale),int(TempRect.height*map.MultiplyScale))) TempRect=self.FacingLeft.get_rect() self.FacingLeft=pygame.transform.scale(self.FacingLeft, (int(TempRect.width*map.MultiplyScale),int(TempRect.height*map.MultiplyScale))) TempRect=self.FacingRight.get_rect() self.FacingRight=pygame.transform.scale(self.FacingRight, (int(TempRect.width*map.MultiplyScale),int(TempRect.height*map.MultiplyScale))) #Generate a 2-integer pair that is the average width of each facing image and the average height of the same. self.bounding=((self.FacingLeft.get_width()+self.FacingUp.get_width()+self.FacingDown.get_width()+self.FacingRight.get_width())//4),((self.FacingLeft.get_height()+self.FacingUp.get_height()+self.FacingDown.get_height()+self.FacingRight.get_height())//4) #Scale each image to that size self.FacingUp=pygame.transform.scale(self.FacingUp,self.bounding) self.FacingDown=pygame.transform.scale(self.FacingDown,self.bounding) self.FacingLeft=pygame.transform.scale(self.FacingLeft,self.bounding) self.FacingRight=pygame.transform.scale(self.FacingRight,self.bounding) #Give the player a starting image self.image=self.FacingDown #Take the rect from the player image and use it as the player rect. self.rect = self.image.get_rect() self.ForcedLeft=self.ForcedRight=self.ForcedUp=self.ForcedDown=False self.KnockedFramesLeft=0 #This function is only called once when the player collides with something bouncy or takes damage(?). def KnockedBack(self,frames, direction): self.ForcedLeft=self.ForcedRight=self.ForcedUp=self.ForcedDown=False self.KnockedFramesLeft=frames if direction=="up": self.ForcedUp=True if direction=="down": self.ForcedDown=True if direction=="left": self.ForcedLeft=True if direction=="right": self.ForcedRight=True #This function moves the player backwards until the frame counter runs out. def KnockedUpdate(self): if self.ForcedLeft: self.MoveLeft() if self.ForcedRight: self.MoveRight() if self.ForcedUp: self.MoveUp() if self.ForcedDown: self.MoveDown() self.KnockedFramesLeft-=1 if self.KnockedFramesLeft==0: self.ForcedLeft=self.ForcedRight=self.ForcedUp=self.ForcedDown=False # In diagonal cases: it works because if the non-colliding direction is figured first, it doesn't collide. If the non-colliding direction is figured second, it's already been moved out of collision. # Took me a while to figure out why it wasn't jumping around on diagonal collision detection like I thought it should. def MoveLeft(self): if not self.ForcedRight: self.rect.x-=PlayerMove if not self.ForcedLeft: self.image=self.FacingLeft self.rect.width=self.FacingLeft.get_width() self.rect.height=self.FacingLeft.get_height() for sprite in pygame.sprite.spritecollide(self,map.map_group, False): if getattr(sprite, 'walkable', True)==False: self.rect.left=sprite.rect.right if getattr(sprite, 'bouncy', False)==True: self.rect.left=sprite.rect.right self.KnockedBack(18,"right") def MoveRight(self): if not self.ForcedLeft: self.rect.x+=PlayerMove if not self.ForcedRight: self.image=self.FacingRight self.rect.width=self.FacingRight.get_width() self.rect.height=self.FacingRight.get_height() for sprite in pygame.sprite.spritecollide(self,map.map_group, False): if getattr(sprite, 'walkable', True)==False: self.rect.right=sprite.rect.left if getattr(sprite, 'bouncy', False)==True: self.rect.right=sprite.rect.left self.KnockedBack(18,"left") def MoveUp(self): if not self.ForcedDown: self.rect.y-=PlayerMove if not self.ForcedUp: self.image=self.FacingUp self.rect.width=self.FacingUp.get_width() self.rect.height=self.FacingUp.get_height() for sprite in pygame.sprite.spritecollide(self,map.map_group, False): if getattr(sprite, 'walkable', True)==False: self.rect.top=sprite.rect.bottom if getattr(sprite, 'bouncy', False)==True: self.rect.top=sprite.rect.bottom self.KnockedBack(18,"down") def MoveDown(self): if not self.ForcedUp: self.rect.y+=PlayerMove if not self.ForcedDown: self.image=self.FacingDown self.rect.width=self.FacingDown.get_width() self.rect.height=self.FacingDown.get_height() for sprite in pygame.sprite.spritecollide(self,map.map_group, False): if getattr(sprite, 'walkable', True)==False: self.rect.bottom=sprite.rect.top if getattr(sprite, 'bouncy', False)==True: self.rect.bottom=sprite.rect.top self.KnockedBack(18,"up") #Creates a list and initializes each pokemon within the party. pokemonList=[playerClass("001Bulbasaur.png"),playerClass("002Ivysaur.png"),playerClass("003VenusaurLumin.png"),playerClass("004CharmanderLuminAuto.png"),playerClass("005CharmeleonLuminAuto.png"),playerClass("006CharizardLuminAuto.png"),playerClass("007SquirtleLightnessAuto.png"),playerClass("019Rattata.png"),playerClass("025Pikachu.png")] #Create a reference to the first pokemon in the list called activePokemon activePokemon=pokemonList[0] activePokemon.rect.topleft=(128,128) #Create the starting point for the player. def pokemonBump(pokemonList,activePokemon): tempPokemon=pokemonList[0] del [pokemonList[0]] pokemonList.append(tempPokemon) del activePokemon activePokemon=pokemonList[0] activePokemon.rect.topleft=tempPokemon.rect.topleft #Point them in the right direction when being switched. #Otherwise, the pokemon would face the same direction they were last time they were visible. if tempPokemon.image==tempPokemon.FacingLeft: activePokemon.image=activePokemon.FacingLeft if tempPokemon.image==tempPokemon.FacingRight: activePokemon.image=activePokemon.FacingRight if tempPokemon.image==tempPokemon.FacingUp: activePokemon.image=activePokemon.FacingUp if tempPokemon.image==tempPokemon.FacingDown: activePokemon.image=activePokemon.FacingDown #Copies over the knocked status. At this rate I'll be copying everything over. I know there has to be a simpler, object-oriented way to only transfer the attributes I want, but I can't figure it out. So, this will have to do. activePokemon.ForcedDown=tempPokemon.ForcedDown activePokemon.ForcedUp=tempPokemon.ForcedUp activePokemon.ForcedLeft=tempPokemon.ForcedLeft activePokemon.ForcedRight=tempPokemon.ForcedRight activePokemon.KnockedFramesLeft=tempPokemon.KnockedFramesLeft return pokemonList,activePokemon def player_input(activePokemon): keys=pygame.key.get_pressed() if keys[pygame.K_LEFT]: activePokemon.MoveLeft() if keys[pygame.K_RIGHT]: activePokemon.MoveRight() if keys[pygame.K_UP]: activePokemon.MoveUp() if keys[pygame.K_DOWN]: activePokemon.MoveDown() if activePokemon.KnockedFramesLeft>=0: activePokemon.KnockedUpdate() return activePokemon
e1dd83460ab412a0c04b0a32e881cb7359a5ef91
[ "Markdown", "Python" ]
5
Python
anonymousAwesome/Zeldamon
fdf2ef82ec13ddb8f0b0bdf3ce3bbc5aed8f0cb0
89093d09aa77124f0bc6512b60235a0cc17a2103
refs/heads/master
<file_sep>// 2017/04/28 // created by <NAME> #pragma once #ifndef __CONE_SIMULATOR_H__ #define __CONE_SIMULATOR_H__ void ConeSimulator(); #endif //__CONE_SIMULATOR_H__ <file_sep>#include <stdio.h> #include <windows.h> #include "calculation_win.h" #define THREAD_NUM 2 #define DATA_NUM 100 #define SPLIT_DATA_NUM (DATA_NUM / THREAD_NUM) typedef struct _thread_arg { int thread_no; int *data; }thread_arg_t; void thread_func(void *arg) { thread_arg_t* targ = (thread_arg_t *)arg; int i; /*2各スレッドに分割されアタデータの処理*/ /*引数データの値とその値に1を加えた値を出力*/ for (i = 0; i < SPLIT_DATA_NUM; i++) { printf("thread%d : %d + 1 = %d\n", targ->thread_no, targ->data[i], targ->data[i] + 1); } } int main() { HANDLE handle[THREAD_NUM]; thread_arg_t tArg[THREAD_NUM]; int data[DATA_NUM]; int i; /*データの初期化*/ for (i = 0; i < DATA_NUM; i++) { data[i] = i; } for (i = 0; i < THREAD_NUM; i++) { tArg[i].thread_no = i; /*1各スレッドへのデータ分割*/ tArg[i].data = &data[SPLIT_DATA_NUM * i]; handle[i] = CreateThread(NULL, 0, (LPTHREAD_START_ROUTINE)thread_func, (void *)&tArg[i], 0, NULL); } /*スレッドの終了を待つ*/ WaitForMultipleObjects(THREAD_NUM, handle, true, INFINITE); return 0; }<file_sep>// 2017/05/06 // written by <NAME> // reference http://www5d.biglobe.ne.jp/stssk/maze/spline.html #include <math.h> #include <stdio.h> #include "include\kine_spline.h" #include "include\kine_debag.h" Spline::Spline() { num = 0; } Spline::~Spline() { } void Spline::initPoint(double *points, int pointValue) { double w[MAX_SPLINE_POINT]; double temp; num = pointValue - 1; //aの値の初期化 for (int i = 0; i <= num; ++i) { a[i] = points[i]; } //cの値の初期化 c[0] = c[num] = 0.0; for (int i = 1; i < num; ++i) { c[i] = 3 * (a[i - 1] - 2 * a[i] + a[i + 1]); } w[0] = 0.0; for (int i = 1; i < num; ++i) { temp = 4.0 - w[i - 1]; c[i] = (c[i] - c[i - 1]) / temp; w[i] = 1.0 / temp; } for (int i = num - 1; i > 0; --i) { c[i] = c[i] - c[i + 1] * w[i]; } //b,dの初期化 b[num] = d[num] = 0.0; for (int i = 0; i < num; ++i) { d[i] = (c[i + 1] - c[i]) / 3.0; b[i] = a[i + 1] - a[i] - c[i] - d[i]; } //for (int i = 0; i < num; ++i) { // printf("a -> %lf\t", a[i]); // printf("b -> %lf\t", b[i]); // printf("c -> %lf\t", c[i]); // printf("d -> %lf\n", d[i]); //} } double Spline::calc(double variable) { //DebagComment("spline::calc"); //printf("variable -> %lf\n", variable); double dt = 0; //minute time int i = (int)floor(variable); //整数部 if (i < 0) { i = 0; } else if (i >= num) { i = num - 1; } dt = variable - (double)i; double buf = a[i] + (b[i] + (c[i] + d[i] * dt) * dt) * dt; //printf("buf -> %lf\n", buf); return buf; }<file_sep>// 2017/04/28 // created by <NAME> ///////////////////////////////////////////////////////// //これがメインプログラム. //主にmain()内にある関数を一つだけ呼び出して使うこと. ///////////////////////////////////////////////////////// #define _USE_MATH_DEFINES #include <iostream> #include <stdio.h> #include <stdlib.h> #include "include\arm_simulator.h" #include "include\kine_debag.h" #include "include\cone_simulator.h" #include "include\Test_console.h" void main() { kinemaDebagON(); int check = 0; for (;;) { int function = -1; char ss[10] = {}; fflush(stdin); std::cout << "*** 使用する機能を選んでね ***" << std::endl; std::cout << " 1 : 7自由度ロボットアームシミュレータ (軽量版)" << std::endl; std::cout << " 2 : 7自由度ロボットアームシミュレータ (フルグラフィクス)" << std::endl; std::cout << " 3 : 円錐シミュレータ" << std::endl; std::cout << " 4 : コンソール" << std::endl; std::cout << " 99 : プログラム終了" << std::endl; std::cout << "\n-> "; fgets(ss, sizeof(ss), stdin); function = atoi(ss); switch (function) { case 1: std::cout << "*** Start : 7 DoF Arm Simulator (Light Version) ***\n"; ArmSimulator(0); break; case 2: std::cout << "*** Start : 7 DoF Arm Simulator (Full Graphics) ***\n"; ArmSimulator(1); break; case 3: std::cout << "*** Start : Cone Simulator ***\n"; ConeSimulator(); break; case 4: std::cout << "*** Start : console ***\n"; TestConsole(); break; case 99: std::cout << "*** program Shutdown ***\n"; exit(1); break; default: DebagComment("*** Error : illegal Input ***"); break; } } } <file_sep>// 2017/04/28 // created by <NAME> #include <Inventor\Win\SoWin.h> #include <Inventor\So.h> #include <vector> #include <time.h> inline void InitRand() { srand((unsigned int)time(NULL)); } //座標点確認用サクランボ描画 void GoalCherry(std::vector<double> position, SoSeparator *GoalSep) { /////////////////////////////////////// SoInput GoalIpt; if (!GoalIpt.openFile("cherryfruit.wrl")) exit(1); SoSeparator *GoalObj1 = SoDB::readAll(&GoalIpt); if (GoalObj1 == NULL) exit(1); /* SoSphere *GoalObj = new SoSphere(); SoTransform *GoalTransform = new SoTransform; GoalTransform->scaleFactor.setValue(0.002, 0.002, 0.002); */ //color SoMaterial *GoalColor = new SoMaterial; GoalColor->diffuseColor.setValue(1, 0, 0); //位置合わせ SoTranslation *GoalTranslation1 = new SoTranslation; //GoalTranslation1->translation.setValue(cherry[0], cherry[1] - 0.03, cherry[2]); GoalTranslation1->translation.setValue(position[0], position[1] - 0.03, position[2]); SoTransform *GoalInitialrot = new SoTransform; //Y GoalSep->addChild(GoalColor); GoalSep->addChild(GoalTranslation1); //GoalSep->addChild(GoalTransform); GoalSep->addChild(GoalObj1); } void PointObj(std::vector<double> position, SoSeparator *redPoint) { InitRand(); SoSphere *redP = new SoSphere; redP->radius = 0.01; SoMaterial *myMaterial = new SoMaterial; myMaterial->diffuseColor.setValue(1, 0, 0); //myMaterial->diffuseColor.setValue((rand() % 101) * 0.01, (rand() % 101) * 0.01, (rand() % 101) * 0.01); SoTranslation *trans = new SoTranslation; trans->translation.setValue(position[0], position[1], position[2]); redPoint->addChild(myMaterial); redPoint->addChild(trans); redPoint->addChild(redP); } void PointObj(SoSeparator *redPoint) { InitRand(); SoSphere *pointObj = new SoSphere; pointObj->radius = 0.01; SoMaterial *red= new SoMaterial; red->diffuseColor.setValue((rand() % 101) * 0.01, (rand() % 101) * 0.01, (rand() % 101) * 0.01); redPoint->addChild(red); redPoint->addChild(pointObj); } void AlmiFlame(std::vector<double> position,SoSeparator *armFlame) { /////////////////////////////////////// SoInput armFlameIpt; if (!armFlameIpt.openFile("hfsh8-8080-1000_vertical.wrl")) exit(1); SoSeparator *armFlameObj = SoDB::readAll(&armFlameIpt); if (armFlameObj == NULL) exit(1); // no.1 flame position (0.11, -0.916, -0.210) // no.2 flame position (-0.11, -0.916, -0.210) /* SoSphere *GoalObj = new SoSphere(); SoTransform *GoalTransform = new SoTransform; GoalTransform->scaleFactor.setValue(0.002, 0.002, 0.002); */ //color SoMaterial *flameColor = new SoMaterial; flameColor->diffuseColor.setValue(0.7, 0.7, 0.7); //位置合わせ SoTranslation *positionConfig = new SoTranslation; positionConfig->translation.setValue(position[0], position[1], position[2]); armFlame->addChild(flameColor); armFlame->addChild(positionConfig); //GoalSep->addChild(GoalTransform); armFlame->addChild(armFlameObj); } //座標系 void CoordinateSystem(SoSeparator *coordinateSystem) { SoFont *myFont = new SoFont; myFont->name.setValue("Tmes-Roman"); myFont->size.setValue(24.0); coordinateSystem->addChild(myFont); SoSeparator *X_text = new SoSeparator; SoSeparator *Y_text = new SoSeparator; SoSeparator *Z_text = new SoSeparator; SoText2 *Xplus = new SoText2; Xplus->string = "X"; SoText2 *Yplus = new SoText2; Yplus->string = "Y"; SoText2 *Zplus = new SoText2; Zplus->string = "Z"; SoTranslation *X_Position = new SoTranslation; SoTranslation *Y_Position = new SoTranslation; SoTranslation *Z_Position = new SoTranslation; X_Position->translation.setValue(0.15, 0, 0); Y_Position->translation.setValue(0, 0.15, 0); Z_Position->translation.setValue(0, 0, 0.15); SoMaterial *blue = new SoMaterial; SoMaterial *red = new SoMaterial; SoMaterial *green = new SoMaterial; red->diffuseColor.setValue(1, 0.1, 0.1); green->diffuseColor.setValue(0.1, 1, 0.1); blue->diffuseColor.setValue(0.1, 0.1, 1); X_text->addChild(X_Position); X_text->addChild(blue); X_text->addChild(Xplus); Y_text->addChild(Y_Position); Y_text->addChild(red); Y_text->addChild(Yplus); Z_text->addChild(Z_Position); Z_text->addChild(green); Z_text->addChild(Zplus); coordinateSystem->addChild(X_text); coordinateSystem->addChild(Y_text); coordinateSystem->addChild(Z_text); } <file_sep>#pragma once // 2017/04/28 // created by <NAME> #ifndef __MY_CONFIG_H__ #define __MY_CONFIG_H__ namespace kine { //通過点の設定値(初期位置と最終位置を含む点の数) const int ROUTE_POINTS = 3; //通過するルートのリンク数(通過点をつなぐ線のこと) const int ROUTE_LINK = ROUTE_POINTS - 1; //自由度の設定 const int MAXJOINT = 8; //7 axis and hand tip DoF //速度計算1ループごとに進む時間 const double TIME_SPAN = 0.01; //台形補間の計算総時間 const double TIME_LENGTH = 2.0; //台形補間の加減速時間 const double ACCEL_TIME = TIME_LENGTH / 4; //手先位置収束しきい値 const double FINGER_THRESHOLD = 0.001; //リンク長さ //肩つけ根(base) const double B_ARM_LENGTH = 0.164; //上腕(upper) const double U_ARM_LENGTH = 0.322; //前腕(forward) const double F_ARM_LENGTH = 0.257; //手先(hand) //const double H_ARM_LENGTH = 0.157; //light simulator const double H_ARM_LENGTH = 0.135; //real simulator //手首からカメラ設置位置の距離 const double WRIST2CAMERA_LENGTH = 0.0405; const double CAMERA_POSITION = 0.10; //カメラ設置位置からカメラまでの距離 const double CAMERA_OFFSET = -0.006; //手先とカメラの中心までのズレ //スペースマウスの値強度 //const double SPACEMOUSE_TRANSLATION_GAIN = 0.0f; //const double SPACEMOUSE_ROTATION_GAIN = 0.0005f; //NULL分のメモリ確保用 const int NR_END = 1; //数値の比較用定数 const double COMPARE_ZERO = 1.0e-6; } #endif // !__MY_CONFIG_H__ <file_sep>// 2017/04/28 // created by <NAME> //7自由度アームシミュレータの心臓部。 //主に3次元モデルの生成、動作に関するコールバック関数(callback) //キーボード操作受けつけ関数(mykeypress) //運動学計算(calcCore)はmyKeyPressの中で,様々な処理を受ける /////////////////////////////////////////////////////////////////// //注意 //c:\coin3d\include\inventor\system\inttypes.h //の //#if !defined(HAVE_INT8_T) && defined(COIN_INT8_T) //typedef COIN_INT8_T int8_t; //#define HAVE_INT8_T 1 //#endif /* !HAVE_INT8_T && COIN_INT8_T */ //を定義していません //他のプログラムでエラーが出る可能性あり. ///////////////////////////////////////////////// //関数は先頭文字が大文字,変数は小文字,単語ごとに頭文字が大文字 //定数は全部大文字 /////////////////////////////////////////////////////////////////// #define _CRT_SECURE_NO_WARNINGS #include "include\camera_position.h" #include "include\kine_target_point.h" #include "include\kine_debag.h" #include "include\kinematics.h" #include "include\kine_vector.h" #include "include\3Dobjects.h" #include "include\kine_config.h" #include "include\kine_trajectory.h" #include <stdio.h> #include <stdlib.h> #include <Inventor\Win\SoWin.h> #include <Inventor\Win\viewers\SoWinExaminerViewer.h> #include <Inventor\So.h> //#include <Inventor\Win\devices\SoWinSpaceball.h> //////////////////////////////////////////////////////////////// //coin3Dと運動学で共通の変数. //coin3Dの引数が変えられないからグローバルにするしか無いものをここに置く //計算結果の描画を何回に一回にするか const double LOOP_SPAN = kine::TIME_SPAN * 1; //経由点を目標点の半径いくらに設定するか.単位はメートル const double VIA_LENGTH = 0.1; //さくらんぼの目標位置.単位はm(メートル) static TarPoints cherryPos; //関節の角度を格納する static double currentJointRad[kine::MAXJOINT] = {}; //手先カメラの位置 static double handCameraCoordinate[3] = {}; //Recording array double positionRec[3 * 100000] = {}; double velocityRec[7 * 100000] = {}; static int loopnum = 0; /////////////////////////////////////////////////////////////////////////////// //ここから関数群 //目標座標設定 void pointInitialize() { //初期姿勢時の手先位置 cherryPos.mid = { 0.601, -0.04, 0.0 }; //搬送部の位置 //cherryPos.mid = { 0.193, -0.435, -0.250 }; //キャリブレーション治具から10cm引き抜いた所 //cherryPos.mid = { -0.116, -0.589, 0.0 }; cherryPos.top = { cherryPos.mid[0] + 0.2, cherryPos.mid[1] + 0.0, cherryPos.mid[2] + 0.0 }; cherryPos.btm = { cherryPos.mid[0] - 0.0, cherryPos.mid[1] - 0.2, cherryPos.mid[2] - 0.0 }; } //アーム各関節の初期値を与える関数.グローバル変数へのアクセスなので. //プログラムのどこからでも起動できるから注意 void CurrentJointRadInit() { currentJointRad[0] = 60 * M_PI / 180 - M_PI / 2;//肩ロール currentJointRad[1] = 0 * M_PI / 180 + M_PI / 2; //肩ピッチ currentJointRad[2] = 0 * M_PI / 180 + M_PI / 2; //肩ヨー currentJointRad[3] = 70 * M_PI / 180; //肘 currentJointRad[4] = 0 * M_PI / 180; //手首ロール currentJointRad[5] = -40 * M_PI / 180; //手首ピッチ currentJointRad[6] = 0 * M_PI / 180; //手先ロール currentJointRad[7] = 0; //使わないパラメータ } void WriteOut() { printf("output velocity start\n"); //OutputMatrixTxt(positionRec, 3, loopnum, "handPosi_"); OutputMatrixTxt(velocityRec, 8, loopnum, "Velo_"); printf("output velocity ended\n"); } //スペースマウスから受け取る数値を格納する //float spaceMouseInput[6]; //使い方の説明 void DisplayDescription() { DebagBar(); printf("==============================================\n"); printf("= 使用方法\n"); printf("= 1.シミュレーション画面をクリックでアクティブにする\n"); printf("= 2.Escキーでキーボード操作モードに切り替える\n"); printf("= 3.シミュレーション開始可能になります\n\n"); printf("= available key -> A, G, H, J, K, L, I, P, R\n\n"); printf("= A key -> move to Goal point\n\n"); printf("= G, H key -> Selfmotion \n\n"); printf("= J, L key -> Hand Yaw control \n\n"); printf("= I, K key -> Hand Pitch control \n\n"); printf("= P key -> Information current position i.e. coordinate, error... \n\n"); printf("= R key -> Reset to initial position, and elapsed times \n\n"); printf("= T key -> Reset Goal position, and elapsed times \n\n"); printf("= W key -> write out parametors \n\n"); printf("= Q key -> Quit Program \n"); printf("==============================================\n"); } //パラメータの表示 void DisplayParametors(kine::Kinematics *arm){ DebagBar(); printf("currentJointRad(deg) 1-> %3.8lf\n", currentJointRad[0] * 180 / M_PI); printf("currentJointRad(deg) 2-> %3.8lf\n", currentJointRad[1] * 180 / M_PI); printf("currentJointRad(deg) 3-> %3.8lf\n", currentJointRad[2] * 180 / M_PI); printf("currentJointRad(deg) 4-> %3.8lf\n", currentJointRad[3] * 180 / M_PI); printf("currentJointRad(deg) 5-> %3.8lf\n", currentJointRad[4] * 180 / M_PI); printf("currentJointRad(deg) 6-> %3.8lf\n", currentJointRad[5] * 180 / M_PI); printf("currentJointRad(deg) 7-> %3.8lf\n", currentJointRad[6] * 180 / M_PI); DebagBar(); //printf("currentJointRad(rad) 1-> %3.8lf\n",currentJointRad[0]); //printf("currentJointRad(rad) 2-> %3.8lf\n",currentJointRad[1]); //printf("currentJointRad(rad) 3-> %3.8lf\n",currentJointRad[2]); //printf("currentJointRad(rad) 4-> %3.8lf\n",currentJointRad[3]); //printf("currentJointRad(rad) 5-> %3.8lf\n",currentJointRad[4]); //printf("currentJointRad(rad) 6-> %3.8lf\n",currentJointRad[5]); //printf("currentJointRad(rad) 7-> %3.8lf\n",currentJointRad[6]); DebagBar(); arm->DisplayCoordinate(); DebagBar(); printf("goal_x -> %3.8lf\n", cherryPos.mid[0]); printf("goal_y -> %3.8lf\n", cherryPos.mid[1]); printf("goal_z -> %3.8lf\n", cherryPos.mid[2]); double finger[3] = {}; double wrist[3] = {}; arm->GetCoordinate(finger); arm->GetwristCoordinate(wrist); printf("error_X -> %3.8lf\n", finger[0] - cherryPos.mid[0]); printf("error_Y -> %3.8lf\n", finger[1] - cherryPos.mid[1]); printf("error_Z -> %3.8lf\n", finger[2] - cherryPos.mid[2]); DebagBar(); std::vector<double> f = { finger[0], finger[1], finger[2]}; std::vector<double> w = { wrist[0], wrist[1],wrist[2] }; std::vector<double> initPos = { 1,0,0 }; std::vector<double> target(3, 0); for (int i = 0; i < 3; ++i) { target[i] = cherryPos.top[i] - cherryPos.btm[i]; } std::vector<double> vec; vec = SubVector(f, w); VectorNormalize(vec); DebagComment("hand direction vector"); DisplayVector(vec); DebagBar(); double postureMatrix[16] = {}; arm->GetHandHTM(currentJointRad, postureMatrix); DisplayRegularMatrix(4, postureMatrix); } //逆運動学を計算 int CalcInverseKinematics(double *speed, kine::Kinematics *arm, bool selfMotion) { //エラーチェック int errorCheck = 0; //CalcIKから返ってくる計算値 double nextRadVelocity[kine::MAXJOINT] = {}; //セルフモーション発動 if (selfMotion == 1) errorCheck = arm->CalcIK(currentJointRad, speed, nextRadVelocity); //擬似逆行列法 //else if (selfMotion == 0) errorCheck = arm->CalcPIK(currentJointRad, speed, nextRadVelocity); //エラーチェック if (errorCheck > 0) return 1; //出力された関節角速度を現在の関節角度に足す. for (int i = 0; i < kine::MAXJOINT - 1; i++) currentJointRad[i] += nextRadVelocity[i]; return 0; } //指先移動軌道を計算 void PositionSpeed(double *currentTime, kine::Kinematics *arm, double *speed) { //手先移動速度の算出 double firstPos[3] = {}; double viaPos[3] = {}; double endPos[3] = {}; double positionBuf[3] = {}; //手先位置 arm->GetCoordinate(firstPos); for (int i = 0; i < 3; ++i) endPos[i] = cherryPos.mid[i]; //経由点の計算 CalcViaPos(cherryPos, VIA_LENGTH, viaPos); //直線軌道 //CalcVelocityLinear(firstPos, endPos, *currentTime, positionBuf); //スプライン CalcVelocitySpline(firstPos, viaPos, endPos, *currentTime, positionBuf); //DebagComment("position buffer"); DisplayVector(3, positionBuf); for (int i = 0; i < 3; ++i) speed[i] = positionBuf[i]; } //手先姿勢計算 void PostureSpeed(double *currentTime, double *speed) { //手先姿勢の速度算出///////////////////////////////////////////////////////// //speedは 3 -> roll, 4 -> yaw , 5 -> pitch double postureBuf[3] = {}; CalcVelocityPosture(currentJointRad, &cherryPos, *currentTime, postureBuf); //DebagComment("posture buffer"); DisplayVector(3, postureBuf); //計算した指先軌道,手先姿勢動作速度の代入 for (int i = 0; i < 3; ++i) speed[i + 3] = postureBuf[i]; //speed[6] = 0; } //運動学計算関数を実行する関数.LOOP_SPANの回数ループさせる void CalcCore(double *currentTime, kine::Kinematics *arm, bool selfMotion, double *speed) { //calcCoreのループタイマー double loopTimer = 0; //エラーチェック int errorCheck = 0; while (1) { //printf("currentTime -> %lf\n", *currentTime); //手先位置の算出 arm->CalcFK(currentJointRad); //手先カメラの算出 //CalcHandCameraPosition(currentJointRad, handCameraCoordinate); //軌道計算 PositionSpeed(currentTime, arm, speed); //手先姿勢計算 PostureSpeed(currentTime, speed); //ヤコビ行列を用いた逆運動学の計算 errorCheck = CalcInverseKinematics(speed, arm, selfMotion); if (errorCheck == 1) { ErrComment("*** calculation error happened ***"); //WriteOut(); exit(1); } //書き出し用配列 velocityRec[loopnum * 8 + 0] = *currentTime; //デバッグ用 for (int i = 1; i < 8; ++i) velocityRec[8 * loopnum + i] = speed[i - 1]; //アウトプット用の書き出し回数カウンタ ++loopnum; //現在時間の更新 *currentTime += kine::TIME_SPAN; //シミュレータ上で描画する時間。 //下の条件文を抜けるとグラフィクスを描画する。 loopTimer += kine::TIME_SPAN; if (loopTimer >= LOOP_SPAN) break; } //DebagComment("calcCore : finished"); } //目標座標の変更を行う関数 void ChengeGoalValue(kine::Kinematics *arm){ printf("Started --- Input Amount of movement ---\n"); //軸選択 double axisInputBuf = 0; // int axisChoiseNum = -1; // char chooseAxis[2]; while (1) { axisChoiseNum = -1; printf("enter to OVER WRITE Axis key (X or Y or Z)\n"); printf("when finished, enter \"Q\" \n ->"); fgets(chooseAxis, 2, stdin); if (chooseAxis[0] == 'x' || chooseAxis[0] == 'X') { printf("Input axis X \n"); axisChoiseNum = 0; } else if (chooseAxis[0] == 'y' || chooseAxis[0] == 'Y') { printf("Input axis Y \n"); axisChoiseNum = 1; } else if (chooseAxis[0] == 'z' || chooseAxis[0] == 'Z') { printf("Input axis Z \n"); axisChoiseNum = 2; } else if (chooseAxis[0] == 'i') { printf("Input 'I' (Reset the goal point to now place\n"); axisChoiseNum = 3; } else if (chooseAxis[0] == 'q') { printf("Exit enter Amount of movement\n\n\n"); break; } else { printf("Unrecognizable. enter again\n\n"); continue; } if (axisChoiseNum > -1 && axisChoiseNum < 3) { printf("enter Value of movement [mm]\n-> "); scanf("%lf", &axisInputBuf); getchar(); axisInputBuf *= 0.001; //cherryPos[i] += axisInputBuf; cherryPos.mid[axisChoiseNum] += axisInputBuf; printf("finished enter value\n\n\n"); } else if (axisChoiseNum = 3) { double handPositionCoord[3] = {}; getchar(); arm->CalcFK(currentJointRad); arm->DisplayCoordinate(); arm->GetCoordinate(handPositionCoord); cherryPos.pointAssignMid(handPositionCoord); printf("reset complite\n"); axisChoiseNum = -1; } } } //座標(x,y,z)により操作するキーボードコールバック関数 void SimulatorKeyPressCB(void *userData, SoEventCallback *eventCB) { //clock_t start, end; //start = clock(); //肘,手首,手先位置を格納する static kine::Kinematics arm; //手先速度格納配列 double speed[7] = {}; //エラーチェックフラグ int check = 0; //経過時間格納変数 static double CurrentTime = 0; //計算機起動フラグ FALSEならoff,TRUEならon bool calcSwitch = FALSE; //セルフモーションフラグ True なら ON int selfMotionOn = TRUE; //関節変数の初期化フラグ static bool currentJointRadInitSwitch = TRUE; const SoEvent *event = eventCB->getEvent(); //関節変数の初期化 if (currentJointRadInitSwitch == TRUE) { CurrentJointRadInit(); currentJointRadInitSwitch = FALSE; pointInitialize(); } //スペースマウスの値取得 /* if (event->isOfType(SoMotion3Event::getClassTypeId())) { SoMotion3Event* tr = (SoMotion3Event*)event; spaceMouseInput[0] = SPACEMOUSE_TRANSLATION_GAIN * tr->getTranslation().getValue()[0]; //x軸 spaceMouseInput[1] = SPACEMOUSE_TRANSLATION_GAIN * tr->getTranslation().getValue()[1]; //y軸 spaceMouseInput[2] = SPACEMOUSE_TRANSLATION_GAIN * tr->getTranslation().getValue()[2]; //z軸 spaceMouseInput[3] = SPACEMOUSE_ROTATION_GAIN * tr->getRotation().getValue()[0]; //α spaceMouseInput[4] = SPACEMOUSE_ROTATION_GAIN * tr->getRotation().getValue()[1]; //y軸回り回転 spaceMouseInput[5] = SPACEMOUSE_ROTATION_GAIN * tr->getRotation().getValue()[2]; //speed[3] = -spaceMouseInput[4]; //ロール speed[4] = -spaceMouseInput[5]; //ヨー speed[5] = spaceMouseInput[3]; //ピッチ calcSwitch = 1; } */ if (SO_KEY_PRESS_EVENT(event, T)) { ChengeGoalValue(&arm); CurrentTime = 0; //Reset VelocityRegulation } //必要な計算等すべてを行うキー A (all) if (SO_KEY_PRESS_EVENT(event, A)) { calcSwitch = TRUE; selfMotionOn = 1; speed[6] = 0.0; } //手先位置を初期姿勢に戻すキー R (restart) if (SO_KEY_PRESS_EVENT(event, R)) { system("cls"); currentJointRadInitSwitch = TRUE; CurrentTime = 0; DisplayDescription(); } //セルフモーション if (SO_KEY_PRESS_EVENT(event, S)) { calcSwitch = TRUE; selfMotionOn = 1; speed[6] = M_PI * kine::TIME_SPAN; } if (SO_KEY_PRESS_EVENT(event, D)) { calcSwitch = TRUE; selfMotionOn = 1; speed[6] = -M_PI * kine::TIME_SPAN; } //手先操作 if (SO_KEY_PRESS_EVENT(event, J)) { calcSwitch = TRUE; selfMotionOn = 1; speed[4] = -M_PI * kine::TIME_SPAN; speed[6] = speed[4] / 3; }//Yaw if (SO_KEY_PRESS_EVENT(event, L)) { calcSwitch = TRUE; selfMotionOn = 1; speed[4] = M_PI * kine::TIME_SPAN; speed[6] = speed[4] / 3; }//Yaw if (SO_KEY_PRESS_EVENT(event, K)) { calcSwitch = TRUE; selfMotionOn = 1; speed[5] = M_PI * kine::TIME_SPAN; speed[6] = 0; }//pitch if (SO_KEY_PRESS_EVENT(event, I)) { calcSwitch = TRUE; selfMotionOn = 1; speed[5] = -M_PI * kine::TIME_SPAN; speed[6] = 0; }//pitch //パラメータ表示 if (SO_KEY_PRESS_EVENT(event, P)) { arm.CalcFK(currentJointRad); DisplayParametors(&arm); } if (SO_KEY_PRESS_EVENT(event, Z)) { kinemaDebagON(); } if (SO_KEY_PRESS_EVENT(event, X)) { kinemaDebagOFF(); } //計算プログラム開始 if (calcSwitch == TRUE) { CalcCore(&CurrentTime, &arm, selfMotionOn, speed); } if (SO_KEY_PRESS_EVENT(event, W)) { WriteOut(); } //プログラム終了 if (SO_KEY_PRESS_EVENT(event, Q)) { //DebagCom("program finished"); exit(1); } //SpeedIntegration(speed); if (check > 0) { ErrComment("\n\n\n*** fatal error ***\n*** please enter 'q' for finish this program ***\n"); exit(1); } //end = clock(); printf("処理時間:%lf[ms]\n",(double)(end - start)/CLOCKS_PER_SEC); //DebagComment("call back finished\n"); } /*SoWinSpaceball* SpaceMouseSet() { float f; if (SoWinSpaceball::exists()) { printf("スペースマウスを検出できません\n"); exit(1); } SoWinSpaceball* sb = new SoWinSpaceball; f = sb->getRotationScaleFactor(); printf("Spacemouse::RotationScaleFactor\t= %f\n", f); f = sb->getTranslationScaleFactor(); printf("Spacemouse::TranslationScaleFactor\t= %f\n", f); return sb; } */ //各関節の回転コールバック static void Arm1RotSensorCallback(void *b_data1, SoSensor *) { SoTransform *rot1 = (SoTransform *)b_data1; rot1->center.setValue(0, 0, 0); rot1->rotation.setValue(SbVec3f(0, 0, 1), currentJointRad[0]); } static void Arm2RotSensorCallback(void *b_data2, SoSensor *) { SoTransform *rot2 = (SoTransform *)b_data2; rot2->center.setValue(0, 0, 0); rot2->rotation.setValue(SbVec3f(0, 0, 1), currentJointRad[1]); } static void Arm3RotSensorCallback(void *b_data3, SoSensor *) { SoTransform *rot3 = (SoTransform *)b_data3; rot3->center.setValue(0, 0, 0); rot3->rotation.setValue(SbVec3f(0, 0, 1), currentJointRad[2]); } static void Arm4RotSensorCallback(void *b_data4, SoSensor *) { SoTransform *rot4 = (SoTransform *)b_data4; rot4->center.setValue(0, 0, 0); rot4->rotation.setValue(SbVec3f(0, 0, 1), currentJointRad[3]); } static void Arm5RotSensorCallback(void *b_data5, SoSensor *) { SoTransform *rot5 = (SoTransform *)b_data5; rot5->center.setValue(0, 0, 0); rot5->rotation.setValue(SbVec3f(0, 0, 1), currentJointRad[4]); //Z } static void Arm6RotSensorCallback(void *b_data6, SoSensor *) { SoTransform *rot6 = (SoTransform *)b_data6; rot6->center.setValue(0, 0, 0); rot6->rotation.setValue(SbVec3f(0, 0, 1), currentJointRad[5]); } static void Arm7RotSensorCallback(void *b_data7, SoSensor *) { SoTransform *rot7 = (SoTransform *)b_data7; rot7->center.setValue(0, 0, 0); rot7->rotation.setValue(SbVec3f(0, 0, 1), currentJointRad[6]); //Y /* static int i = 0; ++i; if (i == 10) printf("fps check start\n"); if (i == 1010) { printf("1000 roops\n"); i = 0; } */ } static void RedPointSensorCallback(void *b_data8, SoSensor *) { SoTranslation *trans8 = (SoTranslation*)b_data8; trans8->translation.setValue(handCameraCoordinate[0], handCameraCoordinate[1], handCameraCoordinate[2]); } static void GoalPointSensorCallback(void *b_data, SoSensor *) { SoTranslation *trans = (SoTranslation*)b_data; trans->translation.setValue(cherryPos.mid[0], cherryPos.mid[1], cherryPos.mid[2]); } void ArmSimulator(int argc){ //説明文の表示 DisplayDescription(); pointInitialize(); //画面の初期化 HWND myWindow = SoWin::init(""); //プログラムツリーの始まり SoSeparator *root = new SoSeparator; SoSeparator *arms = new SoSeparator; //各オブジェクトツリーのセパレータの作成 SoSeparator *basesep = new SoSeparator; SoSeparator *arm1sep = new SoSeparator; SoSeparator *arm2sep = new SoSeparator; SoSeparator *arm3sep = new SoSeparator; SoSeparator *arm4sep = new SoSeparator; SoSeparator *arm5sep = new SoSeparator; SoSeparator *arm6sep = new SoSeparator; SoSeparator *arm7sep = new SoSeparator; //スペースマウスの確認 //if (SoWinSpaceball::exists()) { printf("spaceball No Exists\n"); exit(1); } //spacemouse callback //SoEventCallback *spaceMouseCB = new SoEventCallback; //spaceMouseCB->addEventCallback(SoMotion3Event::getClassTypeId(), MyKeyPressCB, root); //コールバック SoEventCallback *eventcallback = new SoEventCallback; eventcallback->addEventCallback(SoKeyboardEvent::getClassTypeId(), SimulatorKeyPressCB, root); //目標描画 SoSeparator *cherryPosSep = new SoSeparator; GoalCherry(cherryPos.mid, cherryPosSep); //カメラ位置確認用赤玉 SoSeparator *redPointSep = new SoSeparator; SoTranslation *redPointTrans = new SoTranslation; SoTimerSensor *redPointTransMoveSensor = new SoTimerSensor(RedPointSensorCallback, redPointTrans); redPointTransMoveSensor->setInterval(0.01); redPointTransMoveSensor->schedule(); redPointSep->addChild(redPointTrans); PointObj(redPointSep); ////////////////////////////////////////// //目標座標三点確認用 SoSeparator *goalPoints = new SoSeparator; SoSeparator *topSep = new SoSeparator; SoSeparator *midSep = new SoSeparator; SoSeparator *btmSep = new SoSeparator; PointObj(cherryPos.top, topSep); PointObj(cherryPos.mid, midSep); PointObj(cherryPos.btm, btmSep); SoTranslation *goalPointTrans = new SoTranslation; SoTimerSensor *goalPointTransMoveSensor = new SoTimerSensor(GoalPointSensorCallback, goalPointTrans); goalPointTransMoveSensor->setInterval(0.01); goalPointTransMoveSensor->schedule(); goalPoints->addChild(topSep); goalPoints->addChild(midSep); goalPoints->addChild(btmSep); //支柱のアルミフレーム SoSeparator *almiFlame1 = new SoSeparator; SoSeparator *almiFlame2 = new SoSeparator; //std::vector<double> alm1Position = { 0.11, -0.916, -0.210 }; std::vector<double> alm1Position = { 0.0, -0.916, -0.210 }; std::vector<double> alm2Position = { -0.08, -0.916, -0.210 }; AlmiFlame(alm1Position, almiFlame1); AlmiFlame(alm2Position, almiFlame2); //座標系表示 SoSeparator *coordinateSystem = new SoSeparator; CoordinateSystem(coordinateSystem); //座標変換用変数 arm(x)trans xは対応する関節番号 SoTranslation *baseTrans = new SoTranslation; SoTranslation *arm1Trans = new SoTranslation; SoTranslation *arm2Trans = new SoTranslation; SoTranslation *arm3Trans = new SoTranslation; SoTranslation *arm4Trans = new SoTranslation; SoTranslation *arm5Trans = new SoTranslation; SoTranslation *arm6Trans = new SoTranslation; SoTranslation *arm7Trans = new SoTranslation; //部品読み込み SoInput baseIpt; SoInput arm1Ipt; SoInput arm2Ipt; SoInput arm3Ipt; SoInput arm4Ipt; SoInput arm5Ipt; SoInput arm6Ipt; SoInput arm7Ipt; if (argc == 0) { //超簡易版アーム///////////////////////////////////////////////// if (!baseIpt.openFile("Arms1.0/base.wrl")) exit(1); if (!arm1Ipt.openFile("Arms1.0/arm1.wrl")) exit(1); if (!arm2Ipt.openFile("Arms1.0/arm2.wrl")) exit(1); if (!arm3Ipt.openFile("Arms1.0/arm3.wrl")) exit(1); if (!arm4Ipt.openFile("Arms1.0/arm4.wrl")) exit(1); if (!arm5Ipt.openFile("Arms1.0/arm5.wrl")) exit(1); if (!arm6Ipt.openFile("Arms1.0/arm6.wrl")) exit(1); if (!arm7Ipt.openFile("Arms1.0/arm7fix.wrl")) exit(1); baseTrans->translation.setValue(0.0, 0.0, -0.164); arm1Trans->translation.setValue(0.0, 0.0, 0.01); arm2Trans->translation.setValue(0.0, 0.0, 0.154); arm3Trans->translation.setValue(0.0, 0.0, 0.0); arm4Trans->translation.setValue(0.0, 0.0, 0.322); arm5Trans->translation.setValue(0.0, -0.22, 0.0); arm6Trans->translation.setValue(0.0, 0.0, 0.037); arm7Trans->translation.setValue(0.0, -0.022, 0.0); } else if (argc == 1) { //カメラ付きアーム版////////////////////////////////////////////// if (!baseIpt.openFile("Arms4.0/ArmBaseRefine.wrl")) exit(1); if (!arm1Ipt.openFile("Arms4.0/Arm1Refine.wrl")) exit(1); if (!arm2Ipt.openFile("Arms4.0/Arm2Refine.wrl")) exit(1); if (!arm3Ipt.openFile("Arms4.0/Arm3Refine.wrl")) exit(1); if (!arm4Ipt.openFile("Arms4.0/Arm4Refine.wrl")) exit(1); if (!arm5Ipt.openFile("Arms4.0/Arm5Refine.wrl")) exit(1); if (!arm6Ipt.openFile("Arms4.0/Arm6Refine.wrl")) exit(1); if (!arm7Ipt.openFile("Arms4.0/Arm7Finished.wrl")) exit(1); baseTrans->translation.setValue(0.0, 0.0, -0.164); arm1Trans->translation.setValue(0.0, 0.0, 0.006); arm2Trans->translation.setValue(0.0, 0.0, 0.158); arm3Trans->translation.setValue(0.0, 0.007, 0.0); arm4Trans->translation.setValue(0.0, 0.0, 0.329); arm5Trans->translation.setValue(0.0, -0.237, 0.0); arm6Trans->translation.setValue(0.0, 0.0, 0.020); arm7Trans->translation.setValue(0.0, -0.008, 0.0); } //オブジェクトをセパレータに格納//////////////////////////////////////////////////////////////////////// SoSeparator *baseObj = SoDB::readAll(&baseIpt); SoSeparator *arm1Obj = SoDB::readAll(&arm1Ipt); SoSeparator *arm2Obj = SoDB::readAll(&arm2Ipt); SoSeparator *arm3Obj = SoDB::readAll(&arm3Ipt); SoSeparator *arm4Obj = SoDB::readAll(&arm4Ipt); SoSeparator *arm5Obj = SoDB::readAll(&arm5Ipt); SoSeparator *arm6Obj = SoDB::readAll(&arm6Ipt); SoSeparator *arm7Obj = SoDB::readAll(&arm7Ipt); //オブジェクトをセパレータに格納//////////////////////////////////////////////////////////////////////// //.wrlの読み込みエラー判定//////////////////////////////////////////////// if (baseObj == NULL) exit(1); if (arm1Obj == NULL) exit(1); if (arm2Obj == NULL) exit(1); if (arm3Obj == NULL) exit(1); if (arm4Obj == NULL) exit(1); if (arm5Obj == NULL) exit(1); if (arm6Obj == NULL) exit(1); if (arm7Obj == NULL) exit(1); //.wrlの読み込みエラー判定//////////////////////////////////////////////// //関節回転コールバック///////////////////////////////////////////////////////////////////////////////////////// SoTransform *arm1Rot = new SoTransform; SoTransform *arm2Rot = new SoTransform; SoTransform *arm3Rot = new SoTransform; SoTransform *arm4Rot = new SoTransform; SoTransform *arm5Rot = new SoTransform; SoTransform *arm6Rot = new SoTransform; SoTransform *arm7Rot = new SoTransform; SoTimerSensor *arm1MoveSensor = new SoTimerSensor(Arm1RotSensorCallback, arm1Rot); SoTimerSensor *arm2MoveSensor = new SoTimerSensor(Arm2RotSensorCallback, arm2Rot); SoTimerSensor *arm3MoveSensor = new SoTimerSensor(Arm3RotSensorCallback, arm3Rot); SoTimerSensor *arm4MoveSensor = new SoTimerSensor(Arm4RotSensorCallback, arm4Rot); SoTimerSensor *arm5MoveSensor = new SoTimerSensor(Arm5RotSensorCallback, arm5Rot); SoTimerSensor *arm6MoveSensor = new SoTimerSensor(Arm6RotSensorCallback, arm6Rot); SoTimerSensor *arm7MoveSensor = new SoTimerSensor(Arm7RotSensorCallback, arm7Rot); arm1MoveSensor->setInterval(0.01); arm2MoveSensor->setInterval(0.01); arm3MoveSensor->setInterval(0.01); arm4MoveSensor->setInterval(0.01); arm5MoveSensor->setInterval(0.01); arm6MoveSensor->setInterval(0.01); arm7MoveSensor->setInterval(0.01); arm1MoveSensor->schedule(); arm2MoveSensor->schedule(); arm3MoveSensor->schedule(); arm4MoveSensor->schedule(); arm5MoveSensor->schedule(); arm6MoveSensor->schedule(); arm7MoveSensor->schedule(); //関節回転コールバック///////////////////////////////////////////////////////////////////////////////////////// //部品ごとの初期設定/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// SoTransform *arm1InitialRot = new SoTransform; arm1InitialRot->rotation.setValue(SbVec3f(1, 0, 0), 0); SoTransform *arm2InitialRot = new SoTransform; arm2InitialRot->rotation.setValue(SbVec3f(1, 0, 0), -M_PI / 2); SoTransform *arm3InitialRot = new SoTransform; arm3InitialRot->rotation.setValue(SbVec3f(1, 0, 0), M_PI / 2); SoTransform *arm4InitialRot = new SoTransform; arm4InitialRot->rotation.setValue(SbVec3f(1, 0, 0), -M_PI / 2); SoTransform *arm5InitialRot = new SoTransform; arm5InitialRot->rotation.setValue(SbVec3f(1, 0, 0), M_PI / 2); SoTransform *arm6InitialRot = new SoTransform; arm6InitialRot->rotation.setValue(SbVec3f(1, 0, 0), -M_PI / 2); SoTransform *arm7InitialRot = new SoTransform; arm7InitialRot->rotation.setValue(SbVec3f(1, 0, 0), M_PI / 2); //部品ごとの初期設定/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// //セパレータツリー作成/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// basesep->addChild(baseTrans); basesep->addChild(baseObj); //basesep->addChild(coordinateSystem); arm1sep->addChild(arm1Trans); arm1sep->addChild(arm1InitialRot); arm1sep->addChild(arm1Rot); arm1sep->addChild(arm1Obj); //arm1sep->addChild(coordinateSystem); arm2sep->addChild(arm2Trans); arm2sep->addChild(arm2InitialRot); arm2sep->addChild(arm2Rot); arm2sep->addChild(arm2Obj); //arm2sep->addChild(coordinateSystem); arm3sep->addChild(arm3Trans); arm3sep->addChild(arm3InitialRot); arm3sep->addChild(arm3Rot); arm3sep->addChild(arm3Obj); //arm3sep->addChild(coordinateSystem); arm4sep->addChild(arm4Trans); arm4sep->addChild(arm4InitialRot); arm4sep->addChild(arm4Rot); arm4sep->addChild(arm4Obj); //arm4sep->addChild(coordinateSystem); arm5sep->addChild(arm5Trans); arm5sep->addChild(arm5InitialRot); arm5sep->addChild(arm5Rot); arm5sep->addChild(arm5Obj); //arm5sep->addChild(coordinateSystem); arm6sep->addChild(arm6Trans); arm6sep->addChild(arm6InitialRot); arm6sep->addChild(arm6Rot); arm6sep->addChild(arm6Obj); //arm6sep->addChild(coordinateSystem); arm7sep->addChild(arm7Trans); arm7sep->addChild(arm7InitialRot); arm7sep->addChild(arm7Rot); arm7sep->addChild(arm7Obj); arm7sep->addChild(coordinateSystem); //セパレータツリーの作成/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// //部品組み立て部分/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// root->ref(); SoSeparator *rootSep = new SoSeparator; root->addChild(rootSep); rootSep->addChild(coordinateSystem); //world coordinate system //rootSep->addChild(cheerySep); rootSep->addChild(almiFlame1); rootSep->addChild(almiFlame2); rootSep->addChild(goalPoints); //root->addChild(redPointSep); //root->addChild(spaceMouseCB); root->addChild(eventcallback); root->addChild(arms); arms->addChild(basesep); basesep->addChild(arm1sep); arm1sep->addChild(arm2sep); arm2sep->addChild(arm3sep); arm3sep->addChild(arm4sep); arm4sep->addChild(arm5sep); arm5sep->addChild(arm6sep); arm6sep->addChild(arm7sep); //部品組み立て部分/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// //ビュワーの設定/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// SoWinExaminerViewer *myViewer = new SoWinExaminerViewer(myWindow); //myViewer->registerDevice(SpaceMouseSet()); myViewer->setSceneGraph(root); myViewer->setTitle("simulator 7dof arm"); myViewer->setBackgroundColor(SbColor(0.3, 0.3, 0.4)); myViewer->setSize(SbVec2s(720, 600)); myViewer->show(); //ビュワーの設定/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// SoWin::show(myWindow); SoWin::mainLoop(); } //*******************絶対消すな!!!!!************************** /* //座標点確認用サクランボ描画 void GoalCherry(SoSeparator *GoalSep) { /////////////////////////////////////// SoInput GoalIpt; if (!GoalIpt.openFile("cherryfruit.wrl")) exit(1); SoSeparator *GoalObj1 = SoDB::readAll(&GoalIpt); if (GoalObj1 == NULL) exit(1); //color SoMaterial *GoalColor = new SoMaterial; GoalColor->diffuseColor.setValue(1, 0, 0); //位置合わせ SoTranslation *GoalTranslation1 = new SoTranslation; //GoalTranslation1->translation.setValue(HANDGOAL[0], HANDGOAL[1] - 0.03, HANDGOAL[2]); GoalTranslation1->translation.setValue(cherry.mid[0], cherry.mid[1] - 0.03, cherry.mid[2]); SoTransform *GoalInitialrot = new SoTransform; //Y GoalSep->addChild(GoalColor); GoalSep->addChild(GoalTranslation1); //GoalSep->addChild(GoalTransform); GoalSep->addChild(GoalObj1); } void PointObj(std::vector<double> position, SoSeparator *redPoint) { SoSphere *redP = new SoSphere; redP->radius = 0.01; SoMaterial *myMaterial = new SoMaterial; myMaterial->diffuseColor.setValue((rand() % 101) * 0.01, (rand() % 101) * 0.01, (rand() % 101) * 0.01); SoTranslation *trans = new SoTranslation; trans->translation.setValue(position[0], position[1], position[2]); redPoint->addChild(myMaterial); redPoint->addChild(trans); redPoint->addChild(redP); } void PointObj(SoSeparator *redPoint) { SoSphere *redP = new SoSphere; redP->radius = 0.01; SoMaterial *myMaterial = new SoMaterial; myMaterial->diffuseColor.setValue((rand() % 101) * 0.01, (rand() % 101) * 0.01, (rand() % 101) * 0.01); redPoint->addChild(myMaterial); redPoint->addChild(redP); } //アルミフレーム描画 void AlmiFlame1(SoSeparator *armFlame) { /////////////////////////////////////// SoInput armFlameIpt; if (!armFlameIpt.openFile("hfsh8-8080-1000_vertical.wrl")) exit(1); SoSeparator *armFlameObj = SoDB::readAll(&armFlameIpt); if (armFlameObj == NULL) exit(1); //color SoMaterial *GoalColor = new SoMaterial; GoalColor->diffuseColor.setValue(0.7, 0.7, 0.7); //位置合わせ SoTranslation *GoalTranslation = new SoTranslation; GoalTranslation->translation.setValue(0.11, -0.916, -0.210); SoTransform *GoalInitialrot = new SoTransform; //Y armFlame->addChild(GoalColor); armFlame->addChild(GoalTranslation); //GoalSep->addChild(GoalTransform); armFlame->addChild(armFlameObj); } void AlmiFlame2(SoSeparator *armFlame) { /////////////////////////////////////// SoInput armFlameIpt; if (!armFlameIpt.openFile("hfsh8-8080-1000_vertical.wrl")) exit(1); SoSeparator *armFlameObj = SoDB::readAll(&armFlameIpt); if (armFlameObj == NULL) exit(1); //color SoMaterial *GoalColor = new SoMaterial; GoalColor->diffuseColor.setValue(0.7, 0.7, 0.7); //位置合わせ SoTranslation *GoalTranslation = new SoTranslation; GoalTranslation->translation.setValue(-0.11, -0.916, -0.210); SoTransform *GoalInitialrot = new SoTransform; //Y armFlame->addChild(GoalColor); armFlame->addChild(GoalTranslation); //GoalSep->addChild(GoalTransform); armFlame->addChild(armFlameObj); } */ /* void JointLimit() { if (currentJointRad[0] > PI) { currentJointRad[0] = PI; } if (currentJointRad[0] < 0) { currentJointRad[0] = 0; } if (currentJointRad[1] > PI / 2) { currentJointRad[1] = PI / 2; } if (currentJointRad[1] < -PI / 2) { currentJointRad[1] = -PI / 2; } if (currentJointRad[2] > PI / 2) { currentJointRad[2] = PI / 2; } if (currentJointRad[2] < -PI / 2) { currentJointRad[2] = -PI / 2; } if (currentJointRad[3] > PI / 2) { currentJointRad[3] = PI / 2; } if (currentJointRad[3] < 0) { currentJointRad[3] = 0; } if (currentJointRad[4] > PI) { currentJointRad[4] = PI; } if (currentJointRad[4] < -PI) { currentJointRad[4] = -PI; } if (currentJointRad[5] > PI / 2) { currentJointRad[5] = PI / 2; } if (currentJointRad[5] < -PI / 2) { currentJointRad[5] = -PI / 2; } if (currentJointRad[6] > PI) { currentJointRad[6] = PI; } if (currentJointRad[6] < -PI) { currentJointRad[6] = -PI; } } *******************腕初期位置******************************* baseTrans->translation.setValue(0.0, 0.0, 0.0); arm1Trans->translation.setValue(0.0, 0.0, 0.01); arm2Trans->translation.setValue(0.0, 0.0, 0.154); arm3Trans->translation.setValue(0.0, 0.0, 0.0); arm4Trans->translation.setValue(0.0, 0.0, 0.322); arm5Trans->translation.setValue(0.0, -0.22, 0.0); arm6Trans->translation.setValue(0.0, 0.0, 0.037); arm7Trans->translation.setValue(0.0, -0.022, 0.0); ********************************************************** *******************絶対消すな!!!!!************************** *******************腕初期位置 REFINE******************************* baseTrans->translation.setValue(0.0, 0.0, 0.0); arm1Trans->translation.setValue(0.0, 0.0, 0.01); arm2Trans->translation.setValue(0.0, 0.0, 0.158); arm3Trans->translation.setValue(0.0, 0.007, 0.0); arm4Trans->translation.setValue(0.0, 0.0, 0.329); arm5Trans->translation.setValue(0.0, -0.238, 0.0); arm6Trans->translation.setValue(0.0, 0.0, 0.020); arm7Trans->translation.setValue(0.0, -0.007, 0.0); */ /* //アームの回転 /////////////////////////////////////// SorotXYZ *baserot = new SorotXYZ; SorotXYZ *arm1rot = new SorotXYZ; SorotXYZ *arm2rot = new SorotXYZ; SorotXYZ *arm3rot = new SorotXYZ; SorotXYZ *arm4rot = new SorotXYZ; SorotXYZ *arm5rot = new SorotXYZ; SorotXYZ *arm6rot = new SorotXYZ; SorotXYZ *arm7rot = new SorotXYZ; /////////////////////////////////////// //回転角 /////////////////////////////////////// currentJointRad1++; if (currentJointRad1 == 180) { currentJointRad1 = 0; } baserot->angle = -M_PI / 2; //ここは回さない arm1rot->angle = currentJointRad1*M_PI / 180; //currentJointRad1; arm2rot->angle = -M_PI / 4; //currentJointRad2; arm3rot->angle = M_PI / 3; //currentJointRad3; arm4rot->angle = -M_PI / 2; //currentJointRad4; arm5rot->angle = M_PI / 3; //currentJointRad5; arm6rot->angle = -M_PI / 4; //currentJointRad6; arm7rot->angle = M_PI / 3; //currentJointRad7; /////////////////////////////////////// //回転軸 /////////////////////////////////////// baserot->axis = SorotXYZ::Y; arm1rot->axis = SorotXYZ::Z; arm2rot->axis = SorotXYZ::X; arm3rot->axis = SorotXYZ::Y; arm4rot->axis = SorotXYZ::X; arm5rot->axis = SorotXYZ::Y; arm6rot->axis = SorotXYZ::X; arm7rot->axis = SorotXYZ::Y; /////////////////////////////////////// //rotをオブジェクトに追加 /////////////////////////////////////// arms->addChild(baserot); basesep->addChild(arm1rot); arm1sep->addChild(arm2rot); arm2sep->addChild(arm3rot); arm3sep->addChild(arm4rot); arm4sep->addChild(arm5rot); arm5sep->addChild(arm6rot); arm6sep->addChild(arm7rot); /////////////////////////////////////// */<file_sep>#include "include\kine_trajectory.h" #include "include\kine_config.h" #include "include\kine_spline.h" #include "include\trapezoidal_interpolation.h" #include "include\kine_target_point.h" #include "include\kine_quat.h" #include "include\kine_convertor.h" #include "include\kinematics.h" #include "include\kine_debag.h" #include "include\kine_vector.h" //三点の情報を与えると,経由点を持つスプライン曲線を生成する. void CalcVelocitySpline(double *firstPos3, double *viaPos3, double *endPos3, double currentTime, double *moveSpeed3) { static double nowT = 0; static double beforeT = 0; //DebagComment("CalcVelocitySpline : started"); //DisplayVector(3, firstPos3); //DisplayVector(3, viaPos3); //DisplayVector(3, endPos3); double pointX[3] = { firstPos3[0], viaPos3[0], endPos3[0] }; double pointY[3] = { firstPos3[1], viaPos3[1], endPos3[1] }; double pointZ[3] = { firstPos3[2], viaPos3[2], endPos3[2] }; static Spline routeX; static Spline routeY; static Spline routeZ; if (currentTime == 0) {//初期化 //DebagComment("move velocity initialize"); routeX.initPoint(pointX, 3); routeY.initPoint(pointY, 3); routeZ.initPoint(pointZ, 3); nowT = 0; beforeT = 0; for (int i = 0; i < 3; ++i) moveSpeed3[i] = 0.0; } else if (currentTime > 0) {//現在時間が0より大きければ //DebagComment("move velocity calculation"); beforeT = nowT; //動作は節点数ではなくリンクの数 nowT += TrapeInterpolate(kine::ROUTE_LINK, kine::TIME_LENGTH, currentTime); //printf("beforeT = %lf\n", beforeT); //printf("nowT = %lf\n", nowT); moveSpeed3[0] = (routeX.calc(nowT) - routeX.calc(beforeT)); moveSpeed3[1] = (routeY.calc(nowT) - routeY.calc(beforeT)); moveSpeed3[2] = (routeZ.calc(nowT) - routeZ.calc(beforeT)); DisplayVector(3, moveSpeed3); } else if (currentTime > kine::TIME_LENGTH) {//現在時間が動作時間を超したら。 for (int i = 0; i < 3; ++i) moveSpeed3[i] = 0.0; } //DebagComment("move speed"); DisplayVector(3, moveSpeed); } void CalcVelocityLinear(double *firstPos3, double *endPos3, double currentTime, double *moveSpeed3) { int i; static double p2pLength[3]; //DisplayCoordinate(); //さくらんぼの茎に対して直接アプローチするとぶつかるので, //茎の手前に一度移動し,把持面と平行にアプローチする. //通過点(茎手前) if (currentTime < kine::TIME_SPAN) { for (int i = 0; i < 3; ++i) p2pLength[i] = endPos3[i] - firstPos3[i]; } //DebagComment("p2p length"); //DisplayVector(3, p2pLength); //台形補間の速度計算 for (int i = 0; i < 3; ++i) { moveSpeed3[i] = TrapeInterpolate(p2pLength[i], kine::TIME_LENGTH, currentTime); } } //velocity regulation posture関数内で使用するクォータニオン生成関数(初期姿勢) Quat StartPosture(double *currentJointRadian) { kine::Kinematics posture; //DebagComment("initilize first and last posture"); double handPostureRotMat[16] = {}; posture.GetHandHTM(currentJointRadian, handPostureRotMat); Quat currentPostureQ; //double firstEuler[3]; //DebagComment("first posture matrix"); DisplayRegularMatrix(4, handPostureRotMat); RotMat2Quat(handPostureRotMat, currentPostureQ); //DebagComment("first posture quat"); currentPostureQ.display(); return currentPostureQ; } //velocity regulation posture関数内で使用するクォータニオン生成関数(目標姿勢) Quat EndPosture(TarPoints *tarCoord) { double graspRotMat[16] = {}; Quat targetPostureQ; bool graspDirectionFlag = true; //目標把持方向算出(direction Z) std::vector<double> graspV(3, 0); graspV = tarCoord->graspDirection(); //DebagComment("grasp Vector"); DisplayVector(graspV); //目標姿勢算出(direction X) std::vector<double> directionX(3, 0); for (int i = 0; i < 3; ++i) directionX[i] = tarCoord->top[i] - tarCoord->btm[i]; //DebagComment("direction x"); DisplayVector(directionX); //direction X, Zを使って回転行列を求める。 //その時、外積を使ってYは求めます。 int checkDirectX = 0; //directionXのエラー判定 for (int i = 0; i < 3; ++i) { if (directionX[i] < kine::COMPARE_ZERO) ++checkDirectX; } if (checkDirectX < 3) { //エラーじゃないなら姿勢計算する //回転行列を二つのベクトルから出す //DebagComment("function : EndPosture\ncheckDirectX < 3"); DirectVector2RotMat(directionX, graspV, graspRotMat); //DebagComment("target posture matrix"); DisplayRegularMatrix(4, graspRotMat); //回転行列→クォータニオン RotMat2Quat(graspRotMat, targetPostureQ); //DebagComment("target posture Quat"); targetPostureQ.display(); } else if (checkDirectX >= 3) {//エラーなら姿勢はロボットの正面を向くようにする。 DebagComment("function : EndPosture\ncheckDirectX == 3"); targetPostureQ.assign(0.5, 0.5, 0.5, 0.5); } return targetPostureQ; } void CalcVelocityPosture(double *curJointRad, TarPoints *targetCoord, double currentTime, double *postureSpeed) { //初期姿勢クォータニオン static Quat initPostureQ; //目標姿勢クォータニオン static Quat targetPostureQ; //現在のクォータニオン static Quat nowSlerpQ; Quat beforeSlerpQ; //速度生成監視フラグ static bool generateSpeedFlag = true; //初期姿勢などを求める //生成された姿勢情報を元に速度生成を行うか決定する if (currentTime < kine::TIME_SPAN) { Quat checkQ; double checkA[4] = {}; int arrayNum = 0; //初期姿勢算出(quaternion) initPostureQ = StartPosture(curJointRad); //initPostureQ.display(); //目標姿勢算出(Quaternion) targetPostureQ = EndPosture(targetCoord); //targetPostureQ.display(); //同値のクォータニオンが生成されたかチェック checkQ = initPostureQ.sub(targetPostureQ); //クォータニオンを配列に格納 checkQ.Quat2array(checkA); for (int i = 0; i < 4; ++i) if (checkA[i] < kine::COMPARE_ZERO) ++arrayNum; //クォータニオンの中身が全てゼロなら. if (arrayNum == 4) { //DebagComment("function : velocityRegulationPosture\n quat -> same"); generateSpeedFlag = false; } else {//そうじゃなければ //DebagComment("function : velocityRegulationPosture\n quat -> diff"); generateSpeedFlag = true; } } //監視フラグによる分岐(false) if (generateSpeedFlag == false) { for (int i = 0; i < 3; ++i) postureSpeed[i] = 0.0; } //監視フラグによる分岐(true) else if (generateSpeedFlag == true) { static double beforeValue = 0.0; static double nowValue = 0.0; static double constVelocity[3] = {}; //初動は速度ゼロ if (currentTime < kine::TIME_SPAN) { for (int i = 0; i < 3; ++i) postureSpeed[i] = 0.0; beforeValue = 0.0; nowValue = 0.0; nowSlerpQ.assign(initPostureQ); } else if (currentTime >= kine::TIME_SPAN && currentTime < kine::TIME_LENGTH) { //現在時間 //printf("currentTime-> %lf\n", currentTime); //Slerpの0〜1までの補間値 nowValue += TrapeInterpolate(1, kine::TIME_LENGTH, currentTime); //DebagComment("now value"); printf("-> %3.9lf\n", nowValue); beforeSlerpQ.assign(nowSlerpQ); nowSlerpQ = initPostureQ.slerp(nowValue, targetPostureQ); //DebagComment("before slerp Quat"); beforeSlerpQ.display(); //DebagComment("now slerp Quat"); nowSlerpQ.display(); //double beforeMat[16] = {}; //double nowMat[16] = {}; //beforeSlerpQ.quat2RotM(beforeMat); //nowSlerpQ.quat2RotM(nowMat); double beforeSlerpEuler[3] = {}; double nowSlerpEuler[3] = {}; //RotMatrixToEuler(beforeMat, beforeSlerpEuler); //RotMatrixToEuler(nowMat, nowSlerpEuler); beforeSlerpQ.quat2Euler(beforeSlerpEuler); nowSlerpQ.quat2Euler(nowSlerpEuler); ////////////////////////////////////// //DebagComment("before slerp euler"); DisplayVector(3, beforeSlerpEuler); //DebagComment("now slerp euler"); DisplayVector(3, nowSlerpEuler); double eulerVelocity[3] = {}; for (int i = 0; i < 3; ++i) { double subBuf = 0.0; eulerVelocity[i] = (nowSlerpEuler[i] - beforeSlerpEuler[i]); if (fabs(eulerVelocity[i]) > 0.1) eulerVelocity[i] = 0.0; } //DebagComment(" euler velocity "); DisplayVector(3, eulerVelocity); double postureSpeedBuf[3] = {}; Euler2Angular(nowSlerpEuler, eulerVelocity, postureSpeedBuf); postureSpeed[0] = -postureSpeedBuf[1];//1 //roll postureSpeed[1] = -postureSpeedBuf[0];//0 //yaw postureSpeed[2] = -postureSpeedBuf[2];//2 //pitch //DebagComment(" posture speed "); DisplayVector(3, postureSpeed); } else if (currentTime >= kine::TIME_LENGTH) for (int i = 0; i < 3; ++i) { postureSpeed[i] = 0.0; } } //DebagComment("posture speed"); DisplayVector(3, postureSpeed); //DebagComment("calc velocity posture : finished\n"); } void CalcViaPos(TarPoints targetPoints, double via2endLength, double *returnPos3) { std::vector<double> graspV; std::vector<double> modifyV; graspV = targetPoints.graspDirection(); modifyV = mulVector(graspV, via2endLength); for (int i = 0; i < 3; ++i) { returnPos3[i] = targetPoints.mid[i] - modifyV[i]; } } <file_sep>// 2017/04/28 // created by <NAME> #include "include\plane.h" #include "include\kine_vector.h" #include "include\kine_debag.h" //二つの平面方程式のパラメータから角度を得る void AngleOfPlane(double p1[4], double p2[4], double &angle) { double numerator = 0; double denominator = 0; numerator = fabs(p1[0] * p2[0] + p1[1] * p2[1] + p1[2] * p2[2]); denominator = pow(p1[0] * p1[0] + p1[1] * p1[1] + p1[2] * p1[2], 0.5) * pow(p2[0] * p2[0] + p2[1] * p2[1] + p2[2] * p2[2], 0.5); if (denominator == 0) { ErrComment(" angle of plane function : ERROR \n denominator = 0 "); angle = 0.0f; return; } else { angle = acos(numerator / denominator); } } //空間中の3点から平面方程式のパラメータを求める void Plane(std::vector<double> p1, std::vector<double> p2, std::vector<double> p3, std::vector<double> plane) { double v1[3] = { p2[0] - p1[0], p2[1] - p1[1], p2[2] - p1[2] }; double v2[3] = { p3[0] - p1[0], p3[1] - p1[1], p3[2] - p1[2] }; double crossV[3] = {}; CrossVector(v1, v2, crossV); plane[0] = crossV[0]; plane[1] = crossV[1]; plane[2] = crossV[2]; plane[3] = -1 * (crossV[0] * p1[0] + crossV[1] * p1[1] + crossV[2] * p1[2]); for (int i = 0; i < 4; ++i) { if (plane[i] == -0.0) { plane[i] = 0.0; } } } <file_sep>// 2017/04/28 // created by <NAME> #pragma once #ifndef __CAMERA_POSITION_H__ #define __CAMERA_POSITION_H__ void ShortCameraOffset(const double *originMat, double *convertMat); void LongCameraOffset(const double *originMat, double *convertMat); void CalcHandCameraPosition(double *curRad, double *cameraCoord); #endif //__CAMERA_POSITION_H__<file_sep>#include <Inventor/Win/SoWin.h> #include <Inventor/Win/viewers/SoWinExaminerViewer.h> #include <Inventor/nodes/SoSeparator.h> #include <Inventor/nodes/SoMaterial.h> #include <Inventor/nodes/SoSphere.h> #include <Inventor/nodes/SoCube.h> #include <Inventor/nodes/SoCone.h> #include <Inventor/nodes/SoCylinder.h> #include <Inventor/nodes/SoDirectionalLight.h> #include <Inventor/nodes/SoTranslation.h> #include <Inventor/nodes/SoRotationXYZ.h> #include <Inventor/nodes/SoRotation.h> #include <Inventor/nodes/SoNormal.h> #include <Inventor/nodes/SoCoordinate3.h> #include <Inventor/nodes/SoFaceSet.h> #include <Inventor/events/SoKeyboardEvent.h> #include <Inventor/nodes/SoEventCallback.h> #include <Inventor/nodekits/SoCameraKit.h> #include <Inventor/nodekits/SoLightKit.h> #include <Inventor/nodekits/SoSceneKit.h> #include <Inventor/nodekits/SoShapeKit.h> #include <Inventor/nodes/SoPerspectiveCamera.h> #include <Inventor/nodes/SoTransform.h> #include <Inventor/engines/SoCalculator.h> #include <Inventor/engines/SoElapsedTime.h> #include <Inventor/engines/SoTimeCounter.h> #include <Inventor/sensors/SoTimerSensor.h> #include <Inventor/SbVec3f.h> double a; float a1, a2, a3; float c1, c2, c3; float h1, h2, h3; float r1, r2, r3, r4; float l1, l2, l3, l4; float z1, z2, z3, z4, z5, z6, z7; static void ////////////////////首を傾げる headrotatingSensorCallback1(void *h_data1, SoSensor *) { SoTransform *hTransform1 = (SoTransform *)h_data1; hTransform1->center.setValue(0.0, 30.0, 0.0); hTransform1->rotation.setValue(SbVec3f(0., 0., 1.), h1); } static void ////////////////////うなずく headrotatingSensorCallback2(void *h_data2, SoSensor *) { SoTransform *hTransform2 = (SoTransform *)h_data2; hTransform2->center.setValue(0.0, 17.5, 0.0); hTransform2->rotation.setValue(SbVec3f(1., 0., 0.), h2); } static void ////////////////////首を振る headrotatingSensorCallback3(void *h_data3, SoSensor *) { SoTransform *hTransform3 = (SoTransform *)h_data3; hTransform3->center.setValue(0.0, 10.5, 0.0); hTransform3->rotation.setValue(SbVec3f(0., 1., 0.), h3); } static void /////////////////////右腕を回す rarmrotatingSensorCallback1(void *r_data1, SoSensor *) { SoTransform *rTransform1 = (SoTransform *)r_data1; rTransform1->center.setValue(0.0, 0.0, 0.0); rTransform1->rotation.setValue(SbVec3f(1., 0., 0.), r1); } static void ///////////////////////右腕を挙げる rarmrotatingSensorCallback2(void *r_data2, SoSensor *) { SoTransform *rTransform2 = (SoTransform *)r_data2; rTransform2->center.setValue(41.0, 0.0, 0.0); rTransform2->rotation.setValue(SbVec3f(0., 0., 1.), r2); } static void //////////////////////右手首を回す rarmrotatingSensorCallback3(void *r_data3, SoSensor *) { SoTransform *rTransform3 = (SoTransform *)r_data3; rTransform3->center.setValue(0.0, 0.0, 0.0); rTransform3->rotation.setValue(SbVec3f(1., 0., 0.), r3); } static void //////////////////////右肘を曲げる rarmrotatingSensorCallback4(void *r_data4, SoSensor *) { SoTransform *rTransform4 = (SoTransform *)r_data4; rTransform4->center.setValue(88.0, 0.0, 0.0); rTransform4->rotation.setValue(SbVec3f(0., 0., 1.), r4); } static void /////////////////////左腕を回す larmrotatingSensorCallback1(void *l_data1, SoSensor *) { SoTransform *lTransform1 = (SoTransform *)l_data1; lTransform1->center.setValue(0.0, 0.0, 0.0); lTransform1->rotation.setValue(SbVec3f(1., 0., 0.), l1); } static void ///////////////////////左腕を挙げる larmrotatingSensorCallback2(void *l_data2, SoSensor *) { SoTransform *lTransform2 = (SoTransform *)l_data2; lTransform2->center.setValue(-41.0, 0.0, 0.0); lTransform2->rotation.setValue(SbVec3f(0., 0., 1.), l2); } static void //////////////////////左手首を回す larmrotatingSensorCallback3(void *l_data3, SoSensor *) { SoTransform *lTransform3 = (SoTransform *)l_data3; lTransform3->center.setValue(0.0, 0.0, 0.0); lTransform3->rotation.setValue(SbVec3f(1., 0., 0.), l3); } static void //////////////////////左肘を曲げる larmrotatingSensorCallback4(void *l_data4, SoSensor *) { SoTransform *lTransform4 = (SoTransform *)l_data4; lTransform4->center.setValue(-88.0, 0.0, 0.0); lTransform4->rotation.setValue(SbVec3f(0., 0., 1.), l4); } static void ////////////////////肩を動かす boxtranslationSensorCallback1(void *b_data1, SoSensor *) { SoTransform *bTransform1 = (SoTransform *)b_data1; bTransform1->translation.setValue(0, z1, 0); z1 = sin(z2); z2 += 0.03; } static void ////////////////////胸を上下させる boxtranslationSensorCallback2(void *b_data2, SoSensor *) { SoTransform *bTransform2 = (SoTransform *)b_data2; bTransform2->scaleFactor.setValue(z5, z5, 1); z5 = 1.006 + 0.006*z3; z3 = sin(z4); z4 += 0.03; // printf("%f\n",h4); } static void //////////////////////首の回転 boxrotatingSensorCallback3(void *b_data4, SoSensor *) { SoTransform *bTransform3 = (SoTransform *)b_data4; bTransform3->rotation.setValue(SbVec3f(0, 1, 0), z6); z6 = 0.05*sin(z7); z7 += 0.03; } void myKeyPressCB(void *userData, SoEventCallback *eventCB) { const SoEvent *event = eventCB->getEvent(); //頭を動かすkey //////////////////////////////////////////////////// if (SO_KEY_PRESS_EVENT(event, Z)) { h1 += M_PI / 90; } if (SO_KEY_PRESS_EVENT(event, X)) { h2 += M_PI / 90; } if (SO_KEY_PRESS_EVENT(event, C)) { h3 += M_PI / 90; } if (SO_KEY_PRESS_EVENT(event, V)) { h1 -= M_PI / 90; } if (SO_KEY_PRESS_EVENT(event, B)) { h2 -= M_PI / 90; } if (SO_KEY_PRESS_EVENT(event, N)) { h3 -= M_PI / 90; } /////////////////////////////////////////////////////// //右腕を動かす ////////////////////////////////////////////////////// if (SO_KEY_PRESS_EVENT(event, A)) { r1 += M_PI / 90; } if (SO_KEY_PRESS_EVENT(event, S)) { r2 += M_PI / 90; } if (SO_KEY_PRESS_EVENT(event, D)) { r3 += M_PI / 90; } if (SO_KEY_PRESS_EVENT(event, F)) { r4 += M_PI / 90; } if (SO_KEY_PRESS_EVENT(event, G)) { r1 -= M_PI / 90; } if (SO_KEY_PRESS_EVENT(event, H)) { r2 -= M_PI / 90; } if (SO_KEY_PRESS_EVENT(event, J)) { r3 -= M_PI / 90; } if (SO_KEY_PRESS_EVENT(event, K)) { r4 -= M_PI / 90; } /////////////////////////////////////////////////////// //左腕を動かす ////////////////////////////////////////////////////// if (SO_KEY_PRESS_EVENT(event, Q)) { l1 += M_PI / 90; } if (SO_KEY_PRESS_EVENT(event, W)) { l2 += M_PI / 90; } if (SO_KEY_PRESS_EVENT(event, E)) { l3 += M_PI / 90; } if (SO_KEY_PRESS_EVENT(event, R)) { l4 += M_PI / 90; } if (SO_KEY_PRESS_EVENT(event, T)) { l1 -= M_PI / 90; } if (SO_KEY_PRESS_EVENT(event, Y)) { l2 -= M_PI / 90; } if (SO_KEY_PRESS_EVENT(event, U)) { l3 -= M_PI / 90; } if (SO_KEY_PRESS_EVENT(event, I)) { l4 -= M_PI / 90; } /////////////////////////////////////////////////////// eventCB->setHandled(); } int main(int, char **argv) { HWND myWindow = SoWin::init(argv[0]);//radius if (myWindow == NULL) exit(1); SoSeparator *root = new SoSeparator; SoSeparator *MR1 = new SoSeparator; SoSeparator *MR2 = new SoSeparator; SoSeparator *MR3 = new SoSeparator; SoSeparator *MR4 = new SoSeparator; SoSeparator *MR5 = new SoSeparator; SoSeparator *ML1 = new SoSeparator; SoSeparator *ML2 = new SoSeparator; SoSeparator *ML3 = new SoSeparator; SoSeparator *ML4 = new SoSeparator; SoSeparator *ML5 = new SoSeparator; SoSeparator *MH1 = new SoSeparator; SoSeparator *MH2 = new SoSeparator; SoSeparator *MH3 = new SoSeparator; SoSeparator *MH4 = new SoSeparator; //謎の物体X SoCube *Box1 = new SoCube; Box1->width = 60; Box1->height = 25; Box1->depth = 26; SoSeparator *BOX1 = new SoSeparator; SoSeparator *BOX2 = new SoSeparator; SoMaterial *myMaterial = new SoMaterial; myMaterial->diffuseColor.setValue(1, 1, 1); //メタセコイアのデータを読み込みます SoInput myInput; if (!myInput.openFile("data/head_1.WRL")) return (1); SoSeparator *h1_fileContents = SoDB::readAll(&myInput); if (h1_fileContents == NULL) return (1); SoInput myInput2; if (!myInput.openFile("data/head_2.WRL")) return (1); SoSeparator *h2_fileContents = SoDB::readAll(&myInput); if (h2_fileContents == NULL) return (1); SoInput myInput3; if (!myInput.openFile("data/head_3.WRL")) return (1); SoSeparator *h3_fileContents = SoDB::readAll(&myInput); if (h3_fileContents == NULL) return (1); SoInput myInput4; if (!myInput.openFile("data/body.WRL")) return (1); SoSeparator *b_fileContents = SoDB::readAll(&myInput); if (b_fileContents == NULL) return (1); SoInput myInput5; if (!myInput.openFile("data/arm_right_1.WRL")) return (1); SoSeparator *ar1_fileContents = SoDB::readAll(&myInput); if (ar1_fileContents == NULL) return (1); SoInput myInput6; if (!myInput.openFile("data/arm_right_2.WRL")) return (1); SoSeparator *ar2_fileContents = SoDB::readAll(&myInput); if (ar2_fileContents == NULL) return (1); SoInput myInput7; if (!myInput.openFile("data/arm_right_3.WRL")) return (1); SoSeparator *ar3_fileContents = SoDB::readAll(&myInput); if (ar3_fileContents == NULL) return (1); SoInput myInput8; if (!myInput.openFile("data/arm_right_4.WRL")) return (1); SoSeparator *ar4_fileContents = SoDB::readAll(&myInput); if (ar4_fileContents == NULL) return (1); SoInput myInput9; if (!myInput.openFile("data/arm_left_1.WRL")) return (1); SoSeparator *al1_fileContents = SoDB::readAll(&myInput); if (al1_fileContents == NULL) return (1); SoInput myInput10; if (!myInput.openFile("data/arm_left_2.WRL")) return (1); SoSeparator *al2_fileContents = SoDB::readAll(&myInput); if (al2_fileContents == NULL) return (1); SoInput myInput11; if (!myInput.openFile("data/arm_left_3.WRL")) return (1); SoSeparator *al3_fileContents = SoDB::readAll(&myInput); if (al3_fileContents == NULL) return (1); SoInput myInput12; if (!myInput.openFile("data/arm_left_4.WRL")) return (1); SoSeparator *al4_fileContents = SoDB::readAll(&myInput); if (al4_fileContents == NULL) return (1); //パースカメラを定義する SoPerspectiveCamera *Camera = new SoPerspectiveCamera; //各オブジェクトのseparatorを作ります。 ///////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////// SoSeparator *head1 = new SoSeparator; SoSeparator *head2 = new SoSeparator; SoSeparator *head3 = new SoSeparator; SoSeparator *body = new SoSeparator; SoSeparator *ri_arm1 = new SoSeparator; SoSeparator *ri_arm2 = new SoSeparator; SoSeparator *ri_arm3 = new SoSeparator; SoSeparator *ri_arm4 = new SoSeparator; SoSeparator *le_arm1 = new SoSeparator; SoSeparator *le_arm2 = new SoSeparator; SoSeparator *le_arm3 = new SoSeparator; SoSeparator *le_arm4 = new SoSeparator; ///////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////// //各オブジェクトの位置を決めます。 ///////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////// SoTranslation *Transform1 = new SoTranslation; SoTranslation *Transform2 = new SoTranslation; SoTranslation *Transform3 = new SoTranslation; SoTranslation *Transform4 = new SoTranslation; SoTranslation *Transform5 = new SoTranslation; SoTranslation *Transform6 = new SoTranslation; SoTranslation *Transform7 = new SoTranslation; SoTranslation *Transform8 = new SoTranslation; SoTranslation *Transform9 = new SoTranslation; SoTranslation *Transform10 = new SoTranslation; SoTranslation *Transform11 = new SoTranslation; SoTranslation *Transform12 = new SoTranslation; SoTranslation *Transform = new SoTranslation; Transform1->translation.setValue(0.0, 7.5, 0.0); Transform2->translation.setValue(0.0, 17.5, 0.0); Transform3->translation.setValue(0.0, 31.5, 0.0); Transform4->translation.setValue(0.0, 0.0, 0.0); Transform5->translation.setValue(25.5, 0.0, 0.0); Transform6->translation.setValue(41.5, 0.0, 0.0); Transform7->translation.setValue(47.5, 0.0, 0.0); Transform8->translation.setValue(88.5, 0.0, 0.0); Transform9->translation.setValue(-25.5, 0.0, 0.0); Transform10->translation.setValue(-41.5, 0.0, 0.0); Transform11->translation.setValue(-47.5, 0.0, 0.0); Transform12->translation.setValue(-88.5, 0.0, 0.0); Transform->translation.setValue(0.0, -1.8, 0.0); ///////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////// //コールバック関数 //////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////// SoTransform *htransform1 = new SoTransform; SoTransform *htransform2 = new SoTransform; SoTransform *htransform3 = new SoTransform; SoTransform *rtransform1 = new SoTransform; SoTransform *rtransform2 = new SoTransform; SoTransform *rtransform3 = new SoTransform; SoTransform *rtransform4 = new SoTransform; SoTransform *ltransform1 = new SoTransform; SoTransform *ltransform2 = new SoTransform; SoTransform *ltransform3 = new SoTransform; SoTransform *ltransform4 = new SoTransform; SoTransform *bTransform1 = new SoTransform; SoTransform *bTransform2 = new SoTransform; SoTransform *bTransform3 = new SoTransform; SoEventCallback* EventCallback = new SoEventCallback; EventCallback->addEventCallback(SoKeyboardEvent::getClassTypeId(), myKeyPressCB, root); //head SoTimerSensor *headrotatingSensor1 = new SoTimerSensor(headrotatingSensorCallback1, htransform1); SoTimerSensor *headrotatingSensor2 = new SoTimerSensor(headrotatingSensorCallback2, htransform2); SoTimerSensor *headrotatingSensor3 = new SoTimerSensor(headrotatingSensorCallback3, htransform3); //right-arm SoTimerSensor *rarmrotatingSensor1 = new SoTimerSensor(rarmrotatingSensorCallback1, rtransform1); SoTimerSensor *rarmrotatingSensor2 = new SoTimerSensor(rarmrotatingSensorCallback2, rtransform2); SoTimerSensor *rarmrotatingSensor3 = new SoTimerSensor(rarmrotatingSensorCallback3, rtransform3); SoTimerSensor *rarmrotatingSensor4 = new SoTimerSensor(rarmrotatingSensorCallback4, rtransform4); //left-arm SoTimerSensor *larmrotatingSensor1 = new SoTimerSensor(larmrotatingSensorCallback1, ltransform1); SoTimerSensor *larmrotatingSensor2 = new SoTimerSensor(larmrotatingSensorCallback2, ltransform2); SoTimerSensor *larmrotatingSensor3 = new SoTimerSensor(larmrotatingSensorCallback3, ltransform3); SoTimerSensor *larmrotatingSensor4 = new SoTimerSensor(larmrotatingSensorCallback4, ltransform4); SoTimerSensor *boxtranslationSensor1 = new SoTimerSensor(boxtranslationSensorCallback1, bTransform1); SoTimerSensor *boxtranslationSensor2 = new SoTimerSensor(boxtranslationSensorCallback2, bTransform2); SoTimerSensor *boxtranslationSensor3 = new SoTimerSensor(boxrotatingSensorCallback3, bTransform3); headrotatingSensor1->setInterval(0.1); // scheduled once per second headrotatingSensor1->schedule(); headrotatingSensor2->setInterval(0.1); // scheduled once per second headrotatingSensor2->schedule(); headrotatingSensor3->setInterval(0.1); // scheduled once per second headrotatingSensor3->schedule(); rarmrotatingSensor1->setInterval(0.1); // scheduled once per second rarmrotatingSensor1->schedule(); rarmrotatingSensor2->setInterval(0.1); // scheduled once per second rarmrotatingSensor2->schedule(); rarmrotatingSensor3->setInterval(0.1); // scheduled once per second rarmrotatingSensor3->schedule(); rarmrotatingSensor4->setInterval(0.1); // scheduled once per second rarmrotatingSensor4->schedule(); larmrotatingSensor1->setInterval(0.1); // scheduled once per second larmrotatingSensor1->schedule(); larmrotatingSensor2->setInterval(0.1); // scheduled once per second larmrotatingSensor2->schedule(); larmrotatingSensor3->setInterval(0.1); // scheduled once per second larmrotatingSensor3->schedule(); larmrotatingSensor4->setInterval(0.1); // scheduled once per second larmrotatingSensor4->schedule(); boxtranslationSensor1->setInterval(0.01); // scheduled once per second boxtranslationSensor1->schedule(); boxtranslationSensor2->setInterval(0.01); // scheduled once per second boxtranslationSensor2->schedule(); boxtranslationSensor3->setInterval(0.01); // scheduled once per second boxtranslationSensor3->schedule(); //////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////// //各オブジェクトの中身を設定します。 //////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////// head1->addChild(Transform1); head2->addChild(Transform2); head3->addChild(Transform3); body->addChild(Transform4); ri_arm1->addChild(Transform5); ri_arm2->addChild(Transform6); ri_arm3->addChild(Transform7); ri_arm4->addChild(Transform8); le_arm1->addChild(Transform9); le_arm2->addChild(Transform10); le_arm3->addChild(Transform11); le_arm4->addChild(Transform12); head1->addChild(h1_fileContents); head2->addChild(h2_fileContents); head3->addChild(h3_fileContents); body->addChild(b_fileContents); ri_arm1->addChild(ar1_fileContents); ri_arm2->addChild(ar2_fileContents); ri_arm3->addChild(ar3_fileContents); ri_arm4->addChild(ar4_fileContents); le_arm1->addChild(al1_fileContents); le_arm2->addChild(al2_fileContents); le_arm3->addChild(al3_fileContents); le_arm4->addChild(al4_fileContents); //////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////// //右腕の動き /////////////////////////////////////////////////////////// MR1->addChild(rtransform4); MR1->addChild(ri_arm4); MR2->addChild(rtransform3); MR2->addChild(ri_arm3); MR2->addChild(MR1); MR3->addChild(rtransform2); MR3->addChild(ri_arm2); MR3->addChild(MR2); MR4->addChild(rtransform1); MR4->addChild(ri_arm1); MR4->addChild(MR3); MR5->addChild(bTransform1); MR5->addChild(MR4); //左腕の動き /////////////////////////////////////////////////////////// ML1->addChild(ltransform4); ML1->addChild(le_arm4); ML2->addChild(ltransform3); ML2->addChild(le_arm3); ML2->addChild(ML1); ML3->addChild(ltransform2); ML3->addChild(le_arm2); ML3->addChild(ML2); ML4->addChild(ltransform1); ML4->addChild(le_arm1); ML4->addChild(ML3); ML5->addChild(bTransform1); ML5->addChild(ML4); //頭の動き ////////////////////////////////////////////// MH1->addChild(htransform1); MH1->addChild(head3); MH2->addChild(htransform2); MH2->addChild(head2); MH2->addChild(MH1); MH3->addChild(htransform3); MH3->addChild(head1); MH3->addChild(MH2); MH4->addChild(bTransform3); MH4->addChild(MH3); //////////////////////////////////////////////// BOX1->addChild(Transform); BOX1->addChild(myMaterial); BOX1->addChild(Box1); BOX2->addChild(bTransform2); BOX2->addChild(BOX1); root->ref(); /*root->addChild(Camera);*/ root->addChild(EventCallback); root->addChild(body); root->addChild(MH4); root->addChild(MR5); root->addChild(ML5); root->addChild(BOX2); SoWinExaminerViewer *myViewer = new SoWinExaminerViewer(myWindow); myViewer->setSceneGraph(root); myViewer->setTitle("arm-joint"); myViewer->show(); SoWin::show(myWindow); SoWin::mainLoop(); }<file_sep>// 2017/04/28 // created by <NAME> #include "include\kine_matrix.h" #include "include\kine_debag.h" #include "include\lu.h" #include "include\kine_config.h" //#include <stdlib.h> #include <stdio.h> Matrix::Matrix() { mRow = mCol = mNum = 0; m.resize(1); mType = 0; } Matrix::Matrix(int myRow, int myColumn) { mRow = myRow; mCol = myColumn; mNum = 1; m.resize(myRow * myColumn); mType = twoD; } Matrix::Matrix(int myRow, int myColumn, int matrixSize) { mRow = myRow; mCol = myColumn; mNum = matrixSize; m.resize(myRow * myColumn * matrixSize); mType = threeD; } /* //行列用構造体のメモリ解放 void FreeMatrix(Matrix *matrix) { delete[] matrix->m; } */ Matrix::~Matrix() { m.~vector(); } void Matrix::Display() { for (int jnt = 0; jnt < MatSize(); ++jnt) { for (int i = 0; i < mRow; ++i) { for (int j = 0; j < mCol; ++j) { if (j == 0) { printf("|"); } if (mType == twoD) { printf("%lf\t", Mat2D(i, j)); } if (mType == threeD) { printf("%lf\t", Mat3D(jnt, i, j)); } } printf("|\n"); } printf("\n"); } printf("\n"); } void Matrix::Mat2D(int myRow, int myColumn, double val){ m[mCol * myRow + myColumn] = val; } double Matrix::Mat2D(int myRow, int myColumn){ double buf = m[mCol * myRow + myColumn]; return buf; } void Matrix::Mat3D(int matNum, int myRow, int myColumn, double val) { m[mRow * mCol * matNum + mCol * myRow + myColumn] = val; } double Matrix::Mat3D(int matNum, int myRow, int myColumn) { double buf = m[mCol * mRow * matNum + mCol * myRow + myColumn]; return buf; } int Matrix::Row(void) { return mRow; } int Matrix::Column(void) { return mCol; } int Matrix::MatSize(void) { return mNum; } //明示的にマトリックスのメンバ変数を変更 void Matrix::CreateDiMatrix(const int myRow, const int myColumn) { //printf("create di matrix : "); if (myRow == mRow && myColumn == mCol) { //printf("no change\n"); //どちらも変わらないならば更新しない } else { //printf("change \n"); //どちらか変わるなら更新する m.resize(myRow * myColumn); mRow = myRow; mCol = myColumn; mNum = 1; mType = twoD; } } void Matrix::CreateTriMatrix(int myRow, int myColumn, int myMatSize) { //printf("create tri matrix : "); if (myRow == mRow && myColumn == mCol) { //printf("no change\n"); //どちらも変わらないならば更新しない } else { //printf("change\n"); //どちらかでも変わるなら更新する m.resize(myRow * myColumn * myMatSize); mRow = myRow; mCol = myColumn; mNum = myMatSize; mType = threeD; } //printf("create tri matrix finished\n"); } bool Matrix::InverseMatrix(Matrix &returnMat) { //std::cout << "InverseMatrix started\n"; double d = 0; double col[10] = {}; int indx[10] = {}; int check = 0; Matrix detMat; detMat.CreateDiMatrix(mRow, mRow); for (int i = 0; i < mRow; ++i) { for (int j = 0; j < mCol; ++j) { detMat.m[detMat.Column() * i + j] = m[mCol * i + j]; } } check = Ludcmp(detMat.m, detMat.Row(), indx, &d); for (int i = 0; i < detMat.Row(); i++) { d *= detMat.m[detMat.Column() * i + i]; } if (d == 0) { ErrComment("\n.....inverse matrix determinant = 0.....\n\ .....Can not calculate.....\n"); return 1; } if (check > 0) { return check; } check = Ludcmp(m, mRow, indx, &d); for (int j = 0; j < mRow; ++j) { for (int i = 0; i < mRow; ++i) col[i] = 0.0; col[j] = 1.0; Lubksb(m, mRow, indx, col); for (int i = 0; i < mRow; ++i){ returnMat.Mat2D(i,j, col[i]); } } return check; } <file_sep>// 2017/04/28 // created by <NAME> #pragma once #ifndef __TEST_CONSOLE__ #define __TEST_CONSOLE__ void TestConsole(void); #endif // !__TEST_CONSOLE__ <file_sep>// 2017/04/28 // created by <NAME> #pragma once #ifndef __CALC_QUAT_H__ #define __CALC_QUAT_H__ #include "kine_vector.h" #define ELEM(array) (sizeof(array)/sizeof *(array)) #define ROOT_2_INV 0.70710678118 /* クォータニオン構造体 */ enum Element { wq = 0, xq = 1, yq = 2, zq = 3, }; class Quat { private: double w, x, y, z; public: Quat(); Quat(double wValue, double xValue, double yValue, double zValue); Quat(double wValue, std::vector<double> v); Quat(std::vector<double> vec4); Quat(double *vec4); ~Quat(); void display(); //Quat quatFromTwoVector(const std::vector<double> v1, const std::vector<double> v2); //void identify(); void Quat2array(double array4[4]); void assign(); void assign(double wValue, double xValue, double yValue, double zValue); void assign(double wValue, std::vector<double> v); void assign(std::vector<double> vec4); void assign(double *vec4); void assign(Quat originQ); Quat add(Quat c); Quat sub(Quat c); Quat mul(Quat nulQ); Quat mulReal(const double s); Quat divReal(const double s); Quat conjugate(); void normalize(); //double normSqr(); double norm(); //Quat inverse(); double dot(Quat dotQ); std::vector<double> cross(Quat crossQ); Quat slerp(double t, Quat tarQuat); void quat2RotM(double *rotMat); void quat2Euler(double *euler); }; #endif //__CALC_QUAT_H__<file_sep>// 2017/04/28 // created by <NAME> #pragma once #ifndef __HAND_POSTURE_H__ #define __HAND_POSTURE_H__ #include <vector> class TarPoints{ public: std::vector<double> top; //コルク部 std::vector<double> mid; //果柄中点 std::vector<double> btm; //付け根部 TarPoints(); ~TarPoints(); //void CoordinateSwap(std::vector<double> tar1); void display(); std::vector<double> graspDirection(); void pointAssignMid(double *vec3); void pointAssignTop(double *vec3); void pointAssignBtm(double *vec3); }; #endif // !__HAND_POSTURE_H__ <file_sep>#include <stdio.h> #include <math.h> #include <stdlib.h> #include "include\kinemaDebag.h" #include "include\sprainSub.h" #include "include\lu.h" //calculation difference double calcDif(const int n, double *p) { return p[n + 1] - p[n]; } double calcV(const int n, double *x, double *y) { double x_n = calcDif(n, x); double x_n_1 = calcDif(n - 1, x); double y_n = calcDif(n, y); double y_n_1 = calcDif(n - 1, y); return 6 * ((y_n / x_n) - (y_n_1 / x_n_1)); } // n : date number // x : coordinate x matrix // y : coordinate y matrix // u : sprain function's coefficient int CalcU(const int numMat,double *x, double *y, double *u) { Decom("calculation U started"); DisplayVector(numMat, x); DisplayVector(numMat, y); DisplayVector(numMat, u); //Decom("ensure memory started"); //relation calcU double *bufH = Dvector(numMat, numMat); double *invH = Dvector(numMat, numMat); double *v = Dvector(1, numMat); //relation LU separation double d = 0; int check = 0; int *index = Ivector(1, numMat); double *col = Dvector(numMat, numMat); //Decom("buffer H matrix initializing"); for (int i = 0; i < numMat; ++i) { for (int j = 0; j < numMat; ++j) { bufH[numMat * i + j] = 0; } } DisplayRegularMatrix(numMat, bufH); //////////////////////////////////// //Decom("sprain main started"); //main////////////////////////////// bufH[0] = 2 * (calcDif(0, x) + calcDif(1, x)); bufH[1] = calcDif(1, x); for (int i = 1; i < numMat - 2; ++i) { //printf("row number-> %d\n", i); bufH[(numMat - 1) * i + i - 1] = calcDif(i, x); bufH[(numMat - 1) * i + i] = 2 * (calcDif(i, x) + calcDif(i + 1, x)); bufH[(numMat - 1) * i + i + 1] = calcDif(i + 1, x); } bufH[(numMat - 1)*(numMat - 1) - 2] = calcDif(numMat - 2, x); bufH[(numMat-1)*(numMat-1) - 1] = 2 * (calcDif(numMat - 2, x) + calcDif(numMat - 1, x)); DisplayRegularMatrix(numMat,bufH); ////////////////////////////////////////// //Decom("calculation V started"); ////////////////////////////////////////// /* for (int i = 0; i < numMat-1; ++i) { v[i] = calcV(i+1, x, y); printf("%lf\n", v[i]); } */ //LU function///////////////////// //Decom("LU function started"); ////////////////////////////////// check = Ludcmp(bufH, numMat-1, index, &d); if (check > 0) return 1; DisplayRegularMatrix(numMat, bufH); if (check > 0) { Ercom("---fatal error---\n---LU algolism---"); exit(0); } //Decom("lubksb started"); for (int i = 0; i < numMat-1; ++i) { for (int j = 0; j < numMat-1; ++j) { col[j] = 0.0; } col[i] = 1.0; Lubksb(bufH, numMat-1, index, col); for (int j = 0; j < numMat-1; ++j) { invH[(numMat-1) * i + j] = col[j]; //printf("col[%d,%d] -> %lf \n", i, j, col[j]); } } Decom("display matrix current V vector"); DisplayVector(numMat, v); Decom("display Matrix current inverse H Matrix"); DisplayRegularMatrix(numMat, invH); Decom("calculation U matrix"); for (int i = 0; i < numMat-1; ++i) { for (int j = 0; j < numMat - 1; ++j) { //printf("invH(%d,%d) = %lf\n", i, j, invH[((numMat - 1) * i) + j]); //printf("V(%d9 = %lf\n", i, v[j]); //printf("(%d,%d) = %lf\n", i, j, invH[((numMat - 1) * i) + j] * v[j]); u[i] += invH[((numMat - 1) * i) + j] * v[j]; } } DisplayVector(numMat, u); //Decom("free memory"); //free(bufH); //free(invH); //free(v); //free(index); //free(col); //Decom("end calc U function"); //printf("check -> %d\n", check); return 0; } double CalcPlaneSprain(int numMat, double *x, double *y, double *u, double tarX) { int lo = 0; int hi = numMat; int k; double *uu = (double *)malloc((numMat + 2) * sizeof(double)); uu[0] = 0; uu[numMat + 1] = 0; for (int i = 0; i < numMat; ++i) { uu[i+1] = u[i]; } while (hi - lo > 1) { k = (hi + lo) / 2; if (tarX < x[k]) { hi = k; } else { lo = k; } } double constNum[4]; constNum[0] = (u[hi] - u[lo]) / (6 * (x[hi] - x[lo])); constNum[1] = u[lo] / 2.0; constNum[2] = (y[hi] - y[lo]) / (x[hi] - x[lo]) - (x[hi] - x[lo])*(2 * u[lo] + u[hi]) / 6.0; constNum[3] = y[lo]; double yy = 0; double h = tarX - x[lo]; for (int i = 0; i < 4; ++i) { yy += constNum[i]; if (i < 3) { yy = yy * h; } } return yy; } double PlaneSprain(int numMat, double *x, double *y, double tarX) { double *u = (double *)malloc(sizeof(double) * numMat); int check = 0; double yy = 0; //DisplayVector(numMat, x); //DisplayVector(numMat, y); if (!u) { Ercom("fail to prepare memory"); exit(0); } for (int i = 0; i < numMat; ++i) u[i] = 0.0; check += CalcU(numMat, x, y, u); if (check > 0) { Ercom(" ******* LU Disassembly FAILED ******* \n ***** PROGRAM FORCED TEMINATION ***** "); exit(1); } yy = CalcPlaneSprain(numMat, x, y, u, tarX); free(u); return yy; }<file_sep>SoSeparator *root = new SoSeparator; root->ref(); ////光源を作る SoSeparator *scene = new SoSeparator; SoPerspectiveCamera *myCamera = new SoPerspectiveCamera; SoPointLight *myLight = new SoPointLight; myLight->location.setValue(5, 10, 15); scene->addChild(myCamera); scene->addChild(myLight); //セパレーターを作る SoSeparator *SPHERE1 = new SoSeparator; SoSeparator *SPHERE2 = new SoSeparator; SoSeparator *SPHERE3 = new SoSeparator; ////オブジェクトを作る SoSphere *Sphere = new SoSphere; Sphere->radius = 10; SoSphere *Sphere2 = new SoSphere; Sphere2->radius = 3; SoSphere *Sphere3 = new SoSphere; Sphere3->radius = 1; //色をつける SoMaterial *pink = new SoMaterial; /* pink->diffuseColor.setValue(.8, .2, .4);//放散させる、広める pink->specularColor.setValue(1, 0, 0); //鏡のように反射することができる pink->ambientColor.setValue(1, 0, 0); //包囲した、取り巻く pink->emissiveColor.setValue(1, 0, 0); //放射性の pink->shininess = 1.; */ root->addChild(pink); ////位置を決める SoTranslation *Transform1 = new SoTranslation; Transform1->translation.setValue(-10, 0, -100); SoTranslation *Transform2 = new SoTranslation; Transform2->translation.setValue(10, 0, 10); ////各オブジェクトの中身を設定します。 SPHERE1->addChild(Transform1); SPHERE1->addChild(Sphere); SPHERE2->addChild(Transform2); SPHERE2->addChild(Sphere); SPHERE3->addChild(Sphere2); root->addChild(SPHERE1); root->addChild(SPHERE2); root->addChild(SPHERE3); SoWinExaminerViewer *myViewer = new SoWinExaminerViewer(myWindow); myViewer->setSceneGraph(root); myViewer->setTitle("cherry"); myViewer->show(); SoWin::show(myWindow); SoWin::mainLoop();<file_sep>// 2017/04/28 // created by <NAME> #define _USE_MATH_DEFINES #include <math.h> #include "include\kinematics.h" #include "include\camera_position.h" #include "include\kine_Debag.h" #include "include\kine_config.h" //近距離カメラのオフセット。 //originMatにカメラから実際に得た3次元座標を渡すと //オフセットしてconvertMatに返す。(mm) void ShortCameraOffset(const double *originMat, double *convertMat) { convertMat[0] = originMat[2] - 100; convertMat[1] = -originMat[1] - 8; convertMat[2] = -originMat[0] - 50; } //遠距離カメラのオフセット。 //originMatにカメラから実際に得た3次元座標を渡すと //オフセットしてconvertMatに返す。 void LongCameraOffset(const double *originMat, double *convertMat) { convertMat[0] = originMat[2] + 143.0; convertMat[1] = originMat[1] + 208.0; convertMat[2] = originMat[0] - 314.0; } void CameraPositionInit(double *inRad, Matrix &OM) { //DebagCom("Camera Init started"); int row, jnt; double theta[kine::MAXJOINT]; double alpha[kine::MAXJOINT]; double alength[kine::MAXJOINT]; double dlength[kine::MAXJOINT]; /*DebagBar(); for (row = 0; row < MAXJOINT; row++) { cout << inRad[row] << endl; }*/ //a(i-1) リンク間の距離 for (row = 0; row < kine::MAXJOINT; row++) { alength[row] = 0; } alength[kine::MAXJOINT-2] = kine::CAMERA_OFFSET; //alpha(i-1) 関節のねじりの位置 alpha[0] = 0; alpha[1] = -M_PI / 2; alpha[2] = M_PI / 2; alpha[3] = -M_PI / 2; alpha[4] = M_PI / 2; alpha[5] = -M_PI / 2; alpha[6] = M_PI / 2; alpha[7] = M_PI / 2; //d(i) リンク長さ dlength[0] = 0; dlength[1] = 0; dlength[2] = kine::U_ARM_LENGTH; dlength[3] = 0; dlength[4] = kine::F_ARM_LENGTH; dlength[5] = 0; dlength[6] = kine::WRIST2CAMERA_LENGTH; dlength[7] = kine::CAMERA_POSITION; //theta(i) 関節角度 for (row = 0; row < (kine::MAXJOINT - 1); row++) { theta[row] = inRad[row]; } //八番目の関節はないので theta[7] = 0.0; //デバッグ用 double cos_t, sin_t, cos_a, sin_a; for (jnt = 0; jnt < kine::MAXJOINT; jnt++) { cos_t = cos(theta[jnt]); sin_t = sin(theta[jnt]); cos_a = cos(alpha[jnt]); sin_a = sin(alpha[jnt]); cos_t = cos(theta[jnt]); sin_t = sin(theta[jnt]); cos_a = cos(alpha[jnt]); sin_a = sin(alpha[jnt]); OM.Mat3D(jnt, 0, 0, cos_t); OM.Mat3D(jnt, 0, 1, -sin_t); OM.Mat3D(jnt, 0, 2, 0.0); OM.Mat3D(jnt, 0, 3, alength[jnt]); OM.Mat3D(jnt, 1, 0, cos_a*sin_t); OM.Mat3D(jnt, 1, 1, cos_a*cos_t); OM.Mat3D(jnt, 1, 2, -sin_a); OM.Mat3D(jnt, 1, 3, -sin_a*dlength[jnt]); OM.Mat3D(jnt, 2, 0, sin_a*sin_t); OM.Mat3D(jnt, 2, 1, sin_a*cos_t); OM.Mat3D(jnt, 2, 2, cos_a); OM.Mat3D(jnt, 2, 3, cos_a*dlength[jnt]); OM.Mat3D(jnt, 3, 0, 0); OM.Mat3D(jnt, 3, 1, 0); OM.Mat3D(jnt, 3, 2, 0); OM.Mat3D(jnt, 3, 3, 1); } for (int jnt = 0; jnt < kine::MAXJOINT; ++jnt){ for (int i = 0; i < OM.Row(); ++i) { for (int j = 0; j < OM.Column(); ++j) { if (fabs(OM.Mat3D(jnt, i, j) < kine::COMPARE_ZERO)) { //cos()による浮動小数点誤差を0にする OM.Mat3D(jnt, i, j, 0.0); } if (OM.Mat3D(jnt, i, j) == -0.0) { //-0を0にする OM.Mat3D(jnt, i, j, 0.0); } } } } //debag //DebagBar(); //DisplayTriMatrix(OM, MAXJOINT); } void CalcHandCameraPosition(double *currentRadian, double *cameraCoord) { //DebagCom("FK kinematics position started"); Matrix om; om.CreateTriMatrix(4, 4, kine::MAXJOINT); Matrix htm; htm.CreateTriMatrix(4, 4, kine::MAXJOINT); //(1)同次変換行列を作る CameraPositionInit(currentRadian, om); //DisplayTriMatrix(om, MAXJOINT); //(2)同次変換行列を作る kine::CalcHTM(om, htm); //DisplayTriMatrix(htm, MAXJOINT); //(3)同次変換行列の手先位置に関する情報を書き出す. for (int i = 0; i < 3; ++i) { cameraCoord[i] = htm.Mat3D(kine::MAXJOINT - 1, i, 3); } //DisplayVector(3, cameraCoord); om.~Matrix(); htm.~Matrix(); }<file_sep> const int MAX_SPLINE_SIZE = 100; const int PLUS_NULL = 1; class Spline { int num; double a[MAX_SPLINE_SIZE + PLUS_NULL]; double b[MAX_SPLINE_SIZE + PLUS_NULL]; double c[MAX_SPLINE_SIZE + PLUS_NULL]; double d[MAX_SPLINE_SIZE + PLUS_NULL]; public: Spline() { num = 0; } void init(double *sp, int num); double culc(double t); }; <file_sep>// 2017/04/28 // created by <NAME> #pragma once #ifndef __CONVERTOR_H__ #define __CONVERTOR_H__ #include <vector> #include "kine_quat.h" void Euler2Angular(const double nowEuler[3], const double eulerVeclocity[3], double *angleVelocity); //quatanion -> RotateMatrix void RotMat2Quat(const double *rotMat, Quat &returnQuat); //ベクトル回転行列変換 //渡すベクトルは単位ベクトル(ノルムが一)であるように void DirectVector2RotMat(std::vector<double> directionX, std::vector<double> directionY, double *matrix); #endif // !__CONVERTOR_H__ <file_sep>#pragma once //sprain interpolation double PlaneSprain(const int numMat, double *x, double *y, double tarX);<file_sep>#include <stdio.h> #include <iostream> #include <stddef.h> #include <stdlib.h> #include <iomanip> #include <time.h> #include "include\kinematics.h" #include "include\lu.h" #include "include\kinemaDebag.h" static double B_ARM_LENGTH = 0.164; static double U_ARM_LENGTH = 0.322; static double F_ARM_LENGTH = 0.257; static double H_ARM_LENGTH = 0.157; //old hand //static double H_ARM_LENGTH = 0.149; //new hand //デバッグ用横線 void Dbar() { printf("-----------------------------------\n"); } //プロトタイプ宣言 static void InitOM(double *currentRadian, Matrix *OM); static void CalcJacob(Matrix *HTMMat, Matrix *Jacob, int selfmotion); static int PIM(Matrix *mat, Matrix *PIMat); //ludcmp用の一時的な計算用変数 double *vv = SetVector(MAXJOINT); //行列用構造体のメモリ確保 Matrix *CreateDiMatrix(const int row, const int column){ Matrix *temp; temp = new Matrix; temp->m = new double[row*column]; if (!temp->m) { Ercom("***Create Matrix Error***"); } temp->row = row; temp->column = column; return temp; } Matrix *CreateTriMatrix(const int row, const int column, const int numMat) { Matrix *temp; temp = new Matrix; temp->m = new double[row*column*numMat]; if (!temp->m) { Ercom("***Create Matrix Error***"); } temp->row = row; temp->column = column; return temp; } //行列用構造体のメモリ解放 void FreeMatrix(Matrix* matrix) { delete[] matrix; } double *SetVector(int nl) { //cout << "vector malloc started" << endl; double *v = new double[nl + NR_END]; if (!v) { std::cout << "malloc failure in vector()" << std::endl; } return v; } void FreeVector(double *v) { //cout << "free_vector started" << endl; delete[] v; } static int InverseMatrix(Matrix *OriginMat, Matrix *InverseMat) { //std::cout << "InverseMatrix started\n"; double d, col[MAXJOINT] = {}; int indx[MAXJOINT + NR_END] = {}; int check = 0; check = Ludcmp(OriginMat->m, OriginMat->row, indx, &d); if (check > 0) { return check; } for (int j = 0; j < OriginMat->row; j++) { for (int i = 0; i < OriginMat->row; i++)col[i] = 0.0; col[j] = 1.0; Lubksb(OriginMat->m, OriginMat->row, indx, col); for (int i = 0; i < OriginMat->row; i++) { InverseMat->m[OriginMat->row * i + j] = col[i]; } } return check; } static void InitOM(double *inRad, Matrix *OM) { //cout << "OMInit started" << endl; int row, jnt; double theta[MAXJOINT]; double alpha[MAXJOINT]; double alength[MAXJOINT]; double dlength[MAXJOINT]; /*Dbar(); for (row = 0; row < MAXJOINT; row++) { cout << inRad[row] << endl; }*/ //a(i-1) リンク間の距離 for (row = 0; row < MAXJOINT; row++) { alength[row] = 0; } //alpha(i-1) 関節のねじりの位置 alpha[0] = 0; alpha[1] = -M_PI / 2; alpha[2] = M_PI / 2; alpha[3] = -M_PI / 2; alpha[4] = M_PI / 2; alpha[5] = -M_PI / 2; alpha[6] = M_PI / 2; alpha[7] = 0; //d(i) リンク長さ dlength[0] = 0; dlength[1] = 0; dlength[2] = U_ARM_LENGTH; dlength[3] = 0; dlength[4] = F_ARM_LENGTH; dlength[5] = 0; dlength[6] = 0; dlength[7] = H_ARM_LENGTH; //theta(i) 関節角度 theta[0] = inRad[0]; theta[1] = inRad[1]; theta[2] = inRad[2]; theta[3] = inRad[3]; theta[4] = inRad[4]; theta[5] = inRad[5]; theta[6] = inRad[6]; //八番目の関節はないので theta[7] = 0.0; double cos_t,sin_t,cos_a,sin_a; for (jnt = 0; jnt < MAXJOINT; jnt++) { cos_t = cos(theta[jnt]); sin_t = sin(theta[jnt]); cos_a = cos(alpha[jnt]); sin_a = sin(alpha[jnt]); OM->m[OM->column * OM->row * jnt + 4 * 0 + 0] = cos_t; OM->m[OM->column * OM->row * jnt + 4 * 0 + 1] = -sin_t; OM->m[OM->column * OM->row * jnt + 4 * 0 + 2] = 0.0; OM->m[OM->column * OM->row * jnt + 4 * 0 + 3] = alength[jnt]; OM->m[OM->column * OM->row * jnt + 4 * 1 + 0] = cos_a*sin_t; OM->m[OM->column * OM->row * jnt + 4 * 1 + 1] = cos_a*cos_t; OM->m[OM->column * OM->row * jnt + 4 * 1 + 2] = -sin_a; OM->m[OM->column * OM->row * jnt + 4 * 1 + 3] = -sin_a*dlength[jnt]; OM->m[OM->column * OM->row * jnt + 4 * 2 + 0] = sin_a*sin_t; OM->m[OM->column * OM->row * jnt + 4 * 2 + 1] = sin_a*cos_t; OM->m[OM->column * OM->row * jnt + 4 * 2 + 2] = cos_a; OM->m[OM->column * OM->row * jnt + 4 * 2 + 3] = cos_a*dlength[jnt]; OM->m[OM->column * OM->row * jnt + 4 * 3 + 0] = 0; OM->m[OM->column * OM->row * jnt + 4 * 3 + 1] = 0; OM->m[OM->column * OM->row * jnt + 4 * 3 + 2] = 0; OM->m[OM->column * OM->row * jnt + 4 * 3 + 3] = 1; } //cos()にtる浮動小数点誤差を0にする for (row = 0; row < (MAXJOINT) * OM->column * OM->column; row++) { if (fabs(OM->m[row]) < COMPARE_ZERO) { OM->m[row] = 0; } } //-0を0にする for (row = 0; row < (MAXJOINT) * OM->column * OM->column; row++) { if (OM->m[row] == -0) { OM->m[row] = 0; } } //debag //Dbar(); //DisplayTriMatrix(OM, MAXJOINT); } void CalcHTM(Matrix *OM, Matrix *HTMMat) { //cout << "HTMCalc started" << endl; Matrix *tempMat; tempMat = CreateDiMatrix(4, 4); Matrix *sum; sum = CreateDiMatrix(4, 4); //cout <<"HTM Function Started" <<endl; //cout <<"initializing tempMatrix" <<endl; for (int row = 0; row < tempMat->row; row++) { for (int column = 0; column < tempMat->column; column++) { if (row == column) { tempMat->m[4 * row + column] = 1.0; } else { tempMat->m[4 * row + column] = 0.0; } } } //同次変換行列の計算(心臓部)////////////// //cout << "HTM calculation Started" << endl; for (int joint = 0; joint < MAXJOINT; joint++) { for (int row = 0; row < sum->row; row++) { for (int column = 0; column < sum->column; column++) { sum->m[4 * row + column] = tempMat->m[tempMat->column * row + 0] * OM->m[OM->row * OM->column * joint + OM->column * 0 + column] + tempMat->m[tempMat->column * row + 1] * OM->m[OM->row * OM->column * joint + OM->column * 1 + column] + tempMat->m[tempMat->column * row + 2] * OM->m[OM->row * OM->column * joint + OM->column * 2 + column] + tempMat->m[tempMat->column * row + 3] * OM->m[OM->row * OM->column * joint + OM->column * 3 + column]; } } for (int row = 0; row < sum->row; row++) { for (int column = 0; column < sum->column; column++) { tempMat->m[tempMat->column * row + column] = sum->m[sum->column * row + column]; HTMMat->m[HTMMat->row * HTMMat->column * joint + HTMMat->column * row + column] = sum->m[sum->column * row + column]; } } } ////////////(心臓部)//////////////////////// FreeMatrix(tempMat); FreeMatrix(sum); } static void CalcJacob(Matrix *HTMMat, Matrix *Jacob, int selfmotion) { //cout << "JacobCalc started" << endl; int row,joint; double ArmPosition[3] = {}; double PosiVector[3] = {}; for (row = 0; row < 3; row++) { ArmPosition[row] = HTMMat->m[HTMMat->row * (MAXJOINT-1) + 4 * row + 3]; //cout << ArmPosition[i] <<endl; } for (joint = 0; joint < (MAXJOINT-1); joint++) { //0PE,n -> x PosiVector[0] = ArmPosition[0] - HTMMat->m[HTMMat->column * HTMMat->row * joint + 4 * 0 + 3]; PosiVector[1] = ArmPosition[1] - HTMMat->m[HTMMat->column * HTMMat->row * joint + 4 * 1 + 3]; PosiVector[2] = ArmPosition[2] - HTMMat->m[HTMMat->column * HTMMat->row * joint + 4 * 2 + 3]; //Jacobianの外積計算 //J(0,joint) Jacob->m[Jacob->column * 0 + joint] = HTMMat->m[HTMMat->column * HTMMat->row * joint + 4 * 1 + 2] * PosiVector[2] - HTMMat->m[HTMMat->column * HTMMat->row * joint + 4 * 2 + 2] * PosiVector[1]; //J(1,joint) Jacob->m[Jacob->column * 1 + joint] = HTMMat->m[HTMMat->column * HTMMat->row * joint + 4 * 2 + 2] * PosiVector[0] - HTMMat->m[HTMMat->column * HTMMat->row * joint + 4 * 0 + 2] * PosiVector[2]; //J(2,joint) Jacob->m[Jacob->column * 2 + joint] = HTMMat->m[HTMMat->column * HTMMat->row * joint + 4 * 0 + 2] * PosiVector[1] - HTMMat->m[HTMMat->column * HTMMat->row * joint + 4 * 1 + 2] * PosiVector[0]; //J(3,joint) Jacob->m[Jacob->column * 3 + joint] = HTMMat->m[HTMMat->column * HTMMat->row * joint + 4 * 0 + 2]; //J(4,joint) Jacob->m[Jacob->column * 4 + joint] = HTMMat->m[HTMMat->column * HTMMat->row * joint + 4 * 1 + 2]; //J(5,joint) Jacob->m[Jacob->column * 5 + joint] = HTMMat->m[HTMMat->column * HTMMat->row * joint + 4 * 2 + 2]; if (selfmotion) { //J(6,joint) Jacob->m[Jacob->column * 6 + joint] = 0.0; if (joint == 2) { //ひじ関節が第三関節だから(プログラムでは0から連番される) Jacob->m[Jacob->column * 6 + joint] = 1; } } } } //pseudo inverse matrixを計算するプログラム static int PIM(Matrix *mat, Matrix *PIMat) { Matrix *TMat; TMat = CreateDiMatrix(mat->column, mat->row); Matrix *sqMat; sqMat = CreateDiMatrix(mat->row, mat->row); Matrix *detMat; detMat = CreateDiMatrix(mat->row, mat->row); Matrix *IsqMat; IsqMat = CreateDiMatrix(mat->row, mat->row); double col[MAXJOINT + NR_END] = {}; double d = 0; int index[MAXJOINT + NR_END] = {}; int row, column, check=0; //cout << "PIM started" << endl; //Dbar(); std::cout << "original matrix\n"; displayDiMatrix(mat); //転置行列を作る(A^T) for (row = 0; row < mat->row; row++) { for (column = 0; column < mat->column; column++) { TMat->m[mat->row * column + row] = mat->m[mat->column * row + column]; } } /////////////////////転置行列作った //Dbar(); std::cout << "Transform Matrix\n"; displayDiMatrix(TMat); //mat*TMatの計算をする(A・A^T) for (row = 0; row < mat->row; row++) { for (column = 0; column < mat->column; column++) { sqMat->m[mat->row * row + column] = mat->m[mat->column * row + 0] * TMat->m[mat->row * 0 + column] //ここはなぜかfor(int k = 0; k < mat->column; k++) + mat->m[mat->column * row + 1] * TMat->m[mat->row * 1 + column] //のように省略すると + mat->m[mat->column * row + 2] * TMat->m[mat->row * 2 + column] //エラーは出ないけれども + mat->m[mat->column * row + 3] * TMat->m[mat->row * 3 + column] //値が狂ってしまうから + mat->m[mat->column * row + 4] * TMat->m[mat->row * 4 + column] //このままにして置かなければいけない + mat->m[mat->column * row + 5] * TMat->m[mat->row * 5 + column] + mat->m[mat->column * row + 6] * TMat->m[mat->row * 6 + column]; detMat->m[mat->row * row + column] = sqMat->m[mat->row * row + column]; } } ////////////////////////mat*Tmatのおわり //Dbar(); std::cout << "[Original * Transform] matrix\n"; displayDiMatrix(sqMat); //行列式による判定 check = Ludcmp(detMat->m, mat->row, index, &d); for (int i = 0; i < mat->row; i++) { d *= detMat->m[mat->row * i + i];} if (d == 0) { Dbar(); printf(".....determinant = 0.....\n.....Can not calculate.....\n"); Dbar(); return 1; } //正方逆行列を作る((A・A^T)^-1) //cout << "Creating Square Inverse Matrix started" << endl; check = Ludcmp(sqMat->m, mat->row, index, &d); if (check > 0) { return check; } for (int j = 0; j < mat->row; j++) { for (int i = 0; i < mat->row; i++)col[i] = 0.0; col[j] = 1.0; Lubksb(sqMat->m, mat->row, index, col); for (int i = 0; i < mat->row; i++){ IsqMat->m[mat->row * i + j] = col[i]; } } if (check > 0) { printf(".....LU function error.....\n.....Can not calculate.....\n"); return 1; } //cout << "Creating Square Inverse Matrix finished" << endl; //Dbar(); std::cout << "square inverse matrix\n"; DisplayDiMatrix(IsqMat); for (row = 0; row < PIMat->row; row++) { for (column = 0; column < PIMat->column; column++) { PIMat->m[PIMat->column * row + column] = TMat->m[PIMat->column * row + 0] * IsqMat->m[PIMat->column * 0 + column] + TMat->m[PIMat->column * row + 1] * IsqMat->m[PIMat->column * 1 + column] + TMat->m[PIMat->column * row + 2] * IsqMat->m[PIMat->column * 2 + column] + TMat->m[PIMat->column * row + 3] * IsqMat->m[PIMat->column * 3 + column] + TMat->m[PIMat->column * row + 4] * IsqMat->m[PIMat->column * 4 + column] + TMat->m[PIMat->column * row + 5] * IsqMat->m[PIMat->column * 5 + column]; } } //Dbar(); std::cout << "Pseudo inverse matrix\n"; displayDiMatrix(PIMat); for (row = 0; row < mat->row * mat->column; row++) { if (fabs(PIMat->m[row]) < COMPARE_ZERO) { PIMat->m[row] = 0.0; } } //cout << "PIM finished" << endl; FreeMatrix(TMat); FreeMatrix(sqMat); FreeMatrix(detMat); FreeMatrix(IsqMat); return check; } //class HandP の定義 kinematics::kinematics(){ eX = 0; eY = 0; eZ = 0; wX = 0; wY = 0; wZ = 0; X = 0; Y = 0; Z = 0; } kinematics::~kinematics() { } //メンバ変数の出力 void kinematics::DisplayCoordinate() { printf("elbow(x,y,z)\t->\t(%lf\t%lf\t%lf)\n", eX, eZ); printf("wrists(x,y,z)\t->\t(%lf\t%lf\t%lf)\n", wX, wY, wZ); printf("fingers(x,y,z)\t->\t(%lf\t%lf\t%lf)\n", X, Y, Z); } //肘座標を取得 void kinematics::GetElbowCoordinate(double *ec) { ec[0] = eX; ec[1] = eY; ec[2] = eZ; } //手首座標を取得 void kinematics::GetwristCoordinate(double *wc) { wc[0] = wX; wc[1] = wY; wc[2] = wZ; } //手先座標を取得 void kinematics::GetCoordinate(double *c) { c[0] = X; c[1] = Y; c[2] = Z; } //順運動学計算 void kinematics::CalcFK(double *currentRadian, double *currentCoordinate) { //std::cout << "FKkinematicsosition started\n"; Matrix *om; om = CreateTriMatrix(4, 4, MAXJOINT); Matrix *htm; htm = CreateTriMatrix(4, 4, MAXJOINT); //(1)同次変換行列を作る InitOM(currentRadian, om); //displayTriMatrix(om); //(2)同次変換行列を作る CalcHTM(om, htm); //displayTriMatrix(htm); //(3)同次変換行列の手先位置に関する情報を書き出す. //elbow eX = *(htm->m + (htm->column * htm->row * 2 + 4 * 0 + 3)); eY = *(htm->m + (htm->column * htm->row * 2 + 4 * 1 + 3)); eZ = *(htm->m + (htm->column * htm->row * 2 + 4 * 2 + 3)); //wrist wX = *(htm->m + (htm->column * htm->row * 4 + 4 * 0 + 3)); wY = *(htm->m + (htm->column * htm->row * 4 + 4 * 1 + 3)); wZ = *(htm->m + (htm->column * htm->row * 4 + 4 * 2 + 3)); //finger currentCoordinate[0] = X = *(htm->m + (htm->column * htm->row * 7 + 4 * 0 + 3)); currentCoordinate[1] = Y = *(htm->m + (htm->column * htm->row * 7 + 4 * 1 + 3)); currentCoordinate[2] = Z = *(htm->m + (htm->column * htm->row * 7 + 4 * 2 + 3)); FreeMatrix(om); FreeMatrix(htm); } //calc inverse kinematics int kinematics::CalcIK(double *currentRadian, double *handVelocity, double *nextRadVerocity, bool selfMotion) { //std::cout << "self motion calculation started\n"; Matrix *om_m; //original matrix om_m = CreateTriMatrix(4,4, MAXJOINT); Matrix *htm_m; //homogeneous translate matrix htm_m = CreateTriMatrix(4, 4, MAXJOINT); Matrix *jacob_m; //jacobian jacob_m = CreateDiMatrix(7, 7); Matrix *iJacob_m; //inverse jacobian iJacob_m = CreateDiMatrix(7, 7); int check = 0; //同次変換行列の作成 InitOM(currentRadian, om_m); //Dbar(); std::cout << "OM\n"; displayTriMatrix(OM->m, 4, 4); //同次変換行列の積の計算 CalcHTM(om_m, htm_m); //Dbar(); std::cout << "HTM\n"; displayTriMatrix(HTM->m, 4, 4); //ヤコビ行列の計算 CalcJacob(htm_m, jacob_m, selfMotion); //Dbar(); std::cout << "Jacob\n"; displayDiMatrix(Jacob->m, Jacob->row, Jacob->column); //擬似逆行列を作成 InverseMatrix(jacob_m, iJacob_m); //Dbar(); std::cout << "Inverse Jacob\n"; displayDiMatrix(IJacob->m, 7, 7); for (int i = 0; i < (MAXJOINT - 1); i++) { nextRadVerocity[i] = iJacob_m->m[7 * i + 0] * handVelocity[0] + iJacob_m->m[7 * i + 1] * handVelocity[1] + iJacob_m->m[7 * i + 2] * handVelocity[2] + iJacob_m->m[7 * i + 3] * handVelocity[3] + iJacob_m->m[7 * i + 4] * handVelocity[4] + iJacob_m->m[7 * i + 5] * handVelocity[5] + iJacob_m->m[7 * i + 6] * handVelocity[6]; //if (fabs(outRadVelocity[i]) < COMPARE_ZERO) { // outRadVelocity[i] = 0.0; //} } //Dbar(); FreeMatrix(om_m); FreeMatrix(htm_m); FreeMatrix(jacob_m); FreeMatrix(iJacob_m); return check; } void kinematics::VelocityRegulation(const double *targetCoordinate, double *velocity, double *currentTime) { int i; static double p2pLength[3]; //さくらんぼの茎に対して直接アプローチするとぶつかるので,茎の手前に一度移動し,把持面と平行にアプローチする. //通過点(茎手前) if (*currentTime < TIME_SPAN) { p2pLength[0] = targetCoordinate[0] - X; p2pLength[1] = targetCoordinate[1] - Y; p2pLength[2] = targetCoordinate[2] - Z; } ///////////////////////////////// //台形補間の速度計算 if (*currentTime < ACCEL_TIME) { for (i = 0; i < 3; i++) { velocity[i] = TIME_SPAN * p2pLength[i] * (*currentTime) / (ACCEL_TIME * (TIME_LENGTH - ACCEL_TIME)); } } else if (*currentTime >= ACCEL_TIME && *currentTime <= (TIME_LENGTH - ACCEL_TIME)) { for (i = 0; i < 3; i++) { velocity[i] = TIME_SPAN * p2pLength[i] / (TIME_LENGTH - ACCEL_TIME); } } else if (*currentTime >(TIME_LENGTH - ACCEL_TIME) && *currentTime <= TIME_LENGTH) { for (i = 0; i < 3; i++) { velocity[i] = TIME_SPAN * p2pLength[i] * (TIME_LENGTH - (*currentTime)) / (ACCEL_TIME * (TIME_LENGTH - ACCEL_TIME)); } } else if (*currentTime > TIME_LENGTH) { if (fabs(X - targetCoordinate[0]) < FINGER_THRESHOLD) { if (fabs(Y - targetCoordinate[1]) < FINGER_THRESHOLD) { if (fabs(Z - targetCoordinate[2]) < FINGER_THRESHOLD) { velocity[0] = velocity[1] = velocity[2] = 0.0; } } } else{ velocity[0] = TIME_SPAN * (targetCoordinate[0] - X); velocity[1] = TIME_SPAN * (targetCoordinate[1] - Y); velocity[2] = TIME_SPAN * (targetCoordinate[2] - Z); } } //printf(" time Counter-> %lf",&CurrentTime); *currentTime += TIME_SPAN; } //jointvelocity = JV /* //擬似逆行列で動かすやつ,いらなかったくそっぉぉぉぉぉおぉぉぉぉぉぉ!!! int MainCalc(double *inRadian, double *speed, double *outRadVelocity) { //std::cout << "mainCalc" << std::endl; Matrix *OM; OM = Create_Matrix(16, MAXJOINT); Matrix *HTM; HTM = Create_Matrix(16, MAXJOINT); Matrix *Jacob; Jacob = Create_Matrix(6, 7); Matrix *IJacob; IJacob= Create_Matrix(7, 6); int check = 0; int selfmotion = 0; //関数外からの入力値の表示 //入力角度 Dbar(); for (int i = 0; i < MAXJOINT; i++) { printf("%d inrad-> %3.3lf", i, inRadian[i]); printf("/speed->%3.3lf\n", speed[i]); } //同次変換行列の作成 OMInit(inRadian, OM); //同次変換行列の表示 //Dbar(); std::cout << "OM\n"; displayTriMatrix(OM->m, 4, 4); //同次変換行列の積の計算 HTMCalc(OM, HTM); //同次変換行列の表示 //Dbar(); std::cout << "HTM\n"; displayTriMatrix(HTM->m, 4, 4); //ヤコビ行列の計算 JacobCalc(HTM, Jacob, selfmotion); //ヤコビ行列の表示 //Dbar(); std::cout << "Jacob\n"; displayDiMatrix(Jacob->m, Jacob->row, Jacob->column); //擬似逆行列を作成 check = PIM(Jacob, IJacob); //擬似逆行列の表示 //Dbar(); std::cout << "Inverse Jacob\n"; displayDiMatrix(IJacob->m, IJacob->row, IJacob->column); //擬似逆行列が本当に正しいか元の行列と掛けあわせて確認(単位正方行列が出ればOK) //Dbar(); std::cout << "PIMConfirmation\n"; PIMConfirmation(Jacob,IJacob); for (int i = 0; i < (MAXJOINT - 1); i++) { outRadVelocity[i] = IJacob->m[6 * i + 0] * speed[0] + IJacob->m[6 * i + 1] * speed[1] + IJacob->m[6 * i + 2] * speed[2] + IJacob->m[6 * i + 3] * speed[3] + IJacob->m[6 * i + 4] * speed[4] + IJacob->m[6 * i + 5] * speed[5]; //if (fabs(outRadVelocity[i]) < COMPARE_ZERO) { // outRadVelocity[i] = 0.0; //} //std::cout << outRadVelocity[i] << std::endl; } //Dbar(); //std::cout << "mainCalc finished\n"; Free_Matrix(OM); Free_Matrix(HTM); Free_Matrix(Jacob); Free_Matrix(IJacob); return check; } */ <file_sep>// 2017/04/28 // created by <NAME> // reference : numerical recicpes in c #include <stdio.h> #include <stdlib.h> #include <math.h> #include "include\kine_debag.h" const int PLUS_NULL = 1; double *Dvector(long nh) { double *v = (double *)malloc(nh*sizeof(double)); if (!v) printf("malloc failure in vector()\n"); return v + PLUS_NULL; } int *Ivector(long nh) { int *v = (int *)malloc(nh*sizeof(int)); if (!v) printf("malloc failure in vector()\n"); return v + PLUS_NULL; } void Free_dvector(double *v) { //printf("free_vector started\n"); free(v); } void Free_ivector(int *v) { //printf("free_vector started\n"); free(v); } int Ludcmp(std::vector<double> &mat, int matSize, int *index, double *d) { int i, j, jmax = 0, k; double big, dum, sum, temp; double *vv; double TINY = 1.0e-20; vv = Dvector(matSize); *d = 1.0; ///スケーリング情報 for (i = 0; i < matSize; i++) { big = 0.0; for (j = 0; j < matSize; j++) { if ((temp = fabs(mat[matSize*i + j]))>big) { big = temp; } } if (big == 0.0) { ErrComment("Singular matrix in routine ludcmp"); return 1; } vv[i] = 1.0 / big; } /////////////////////////////////////////// //Crout方を用いる.列についてのループ for (i = 0; i < matSize; i++) { for (j = 0; j < i; j++) { sum = mat[matSize * j + i]; for (k = 0; k < j; k++) { sum -= mat[matSize * j + k] * mat[matSize * k + i]; } mat[j * matSize + i] = sum; } big = 0.0; for (j = i; j < matSize; j++) { sum = mat[matSize*j + i]; for (k = 0; k < i; k++) { sum -= mat[matSize*j + k] * mat[matSize * k + i]; } mat[matSize * j + i] = sum; dum = vv[j] * fabs(sum); if (dum >= big) { big = dum; jmax = j; } } if (i != jmax) { for (j = 0; j < matSize; j++) { dum = mat[matSize * jmax + j]; mat[matSize * jmax + j] = mat[matSize * i + j]; mat[matSize * i + j] = dum; } *d = -(*d); vv[jmax] = vv[i]; } index[i] = jmax; if (mat[matSize * i + i] == 0.0) { mat[matSize * i + i] = TINY; ErrComment("Matrix:: ludcmp : tiny"); exit(1); } if (i != (matSize - 1)) { dum = 1.0 / (mat[matSize*i + i]); for (j = i + 1; j < matSize; j++) { mat[matSize * j + i] *= dum; } } } //free(vv); return 0; } void Lubksb(std::vector<double> &mat, int matSize, int *index, double *b) { int i, ii = -1, ip, j; double sum; for (i = 0; i < matSize; i++) { ip = index[i]; sum = b[ip]; b[ip] = b[i]; if (ii != -1) { for (j = ii; j < i; j++) { sum -= mat[matSize*i + j] * b[j]; } } else if (sum != 0.0) { ii = i; } b[i] = sum; } for (i = (matSize - 1); i >= 0; i--) { sum = b[i]; for (j = i + 1; j < matSize; j++) { sum -= mat[i*matSize + j] * b[j]; } b[i] = sum / mat[i*matSize + i]; } } <file_sep>// 2017/04/28 // created by <NAME> #pragma once #ifndef __SPLINE_CLASS_H__ #define __SPLINE_CLASS_H__ const int MAX_SPLINE_POINT = 10; class Spline { public: Spline(); ~Spline(); void initPoint(double *points, int pointValue); double calc(double t); private: double a[MAX_SPLINE_POINT]; double b[MAX_SPLINE_POINT]; double c[MAX_SPLINE_POINT]; double d[MAX_SPLINE_POINT]; int num; }; #endif // !__SPLINE_CLASS_H__ <file_sep>#pragma once #include "kine_target_point.h" //スプライン曲線 void CalcVelocitySpline(double *firstPos, double *viaPos, double *endPos, double currentTime, double *moveSpeed); //直線軌道 void CalcVelocityLinear(double *firstPos, double *endPos, double currentTime, double *speed); //手先のクォータニオン姿勢操作 void CalcVelocityPosture(double *curJointRad, TarPoints *targetCoord, double currentTime, double *postureSpeed); void CalcViaPos(TarPoints targetPoints, double via2endLength, double *returnPos3);<file_sep>// 2017/04/28 // created by <NAME> #pragma once #ifndef __PLANE_H__ #define __PLANE_H__ #include <vector> void AngleOfPlane(double p1[4], double p2[4], double &angle); void Plane(std::vector<double> p1, std::vector<double> p2, std::vector<double> p3, std::vector<double> plane); #endif // !__PLANE_H__ <file_sep>#include <iostream> #include <Inventor\So.h> #include <Inventor\events\SoEvent.h> #include <Inventor\Win\SoWin.h> #include <Inventor\events\SoSpaceballButtonEvent.h> #include <Inventor\Win\devices\SoWinSpaceball.h> #include <Inventor\Win\viewers\SoWinExaminerViewer.h> #include <Inventor\sensors\SoTimerSensor.h> #define SPACEMOUSE_TRANSLATION_GAIN 0.05f #define SPACEMOUSE_ROTATION_GAIN 0.05f float SpacemouseInput[6]; static void SpaceMouseXaxisCB(void *b_data, SoSensor *) { SoTransform *XTransform = (SoTransform *)b_data; XTransform->rotation.setValue(SbVec3f(1, 0, 0), SpacemouseInput[3]); } static void SpaceMouseYaxisCB(void *b_data, SoSensor *) { SoTransform *YTransform = (SoTransform *)b_data; YTransform->rotation.setValue(SbVec3f(0, 1, 0), -SpacemouseInput[5]); } static void SpaceMouseZaxisCB(void *b_data, SoSensor *) { SoTransform *ZTransform = (SoTransform *)b_data; ZTransform->rotation.setValue(SbVec3f(0, 0, 1), SpacemouseInput[4]); } SoWinSpaceball* SpaceMouseSet(){ float f; if (SoWinSpaceball::exists()) { printf("スペースマウスを検出できません\n"); exit(1); } SoWinSpaceball* sb = new SoWinSpaceball; f = sb->getRotationScaleFactor(); printf("Spacemouse::RotationScaleFactor\t= %f\n", f); f = sb->getTranslationScaleFactor(); printf("Spacemouse::TranslationScaleFactor\t= %f\n", f); return sb; } void Coin3DSpaceMouseEventCB(void* data, SoEventCallback *eventCB){ //printf("event callback started\n"); const SoEvent* ev = eventCB->getEvent(); if (ev->isOfType(SoMotion3Event::getClassTypeId())) { SoMotion3Event* tr = (SoMotion3Event*)ev; SpacemouseInput[0] += SPACEMOUSE_TRANSLATION_GAIN * tr->getTranslation().getValue()[0]; SpacemouseInput[1] += SPACEMOUSE_TRANSLATION_GAIN * tr->getTranslation().getValue()[1]; SpacemouseInput[2] += SPACEMOUSE_TRANSLATION_GAIN * tr->getTranslation().getValue()[2]; SpacemouseInput[3] += SPACEMOUSE_ROTATION_GAIN * tr->getRotation().getValue()[0]; SpacemouseInput[4] += SPACEMOUSE_ROTATION_GAIN * tr->getRotation().getValue()[1]; SpacemouseInput[5] += SPACEMOUSE_ROTATION_GAIN * tr->getRotation().getValue()[2]; } } int main(void) { printf("start this program\n"); HWND MainWindow = SoWin::init(""); if (MainWindow == NULL) exit(1); printf("Success main window creation\n"); //root separator create SoSeparator *root = new SoSeparator; root->ref(); //viewer configration SoWinExaminerViewer *MainViewer = new SoWinExaminerViewer(MainWindow); MainViewer->setSceneGraph(root); MainViewer->setTitle("It is testing!"); MainViewer->setSize(SbVec2s(640, 480)); MainViewer->setBackgroundColor(SbColor(0, 0, 0)); printf("Success main viewer configuration\n"); if (SoWinSpaceball::exists()) { printf("space ball NO exists\n"); exit(1); } //space mouse callback create SoTransform *SpaceMouseTransformX = new SoTransform; SoTransform *SpaceMouseTransformY = new SoTransform; SoTransform *SpaceMouseTransformZ = new SoTransform; SoEventCallback *SpaceMouseCB = new SoEventCallback; SpaceMouseCB->addEventCallback(SoMotion3Event::getClassTypeId(), Coin3DSpaceMouseEventCB, root); SoTimerSensor *SpaceMouseSensorX = new SoTimerSensor(SpaceMouseXaxisCB, SpaceMouseTransformX); SpaceMouseSensorX->setInterval(0.1); SpaceMouseSensorX->schedule(); SoTimerSensor *SpaceMouseSensorY = new SoTimerSensor(SpaceMouseYaxisCB, SpaceMouseTransformY); SpaceMouseSensorY->setInterval(0.1); SpaceMouseSensorY->schedule(); SoTimerSensor *SpaceMouseSensorZ = new SoTimerSensor(SpaceMouseZaxisCB, SpaceMouseTransformZ); SpaceMouseSensorZ->setInterval(0.1); SpaceMouseSensorZ->schedule(); SoSeparator *obj1 = new SoSeparator; SoSeparator *obj2 = new SoSeparator; SoSeparator *obj3 = new SoSeparator; SoCube *box1 = new SoCube; box1->width = 1.0; box1->height = 0.1; box1->depth = 0.1; SoCube *box2 = new SoCube; box2->width = 0.1; box2->height = 1.0; box2->depth = 0.1; SoCube *box3 = new SoCube; box3->width = 0.1; box3->height = 0.1; box3->depth = 1.0; SoTranslation *trans1 = new SoTranslation; SoTranslation *trans2 = new SoTranslation; SoTranslation *trans3 = new SoTranslation; trans1->translation.setValue(-0.5, 0, 0); trans2->translation.setValue(0, 0, 0); trans3->translation.setValue(0.5, 0, 0); obj1->addChild(trans1); obj1->addChild(SpaceMouseTransformX); obj1->addChild(box1); obj2->addChild(trans2); obj2->addChild(SpaceMouseTransformY); obj2->addChild(box2); obj3->addChild(trans3); obj3->addChild(SpaceMouseTransformZ); obj3->addChild(box3); root->addChild(SpaceMouseCB); root->addChild(obj1); root->addChild(obj2); root->addChild(obj3); MainViewer->registerDevice(SpaceMouseSet()); MainViewer->show(); SoWin::show(MainWindow); SoWin::mainLoop(); }<file_sep>#pragma once #ifndef __kinematics_H_INCLUDED__ #define __kinematics_H_INCLUDED__ #define _USE_MATH_DEFINES #include <stdio.h> #include <math.h> typedef struct { int row; int column; double *m; }Matrix; #define FREE_ARG char* const int MAXJOINT = 8; //7 axis and hand tip DoF const int NR_END = 1; const double PI = 3.14159265359; const double COMPARE_ZERO = 1e-9; //シミュレータ側で使用する関数 //* //速度計算1ループごとに進む時間 const double TIME_SPAN = 0.001; //計算結果の描画を何回に一回にするか const double LOOP_SPAN = TIME_SPAN * 100; //台形補間の計算総時間 const double TIME_LENGTH = 2.0; //台形補間の加減速時間 const double ACCEL_TIME = TIME_LENGTH / 4; //総時間の25% //手先位置収束しきい値 const double FINGER_THRESHOLD = 0.001; //スペースマウスの値強度 const double SPACEMOUSE_TRANSLATION_GAIN = 0.0f; const double SPACEMOUSE_ROTATION_GAIN = 0.0005f; // const double HAND_POSTURE_GAIN = 0.01; //*/ ///////////////////////////////////////////////// Matrix *CreateDiMatrix(const int row, const int column); Matrix *CreateTriMatrix(const int row, const int column, const int numMat); void FreeMatrix(Matrix* matrix); double *SetVector(int nl); void FreeVector(double *v); void CalcHTM(Matrix *OM, Matrix *HTMMat); class kinematics { public: //肘:elbow:e,手首:wrist:w,手先:finger:f double eX, eY, eZ; double wX, wY, wZ; double X, Y, Z; public: kinematics(); ~kinematics(); void DisplayCoordinate(); void GetElbowCoordinate(double *ec); void GetwristCoordinate(double *wc); void GetCoordinate(double *fc); void CalcFK(double *currentRadian, double *currentCoordinate); int CalcIK(double *currentRadian, double *handVelocity, double *nextRadVerocity, bool selfMotion); void kinematics::VelocityRegulation(const double *targetCoordinate, double *velocity, double *currentTime); }; void Dbar(); #endif<file_sep>#include <iostream> #include <Eigen\Dense> #define _TCHAR char #define _tmain main int _tmain(int argc, _TCHAR* argv[]) { Eigen::MatrixXd A(9, 9); std::cout << A; return 0; } <file_sep>#include "include\cameraOffset.h" //近距離カメラのオフセット。 //originMatにカメラから実際に得た3次元座標を渡すと //オフセットしてconvertMatに返す。 void ShortCameraOffset(const double *originMat, double *convertMat) { convertMat[0] = originMat[2] - 109; convertMat[1] = originMat[1] - 2; convertMat[2] = originMat[0] + 100; } //遠距離カメラのオフセット。 //originMatにカメラから実際に得た3次元座標を渡すと //オフセットしてconvertMatに返す。 void LongCameraOffset(const double *originMat, double *convertMat) { convertMat[0] = originMat[2] + 143.0; convertMat[1] = originMat[1] + 208.0; convertMat[2] = originMat[0] - 314.0; }<file_sep>// 2017/04/28 // created by <NAME> #pragma once #ifndef __LU_H__ #define __LU_H__ double *Dvector(long nh); void Free_dvector(double *v); int *Ivector(long nh); void Free_ivector(int *v); int Ludcmp(std::vector<double> &m, int n, int *index, double *d); void Lubksb(std::vector<double> &m, int matSize, int *index, double *b); #endif // !__LU_H__ <file_sep>// 2017/04/28 // created by <NAME> #pragma once #ifndef __3D_OBJECTS_H__ #define __3D_OBJECTS_H__ #include <vector> #include <Inventor\Win\SoWin.h> #include <Inventor\So.h> void GoalCherry(std::vector<double> position, SoSeparator *GoalSep); void PointObj(std::vector<double> position, SoSeparator *redPoint); void PointObj(SoSeparator *redPoint); void AlmiFlame(std::vector<double> position, SoSeparator *armFlame); void CoordinateSystem(SoSeparator *coordinateSystem); #endif //__3D_OBJECTS_H__<file_sep>// 2017/04/28 // created by <NAME> #include "include\Test_console.h" //この下にテストしたいプログラムのインクルードを書こう #include "include\kine_debag.h" #include "include\kine_quat.h" #include "include\trapezoidal_interpolation.h" #include "include\kine_config.h" #include "include\kine_trajectory.h" #include <stdio.h> double outQ[4 * 100000] = {}; double outM[16 * 100000] = {}; double outE[3 * 100000] = {}; void TestConsole(void){ double f[3] = { 1,2,3 }; double v[3] = { 4,5,6 }; double e[3] = { 9,8,7 }; for (double i = 0; i < 1; i += 0.1) { double buf[3] = {}; TrapeInterpolate(1, 1, i); CalcVelocitySpline(f, v, e, i, buf); DisplayVector(3, buf); } } /* Quat init(0.5, -0.5, 0.5, 0.5); Quat end(0.653281, 0.270598, 0.270598, 0.653281); Quat current; double recQ[4] = {}; double recM[16] = {}; double recE[3] = {}; int counter = 0; double currentTime = 0; for (double i = 0; i < 1; i += TIME_SPAN) { current = init.slerp(i, end); current.Quat2array(recQ); for (int j = 0; j < 4; ++j) outQ[4 * counter + j] = recQ[j]; current.quat2RotM(recM); for (int j = 0; j < 16; ++j) outM[16 * counter + j] = recM[j]; current.quat2Euler(recE); for (int j = 0; j < 3; ++j) outE[3 * counter + j] = recE[j]; ++counter; } OutputMatrixTxt(outQ, 4, counter, "quatTest"); OutputMatrixTxt(outM, 16, counter, "matTest"); OutputMatrixTxt(outE, 3, counter, "eulerTest"); */ <file_sep>// 2017/04/28 // created by <NAME> #include <cmath> #include "include\kinematics.h" #include "include\kine_debag.h" #include "include\kine_vector.h" #include "include\kine_target_point.h" #include "include\kine_config.h" TarPoints::TarPoints() { top = { 0,0,0 }; mid = { 0,0,0 }; btm = { 0,0,0 }; } TarPoints::~TarPoints() {} /* void TarPoints::CoordinateSwap(std::vector<double> tar1) { std::vector<double> buf(3,0); } */ void TarPoints::display() { DebagComment("target top coordinate"); DisplayVector(top); DebagComment("target middle coordinate"); DisplayVector(mid); DebagComment("target bottom coordinate"); DisplayVector(btm); } double calcMiddlePoint(double top, double bottom) { double buf = 0; buf = fabs(top - bottom) / 2; return bottom + buf; } std::vector<double> TarPoints::graspDirection() { //DebagComment("GraspDirection"); //DisplayVector(top); //DisplayVector(mid); //DisplayVector(btm); std::vector<double> top2midV; std::vector<double> top2btmV; std::vector<double> crossV; std::vector<double> returnV(3, 0); top2midV = SubVector(mid, top); top2btmV = SubVector(btm, top); VectorNormalize(top2midV); VectorNormalize(top2btmV); //DebagComment("top2midV"); DisplayVector(top2midV); //DebagComment("top2btmV"); DisplayVector(top2btmV); //ベクトル方向が一緒か確認 int sameVectorFlag = 0; for (int i = 0; i < 3; ++i) { if (top2midV[i] == top2btmV[i]) { ++sameVectorFlag; } } if (sameVectorFlag == 3) { DebagComment(" grasp direction : same vector "); returnV[0] = 1.0; returnV[1] = 0.0; returnV[2] = 0.0; //for (int i = 0; i < 3; ++i) tempMidV[i] = calcMiddlePoint(top[i], btm[i]); //for (int i = 0; i < 3; ++i) returnV[i] = tempMidV[i] - mid[i]; VectorNormalize(returnV); DebagComment("graspVector"); DisplayVector(returnV); return returnV; } crossV = CrossVector(top2midV, top2btmV); VectorNormalize(crossV); //DebagComment("crossVec"); DisplayVector(crossV); returnV = CrossVector(crossV, top2btmV); VectorNormalize(returnV); int errorFlag = 0; for (int i = 0; i < 3; ++i) { if (std::isnan(returnV[i])) { ++errorFlag; } if (std::isinf(returnV[i])) { ++errorFlag; } } if (errorFlag > 0) { DebagComment("grasp direction : cannot calculate"); double tempMidV[3] = {}; for (int i = 0; i < 3; ++i) tempMidV[i] = calcMiddlePoint(top[i], btm[i]); for (int i = 0; i < 3; ++i) returnV[i] = tempMidV[i] - mid[i]; VectorNormalize(returnV); return returnV; } //もし腕が180°ひっくり返るような把持方向なら直す if (returnV[0] < 0) { for (int i = 0; i < 3; ++i) { returnV[i] = -1 * returnV[i]; } } //xの方向を向く //もし,crossベクトルのZ軸が負の場合は,returnVecの値にマイナスを掛けて逆方向にする //if (crossV[2] > 0) for (int i = 0; i < graspV.size(); ++i)graspV[i] = -1 * graspV[i]; //DebagComment("grasp Vector"); DisplayVector(graspV); return returnV; } void TarPoints::pointAssignMid(double *vec3) { mid = { vec3[0], vec3[1], vec3[2] }; } void TarPoints::pointAssignTop(double *vec3) { top = { vec3[0], vec3[1], vec3[2] }; } void TarPoints::pointAssignBtm(double *vec3) { btm = { vec3[0], vec3[1], vec3[2] }; } <file_sep>// 2017/04/28 // created by <NAME> #include <stdio.h> //#include "include\trapezoidal_interpolation.h" #include "include\kine_debag.h" #include "include\kine_config.h" double TrapeInterpolate(const double move_length, const double time_length, const double currentTime) { //DebagComment("trape interpolate"); double buf = 0; if (currentTime < kine::ACCEL_TIME) { buf = kine::TIME_SPAN * (currentTime / kine::ACCEL_TIME) * (move_length /(kine::TIME_LENGTH - kine::ACCEL_TIME)); return buf; } else if (currentTime >= kine::ACCEL_TIME && currentTime <= (time_length - kine::ACCEL_TIME)) { buf = kine::TIME_SPAN * ((move_length) / (time_length - kine::ACCEL_TIME)); return buf; } else if (currentTime >(time_length - kine::ACCEL_TIME) && currentTime <= time_length) { buf = kine::TIME_SPAN * (move_length * (time_length - currentTime)) / ((time_length - kine::ACCEL_TIME) * kine::ACCEL_TIME); return buf; } else if(currentTime > time_length){ return 0.0; } }<file_sep>// 2017/04/28 // created by <NAME> #pragma once #ifndef __TRAPEQOIDAL_INTERPOLATIN_H__ #define __TRAPEQOIDAL_INTERPOLATIN_H__ double TrapeInterpolate(const double move_length, const double time_length, const double currentTime); #endif //__TRAPEQOIDAL_INTERPOLATIN_H__ <file_sep>//cone Simulator // 2017/04/28 // created by <NAME> #include "include\kine_quat.h" #include "include\kine_vector.h" #include "include\kine_debag.h" #include "include\cone_simulator.h" #include "include\3Dobjects.h" #include "include\kine_target_point.h" #include "include\kine_config.h" #include "include\kine_convertor.h" #include "include\kinematics.h" #include "include\trapezoidal_interpolation.h" #include <Inventor\Win\SoWin.h> #include <Inventor\Win\viewers\SoWinExaminerViewer.h> #include <Inventor\so.h> //データ格納用配列 double outputEuler[4 * 100000] = {}; double outputAngular[4 * 100000] = {}; //動作ループカウンター int counter = 0.0; float quaternion[4] = {1,0,0,0}; Quat firstPostureQ( 0.5, //w 0.5, //x 0.5, //y 0.5 //z ); Quat endPostureQ( 0.5, //w 0.5, //x 0.5, //y 0.5 //z ); static void moveSensorCallback(void *b_data, SoSensor *){ SoTransform *rot = (SoTransform *)b_data; rot->center.setValue(0, 0.0, 0); rot->rotation.setValue(quaternion); } void KeyPressCB(void *userData, SoEventCallback *eventCB) { //現在時間 static double currentTime = 0; static double nowTime = 0; static double beforeTime = 0; static double constVelocity[3] = {}; //初期姿勢クォータニオン TarPoints centerPoint; const SoEvent *event = eventCB->getEvent(); if (SO_KEY_PRESS_EVENT(event, SPACE)) { int whileCounter = 0.0; while (1) { if (currentTime == 0.0) { double bufm[16] = {}; double bufArray[4] = {}; firstPostureQ.Quat2array(bufArray); for (int i = 0; i < 4; ++i) quaternion[i] = bufArray[i]; DebagComment("first\n"); firstPostureQ.display(); firstPostureQ.quat2RotM(bufm); DisplayRegularMatrix(4, bufm); DebagComment("end\n"); endPostureQ.display(); endPostureQ.quat2RotM(bufm); DisplayRegularMatrix(4, bufm); beforeTime = 0.0; nowTime = 0.0; } else if (currentTime >= kine::TIME_SPAN && currentTime < kine::TIME_LENGTH) { printf("currentTime -> %3.9lf\n", currentTime); beforeTime = nowTime; nowTime += TrapeInterpolate(1, kine::TIME_LENGTH, currentTime); //printf("now time %lf\n", nowTime); //printf("before time %lf\n", beforeTime); Quat currentSlerpQ = firstPostureQ.slerp(nowTime, endPostureQ); Quat beforeSlerpQ = firstPostureQ.slerp(beforeTime, endPostureQ); double q[4] = {}; currentSlerpQ.Quat2array(q); quaternion[0] = q[1]; quaternion[1] = q[2]; quaternion[2] = q[3]; quaternion[3] = q[0]; double bufEulerN[3] = {}; double bufEulerB[3] = {}; currentSlerpQ.quat2Euler(bufEulerN); beforeSlerpQ.quat2Euler(bufEulerB); double eulerVelocity[3] = {}; if (currentTime < kine::ACCEL_TIME) { for (int i = 0; i < 3; ++i) { eulerVelocity[i] = bufEulerN[i] - bufEulerB[i]; constVelocity[i] = eulerVelocity[i]; } } else if (currentTime >= kine::ACCEL_TIME && currentTime <= (kine::TIME_LENGTH - kine::ACCEL_TIME)) { for (int i = 0; i < 3; ++i) eulerVelocity[i] = constVelocity[i]; } else if (currentTime > (kine::TIME_LENGTH - kine::ACCEL_TIME) && currentTime < kine::TIME_LENGTH) { for (int i = 0; i < 3; ++i) eulerVelocity[i] = bufEulerN[i] - bufEulerB[i]; } //DisplayVector(3, eulerVelocity); double bufAngular[3] = {}; Euler2Angular(bufEulerN, eulerVelocity, bufAngular); //output parametor outputEuler[counter * 4] = currentTime; outputAngular[counter * 4] = currentTime; for (int i = 0; i < 3; ++i) outputEuler[counter * 4 + i + 1] = bufEulerN[i]; for (int i = 0; i < 3; ++i) outputAngular[counter * 4 + i + 1] = bufAngular[i]; if (currentTime > kine::TIME_LENGTH && currentTime <= kine::TIME_LENGTH + kine::TIME_SPAN) DebagComment("slerp conplete"); //if ((whileCounter * TIME_SPAN) >= LOOP_SPAN) break; } else if (currentTime >= kine::TIME_LENGTH) { printf("finished\n"); break; } currentTime += kine::TIME_SPAN; ++counter; ++whileCounter; if (whileCounter >= kine::TIME_LENGTH * kine::TIME_SPAN) { break; } } } if (SO_KEY_PRESS_EVENT(event, R)) { currentTime = 0.0; nowTime = 0; beforeTime = 0; } if (SO_KEY_PRESS_EVENT(event, W)) { OutputMatrixTxt(outputEuler, 4, counter, "SlerpTest_Euler"); OutputMatrixTxt(outputAngular, 4, counter, "SlerpTest_anglaur"); } if (SO_KEY_PRESS_EVENT(event, Q)) { exit(1); } } void coneObject(SoSeparator *sep) { SoSeparator *sep1 = new SoSeparator; SoSeparator *sep2 = new SoSeparator; SoSeparator *sep3 = new SoSeparator; //オブジェクトの生成 SoCone *cone1Obj = new SoCone; SoCone *cone2Obj = new SoCone; SoCone *cone3Obj = new SoCone; //オブジェクトのパラメータ cone1Obj->bottomRadius = 0.01; cone1Obj->height = 0.1; cone2Obj->bottomRadius = 0.01; cone2Obj->height = 0.1; cone3Obj->bottomRadius = 0.01; cone3Obj->height = 0.1; //部品同士の位置決め SoTranslation *cone1Trans = new SoTranslation; SoTranslation *cone2Trans = new SoTranslation; SoTranslation *cone3Trans = new SoTranslation; cone1Trans->translation.setValue(0.0, 0.05, 0.0); cone2Trans->translation.setValue(0.0, 0.05, 0.0); cone3Trans->translation.setValue(0.0, 0.05, 0.0); SoTransform *cone1rot = new SoTransform; cone1rot->center.setValue(0, 0, 0.0); cone1rot->rotation.setValue(SbVec3f(1, 0, 0), M_PI / 2); SoTransform *cone2rot = new SoTransform; cone2rot->center.setValue(0, 0, 0.0); //cone2rot->rotation.setValue(SbVec3f(0, 1, 0), M_PI / 2); SoTransform *cone3rot = new SoTransform; cone3rot->center.setValue(0, 0, 0.0); cone3rot->rotation.setValue(SbVec3f(0, 0, 1), -M_PI / 2); //色(RGB) SoMaterial *red = new SoMaterial; red->diffuseColor.setValue(1.0, 0.0, 0.0); SoMaterial *blue = new SoMaterial; blue->diffuseColor.setValue(0.0, 0.0, 1.0); SoMaterial *green= new SoMaterial; green->diffuseColor.setValue(0.0, 1.0, 0.0); sep1->addChild(blue); //x sep1->addChild(cone1rot); sep1->addChild(cone1Trans); sep1->addChild(cone1Obj); sep2->addChild(green); //y sep2->addChild(cone2rot); sep2->addChild(cone2Trans); sep2->addChild(cone2Obj); sep3->addChild(red); //z sep3->addChild(cone3rot); sep3->addChild(cone3Trans); sep3->addChild(cone3Obj); sep->addChild(sep1); sep->addChild(sep2); sep->addChild(sep3); } void ConeSimulator() { HWND coneWindow = SoWin::init(""); SoSeparator *root = new SoSeparator; //event call back SoEventCallback *eventcallback = new SoEventCallback; eventcallback->addEventCallback(SoKeyboardEvent::getClassTypeId(), KeyPressCB, root); SoSeparator *coneSep = new SoSeparator; SoSphere *origin = new SoSphere; origin->radius = (0.01); //cone generate SoSeparator *coneObj = new SoSeparator; coneObject(coneObj); //rotation callback SoTransform *coneRot = new SoTransform; SoTimerSensor *coneMoveSensor = new SoTimerSensor(moveSensorCallback, coneRot); coneSep->addChild(coneRot); coneSep->addChild(coneObj); coneMoveSensor->setInterval(0.01); coneMoveSensor->schedule(); SoSeparator *coord = new SoSeparator; CoordinateSystem(coord); //addchild root->ref(); root->addChild(coord); root->addChild(origin); root->addChild(eventcallback); root->addChild(coneSep); //viewer configuration SoWinExaminerViewer *coneViewer = new SoWinExaminerViewer(coneWindow); coneViewer->setSceneGraph(root); coneViewer->setTitle("*** Cone Simulator ***"); coneViewer->setBackgroundColor(SbColor(0.3, 0.3, 0.4)); coneViewer->setSize(SbVec2s(720, 600)); coneViewer->show(); SoWin::show(coneWindow); SoWin::mainLoop(); }<file_sep>// 2017/04/28 // created by <NAME> #pragma once #ifndef __CALC_VECTOR_H__ #define __CALC_VECTOR_H__ #include <vector> // void DisplayVector(const std::vector<double> v); std::vector<double> AddVector(const std::vector<double> reftV, const std::vector<double> rightV); std::vector<double> SubVector(const std::vector<double> reftV, const std::vector<double> rightV); std::vector<double> mulVector(const std::vector<double> reftV, const double mulValue); std::vector<double> ArrayToVect(double *originArray); //内積 double InnerVectorSqr(const std::vector<double> v1, const std::vector<double> v2); double InnerVector(const std::vector<double> v1, const std::vector<double> v2); double InnerVector(const double reftV[3], const double rightV[3]); //外積 std::vector<double> CrossVector(const std::vector<double> &reftV, const std::vector<double> &rightV); void CrossVector(const double reftV[3], const double rightV[3], double *returnV); //正規化 void VectorNormalize(std::vector<double> &returnV); //回転角算出 double GetRotValue(std::vector<double> &curAxis, std::vector<double> &tarAxis); #endif //__CALC_VECTOR_H__<file_sep>#include <Inventor\Win\SoWin.h> #include <Inventor\Win\viewers\SoWinExaminerViewer.h> #include <Inventor\SoDB.h> #include <Inventor\nodes\SoMaterial.h> #include <Inventor\nodes\SoRotationXYZ.h> #include <Inventor\nodes\SoScale.h> #include <Inventor\nodes\SoCone.h> #include <Inventor\nodes\SoCube.h> #include <Inventor\nodes\SoSeparator.h> #include <Inventor\nodes\SoTranslation.h> #include <Inventor\nodes\SoPerspectiveCamera.h> #include <Inventor\SoInput.h> #include <Inventor\nodes\SoDirectionalLight.h> #include <stdlib.h> int main(int argc,char **argv) { //Open Inventorを初期化し、 //Open Inventor Xライブラリを使用してウィンドウを作成する HWND myWindow = SoWin::init(argv[0]); if (myWindow == NULL)exit(1); //シーンを作成する。 SoSeparator *root1 = new SoSeparator; SoSeparator *root2 = new SoSeparator; root1->ref(); root2->ref(); //カメラを作り、シーンに追加する。 SoPerspectiveCamera *myCamera = new SoPerspectiveCamera; root1->addChild(myCamera); root2->addChild(myCamera); //シーンに高原を追加する。位置はデフォルト。 root1->addChild(new SoDirectionalLight); root2->addChild(new SoDirectionalLight); //材質を作り、色を赤にし、シーンに追加する。 SoMaterial *myMaterial1 = new SoMaterial; SoMaterial *myMaterial2 = new SoMaterial; myMaterial1->diffuseColor.setValue(1, 0, 0); myMaterial2->diffuseColor.setValue(0, 1, 0); root1->addChild(myMaterial1); root2->addChild(myMaterial2); //シーンに円錐を追加する root1->addChild(new SoCone); root2->addChild(new SoCone); //Winユーティリティライブラリを使用し、描画エリアをつくる。 //描画エリアはメインウィンドウに現れる。 SoWinRenderArea *myRenderArea = new SoWinRenderArea(myWindow); //シーン全体が見えるようにカメラを設定する。 myCamera->viewAll(root1, myRenderArea->getViewportRegion()); myCamera->viewAll(root2, myRenderArea->getViewportRegion()); //myRenderAreaにシーンを移動し、タイトルを変更する。 myRenderArea->setSceneGraph(root2); myRenderArea->setSceneGraph(root1); myRenderArea->setTitle("Hello Cone"); myRenderArea->show(); SoWin::show(myWindow); SoWin::mainLoop(); }<file_sep>// 2017/04/28 // created by <NAME> #pragma once #ifndef __KINEMA_DEBAG_H__ #define __KINEMA_DEBAG_H__ #include "include\kine_matrix.h" //display void kinemaDebagON(void); void kinemaDebagOFF(void); void DebagBar(void); void DebagComment(char *c); void DebagCommentEnt(char *c); void ErrComment(char *c); void DisplayVector(const int n, const double *v); void DisplayVector(const int n, const float *v); void DisplayRegularMatrix(const int n, double *mat); void OutputMatrixTxt(double *m, const int column, double loopnum, char *filename); void DisplayDiMatrix(Matrix *m); void DisplayTriMatrix(Matrix *m, int dispNum); void PushEnter(void); #endif // !__KINEMA_DEBAG_H__ <file_sep>#pragma once void ShortCameraOffset(const double *originMat, double *convertMat); void LongCameraOffset(const double *originMat, double *convertMat);<file_sep>// 2017/04/28 // created by <NAME> #define _CRT_SECURE_NO_WARNINGS #include <stdio.h> #include <time.h> #include <string.h> #include <fstream> #include "include\kinematics.h" #include "include\kine_debag.h" #include "include\kine_vector.h" #include "include\kine_config.h" int DEBAG = 0; void kinemaDebagON(void) { DEBAG = 1; DebagComment("kinemaDebag On"); } void kinemaDebagOFF(void) { DebagComment("kinemaDebag OFF"); DEBAG = 0; } //デバッグ用横線 void DebagBar(void) { printf("\n-----------------------------------------------------\n"); } // comment for debag void DebagComment(char *c) { if (DEBAG == 1) { DebagBar(); printf("%s\n", c); } } void DebagCommentEnt(char *c) { if (DEBAG == 1) { DebagBar(); printf("%s : push ENTER\n", c); DebagBar(); PushEnter(); } } void ErrComment(char *c) { DebagBar(); printf("Error Comment\n%s\n", c); printf(" : push ENTER : \n"); DebagBar(); PushEnter(); } void DisplayVector(const int n, const double *v) { if (DEBAG == 1) { //printf("display Vector\n"); for (int i = 0; i < n; ++i) { printf("v[%d]-> %3.8lf\n", i, v[i]); } printf("\n"); } } void DisplayVector(const int n, const float *v) { if (DEBAG == 1) { //printf("display Vector\n"); for (int i = 0; i < n; ++i) { printf("v[%d]-> %3.8lf\n", i, v[i]); } printf("\n"); } } void DisplayRegularMatrix(const int n, double *mat) { if (DEBAG == 1) { //printf("display Matrix \n"); for (int i = 0; i < n; ++i) { for (int j = 0; j < n; ++j) { printf("%3.6lf\t", mat[n * i + j]); } printf("\n"); } printf("\n"); } } void OutputMatrixTxt(double *m, const int column, double loopnum, char *filename) { std::ofstream fout; time_t t = time(NULL); struct tm *pnow = localtime(&t); char name[200] = ""; char timename[100] = ""; sprintf(timename, "%04d%02d%02d%02d%02d%02d", pnow->tm_year + 1900, pnow->tm_mon + 1, pnow->tm_mday, pnow->tm_hour, pnow->tm_min, pnow->tm_sec); strcat(name, filename); strcat(name, timename); strcat(name, ".txt"); printf("\n output to - %s - file \n", name); fout.open(name); if (!fout) { printf("%s\n", filename); ErrComment("file open error"); fout.close(); PushEnter(); exit(1); } for (int i = 0; i < loopnum; ++i) { if (i < kine::TIME_LENGTH / kine::TIME_SPAN) { for (int j = 0; j < column; ++j) { fout << m[column * i + j] << "\t"; } fout << "\n"; } } fout.close(); printf("output finished\n"); } void PushEnter(void) { while (getchar() != '\n') continue; } <file_sep>// 2017/04/28 // created by <NAME> #pragma once #ifndef __KINEMATICS_H__ #define __KINEMATICS_H__ #include "kine_matrix.h" #include "kine_target_point.h" #include "kine_quat.h" namespace kine { //関節角度から同次変換行列を生成する void InitOM(double *currentRadian, Matrix &OM); //同次変換行列を関節ごとに算出する。 void CalcHTM(Matrix OM, Matrix &HTM); //ヤコビ行列を生成する。 void CalcJacob(Matrix HTM, int selfmotion, Matrix &Jacob); //疑似逆行列を生成する。 int PIM(Matrix mat, Matrix &PIMat); //運動学クラス class Kinematics { public: //TarPoints *ch; Kinematics(); ~Kinematics(); void DisplayCoordinate(); void GetElbowCoordinate(double *ec); void GetwristCoordinate(double *wc); void GetCoordinate(double *fc); void GetHandHTM(double *currentRadian, double *htmMat); void CalcFK(double *currentRadian); int CalcIK(double *currentRadian, double *handVelocity, double *nextRadVerocity); int CalcPIK(double *currentRadian, double *handVelocity, double *nextRadVerocity); void Pick(double *curJointRad, TarPoints tarCoord, double *currentTime, double *nextRadVelocity); private: //肘:elbow:e,手首:wrist:w,手先:finger:f //よく呼び出す変数 Matrix om; Matrix htm; Matrix jacob; Matrix iJacob; //座標値を持っている関数 double eX, eY, eZ; double wX, wY, wZ; double X, Y, Z; }; } #endif// !__KINEMATICS_H__<file_sep>// 2017/04/28 // created by <NAME> #pragma once #ifndef __ARM_SIMULATOR_H__ #define __ARM_SIMULATOR_H__ void ArmSimulator(int argc); #endif //__ARM_SIMULATOR_H__<file_sep>// 2017/04/28 // created by <NAME> #define _USE_MATH_DEFINES #include <stdio.h> #include <math.h> #include "include\kine_quat.h" #include "include\kine_debag.h" #include "include\kine_config.h" #include "include\kine_convertor.h" #include "include\kine_vector.h" #define QUAT_ELEM 4 //Quatenion Elements void NormalizeQuatMatrix(double *m); //constractor Quat::Quat() { x = y = z = 0.0; w = 1.0; } Quat::Quat(double wValue, double xValue, double yValue, double zValue) { w = wValue; x = xValue; y = yValue; z = zValue; } Quat::Quat(double wValue, std::vector<double> vec3) { w = wValue; x = vec3[0]; y = vec3[1]; z = vec3[2]; } Quat::Quat(std::vector<double> vec4) { w = vec4[0]; x = vec4[1]; y = vec4[2]; z = vec4[3]; } Quat::Quat(double *vec4) { w = vec4[0]; x = vec4[1]; y = vec4[2]; z = vec4[3]; } Quat::~Quat(){} void Quat::Quat2array(double array4[4]) { array4[0] = w; array4[1] = x; array4[2] = y; array4[3] = z; } void Quat::assign() { x = y = z = 0.0; w = 1.0; } void Quat::assign(double wValue, double xValue, double yValue, double zValue) { w = wValue; x = xValue; y = yValue; z = zValue; } void Quat::assign(double wValue, std::vector<double> vec3) { w = wValue; x = vec3[0]; y = vec3[1]; z = vec3[2]; } void Quat::assign(std::vector<double> vec4) { w = vec4[0]; x = vec4[1]; y = vec4[2]; z = vec4[3]; } void Quat::assign(double *vec4) { w = vec4[0]; x = vec4[1]; y = vec4[2]; z = vec4[3]; } void Quat::assign(Quat originQ) { double buf[4] = {}; originQ.Quat2array(buf); w = buf[0]; x = buf[1]; y = buf[2]; z = buf[3]; } //calculation Quat Quat::add(Quat c) { Quat returnQ; double bufC[4] = {}; c.Quat2array(bufC); double bufA[4] = {}; Quat2array(bufA); double addBuf[4] = {}; for (int i = 0; i < 4; ++i) addBuf[i] = bufA[i] + bufC[i]; returnQ.assign(addBuf); return returnQ; } Quat Quat::sub(Quat c) { Quat returnQ; double bufC[4] = {}; c.Quat2array(bufC); double bufA[4] = {}; Quat2array(bufA); double subBuf[4] = {}; for (int i = 0; i < 4; ++i) subBuf[i] = bufA[i] - bufC[i]; returnQ.assign(subBuf); return returnQ; } Quat Quat::mul(const Quat q2) { Quat returnQuat; returnQuat.w = w * q2.w - (x * q2.x + y * q2.y + z * q2.z); returnQuat.x = x * q2.w + w * q2.x - z * q2.y + y * q2.z; returnQuat.y = y * q2.w + z * q2.x + w * q2.y - x * q2.z; returnQuat.z = z * q2.w - y * q2.x + x * q2.y + w * q2.z; return returnQuat; } Quat Quat::mulReal(const double s) { Quat returnQ; double bufA[4] = {}; Quat2array(bufA); double mulBuf[4] = {}; for (int i = 0; i < 4; ++i) mulBuf[i] = bufA[i] * s; returnQ.assign(mulBuf); return returnQ; } Quat Quat::divReal(const double s) { Quat returnQ; double bufA[4] = {}; Quat2array(bufA); double divBuf[4] = {}; for (int i = 0; i < 4; ++i) divBuf[i] = bufA[i] / s; returnQ.assign(divBuf); return returnQ; } //共役 Quat Quat::conjugate() { Quat returnQuat; returnQuat.w = w; returnQuat.x = x * (-1); returnQuat.y = y * (-1); returnQuat.z = z * (-1); return returnQuat; } //normalize(正規化) void Quat::normalize() { double n = norm(); w /= n; x /= n; y /= n; z /= n; } //ノルム double Quat::norm() { double xx = x * x; double yy = y * y; double zz = z * z; double ww = w * w; return pow(ww + xx + yy + zz, 0.5); } //内積 double Quat::dot(Quat dotQ) { double bufA[4] = {}; double bufB[4] = {}; Quat2array(bufA); dotQ.Quat2array(bufB); double bufDot = 0.0; for (int i = 0; i < 4; ++i) bufDot += bufA[i] * bufB[i]; return bufDot; } //外積 std::vector<double> Quat::cross(Quat crossQ) { std::vector<double> returnV; double aQ[4] = {}; double bQ[4] = {}; Quat2array(aQ); crossQ.Quat2array(bQ); returnV[0] = aQ[yq] * bQ[zq] - aQ[zq] * bQ[yq]; returnV[1] = aQ[zq] * bQ[xq] - aQ[xq] * bQ[zq]; returnV[2] = aQ[xq] * bQ[yq] - aQ[yq] * bQ[xq]; return returnV; } double clamp(double target, double min, double max) { double buf = 0; if (target < min) { buf = target; } else { buf = min; } if (buf < max) { return max; } else { return buf; } } Quat Quat::slerp(double t, Quat tarQuat) { //回転角算出 /* normalize(); tarQuat.normalize(); double dotResult = dot(tarQuat); const double DOT_THRESHOLD = 0.9995; if (fabs(dotResult) > DOT_THRESHOLD) { Quat buf1 = sub(tarQuat); Quat buf2 = buf1.mulReal(t); return sub(buf2); } Quat minusTarQuat; if (dotResult < 0.0f) { minusTarQuat = tarQuat.mulReal(-1); dotResult = -1 * dotResult; } clamp(dotResult, -1, 1); double theta_0 = acos(dotResult); double theta = theta_0 * t; Quat altQuat = tarQuat.sub(mulReal(dotResult)); altQuat.normalize(); Quat returnQ = mulReal(cos(theta)); return returnQ.add(altQuat.mulReal(sin(theta))); */ double curNorm = norm(); double tarNorm = tarQuat.norm(); double rotValBuf = dot(tarQuat) / (curNorm * tarNorm); double rotValue = acosf(rotValBuf); //補間 double sin_rV = sinf(rotValue); double kx = sin((1 - t) * rotValue) / sin_rV; double ky = sin(t * rotValue) / sin_rV; //補間値 Z 計算 Quat kxX = mulReal(kx); Quat kyY = tarQuat.mulReal(ky); return kxX.add(kyY); } //display void Quat::display() { printf("w -> %3.6lf\n", w); printf("x -> %3.6lf\n", x); printf("y -> %3.6lf\n", y); printf("z -> %3.6lf\n", z); DebagBar(); } //クォータニオンから回転行列を返す void Quat::quat2RotM(double *rotMat) { //display(); normalize(); //display(); double xx = x * x; double yy = y * y; double zz = z * z; double ww = w * w; double xy = x * y; double yz = y * z; double zx = z * x; double xw = x * w; double yw = y * w; double zw = z * w; double invs = 1 / (xx + yy + zz + ww); rotMat[4 * 0 + 0] = 1.0 - 2 * (yy + zz) * invs; rotMat[4 * 0 + 1] = 2.0 * (xy - zw) * invs; rotMat[4 * 0 + 2] = 2.0 * (zx + yw); rotMat[4 * 0 + 3] = 0; rotMat[4 * 1 + 0] = 2.0 * (xy + zw); rotMat[4 * 1 + 1] = 1.0 - 2 * (xx + zz) * invs; rotMat[4 * 1 + 2] = 2.0 * (yz - xw); rotMat[4 * 1 + 3] = 0; rotMat[4 * 2 + 0] = 2.0 * (zx - yw); rotMat[4 * 2 + 1] = 2.0 * (yz + xw); rotMat[4 * 2 + 2] = 1.0 - 2 * (xx + yy) * invs; rotMat[4 * 2 + 3] = 0; rotMat[4 * 3 + 0] = 0; rotMat[4 * 3 + 1] = 0; rotMat[4 * 3 + 2] = 0; rotMat[4 * 3 + 3] = 1.0; /* rotMat[4 * 0 + 0] = (ww + xx - yy - zz); rotMat[4 * 0 + 1] = 2.0 * (xy - zw); rotMat[4 * 0 + 2] = 2.0 * (zx + yw); rotMat[4 * 0 + 3] = 0; rotMat[4 * 1 + 0] = 2.0 * (xy + zw); rotMat[4 * 1 + 1] = (ww - xx + yy - zz); rotMat[4 * 1 + 2] = 2.0 * (yz - xw); rotMat[4 * 1 + 3] = 0; rotMat[4 * 2 + 0] = 2.0 * (zx - yw); rotMat[4 * 2 + 1] = 2.0 * (yz + xw); rotMat[4 * 2 + 2] = (ww - xx - yy + zz); rotMat[4 * 2 + 3] = 0; rotMat[4 * 3 + 0] = 0; rotMat[4 * 3 + 1] = 0; rotMat[4 * 3 + 2] = 0; rotMat[4 * 3 + 3] = 1.0; */ } /* void Quat::quat2Euler(double *euler) { //下のサイトを参考に,運動学計算を行うに当たって //楽なように書き直してます. //euler角をφ,θ,ψの順に書き出したいのです. //jacobian の計算のときに与える速度vが,v = {x,y,z,φ,θ,ψ}だから //http://www.euclideanspace.com/maths/geometry/rotations/conversions/quaternionToEuler/ //https://en.wikipedia.org/wiki/Conversion_between_quaternions_and_Euler_angles double xsqr = x * x; double ysqr = y * y; double zsqr = z * z; double wsqr = w * w; // roll (x-axis rotation) double t0 = 2.0 * (w * x + y * z); double t1 = +1.0 - 2.0 * (xsqr + ysqr); euler[0] = std::atan2(t0, t1); //roll // pitch (y-axis rotation) double t2 = +2.0 * (w * y - z * x); t2 = t2 > 1.0 ? 1.0 : t2; t2 = t2 < -1.0 ? -1.0 : t2; euler[1] = std::asin(t2); //pitch // yaw (z-axis rotation) double t3 = +2.0 * (w * z + x * y); double t4 = +1.0 - 2.0 * (ysqr + zsqr); euler[2] = std::atan2(t3, t4); //yaw } */ bool isRotationMatrix(const double *m) { //https://www.learnopencv.com/rotation-matrix-to-euler-angles/ double rotMat[9] = {}; double rotMatT[9] = {}; for (int i = 0; i < 3; ++i) { for (int j = 0; j < 3; ++j) { rotMat[3 * i + j] = m[4 * i + j]; } } for (int i = 0; i < 3; ++i) { for (int j = 0; j < 3; ++j) { rotMatT[3 * i + j] = m[4 * j + i]; } } double shouldBeIdentity[9] = {}; for (int i = 0; i < 3; ++i) { for (int j = 0; j < 3; ++j) { for (int k = 0; k < 3; ++k) { shouldBeIdentity[3 * i + j] += rotMatT[3 * i + k] * rotMat[3 * k + j]; } } } double normBuf = 0.0f; for (int i = 0; i < 3; ++i) { normBuf += pow(shouldBeIdentity[3 * i + i], 2); } double norm = 0.0f; norm = pow(normBuf, 0.5); if (fabs(norm) > 1e-6) { return true; } else { return false; } } //同次変換行列を渡してオイラー角を得る void RotMat2Euler(const double *rotMat, double *euler) { //https://www.learnopencv.com/rotation-matrix-to-euler-angles/ if (isRotationMatrix(rotMat) == true) { //printf(" valid matrix \n"); } else { printf("ERROR : RotMatrixToEuler\n"); printf("*** invalid matrix ***\n"); } double sy = pow(pow(rotMat[4 * 0 + 0], 2) + pow(rotMat[4 * 1 + 0], 2), 0.5); if (sy < 1e-6) { euler[0] = atan2(-rotMat[4 * 1 + 2], rotMat[4 * 1 + 1]); euler[1] = atan2(rotMat[4 * 2 + 0], sy); euler[2] = 0; } else { euler[0] = atan2(rotMat[4 * 2 + 1], rotMat[4 * 2 + 2]); euler[1] = atan2(-rotMat[4 * 2 + 0], sy); euler[2] = atan2(rotMat[4 * 1 + 0], rotMat[4 * 0 + 0]); } } void RotMat2EulerZXZ(double *m, double *euler) { double buf = pow(m[4 * 0 + 2], 2) + pow(m[4 * 1 + 2], 2); euler[0] = atan2(m[4 * 0 + 2], m[4 * 1 + 2]); euler[1] = acos(m[4 * 2 + 2]); euler[2] = atan2(m[4 * 2 + 0], -m[4 * 2 + 1]); } //zyx void RotMat2EulerZYX(const double *rotMat, double *euler) { if (rotMat[4 * 0 + 2] < -0.998) { euler[0] = M_PI / 2; euler[1] = 0; euler[2] = euler[0] + atan2(rotMat[4 * 1 + 0], rotMat[4 * 2 + 0]); return; } else if (rotMat[4 * 0 + 2] > 0.998) { euler[0] = M_PI / 2; euler[1] = 0; euler[2] = -euler[0] + atan2(-1 * rotMat[4 * 1 + 0], -1 * rotMat[4 * 2 + 0]); return; } else { double x1 = -asin(rotMat[4 * 0 + 2]); double x2 = M_PI - x1; double y1 = atan2(rotMat[4 * 1 + 2] / cos(x1), rotMat[4 * 2 + 2] / cos(x1)); double y2 = atan2(rotMat[4 * 1 + 2] / cos(x2), rotMat[4 * 2 + 2] / cos(x2)); double z1 = atan2(rotMat[4 * 0 + 1] / cos(x1), rotMat[4 * 0 + 0] / cos(x1)); double z2 = atan2(rotMat[4 * 0 + 1] / cos(x2), rotMat[4 * 0 + 0] / cos(x2)); if (fabs(x1) + fabs(y1) + fabs(z1) <= fabs(x2) + fabs(y2) + fabs(z2)) { euler[0] = x1; euler[1] = y1; euler[2] = z1; } else { euler[0] = x2; euler[1] = y2; euler[2] = z2; } } //euler[0] = atan2(rotMat[4 * 1 + 2], rotMat[4 * 2 + 2]); //euler[1] = asin(-1 * rotMat[4 * 0 + 2]); //euler[2] = atan2(rotMat[4 * 0 + 1], rotMat[4 * 0 + 0]); } //zxzのオイラー角変換zxz void Quat::quat2Euler(double *euler) { double bufMat[16] = {}; quat2RotM(bufMat); //DebagComment("quat2rotMat"); DisplayRegularMatrix(4, bufMat); double bufEuler[3] = {}; RotMat2EulerZXZ(bufMat, bufEuler); //RotMat2EulerZYX(bufMat, bufEuler); //DebagComment("rotMat2euler"); DisplayVector(3, bufEuler); euler[0] = bufEuler[0]; euler[1] = bufEuler[1]; euler[2] = bufEuler[2]; //zyxのとき //euler[0] = bufEuler[0];//1 z //euler[1] = bufEuler[1];//2 x //euler[2] = bufEuler[2];//0 z } /* //xyz void Quat::quat2Euler(double *euler) { //回転行列を得る。 double m[16] = {}; quat2RotM(m); RotMatrixToEuler(m, euler); } */ void NormalizeQuatMatrix(double *m) { double a[3] = { m[0],m[4],m[8] }; double b[3] = { m[1],m[5],m[9] }; double c[3] = { m[2],m[6],m[10] }; double bufc = 0.0; bufc = InnerVector(c, c); for (int i = 0; i < 3; ++i) { c[i] = c[i] / bufc; } double bufa[3] = {}; } //quatanion rotatation /* Quat QuatRotate(const std::vector<double> &curPosi, const std::vector<double> &rotAxis,double rotValue) { int count = 0; for (int i = 0; i < 3; ++i) if (curPosi[i] == rotAxis[i]) ++count; if(count == 3){ printf("===========quat zero start===========\n"); Quat temp(0, 0, 0, 0); return temp; } else { printf("===========rotate start===========\n"); double cos_q, sin_q; cos_q = cos(rotValue / 2); sin_q = sin(rotValue / 2); //printf("cos -> %lf\tsin -> %lf\n", cos_q, sin_q); Quat currentQuat(0, curPosi[0], curPosi[1], curPosi[2]); Quat rotQuat(cos_q, rotAxis[0] * sin_q, rotAxis[1] * sin_q, rotAxis[2] * sin_q); Quat invRotQuat; Quat tempQuat; rotQuat.normalize(); invRotQuat = rotQuat.conjugate(); tempQuat = invRotQuat.mul(currentQuat); //printf("rotQuat\n"); //DisplayQuat(rotQuat); //printf("invRotQuat\n"); //DisplayQuat(invRotQuat); return tempQuat.mul(rotQuat); } } */ /* //sample program void QuatRotateSample() { std::vector<double> currentPosition{ 10, 0, 0 }; std::vector<double> rotateAxis{ 0, 0, 1 }; double rotateValue = M_PI / 2; Quat rotateQuatenion; rotateQuatenion = QuatRotate(currentPosition, rotateAxis, rotateValue); printf("rotate Quatanion\n"); DisplayQuat(rotateQuatenion); printf("finished sample program\n"); } */<file_sep>// 2017/04/28 // created by <NAME> #define _USE_MATH_DEFINES #include "include\kine_vector.h" #include "include\kine_quat.h" #include "include\kine_config.h" #include "include\kine_debag.h" #include <math.h> void Euler2Angular(const double nowEuler[3], const double eulerVelocity[3], double *angleVelocity) { //euler[0] = φ, euler[1] = θ, euler[2] = ψに対応している(はず) //DebagComment("now euler vector"); //DisplayVector(3, nowEuler); //DebagComment("euler velocity"); //DisplayVector(3, eulerVelocity); double euler2angularM[9] = {}; //phi, theta, psi euler2angularM[0] = 0; euler2angularM[1] = -sin(nowEuler[0]); euler2angularM[2] = cos(nowEuler[0]) * sin(nowEuler[1]); euler2angularM[3] = 0; euler2angularM[4] = cos(nowEuler[0]); euler2angularM[5] = sin(nowEuler[0]) * sin(nowEuler[1]); euler2angularM[6] = 1; euler2angularM[7] = 0; euler2angularM[8] = cos(nowEuler[1]); //DebagComment("transform matrix"); //DisplayRegularMatrix(3, euler2angularM); for (int i = 0; i < 3; ++i) { for (int j = 0; j < 3; ++j) { angleVelocity[i] += (euler2angularM[3 * i + j] * eulerVelocity[j]); } } //DebagComment("angle velocity"); DisplayVector(3, angleVelocity); //printf("euler to angular finished\n"); } inline float SIGN(float x) { if (x >= 0.0f) { return 1.0f; } else { return -1.0f; } } void RotMat2Quat(const double *rotMat, Quat &quat) { //DebagComment("rotation matrix to quaternion"); //http://www.euclideanspace.com/maths/geometry/rotations/conversions/matrixToQuaternion/ double trace = rotMat[4 * 0 + 0] + rotMat[4 * 1 + 1] + rotMat[4 * 2 + 2]; double q[4] = {}; if (trace > 0) { double s = 0.5 / powf(trace + 1.0f, 0.5); q[0] = 0.25f / s; q[1] = (rotMat[4 * 2 + 1] - rotMat[4 * 1 + 2]) * s; q[2] = (rotMat[4 * 0 + 2] - rotMat[4 * 2 + 0]) * s; q[3] = (rotMat[4 * 1 + 0] - rotMat[4 * 0 + 1]) * s; quat.assign(q); } else { if (rotMat[4 * 0 + 0] > rotMat[4 * 1 + 1] && rotMat[4 * 0 + 0] > rotMat[4 * 2 + 2]) { double s = 2.0f * powf(1.0f + rotMat[4 * 0 + 0] - rotMat[4 * 1 + 1] - rotMat[4 * 2 + 2], 0.5); q[0] = (rotMat[4 * 2 + 1] - rotMat[4 * 1 + 2]) / s; q[1] = 0.25f * s; q[2] = (rotMat[4 * 0 + 1] + rotMat[4 * 1 + 0]) / s; q[3] = (rotMat[4 * 1 + 2] + rotMat[4 * 2 + 1]) / s; } else if (rotMat[4 * 1 + 1] > rotMat[4 * 2 + 2]) { double s = 2.0f * powf(1.0f - rotMat[4 * 0 + 0] + rotMat[4 * 1 + 1] - rotMat[4 * 2 + 2], 0.5); q[0] = (rotMat[4 * 0 + 2] - rotMat[4 * 2 + 0]) / s; q[1] = (rotMat[4 * 0 + 1] + rotMat[4 * 1 + 0]) / s; q[2] = 0.25f * s; q[3] = (rotMat[4 * 1 + 2] + rotMat[4 * 2 + 1]) / s; } else { double s = 2.0f * powf(1.0f - rotMat[4 * 0 + 0] - rotMat[4 * 1 + 1] + rotMat[4 * 2 + 2], 0.5); q[0] = (rotMat[4 * 1 + 0] - rotMat[4 * 0 + 1]) / s; q[1] = (rotMat[4 * 0 + 2] + rotMat[4 * 2 + 0]) / s; q[2] = (rotMat[4 * 1 + 2] + rotMat[4 * 2 + 1]) / s; q[3] = 0.25f * s; } } for (int i = 0; i < 4; ++i) { if (fabs(q[i]) < kine::COMPARE_ZERO) { q[i] = 0.0; } } quat.assign(q); } void DirectVector2RotMat(std::vector<double> directionX, std::vector<double> directionZ, double *matrix) { //DebagComment("vector to rotation matrix"); VectorNormalize(directionX); VectorNormalize(directionZ); //printf("x\n");DisplayVector(directionX); //printf("z\n"); DisplayVector(directionZ); //DebagComment("cross product vector z axis "); std::vector<double> directionY(3, 0); directionY = CrossVector(directionZ, directionX); //DebagComment("normalize vector x axis "); VectorNormalize(directionY); //DebagComment("direction x"); DisplayVector(directionX); //DebagComment("direction y"); DisplayVector(directionY); //DebagComment("direction z"); DisplayVector(directionZ); //DebagComment("initializing rotation matrix in VecToRotMat"); matrix[0] = directionX[0]; matrix[4] = directionX[1]; matrix[8] = directionX[2]; matrix[12] = 0; matrix[1] = directionY[0]; matrix[5] = directionY[1]; matrix[9] = directionY[2]; matrix[13] = 0; matrix[2] = directionZ[0]; matrix[6] = directionZ[1]; matrix[10] = directionZ[2]; matrix[14] = 0; matrix[3] = 0; matrix[7] = 0; matrix[11] = 0; matrix[15] = 1; //DisplayRegularMatrix(4, matrix); for (int i = 0; i < 16; ++i) { if (fabs(matrix[i]) < kine::COMPARE_ZERO) { matrix[i] = 0.0; } if (matrix[i] == -0.0) { matrix[i] == 0.0; } } //DebagComment("vector to rotation matrix finished"); } <file_sep>// 2017/04/28 // created by <NAME> #define _USE_MATH_DEFINES //#include <iostream> //#include <math.h> #include "include\kine_debag.h" #include "include\kine_vector.h" #include "include\kine_config.h" std::vector<double> AddVector(const std::vector<double> reftV, const std::vector<double> rightV) { std::vector<double> returnV(reftV.size(),0); for (unsigned int i = 0; i < reftV.size(); ++i) { returnV[i] = reftV[i] + rightV[i]; } return returnV; } std::vector<double> SubVector(const std::vector<double> originV, const std::vector<double> minusV) { std::vector<double> returnV(originV.size(), 0); for (unsigned int i = 0; i < originV.size(); ++i) { returnV[i] = originV[i] - minusV[i]; } return returnV; } //実数の掛け算 std::vector<double> mulVector(const std::vector<double> originV, const double mulValue) { std::vector<double> returnV(3, 0); for (int i = 0; i < originV.size(); ++i) { returnV[i] = originV[i] * mulValue; } return returnV; } std::vector<double> ArrayToVect(double *originArray) { std::vector<double> returnVector; returnVector.assign(&originArray[0], &originArray[3]); return returnVector; } double InnerVectorSqr(std::vector<double> v1, std::vector<double> v2) { double buf = 0; //DebagComment("inner vector square"); buf = v1[0] * v2[0] + v1[1] * v2[1] +v1[2] * v2[2]; if (buf < 0) { //DebagCom("calculation result : minus value"); buf *= -1; //translate plus } //DebagComment("inner vector square finished"); return buf; } double InnerVector(std::vector<double> v1, std::vector<double> v2) { double buf = 0; //DebagComment("inner vector"); buf = sqrt(InnerVectorSqr(v1, v2)); //DebagComment("inner vector finished"); return buf; } double InnerVector(const double reftV[3], const double rightV[3]) { double buf = 0; for (int i = 0; i < 3; ++i) { buf += reftV[i] * rightV[i]; } buf = pow(buf, 0.5); return buf; } //#include <vector> version std::vector<double> CrossVector(const std::vector<double> &reftV, const std::vector<double> &rightV) { //DebagComment("cross vector"); std::vector<double> returnV(3,0); returnV[0] = reftV[1] * rightV[2] - reftV[2] * rightV[1]; returnV[1] = reftV[2] * rightV[0] - reftV[0] * rightV[2]; returnV[2] = reftV[0] * rightV[1] - reftV[1] * rightV[0]; //負のゼロを正のゼロに変換 for (int i = 0; i < 3; ++i) { if (returnV[i] == -0.0) { returnV[i] = 0.0; } } //DebagComment("return : cross vector"); //DisplayVector(returnV); return returnV; } //array version void CrossVector(const double reftV[3], const double rightV[3], double *returnV) { returnV[0] = reftV[1] * rightV[2] - reftV[2] * rightV[1]; returnV[1] = reftV[2] * rightV[0] - reftV[0] * rightV[2]; returnV[2] = reftV[0] * rightV[1] - reftV[1] * rightV[0]; } void VectorNormalize(std::vector<double> &returnV) { double normBuf; normBuf = InnerVector(returnV, returnV); for (int i = 0; i < 3; ++i) { returnV[i] /= normBuf; } } //calculate rotate value between 2 vector; double GetRotValue(std::vector<double> &curAxis, std::vector<double> &tarAxis) { double cur = 0; double tar = 0; double cosValue; VectorNormalize(curAxis); VectorNormalize(tarAxis); cur = InnerVector(curAxis, curAxis); //printf("currentAxisNorm -> %lf\n", cur); tar = InnerVector(tarAxis, tarAxis); //printf("targetAxisNorm -> %lf\n", tar); cosValue = InnerVector(curAxis, tarAxis) / (cur * tar); //printf("cosValue -> %lf\n", cosValue); //printf("%lf\n", theta); //printf("rotValue -> %3.9lf\n", fabs(acos(cosValue))); return fabs(acos(cosValue)); } /* double *SetVector(int nl) { //cout << "vector malloc started" << endl; double *v = new double[nl + NR_END]; if (!v) { std::cout << "memory failure in vector()" << std::endl; } return v; } void FreeVector(double *v) { //cout << "free_vector started" << endl; delete[] v; } */ void DisplayVector(std::vector<double> v) { //printf("display Vector\n"); for (int i = 0; i < v.size(); ++i) { printf("v[%d]-> %3.8lf\n", i, v[i]); } }
0568257390ad289220134f0dcee8f4803cd734aa
[ "C", "C++" ]
47
C
EikiObara/simulator_backup
957e2339d1ccb3ea68d15082073e3e9108f3d8ed
228fdf59d39f1ddc9c16cbcb55e48aaf936c84c7
refs/heads/main
<repo_name>180485/discovering-laravel<file_sep>/blade-app/app/Http/Controllers/PagesController.php <?php namespace App\Http\Controllers; use App\Http\Controllers\PagesController; class PagesController extends Controller { public function index() { return view ("layouts/main"); } public function form() { return view ("form"); } public function footer() { return view ("footer"); } public function contact() { return view ("contact"); } public function image() { return view ("image"); } } ?><file_sep>/blade-app/app/Http/Controllers/PostController.php <?php namespace App\Http\Controllers; use Illuminate\Http\Request; use App\Models\Post; class PostController extends Controller { /** * Show the application dashboard. * * @return \Illuminate\Http\Response */ public function create() { return view('create_post'); } public function store(Request $request) { $request->validate([ 'username' => '<PASSWORD>', 'password' => '<PASSWORD>', 'email' => 'required' ]); return redirect()->back()->with('message', 'HEY WELCOME TO LARAVEL!'); } }<file_sep>/blade-app/routes/web.php <?php use Illuminate\Support\Facades\Route; /* |-------------------------------------------------------------------------- | Web Routes |-------------------------------------------------------------------------- | | Here is where you can register web routes for your application. These | routes are loaded by the RouteServiceProvider within a group which | contains the "web" middleware group. Now create something great! | */ //exercise 2 blade view pages route::get('/', 'App\Http\Controllers\PagesController@index'); route::get('/form', 'App\Http\Controllers\PagesController@form'); route::get('/index', 'App\Http\Controllers\PagesController@index'); route::get('/contact', 'App\Http\Controllers\PagesController@contact'); route::get('/contact', 'App\Http\Controllers\CreatePostController@index'); route::get('/index', 'App\Http\Controllers\PagesController@image'); route::get('/', 'App\Http\Controllers\PagesController@image'); //exercise 2 validation form route::post('/form', 'App\Http\Controllers\PostController@store'); route::get('/post', 'App\Http\Controllers\PostController@create'); //exercise 3
48a0f9082ef67fc6bc540a857734d5f549b7c278
[ "PHP" ]
3
PHP
180485/discovering-laravel
75feb937326b59d08441c50be89d3f893a30a343
8e77dffe5b0a74417a137e539dd114d9df606393
refs/heads/master
<file_sep>import React from 'react'; import './App.css'; import Info from "./Info.js" function App() { return ( <div className="container"> <header className="AppHeader"> <h1>Am I Chasing?</h1> </header> <body className="AppBody"> <Info /> </body> </div> ); } export default App;
8aa47548da7b705c864b6ef2f2eaa2b9b542d467
[ "JavaScript" ]
1
JavaScript
jonathan-villanueva/stop-chasing
32922837df22eab387978d8833c880a803140892
464a9bf8323edcc3c8d8cc70b9d098247cafb4e1
refs/heads/master
<repo_name>aiadaniel/FirstVue<file_sep>/src/api/getData.js import {fetch} from './fetch' export const getHotTag = data => fetch('/tag/hot'); export const getBlogList = data => fetch('/blog/list'); export const getLastRecentUser = data => fetch('/user/lastrecent');
4050ec1f4c94bf7ee162c38a0ca929de33af04b6
[ "JavaScript" ]
1
JavaScript
aiadaniel/FirstVue
895ae847c1db963480876ac23889186090886b33
15f7bd46fa2eaa6dcc8a5240d192e59f8f9718d2
refs/heads/master
<file_sep>import { Injectable } from '@angular/core'; import {HttpClient} from "@angular/common/http"; import {Observable} from "rxjs"; import { Course } from '../dtos/course'; export const MAIN_URL= "http://localhost:8085"; const URL="api/v1/courses"; @Injectable() export class Coursservice { constructor(private http:HttpClient){ } saveCourses(course: Course): Observable<boolean>{ return this.http.post<boolean>(MAIN_URL + URL,course); } getAllCourses(): Observable<Array<Course>>{ return this.http.get<Array<Course>>(MAIN_URL + URL); } searchCourse(id :String): Observable<Course>{ return this.http.get<Course>(MAIN_URL + URL + "/"+id); } deleteCourse(id: string): Observable<boolean>{ return this.http.delete<boolean>(MAIN_URL+ URL + "/" + id); } getTotalCourses(): Observable<number>{ return this.http.get<number>(MAIN_URL + URL + "/count"); } } <file_sep>import { Injectable } from '@angular/core'; import {HttpClient} from "@angular/common/http"; import { StudentDTO } from '../dtos/student-dto'; import {Observable} from "rxjs"; export const MAIN_URL= "http://localhost:8085"; const URL="/api/v1/students"; @Injectable() export class Studentservice { constructor(private http:HttpClient){} saveStudent(student: StudentDTO): Observable<boolean>{ return this.http.post<boolean>(MAIN_URL+URL,student); } getAllStudent(): Observable<Array<StudentDTO>>{ return this.http.get<Array<StudentDTO>>(MAIN_URL + URL); } } <file_sep>import { Component, OnInit } from '@angular/core'; import { StudentDTO } from 'src/app/dtos/student-dto'; import { Studentservice } from 'src/app/service/studentservice'; @Component({ selector: 'app-page1', templateUrl: './page1.component.html', styleUrls: ['./page1.component.css'] }) export class Page1Component implements OnInit { students: Array<StudentDTO> = []; selectedStudent: StudentDTO = new StudentDTO(); constructor(private studentservice:Studentservice) { } ngOnInit() { this.loadAllStudent(); } loadAllStudent(): void { this.studentservice.getAllStudent().subscribe( (result) => { this.students = result; console.log(this.students); } ) } } <file_sep>import { Component, OnInit } from '@angular/core'; import { FormGroup, FormControl, Validators } from '@angular/forms'; import { AuthService } from 'src/app/service/auth-service/auth.service'; import { User } from 'src/app/dtos/user'; @Component({ selector: 'app-login-layout', templateUrl: './login-layout.component.html', styleUrls: ['./login-layout.component.css'] }) export class LoginLayoutComponent implements OnInit { loginForm=new FormGroup({ 'username':new FormControl('', [ Validators.required]), 'userpassword':new FormControl('', [ Validators.required]), }); get username(){ return this.loginForm.get('username'); } get userpassword(){ return this.loginForm.get('userpassword'); } user:User = new User(); failed:boolean; constructor(private authService : AuthService) { } ngOnInit() { } // login(){ // console.log(this.UserName.value); // alert(this.UserName.value) // console.log(this.Password.value); // alert(this.Password.value); // this.authService.login(this.UserName.value, this.Password.value); // } login(): void{ this.authService.login(this.user).subscribe( (result)=>{ this.failed = !result; } ); } } <file_sep>import {Component, OnInit} from '@angular/core'; import {FormGroup, FormControl, Validators} from "@angular/forms"; import { StudentDTO } from 'src/app/dtos/student-dto'; import { Studentservice } from 'src/app/service/studentservice'; @Component({ selector: 'app-page2', templateUrl: './page2.component.html', styleUrls: ['./page2.component.css'] }) export class Page2Component implements OnInit { form=new FormGroup({ 'studentid': new FormControl('',[ Validators.required, Validators.minLength(4) ]), 'studentname':new FormControl('', [ Validators.required ]), 'studentcontact':new FormControl('',[ Validators.required ]), 'studentaddress':new FormControl('',[ Validators.required ]) }); get studentid(){ return this.form.get('studentid'); } get studetname(){ return this.form.get('studentname'); } get studentcontact(){ return this.form.get('studentcontact') } get studentaddress(){ return this.form.get('studentaddress') } selectedStudent: StudentDTO = new StudentDTO(); constructor(private studentservice:Studentservice) { } ngOnInit() { } saveStudent(): void { this.studentid.setValue('studentid') this.studetname.setValue('studentname') this.studentcontact.setValue('studentcontact') this.studentaddress.setValue('studentaddress') this.studentservice.saveStudent(this.selectedStudent).subscribe( (result) => { if (result) { console.log(this.selectedStudent); alert("Student has been saved successfully.."); } else { alert("Failed to save the Student.."); } } ); } } <file_sep>export class Course { cid:string; cname:string; cperiod:string } <file_sep>import { Component, OnInit, ViewChild } from '@angular/core'; import { Course } from 'src/app/dtos/course'; import { Coursservice } from 'src/app/service/coursservice'; @Component({ selector: 'app-page4', templateUrl: './page4.component.html', styleUrls: ['./page4.component.css'] }) export class Page4Component implements OnInit { courses: Array<Course> = []; selectedCourse: Course = new Course(); // tempCourse: Course = null; // manuallySelected: boolean = false; // serchedCourse: Course = new Course(); constructor(private courseservice:Coursservice) { } ngOnInit() { this.loadAllCourses; } loadAllCourses(): void { this.courseservice.getAllCourses().subscribe( (result) => { this.courses = result; console.log(this.courses); } ) } // clear(): void { // let index = this.courses.indexOf(this.selectedCourse); // if (index !== -1) { // this.courses[index] = this.tempCourse; // this.tempCourse = null; // } // this.selectedCourse = new Course(); // this.manuallySelected = false; // } // selectCourse(course: Course): void { // this.clear(); // this.selectedCourse= course; // this.tempCourse = Object.assign({}, course); // this.manuallySelected = true; // } // tableClick(course:Course):void{ // this.courseservice.searchCourse(course.cid).subscribe( // (result)=>{ // this.selectedCourse = result; // } // ); // } // deletCourse(courseid :Course):void { // if (confirm("Are you sure you want to delete this Course?")) { // this.courseservice.deleteCourse(courseid.cid).subscribe( // (result) => { // if (result) { // alert("Course has been Deleted successfully"); // } else { // alert("Failed to deleted course"); // } // this.loadAllCourses(); // } // ) // } // } } <file_sep>export class StudentDTO { studentid:string; studentname:string; studentcontact:string; studentaddress:string; } <file_sep>import {Injectable} from "@angular/core"; import {HttpClient} from "@angular/common/http"; import {Router} from "@angular/router"; import { User } from 'src/app/dtos/user'; import { MAIN_URL } from '../studentservice'; import {Observable} from "rxjs"; import {map} from "rxjs/operators"; const URL= "/api/v1/login"; @Injectable() export class AuthService { // private isLogin: boolean = false; // get isLoggedIn() { // if (sessionStorage.getItem("token")) { // return true; // } // return false; // } // constructor(private router: Router) { } // login(userName: string, password: string) { // sessionStorage.setItem("token", "token"); // this.router.navigate(['/home']); // } // logout() { // //this.isLogin = false; // sessionStorage.removeItem("token"); // this.router.navigate(['/login']); // } constructor(private http:HttpClient,private router:Router){} login(user:User):Observable<boolean> { return this.http.post<boolean>(MAIN_URL + URL, user) .pipe( map((result)=>{ sessionStorage.setItem("token", result + ""); if (result){ this.router.navigate(['/home']); } return result; }) ) } isAuthenticated(): boolean{ if (sessionStorage.getItem("token")){ return sessionStorage.getItem("token") == 'false' ? false: true; } } logout(): void{ sessionStorage.removeItem("token"); this.router.navigate(['/login']); } }
726682aeba35391ee25afec71b05cbb2c70d4111
[ "TypeScript" ]
9
TypeScript
UKHasantha/Lazy-Loading
1726508de4f1ee164605e7c5cd81b72d976c728c
78ecbfea90a91f5c7fb16941df963fe500bceedc
refs/heads/master
<file_sep><?php namespace laravel\bridgebb; class ext extends \phpbb\extension\base { }<file_sep><!-- BEGIN forumrow --> <!-- IF (forumrow.S_IS_CAT and not forumrow.S_FIRST_ROW) or forumrow.S_NO_CAT --> </ul> </div> <!-- ENDIF --> <!-- EVENT forumlist_body_category_header_before --> <!-- IF forumrow.S_IS_CAT or forumrow.S_FIRST_ROW or forumrow.S_NO_CAT --> <div class="bg-gray m-y-1 p-a-1 img-rounded"> <!-- EVENT forumlist_body_category_header_row_prepend --> <div class="row color-white"> <div class="col-sm-6"> <!-- IF forumrow.S_IS_CAT --> <a href="{forumrow.U_VIEWFORUM}" class="color-white text-uppercase">{forumrow.FORUM_NAME}</a> <!-- ELSE --> {L_FORUM} <!-- ENDIF --> </div> <div class="col-sm-1 text-xs-center"> {L_TOPICS} </div> <div class="col-sm-1 text-xs-center"> {L_POSTS} </div> <div class="col-sm-4"> {L_LAST_POST} </div> </div> <!-- EVENT forumlist_body_category_header_row_append --> <ul class="list-group"> <!-- ENDIF --> <!-- EVENT forumlist_body_category_header_after --> <!-- IF not forumrow.S_IS_CAT --> <!-- EVENT forumlist_body_forum_row_before --> <li class="list-group-item<!-- IF forumrow.S_ROW_COUNT is even --> bg-gray-lighter<!-- ENDIF -->"> <!-- EVENT forumlist_body_forum_row_prepend --> <div class="row"> <div class="col-sm-6"> <h5 class="list-group-item-heading"><i class="fa fa-folder-open"></i> <a href="{forumrow.U_VIEWFORUM}">{forumrow.FORUM_NAME}</a></h5> <!-- IF forumrow.FORUM_DESC -->{forumrow.FORUM_DESC}<!-- ENDIF --> </div> <div class="col-sm-1 text-xs-center"> {forumrow.TOPICS} </div> <div class="col-sm-1 text-xs-center"> {forumrow.POSTS} </div> <div class="col-sm-4"> <!-- IF forumrow.CLICKS --> {L_REDIRECTS}{L_COLON} {forumrow.CLICKS} <!-- ELSEIF not forumrow.S_IS_LINK --> <!-- IF forumrow.S_DISPLAY_SUBJECT --> <!-- EVENT forumlist_body_last_post_title_prepend --> <div> <a href="{forumrow.U_LAST_POST}" title="{forumrow.LAST_POST_SUBJECT}">{forumrow.LAST_POST_SUBJECT_TRUNCATED}</a> <!-- IF not S_IS_BOT --> <a href="{forumrow.U_LAST_POST}">{LAST_POST_IMG}</a> <!-- ENDIF --> </div> <!-- ENDIF --> <!-- IF forumrow.LAST_POST_TIME --> <div> {L_POST_BY_AUTHOR} {forumrow.LAST_POSTER_FULL} </div> <div> {forumrow.LAST_POST_TIME} </div> <!-- ELSE --> {L_NO_POSTS} <!-- ENDIF --> <!-- ENDIF --> </div> </div> <!-- EVENT forumlist_body_forum_row_append --> </li> <!-- EVENT forumlist_body_forum_row_after --> <!-- ENDIF --> <!-- IF forumrow.S_LAST_ROW --> </ul> </div> <!-- EVENT forumlist_body_last_row_after --> <!-- ENDIF --> <!-- BEGINELSE --> <strong>{L_NO_FORUMS}</strong> <!-- END forumrow --> <file_sep># warriormachines-phpbb ```shell docker build --rm --force-rm --tag="warriormachines/warriormachines-phpbb" ./ ``` <file_sep># warriormachines/warriormachines-phpbb FROM debian:jessie MAINTAINER "<NAME>" <<EMAIL>> # Copy the directory from the native host into the container. (Either from the local dev machine or GitHub, depending on where this container is built.) COPY . /var/www/html/public/forums WORKDIR /var/www/html/public/forums RUN chown -R www-data:www-data . \ && chmod -R 777 cache files images/avatars/upload store VOLUME /var/www/html/public/forums CMD ["/bin/sh", "-c", "while true; do sleep 1; done"]
728dffe3f993121a15a930cd805977b17e297933
[ "Markdown", "Dockerfile", "HTML", "PHP" ]
4
PHP
WarriorMachines/warriormachines-phpbb
40d23e61421a6f03764d18e68d19110a39610223
b8456f20cc5e52eb0c87979450f8f427c8edbc5f
refs/heads/master
<file_sep>#!/usr/bin/python import json data = open('www/data/data-pb.json').read() checksum = open('www/data/data-pb.md5').read() version = open('www/data/api_version.txt').read() code = "var API_VERSION = %d;\n\n" % int(version) code += "var INITIAL_CHECKSUM = '%s';\n\n" % checksum code += 'var INITIAL_DATA = ' + data + ';' open('www/js/initialdata.js', 'w').write(code) <file_sep>#!/usr/bin/env python #coding: utf-8 import json, urllib, sys, os try: DEST = sys.argv[1] except IndexError: DEST = 'www/data' BASE_URL = 'http://emergencias.cultura.gov.br/wp-content/uploads/json' def load(name): data = urllib.urlopen('%s/%s-pb.json' % (BASE_URL, name)).read() return json.loads(data) events = load('events') spaces = load('spaces') speakers = load('speakers') spaces = load('spaces') meetings = {} territories = {} for event in events: types = [] encontros = [] percursos = [] event['startsOn'] = event['startsOn'][:8] + '%02d' % (int(event['startsOn'][8:])+1) for track in event['terms']['tracks']: if track.startswith('Encontro '): encontro = track[9:] if encontro.startswith('de '): encontro = encontro[3:] if encontro.startswith('Rede '): encontro = encontro[5:] if encontro.startswith('Redes'): encontro = encontro[6:] if encontro.startswith('de '): encontro = encontro[3:] encontro = encontro.replace(' e ', '').replace(' ', '') encontros.append(encontro) meetings[encontro] = 1 elif track.startswith('Percurso '): percurso = track[9:] percurso = percurso.replace(' e ', '').replace(' ', '') percursos.append(percurso) territories[percurso] = 1 elif track.startswith('Percursos Territoriais'): pass else: types.append(track) event['terms']['types'] = types event['terms']['meetings'] = encontros event['terms']['territories'] = percursos del event['terms']['tracks'] ind = 4 meetings_data = [] for meeting in sorted(meetings.keys()): meetings_data.append({ 'id': meeting, }) territories_data = [] for territory in sorted(territories.keys()): territories_data.append({ 'id': territory, }) #meetings_data[0]['telegram'] = 'http://emergencias.hacklab.com.br/chats/Xis' #territories_data[0]['telegram'] = 'http://emergencias.hacklab.com.br/chats/Xis' for space in spaces: if space['name'] == u'Pra\xe7<NAME>\xe1': space['name'] = "<NAME>" open(os.path.join(DEST, 'events-pb.json'), 'w').write(json.dumps(events, indent=ind)) open(os.path.join(DEST, 'meetings-pb.json'), 'w').write(json.dumps(meetings_data, indent=ind)) open(os.path.join(DEST, 'territories-pb.json'), 'w').write(json.dumps(territories_data, indent=ind)) open(os.path.join(DEST, 'speakers-pb.json'), 'w').write(json.dumps(speakers, indent=ind)) open(os.path.join(DEST, 'spaces-pb.json'), 'w').write(json.dumps(spaces, indent=ind)) <file_sep>#!/usr/bin/python # Este servidor foi criado pro desenvolvimento, pra simular uma conexao lenta durante import tornado.ioloop import tornado.web import tornado.options import time, random class MainHandler(tornado.web.RequestHandler): def get(self, name, ext): if ext == 'json': time.sleep(2) self.write(open('www/data/%s-pb.%s' % (name, ext)).read()) #self.write('%d' % (random.random()*10000)) def make_app(): return tornado.web.Application([ (r"/data/(.+)-pb.(json|md5)", MainHandler), ], debug=True) if __name__ == "__main__": tornado.options.parse_command_line() app = make_app() app.listen(8000) tornado.ioloop.IOLoop.current().start() <file_sep><ion-view view-title="Sobre"> <ion-content> <article class="single text-center"> <div class="post-content clearfix"> <h4>Aplicativo Emergências</h4> <p>O Aplicativo Emergências é resultado da articulação colaborativa de agentes da sociedade civil e do governo. Desenvolvido pelo Hacklab, contou com o apoio do Instituto Mutirão e da Rede Fora do Eixo, que atenderam a provocação da Secretaria de Cidadania e Diversidade Cultural em fazer uso da API de dados abertos disponibilizada pelo Ministério da Cultura.</p> <div class="logos_sobre"> <a href="#" onclick="window.open('http://hacklab.com.br', '_system', 'location=yes'); return false;"> <img class="logo_hacklab" src="img/hacklab.png"/> </a> <a href="#" onclick="window.open('http://institutomutirao.org/', '_system', 'location=yes'); return false;"> <img class="logo_mutirao" src="img/mutirao.png"/> </a> </div> <p>Agradecemos a todos que se prontificaram a nos ajudar pra viabilizar este app. Este é o nosso apoio ao Emergências, e quem quiser colaborar no desenvolvimento e saber mais sobre o processo, é só colar no #EncontroHacker!</p> <p>Um salve pra <b><NAME> e Isabella</b>, que se prontificaram a ajudar com as crianças enquanto os hackers mergulhavam no código, pro <b><NAME></b> e a equipe do Coletivo Carpas, que deram uma força com a publicação do app. E se esquecemos alguém, vai na próxima versão, que estamos em cima da hora ;-). Tamo junto!</p> <p>Colabore: <a href="#" onclick="window.open('https://github.com/hacklabr/emergencias-app', '_system', 'location=yes'); return false;">https://github.com/hacklabr/emergencias-app</a></p> </div> </article> <!-- .single --> </ion-content> </ion-view> <file_sep>#!/usr/bin/env python # -*- coding: utf-8 -*- import json, urllib, sys, os, md5, datetime API_VERSION=3 try: DEST = sys.argv[1] except IndexError: DEST = 'www/data' BASE_URL = 'http://emergencias.cultura.gov.br/wp-content/uploads/json' def load(name): data = urllib.urlopen('%s/%s-pb.json' % (BASE_URL, name)).read() return json.loads(data) def get_index(data): index = {} for item in data: index[item['id']] = item return index events = load('events') spaces = load('spaces') speakers = load('speakers') for space in spaces: del space['shortDescription'] for spk in speakers: for key in ('speaker_title', 'speaker_keynote', 'shortDescription'): del spk[key] def format_description(desc): ps = desc.split('\n') desc = '' for p in ps: if not p: continue desc += '<p>%s</p>\n' % p return desc; for speaker in speakers: speaker['description'] = format_description(speaker['description']) speakers_ind = get_index(speakers) spaces_ind = get_index(spaces) meetings = {} territories = {} final_events = [] def format_date(date): if not date: return '' week = [ '2ª feira', '3ª feira', '4ª feira', '5ª feira', '6ª feira', 'Sábado', 'Domingo' ] date = datetime.datetime.strptime(date, '%Y-%m-%d') return '%02d/%02d - %s' % (date.day, date.month, week[date.weekday()]) for event in events: types = [] encontros = [] percursos = [] event['description'] = format_description(event['description']) for track in event['terms']['tracks']: if track.startswith('Encontro '): encontro = track[9:] if encontro.startswith('de '): encontro = encontro[3:] if encontro.startswith('Rede '): encontro = encontro[5:] if encontro.startswith('Redes'): encontro = encontro[6:] if encontro.startswith('de '): encontro = encontro[3:] encontro = encontro.replace(' e ', '').replace(' ', '') encontros.append(encontro) meetings[encontro] = 1 elif track.startswith('Percurso '): percurso = track[9:] percurso = percurso.replace(' e ', '').replace(' ', '') percursos.append(percurso) territories[percurso] = 1 elif track.startswith('Percursos Territoriais'): pass else: types.append(track) event['types'] = types event['meetings'] = encontros event['territories'] = percursos del event['terms'] spk = [] for speaker in event['speakers']: spk.append(speakers_ind[speaker]) event['speakers'] = spk spaceId = event.pop('spaceId') if spaceId: event['space'] = spaces_ind[spaceId] else: event['space'] = { 'name': '' } if event['space']['name'] == u'Pra\xe7a Mau\xe1': event['space']['name'] = "Praça Quinze" event['date'] = format_date(event['startsOn']) keys = ['registration_code_text', 'defaultImageThumb', 'timestamp', 'defaultImage', 'registration_code_title', 'registration_code', 'shortDescription', ] for key in keys: del event[key] final_events.append(event) events = final_events ind = 4 meetings_data = [] for meeting in sorted(meetings.keys()): meetings_data.append({ 'id': meeting, }) territories_data = [] for territory in sorted(territories.keys()): territories_data.append({ 'id': territory, }) #meetings_data[0]['telegram'] = 'http://emergencias.hacklab.com.br/chats/Xis' #territories_data[0]['telegram'] = 'http://emergencias.hacklab.com.br/chats/Xis' data = { 'events': events, 'meetings': meetings_data, 'territories': territories_data, } data = json.dumps(data, indent=ind) open(os.path.join(DEST, 'data-pb.json'), 'w').write(data) open(os.path.join(DEST, 'data-pb.md5'), 'w').write(md5.md5(data).hexdigest()) open(os.path.join(DEST, 'api_version.txt'), 'w').write('%d' % API_VERSION) <file_sep>angular.module('emergencias.controllers', []) // .controller('TrackCtrl', function($rootScope, $scope, $stateParams, Emergencias, Conn){ // $scope.tracks = [ // { 'name': 'Hackers' }, // { 'name': 'Feminismos' }, // { 'name': 'Resistência Urbana na América Latina' }, // { 'name': 'Redes, Movimentos e Entidades de Artes Cênicas' }, // { 'name': 'Cultura e Infância' }, // { 'name': 'Indigenas' }, // { 'name': 'LGBT' }, // ] // }) .controller('ProgramacaoCtrl', function($rootScope, $scope, $stateParams, Event, Meeting, Territory, $localStorage) { if ($stateParams.meeting) { Meeting.get($stateParams.meeting).then(function(data) { $scope.meeting = data; }); } if ($stateParams.territory) { Territory.get($stateParams.territory).then(function(data) { $scope.territory = data; }); } Event.cached.then(function(events) { $scope.events = events }); Event.renew.then(function(events) { if (events != null) { $scope.events = events } }); }) .controller('RedesCtrl', function($rootScope, $scope, Meeting, $localStorage) { Meeting.cached.then(function(meetings) { $scope.meetings = meetings }); Meeting.renew.then(function(meetings) { if (meetings != null) { $scope.meetings = meetings } }); }) .controller('PercursosCtrl', function($rootScope, $scope, Territory, $localStorage) { Territory.cached.then(function(territories) { $scope.territories = territories }); Territory.renew.then(function(territories) { if (territories != null) { $scope.territories = territories } }); }) .controller('FilterCtrl', function($rootScope, $scope, $localStorage) { $scope.search_text = ''; }) .controller('EventCtrl', function($rootScope, $scope, $stateParams, Event, $ionicModal, $state){ $scope.$on('$ionicView.beforeEnter', function(){ $rootScope.curr = 'event'; }); $scope.$on('$ionicView.beforeLeave', function(){ $rootScope.curr = false; }); $scope.view = { hasMore : false } if($stateParams.event){ Event.get($stateParams.event).then(function (event) { $scope.event = event; }); } else { $state.go("emergencias.programacao()") } }) .controller('ButtonsCtrl', function($scope, $ionicSideMenuDelegate, $rootScope, $ionicGesture){ ionic.Platform.ready(function(){ $ionicGesture.on('swiperight', function(){ }, angular.element(document.querySelector("#menu-view")), {}); $scope.$watch(function(){ return $ionicSideMenuDelegate.isOpenLeft(); }, function(isOpen){ var leftMenu = angular.element(document.querySelector("#left-menu")); if(isOpen){ leftMenu.removeClass('hidden'); } else { leftMenu.addClass('hidden'); } $rootScope.$emit("sidemenu_toggle", isOpen); }); $scope.toggleLeftSideMenu = function() { $ionicSideMenuDelegate.toggleLeft(); } }); }) .controller('AppCtrl', function($scope, $rootScope, $localStorage, Notifications, $cordovaSocialSharing, GlobalConfiguration) { Notifications.init(); $scope.notifications = Notifications }) .controller('NotificationsCtrl', function($scope, $rootScope, Notifications, $localStorage, $ionicPush, GlobalConfiguration) { $scope.$on('$ionicView.beforeEnter', function(){ Notifications.readAll(); }); $scope.notifications = Notifications }) <file_sep>app = angular.module('emergencias.services', []); app.service('Util', function() { this.index_obj = function(obj_list) { var indexed_obj = {}; obj_list.forEach(function(obj) { indexed_obj[obj.id] = obj; }); return indexed_obj; } }) app.service('Cache', function($http, $q, GlobalConfiguration, $localStorage, Util) { var self = this; var timeout = 5; this.store = function(data, checksum) { $localStorage.apiVersion = API_VERSION; $localStorage.cachedChecksum = checksum; $localStorage.cachedData = data; $localStorage.cachedIndex = { 'meetings': Util.index_obj(data.meetings), 'territories': Util.index_obj(data.territories), 'events': Util.index_obj(data.events) } $localStorage.lastUpdate = new Date().getTime() } if (!$localStorage.apiVersion || $localStorage.apiVersion < API_VERSION) { self.store(INITIAL_DATA, INITIAL_CHECKSUM); } this.getIndex = function(name) { return $q.when($localStorage.cachedIndex[name]); } this.getCached = function(name) { return $q.when($localStorage.cachedData[name]); } this.getNew = function(name) { var diff = new Date().getTime() - $localStorage.lastUpdate if (diff < timeout) { return $q.when(null); } var url = GlobalConfiguration.BASE_URL + '/data-pb.md5?'+name; return $http.get(url, {cache : false}).then(function(data) { var checksum = data.data if ($localStorage.cachedChecksum == checksum) return null; url = GlobalConfiguration.BASE_URL + '/data-pb.json'; return $http.get(url, {cache: false}).then(function(data) { self.store(data.data, checksum) return data.data[name]; }); }); } this.get = function(name) { return self.getNew(name).then(function(data) { return $localStorage.cachedData[name]; }) } }) app.service('Meeting', function($q, $http, GlobalConfiguration, Cache) { var self = this; this.cached = Cache.getCached('meetings').then(function(data) { return data; }) this.renew = Cache.getNew('meetings').then(function(data) { return data }) this.indexed_meetings = Cache.getIndex('meetings') this.get = function(id) { return self.indexed_meetings.then(function(index) { return index[id] }) } }) app.service('Territory', function($http, GlobalConfiguration, Cache) { var self = this; this.cached = Cache.getCached('territories').then(function(data) { return data; }) this.renew = Cache.getNew('territories').then(function(data) { return data }) this.indexed_territories = Cache.getIndex('territories') this.get = function(id) { return self.indexed_territories.then(function(index) { return index[id] }) } }) app.service('Event', function($q, $http, GlobalConfiguration, Cache) { var self = this; this.cached = Cache.getCached('events').then(function(data) { return data; }) this.renew = Cache.getNew('events').then(function(data) { return data }) this.indexed_events = Cache.getIndex('events') this.get = function(id) { return self.indexed_events.then(function(index) { return index[id] }) } }); app.service('Notifications', function($http, $localStorage) { var self = this; if (!$localStorage.messages) { $localStorage.messages = []; $localStorage.unread = 0; } this.messages = $localStorage.messages; this.unread = $localStorage.unread; this.count = this.messages.length this.commit = function() { $localStorage.messages = self.messages; $localStorage.unread = self.unread; } this.notify = function(message) { self.unread += 1; self.messages.unshift(message); self.count = self.messages.length; self.commit(); } this.getMessages = function() { return self.messages; } this.readAll = function(){ self.unread = 0 self.commit(); } this.init = function(){ Ionic.io(); var push_register_callback = function(pushToken) { console.log('Registered token:', pushToken.token); user.addPushToken(pushToken); user.save(); // you NEED to call a save after you add the token }; var push_config = { "debug": true, canShowAlert: true, //Can pushes show an alert on your screen? canSetBadge: true, //Can pushes update app icon badges? canPlaySound: true, //Can notifications play a sound? canRunActionsOnWake: true, //Can run actions outside the app, // android: { // icon: 'icon' // }, "onNotification": function(notification) { var message = {}; message.message = notification.text; if (notification.title === 'emergencias-app') { if (notification.payload && notification.payload.title) { message.title = notification.payload.title; notification.title = notification.payload.title; } else { notification.title = ''; } } else { message.title = notification.title; } // notification.image = '' self.notify(message); return notification; }, "onRegister": push_register_callback }; var push = new Ionic.Push(push_config); // FIXME: the above method should be used // $ionicPush.init(push_config); var user = Ionic.User.current(); // this will give you a fresh user or the previously saved 'current user' // var user = $ionicUser.current(); // if the user doesn't have an id, you'll need to give it one. if (!user.id) { user.id = Ionic.User.anonymousId(); } // Identify your user with the Ionic User Service user.save(); push.register(push_register_callback); // $ionicPush.register(push_config); }; }) <file_sep># Download e build ------------------ Se você já tem o npm instalado, basta fazer: * Instalar o ionic globalmente ``` $ sudo npm -g install cordova ionic bower ``` * Clonar o repositório ``` $ git clone https://github.com/hacklabr/emergencias-app.git ``` * Fazer o build padrão ``` $ cd emergencias-app $ ionic state reset $ bower install ``` * Fazer o setup SASS ``` $ ionic setup sass ``` * Rodar ``` $ ionic serve ``` * Para rodar no navegador, adicione um proxy com ``` $ gulp add-proxy ``` Ele vai te dar uma url padrão e abrir o navegador automaticamente! * Ou para rodar no navegador o problema de cross-origin do localhost: ``` chromium --disable-web-security ``` E abrir o URL [http://localhost:8100](http://localhost:8100) # Editando ---------- Na raiz do projeto você terá o diretorio scss onde ficará seu sass. só editar! O ionic serve já faz o watch dos arquivos, recompila na alteração e faz o livereolad * Resources * http://ionicframework.com/docs/cli/sass.html * http://learn.ionicframework.com/formulas/working-with-sass/ * http://ionicframework.com/docs/components # Rodando no celular Android ou Emulador Para isso, você precisará ter a SDK Android instalada * Instala o phonegap ``` $ npm install phonegap ``` * Adiciona a plataforma android ao projeto (aqui, se a SDK não estiver instalada já haverá falha) ``` $ ionic platform add android ``` * Remove o proxy adicionado ``` $ gulp remove-proxy ``` * Aqui, precisamos ter um dispositivo plugado ao computador aceitando instalação de fontes desconhecidas e com o modo desenvolvedor ativado. ``` $ ionic run android ``` * Para emular, é necessário que se crie um disposivo usando o Android SDK Manager ``` $ android ``` * Uma vez criado o dispositivo ``` $ ionic emulate android ``` # Limpando binários para ios ``` $ bash clean_execs.sh ``` <file_sep>angular.module("emergencias.config", []) // .factory('Conn', function(){ // CONN = "DEFAULT"; // // Connection Change Handler // This function just change the global connection type // var connChangeHandler = function(conn){ // if(window.Connection) { // if(Connection.NONE == conn.type){ // emergencias.value('CONN', Connection.NONE); // } else if(Connection.ETHERNET == conn.type // || Connection.WIFI == conn.type // || Connection.CELL_4G){ // CONN = "FAST"; // } else { // CONN = "SLOW"; // } // } else { // CONN = "UNKNOWN"; // } // } // // document.addEventListener("online", connChangeHandler, false); // document.addEventListener("offline", connChangeHandler, false); // // return { // type: function(){ // return CONN; // } // } // }) .config(function($sceProvider) { // Completely disable SCE. For demonstration purposes only! // Do not use in new projects. $sceProvider.enabled(false); }) .factory('GlobalConfiguration', function(){ return { BASE_URL : "http://emergencias.hacklab.com.br/api3", //BASE_URL : 'http://localhost:8000/data', //BASE_URL: 'http://emergencias.cultura.gov.br/wp-content/uploads/json', TEMPLATE_URL : "http://emergencias.hacklab.com.br/2015/wp-content/themes/viradacultural-2015", // seens deprecated SOCIAL_API_URL : "http://emergencias.hacklab.com.br/2015/api", SHARE_URL : "http://emergencias.hacklab.com.br/2015", TERMS_URL: "http://www.google.com", PRAVACY_URL: "http://www.uol.com.br", APP_ID: 'b3b396b4' } }); //http://emergencias.cultura.gov.br/wp-content/uploads/json/spaces-pb.json //http://emergencias.cultura.gov.br/wp-content/uploads/json/speakers-pb.json
36c127c13ec84f181b543e63d5335a270f52fa6f
[ "JavaScript", "Python", "HTML", "Markdown" ]
9
Python
alexsandrocruz/emergencias-app
15761c5a4802cce92b9325cdd2559f52c3a390c0
589f5e46f13ce6ee0aa9d8e01a47d7c26a23298e
refs/heads/master
<file_sep>SELECT country, CAST(AVG(CAST(a.bore * a.bore * a.bore / 2 AS NUMERIC(6, 2))) AS NUMERIC(6, 2)) avg_mw FROM ( SELECT sh.name, cl.country, cl.bore FROM Ships sh, Classes cl WHERE sh.class = cl.class UNION SELECT DISTINCT o.ship, cl.country, cl.bore FROM Outcomes o, Classes cl WHERE o.ship = cl.class ) a GROUP BY country;<file_sep>SELECT maker FROM product EXCEPT SELECT maker FROM Product p JOIN ( SELECT model FROM Product WHERE type LIKE 'PC' EXCEPT SELECT model FROM PC ) m ON m.Model = p.Model;<file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Lesson2 { /* * Исполнитель: * <NAME> * * Задание №3 * С клавиатуры вводятся числа, пока не будет введен 0. Подсчитать сумму всех нечетных положительных чисел. */ class Task3 { /// <summary> /// Метод выводит в кнсоль сумму всех нечетных положительных чисел, введенных пользователем с клавиатуры. /// </summary> public static void Go() { int sum = 0; do { CommonMethods.ColoredWriteLine("Введите число:", ConsoleColor.Yellow); int a = CommonMethods.SetIntParametr(); if (a == 0) break; if (a % 2 != 0 && a > 0) sum += a; } while (true); CommonMethods.ColoredWriteLine($"Сумма всех нечетных положительных чисел:\n{sum}", ConsoleColor.Cyan); } } } <file_sep>WITH cte AS ( SELECT ROW_NUMBER() OVER(ORDER BY maker, ordr) num, maker, type FROM ( SELECT DISTINCT maker, type, CASE WHEN type = 'PC' THEN 'a' WHEN type = 'Laptop' THEN 'b' WHEN type = 'Printer' THEN 'c' END [ordr] FROM Product ) q) SELECT num, CASE WHEN(num > 1) AND maker = ( SELECT c1.maker FROM cte c1 WHERE c1.num = (c.num - 1) ) THEN '' ELSE c.maker END maker, type FROM cte c ORDER BY num;<file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Task4 { class Task4 { static void Main(string[] args) { int x, y; Console.ForegroundColor = ConsoleColor.Yellow; Console.WriteLine("Введите первую переменную \"x\":"); x = SetValue(); Console.ForegroundColor = ConsoleColor.Yellow; Console.WriteLine("Введите вторую переменную \"y\":"); y = SetValue(); Console.ForegroundColor = ConsoleColor.Yellow; Console.WriteLine("Меняем местами первым способом:"); Swap1(ref x, ref y); Console.ForegroundColor = ConsoleColor.White; Console.WriteLine($"x = {x}\ny = {y}"); Console.ForegroundColor = ConsoleColor.Yellow; Console.WriteLine("Меняем обратно вторым способом:"); Swap1(ref x, ref y); Console.ForegroundColor = ConsoleColor.White; Console.WriteLine($"x = {x}\ny = {y}"); Console.ReadLine(); } static void Swap1(ref int a, ref int b) { a = a + b; b = a - b; a = a - b; } static void Swap2(int a, int b) { a = a + b; b = a ^ b; a = a ^ b; } static int SetValue() { do { int a = 0; Console.ForegroundColor = ConsoleColor.White; if (Int32.TryParse(Console.ReadLine(), out a)) return a; else { Console.ForegroundColor = ConsoleColor.Yellow; Console.WriteLine("Введенное значение не является целым числом!\nПопробуйте еще раз!"); } } while (true); } } } <file_sep>SELECT maker FROM Product pr JOIN PC p ON p.model = pr.model AND p.speed >= 750 INTERSECT SELECT maker FROM Product pr JOIN Laptop l ON l.model = pr.model AND l.speed >= 750;<file_sep>SELECT SUM(rem) rem FROM ( SELECT SUM(inc) rem FROM Income_o UNION ALL SELECT-SUM(out) FROM Outcome_o ) q;<file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Lesson3 { /* * Исполнитель: * <NAME> * * Задание №2 * а) С клавиатуры вводятся числа, пока не будет введен 0 (каждое число в новой строке). * Требуется подсчитать сумму всех нечетных положительных чисел. * Сами числа и сумму вывести на экран; Используя tryParse; * б) Добавить обработку исключительных ситуаций на то, что могут быть введены некорректные данные. * При возникновении ошибки вывести сообщение. */ class Task2 { /// <summary> /// Метод выводит в кнсоль сумму всех нечетных положительных чисел, введенных пользователем с клавиатуры. /// </summary> public static void Go() { CommonMethods.ColoredWriteLine(TasksDescription.Task2Text, ConsoleColor.Cyan); int sum = 0; do { CommonMethods.ColoredWriteLine("Введите число:", ConsoleColor.Yellow); int a = CommonMethods.SetIntParametr(); //int a = SetIntParametrExProcessing(); // Реализация того же метода с использованием try{ } catch{ } if (a == 0) break; if (a % 2 != 0 && a > 0) sum += a; } while (true); CommonMethods.ColoredWriteLine($"Сумма всех нечетных положительных чисел:\n{sum}", ConsoleColor.Cyan); } } }<file_sep>WITH q AS ( SELECT s.ID_Psg, p.name, sq.trip_no, sq.place FROM ( SELECT ID_Psg FROM Pass_in_trip GROUP BY ID_psg HAVING COUNT(trip_no) = COUNT(DISTINCT place)) s JOIN Pass_in_trip sq ON sq.ID_psg = s.ID_psg JOIN Passenger p ON p.ID_psg = s.ID_psg ) SELECT name, SUM(diff) time_in_trip FROM ( SELECT t.trip_no, q.name, CASE WHEN ((DATEPART(hh, time_out) > DATEPART(hh, time_in)) OR ((DATEPART(hh, time_out) = DATEPART(hh, time_in)) AND (DATEPART(minute, time_out) > DATEPART(minute, time_in)))) THEN (SELECT 24*60 + (DATEDIFF(minute, time_out, time_in))) ELSE (SELECT DATEDIFF(minute, time_out, time_in)) END diff FROM Trip t JOIN q ON q.trip_no = t.trip_no) qs GROUP BY name ORDER BY time_in_trip<file_sep>SELECT SUM(rem) rem FROM ( SELECT SUM(inc) rem FROM Income_o WHERE date < '20010415' UNION ALL SELECT-SUM(out) FROM Outcome_o WHERE date < '20010415' ) q;<file_sep>SELECT name FROM Ships WHERE name LIKE '%[A-Za-z0-9]% %[A-Za-z0-9]% %[A-Za-z0-9]%' UNION SELECT ship FROM Outcomes WHERE ship LIKE '%[A-Za-z0-9]% %[A-Za-z0-9]% %[A-Za-z0-9]%';<file_sep>SELECT CAST(AVG(numGuns * 1.0) AS NUMERIC(8, 2)) avg_numGuns FROM Classes c WHERE c.type = 'bb';<file_sep>SELECT TOP 1 WITH TIES name, tripCount FROM ( SELECT pit.ID_psg, ( SELECT COUNT(trip_no) FROM Pass_in_trip p WHERE p.ID_psg = pit.ID_psg ) tripCount FROM Pass_in_trip pit JOIN Trip t ON pit.trip_no = t.trip_no GROUP BY ID_psg HAVING COUNT(DISTINCT ID_comp) = 1 ) q JOIN Passenger p ON p.ID_psg = q.ID_psg ORDER BY tripCount DESC;<file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Lesson6 { /* * Исполнитель: * <NAME> * * Задание №1 * Изменить программу вывода функции так, чтобы можно было передавать функции типа * double(double,double). Продемонстрировать работу на функции с функцией a*x^2 и функцией * a*sin(x). */ public delegate double Fun(double a, double b); class Task1 { public static void Main(string[] args) { Lesson6.Support.ColoredWriteLine("Введите значение x1:", ConsoleColor.Yellow); double a = Support.SetDoubleParametr(); Support.ColoredWriteLine("Введите значение x2:", ConsoleColor.Yellow); double b = Support.SetDoubleParametr(); Support.ColoredWriteLine("Введите значение аргумента a:", ConsoleColor.Yellow); double c = Support.SetDoubleParametr(); Support.ColoredWriteLine("Функция a*x^2", ConsoleColor.Yellow); Table(delegate (double x, double y) { return y * x * x; }, a, b, c); Support.ColoredWriteLine("Функция a*(sin(x))", ConsoleColor.Yellow); Table(delegate (double x, double y) { return y * Math.Sin(x); }, a, b, c); Console.ReadLine(); } /// <summary> /// Функция табулирования /// </summary> /// <param name="F">Функция</param> /// <param name="a">Занчение x "от"</param> /// <param name="b">Значение x "до"</param> /// <param name="c">Аргумент</param> static void Table(Fun F, double a, double b, double c) { Console.WriteLine("----X----Y--------"); while(a <= b) Support.ColoredWriteLine(String.Format("|{0,8:0.000}|{1,8:0.000}", a, F(a++, c)), ConsoleColor.Cyan); Console.WriteLine("-------------------"); } } } <file_sep>-- Найдите производителей, выпускающих по меньшей мере три различных модели ПК. Вывести: Maker, число моделей ПК. SELECT maker, COUNT(*) model_qty FROM Product WHERE type = 'pc' GROUP BY maker HAVING COUNT(*) > 2;<file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Lesson4 { /* * Исполнитель: * <NAME> * * Задание №6 * Написать игру “Верю. Не верю”. В файле хранятся некоторые данные и правда это или нет. * Например: “Шариковую ручку изобрели в древнем Египте”, “Да”. * Компьютер загружает эти данные, случайным образом выбирает 5 вопросов и задает их игроку. * Игрок пытается ответить правда или нет, то что ему загадали и набирает баллы. Список вопросов ищите во вложении или можно воспользоваться Интернетом. */ class Task6 { public static void Go() { bool exit = false; const int maxQuestions = 5; //Кол-во вопросов в раунде игры Random r = new Random(); string fileName = "..\\..\\Data\\BelieveOrNotBelieve.txt"; // Приветствие и печать правил игры CommonMethods.ColoredWriteLine(TasksDescription.Task6Description, ConsoleColor.Cyan); BelieveOrNot[] believeOrNot = BelieveOrNot.GenerateFromFile(fileName); int[] questionsNumbers = new int[maxQuestions]; //Если оставить массив, проиницилизированным нолями, вопрос с индексом ноль никогда не попадёт в выборку for (int j = 0; j < questionsNumbers.Length; j++) questionsNumbers[j] = believeOrNot.Length + 1; // Таким образом, массив проинициализирован индексами, для которых непредусмотрены вопросы while (!exit) { int i = 0; while (i < maxQuestions) // Заполняем массив неповторяющимися номерами вопросов, которые будут заданы игроку { int nextQuestion = r.Next(0, believeOrNot.Length); if (RepeatedQuestionsCheck(questionsNumbers, nextQuestion)) { questionsNumbers[i] = nextQuestion; i++; } } i = 0; bool restart = false; // начать заново int score = 0; // счет игрока bool skip = false; // Если для ответа введён некорректный символ, пропускаем ход CommonMethods.ColoredWriteLine(TasksDescription.StartGame, ConsoleColor.Magenta); while (!restart && i != questionsNumbers.Length) { if (!skip) CommonMethods.ColoredWriteLine(believeOrNot[questionsNumbers[i]].Question, ConsoleColor.Yellow); skip = false; string choice = Console.ReadLine(); switch (choice) { case "+": // Верю if (believeOrNot[questionsNumbers[i]].Answer) { score++; CommonMethods.ColoredWriteLine("Верно!", ConsoleColor.Green); } else CommonMethods.ColoredWriteLine("Не верно!", ConsoleColor.Red); break; case "-": // Не верю if (!believeOrNot[questionsNumbers[i]].Answer) { score++; CommonMethods.ColoredWriteLine("Верно!", ConsoleColor.Green); } else CommonMethods.ColoredWriteLine("Не верно!", ConsoleColor.Red); break; case "r": // Рестарт restart = true; break; case "q": // Выход из игры exit = true; break; default: CommonMethods.ColoredWriteLine("Непредвиденное действие!", ConsoleColor.Red); skip = true; break; } if (restart || exit) break; if (!skip) { if (i++ == questionsNumbers.Length - 1) { CommonMethods.ColoredWriteLine("Поздравляем!\nВы закончили игру со счетом: " + score + " из " + questionsNumbers.Length, ConsoleColor.Cyan); exit = !IsAnotherRound(); break; } } } if (exit) break; // Задаём вопросы игроку } } /// <summary> /// метод проверки повторяющихся вопросов /// </summary> /// <param name="a">Массив уже выбранных вопросов</param> /// <param name="q">Номер выбранного вопроса</param> /// <returns>Подходит или нет</returns> static bool RepeatedQuestionsCheck(int[] a, int q) { for (int i = 0; i < a.Length; i++) { if (a[i] == q) return false; } return true; } /// <summary> /// Метод определяет, будет ли игрок участвовать в следующем раунде /// </summary> /// <returns>Да/Нет</returns> static bool IsAnotherRound() { CommonMethods.ColoredWriteLine("Жнлаете еще сыграть?\nВыберите \"+\", если хотите продолжить или нажмите любую клавишк, чтобы выйти.", ConsoleColor.Yellow); return Console.ReadLine().Equals("+"); } } }<file_sep>-- Найдите номер модели, объем памяти и размеры экранов ПК-блокнотов, цена которых превышает 1000 дол. SELECT model, ram, screen FROM Laptop WHERE price > 1000;<file_sep>using System; using System.IO; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Lesson4 { /* * Исполнитель: * <NAME> * * Класс для работы с двумерным массивом */ class MyArrayTwoDim { static char delimiter = '\t'; int[,] a; #region Свойства /// <summary> /// Минимальный элемент массива /// </summary> public int Min { get { int min = a[0, 0]; for (int i = 0; i < a.GetLength(0); i++) for (int j = 0; j < a.GetLength(1); j++) if (a[i, j] < min) min = a[i, j]; return min; } } /// <summary> /// Максимальный элемент массива /// </summary> public int Max { get { int max = a[0, 0]; for (int i = 0; i < a.GetLength(0); i++) for (int j = 0; j < a.GetLength(1); j++) if (a[i, j] > max) max = a[i, j]; return max; } } /// <summary> /// Кол-во положительныъ элеентов массива /// </summary> public int CountPositive { get { int count = 0; for (int i = 0; i < a.GetLength(0); i++) for (int j = 0; j < a.GetLength(1); j++) if (a[i, j] > 0) count++; return count; } } /// <summary> /// Значение среднего элемента массива /// </summary> public double Average { get { double sum = 0; for (int i = 0; i < a.GetLength(0); i++) for (int j = 0; j < a.GetLength(1); j++) sum += a[i, j]; return sum / a.GetLength(0) / a.GetLength(1); } } #endregion #region Конструкторы /// <summary> /// Конструктор, задающий размер массива и значение его элементов /// </summary> /// <param name="n">Размер массива</param> /// <param name="el">Значение элементов массива</param> public MyArrayTwoDim(int n, int el) { a = new int[n, n]; for (int i = 0; i < n; i++) for (int j = 0; j < n; j++) a[i, j] = el; } /// <summary> /// Конструктор, задающий размер массива и заполняющий его случайными элементами /// </summary> /// <param name="n">Размер массива</param> /// <param name="min">Нижняя граница значения для диапазона случайных чисел включительно</param> /// <param name="max">Верхняя граница значения для диапазона случайных чисел не включительно</param> public MyArrayTwoDim(int n, int min, int max) { a = new int[n, n]; Random rnd = new Random(); for (int i = 0; i < n; i++) for (int j = 0; j < n; j++) a[i, j] = rnd.Next(min, max); } /// <summary> /// Конструктор, создающий массив на основании данных, загруженных из файла /// </summary> /// <param name="fileName"></param> public MyArrayTwoDim(string fileName) { string s = ""; if (!File.Exists(fileName)) CommonMethods.ColoredWriteLine("Файл не существует!", ConsoleColor.Red); else { s = File.ReadAllText(fileName); string[] sa = s.Split('\n'); a = new int[sa.Length, sa[0].Split(delimiter).Length]; for (int i = 0; i < sa.Length; i++) { for (int j = 0; j < sa[i].Split(delimiter).Length; j++) int.TryParse(sa[i].Split(delimiter)[j], out a[i, j]); } } } #endregion #region Методы /// <summary> /// Вывод массива в виде строки /// </summary> /// <returns>Строковое представление массива</returns> public override string ToString() { string s = ""; for (int i = 0; i < a.GetLength(0); i++) { for (int j = 0; j < a.GetLength(1); j++) s += a[i, j] + delimiter.ToString(); s += ((i != a.GetLength(0) - 1) ? "\n" : ""); //Если последняя строка, не ставим перенос } return s; } /// <summary> /// Сумма элементов массива /// </summary> /// <returns>Сумма</returns> public int Sum() { int sum = 0; for (int i = 0; i < a.GetLength(0); i++) for (int j = 0; j < a.GetLength(1); j++) sum += a[i, j]; return sum; } /// <summary> /// Сумма всех элементов массива, больше заданного /// </summary> /// <param name="constraint"></param> /// <returns></returns> public int Sum(int constraint) { int sum = 0; for (int i = 0; i < a.GetLength(0); i++) for (int j = 0; j < a.GetLength(1); j++) if (a[i, j] > constraint) sum += a[i, j]; return sum; } /// <summary> /// Метод, передающий индекс последнего вхождения элемента массива с максимальным значением /// </summary> /// <param name="ind">Индекс</param> public void IndexOfMax(out int[] ind) { ind = new int[2]; int max = Max; for (int i = 0; i < a.GetLength(0); i++) for (int j = 0; j < a.GetLength(1); j++) if (a[i, j] == max) { ind[0] = i+1; ind[1] = j+1; } } /// <summary> /// Запись массива в файл /// </summary> /// <param name="fileName">Полное имя файла</param> public void WriteToFile(string fileName) { if (a.Length != 0) { if (!File.Exists(fileName)) File.Create(fileName).Dispose(); StreamWriter sw = new StreamWriter(fileName, false); for (int i = 0; i < a.GetLength(0); i++) { for (int j = 0; j < a.GetLength(1); j++) sw.Write(a[i, j] + ((j == a.GetLength(1)-1) ? "" : delimiter.ToString())); // Не добавляем разделитель, если последний элемент в строке if (i != a.GetLength(0)-1) sw.Write("\n"); } sw.Close(); } } #endregion } }<file_sep>SELECT c.class, MIN(launched) launched FROM CLasses c LEFT JOIN Ships s ON s.class = c.class GROUP BY c.class;<file_sep>SELECT TOP 1 WITH TIES maker FROM ( SELECT DISTINCT pr.maker, p.ram, p.speed FROM pc p JOIN Product pr ON pr.model = p.model WHERE maker IN ( SELECT DISTINCT maker FROM Product pr WHERE type = 'printer' ) ) a ORDER BY a.ram, a.speed DESC;<file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Lesson4 { /* * Исполнитель: * <NAME> * * Задание №2 * а) Дописать класс для работы с одномерным массивом. Реализовать конструктор, создающий массив заданной размерности и заполняющий массив числами от начального значения с заданным шагом. * Создать свойство Sum, которые возвращают сумму элементов массива, метод Inverse, меняющий знаки у всех элементов массива, * Метод Multi, умножающий каждый элемент массива на определенное число, свойство MaxCount, возвращающее количество максимальных элементов. * В Main продемонстрировать работу класса. * б)*Добавить конструктор и методы, которые загружают данные из файла и записывают данные в файл. * * Реализация класса одномерного массива реализована в классе MyArray, файла MyArray.cs */ class Task2 { public static void Go() { string fileName = "..\\..\\Data\\Task2Data.txt"; CommonMethods.ColoredWriteLine(TasksDescription.Task2Description, ConsoleColor.Cyan); CommonMethods.ColoredWriteLine("Введите кол-во эл-тов массива:", ConsoleColor.Yellow); int n = CommonMethods.SetIntParametr(); CommonMethods.ColoredWriteLine("Введите значение первого эл-та массива:", ConsoleColor.Yellow); int fEl = CommonMethods.SetIntParametr(); CommonMethods.ColoredWriteLine("Введите шаг для значений эл-ов массива:", ConsoleColor.Yellow); int step = CommonMethods.SetIntParametr(); MyArray myArray = new MyArray(n, fEl, step); CommonMethods.ColoredWriteLine(myArray.ToString(), ConsoleColor.Cyan); CommonMethods.ColoredWriteLine($"Сумма эл-ов массива:\n{myArray.Sum}", ConsoleColor.Cyan); CommonMethods.ColoredWriteLine("Введите число, на которое хотите умножить эл-ты массива:", ConsoleColor.Yellow); int mlt = CommonMethods.SetIntParametr(); myArray.Multi(mlt); CommonMethods.ColoredWriteLine($"Массив:\n{myArray.ToString()}", ConsoleColor.Cyan); CommonMethods.ColoredWriteLine($"Мксимальный элемент:\n{myArray.Max}", ConsoleColor.Cyan); CommonMethods.ColoredWriteLine($"Кол-во максимальных эл-ов:\n{myArray.MaxCount}", ConsoleColor.Cyan); CommonMethods.ColoredWriteLine("Чтение массива из файла:", ConsoleColor.Yellow); myArray = new MyArray(fileName); CommonMethods.ColoredWriteLine($"Массив:\n{myArray.ToString()}", ConsoleColor.Cyan); myArray.Inverse(); CommonMethods.ColoredWriteLine($"Инверсия массива:\n{myArray.ToString()}", ConsoleColor.Cyan); myArray.WriteToFile(fileName); CommonMethods.ColoredWriteLine("Массив успешно записан в файл!", ConsoleColor.Yellow); } } }<file_sep>using System; using System.Windows.Forms; using System.Drawing; using System.Collections.Generic; namespace Asteroids { class SplashScreen { public static List<Button> BtnList { get; set; } = new List<Button>(); // Список кнопок формы // Кнопка "Начать игру" public static Button StartGameBtn = new Button() { Size = Settings.ButtonSize, Text = Settings.GameStart, Font = new Font(Settings.MainFont, 18F, FontStyle.Italic), ForeColor = Color.White, BackColor = Color.Transparent, FlatStyle = FlatStyle.Popup, Location = new Point(Settings.FieldWidth / 2 - Settings.ButtonSize.Width / 2, 10) }; // Кнопка "Выйти" public static Button ExitBtn = new Button() { Size = Settings.ButtonSize, Text = Settings.GameEnd, Font = new Font(Settings.MainFont, 18F, FontStyle.Italic), ForeColor = Color.White, BackColor = Color.Transparent, FlatStyle = FlatStyle.Popup, Location = new Point(Settings.FieldWidth / 2 - Settings.ButtonSize.Width / 2, 10) }; // Кнопка "Перейти на новый уровень" public static Button NewLevelBtn = new Button() { Size = Settings.ButtonSize, Text = Settings.GameNextLvl, Visible = false, Font = new Font(Settings.MainFont, 18F, FontStyle.Italic), ForeColor = Color.White, BackColor = Color.Transparent, FlatStyle = FlatStyle.Popup, Location = new Point(Settings.FieldWidth / 2 - Settings.ButtonSize.Width / 2, 10) }; // Кнопка "Сыграть еще раз" public static Button OneMoreGameBtn = new Button() { Size = Settings.ButtonSize, Text = Settings.GamePlayOneMore, Visible = false, Font = new Font(Settings.MainFont, 18F, FontStyle.Italic), ForeColor = Color.White, BackColor = Color.Transparent, FlatStyle = FlatStyle.Popup, Location = new Point(Settings.FieldWidth / 2 - Settings.ButtonSize.Width / 2, 10) }; public static void Greeting(Form form) { BtnList.Clear(); BtnList.Add(StartGameBtn); BtnList.Add(ExitBtn); form.Controls.Add(OneMoreGameBtn); form.Controls.Add(NewLevelBtn); for (int i = 0; i < BtnList.Count; i++) { int startPos = GetStartPos(); BtnList[i].Location = new Point(BtnList[i].Location.X, startPos + (i * Settings.ButtonSize.Height) + (i * Settings.HeightBetweenButtons)); form.Controls.Add(BtnList[i]); } #region Описание событий // Событие нажатия "Начать игру" StartGameBtn.Click += (object sender, EventArgs e) => { foreach (var b in BtnList) b.Visible = false; if (MessageBox.Show("Игра началась!\n" + Settings.GameRules, $"Привет, {Settings.UserName}!", MessageBoxButtons.OK, MessageBoxIcon.Asterisk) == DialogResult.OK) Game.BasicLoad(); }; // Событие нажатия "Выход" ExitBtn.Click += (object sender, EventArgs e) => { if (MessageBox.Show("Вы уверены, что хотите выйти?", "Выход", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes) Application.Exit(); }; // Событие нажатия клавиш form.KeyDown += (object sender, KeyEventArgs e) => { if (e.KeyCode == Keys.Space) Game.Ship?.Fire(true); if (e.KeyCode == Keys.Up) Game.Ship?.Up(true); if (e.KeyCode == Keys.Down) Game.Ship?.Down(true); if (e.KeyCode == Keys.Left) Game.Ship?.Left(true); if (e.KeyCode == Keys.Right) Game.Ship?.Right(true); }; form.KeyUp += (object sender, KeyEventArgs e) => { if (e.KeyCode == Keys.Space) Game.Ship?.Fire(false); if (e.KeyCode == Keys.Up) Game.Ship?.Up(false); if (e.KeyCode == Keys.Down) Game.Ship?.Down(false); if (e.KeyCode == Keys.Left) Game.Ship?.Left(false); if (e.KeyCode == Keys.Right) Game.Ship?.Right(false); }; OneMoreGameBtn.Click += (object sender, EventArgs e) => Game.Restart(); NewLevelBtn.Click += (object sender, EventArgs e) => Game.ChangeDifficultLevel(Game.DiffLvl++); #endregion } public static int GetStartPos() => Settings.FieldHeight / 2 - (BtnList.Count * Settings.ButtonSize.Height + (BtnList.Count - 1) * Settings.HeightBetweenButtons); } } <file_sep>SELECT COALESCE(inc.[point], outc.[point]) point, COALESCE(inc.[date], outc.[date]) date, SUM(outc.out) out, SUM(inc.inc) inc FROM Income inc FULL JOIN Outcome outc ON 1 = 0 GROUP BY COALESCE(inc.[point], outc.[point]), COALESCE(inc.[date], outc.[date]);<file_sep>using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace GuessNumber { public partial class Form1 : Form { Random r = new Random(); int guessNumber = 0; public Form1() { InitializeComponent(); } /// <summary> /// Проверка вводимых символов: если не Enter, не Backspace и не число - отбрасывать /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void textBox1_KeyPress(object sender, KeyPressEventArgs e) { e.Handled = !int.TryParse(e.KeyChar.ToString(), out int isNumber) && (e.KeyChar != (char)Keys.Enter) && (e.KeyChar != (char)Keys.Back); } // Загрузка формы private void Form1_Load(object sender, EventArgs e) { // Сбрасываем состояния элементов ResetControls(); } // Нажаие клавиши Enter private void textBox1_KeyDown(object sender, KeyEventArgs e) { if (e.KeyCode == Keys.Enter) { if (int.TryParse(tbGuessNum.Text, out int num)) if (num == guessNumber) { lblStatusValue.Text = "Угадали!"; if (MessageBox.Show("Вы угадали!\nХотите сыграть еще раз?", "Поздравляем!", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes) ResetControls(); else Application.Exit(); } else { lblStatusValue.Text = ((num > guessNumber) ? "Нужно меньше!" : "Нужно больше!"); tbGuessNum.Text = ""; lblStatusValue.Visible = true; } // Отключаем звук нажатия клавиши Enter, т.к. раздражает e.Handled = true; e.SuppressKeyPress = true; } } // Новая игра private void newGameToolStripMenuItem_Click(object sender, EventArgs e) { ResetControls(); } // Показать число private void showNumberToolStripMenuItem_Click(object sender, EventArgs e) { MessageBox.Show("Число:\n" + guessNumber, "Информация!", MessageBoxButtons.OK, MessageBoxIcon.Information); } // Выход из игры private void exitToolStripMenuItem_Click(object sender, EventArgs e) { if (MessageBox.Show("Вы точно уверены, что хотите выйти?", "Внимание!", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes) Application.Exit(); } /// <summary> /// Сбросить в исходное состояние все элементы управления /// </summary> private void ResetControls() { lblStatusValue.Visible = false; tbGuessNum.Text = ""; guessNumber = r.Next(1, 101); } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Lesson3 { /* * Исполнитель: * <NAME> * * Домашнее задание после урока №3 */ class Program { static void Main(string[] args) { CommonMethods.CenterOutput(); bool exit = false; while (!exit) { CommonMethods.ColoredWriteLine(TasksDescription.TaskList, ConsoleColor.Magenta); int choice = CommonMethods.SetIntParametr(); switch (choice) { case 0: CommonMethods.ColoredWriteLine("Всего доброго!", ConsoleColor.Cyan); exit = true; break; #region Задание 1 case 1: Task1.Go(); break; #endregion #region Задание 2 case 2: Task2.Go(); break; #endregion #region Задание 3 case 3: Task3.Go(); break; #endregion default: CommonMethods.ColoredWriteLine("Пункт не предусматривается системой!", ConsoleColor.Red); break; } } } } } <file_sep>using System; using System.IO; using System.Text.RegularExpressions; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Task6 { class Task6 { /* * Исполнитель: * <NAME> * * Задача №6 * В заданной папке найти во всех html файлах теги <img src=...> и вывести названия картинок. Использовать регулярные выражения. */ static void Main(string[] args) { Regex r = new Regex("<img.+?src=[\\\"'](.+?)[\\\"'].*?", RegexOptions.IgnoreCase); string[] files = Directory.GetFiles("..\\..\\Data", "*.html", SearchOption.AllDirectories); foreach (string item in files) { string content = File.ReadAllText(item); if (r.IsMatch(content)) Lesson6.Support.ColoredWriteLine($"Файл:\n{Path.GetFullPath(item)}", ConsoleColor.Yellow); foreach (Match match in r.Matches(content)) Lesson6.Support.ColoredWriteLine(match.Groups[1].Value, ConsoleColor.Cyan); } Console.ReadLine(); } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Lesson2 { /* * Исполнитель: * <NAME> * * Задание №6 * Написать программу подсчета количества “Хороших” чисел в диапазоне от 1 до 1 000 000 000. * Хорошим называется число, которое делится на сумму своих цифр. * Реализовать подсчет времени выполнения программы, используя структуру DateTime. */ class Task6 { public static void Go() { DateTime start = DateTime.Now; const int num = 1000000000; int count = 0; for (int i = 1; i <= num; i++) { if (isAGoodNumber(i)) count++; } TimeSpan timeSpan = DateTime.Now - start; CommonMethods.ColoredWriteLine($"Кол-во \"Хороших\" чисел от {1} до {num}: {count}.", ConsoleColor.Cyan); CommonMethods.ColoredWriteLine($"Время выполнения программы: " + $"{timeSpan.Seconds + timeSpan.Seconds * timeSpan.Minutes + timeSpan.Seconds * timeSpan.Minutes*timeSpan.Hours}.{timeSpan.Milliseconds} секунд.", ConsoleColor.Cyan); } /// <summary> /// Проверяет, делится ли без остатка число на сумму своих цифр /// </summary> /// <param name="num">Исходное число</param> /// <returns>Да/Нет</returns> public static bool isAGoodNumber(int num) { int sum = 0; string str = num.ToString(); #region Способ номер раз //while (num != 0) //{ // sum += num % 10; // num /= 10; //} #endregion #region Способ номер два (пошустрее) for (int i = 0; i < str.Length; i++) sum += str[i] - 48; // 48 - код символа "0" #endregion return num % sum == 0; } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Task2 { class Task2 { static void Main(string[] args) { // weight Console.ForegroundColor = ConsoleColor.Yellow; Console.WriteLine("Введите свой вес в килограммах:"); int weight = 0; do { Console.ForegroundColor = ConsoleColor.White; if (Int32.TryParse(Console.ReadLine(), out weight)) break; else { Console.ForegroundColor = ConsoleColor.Yellow; Console.WriteLine("Введенное значение не является целым числом!\n Попробуйте еще раз!"); } } while (true); // height Console.ForegroundColor = ConsoleColor.Yellow; Console.WriteLine("Введите свой рост в метрах (разделитель - запятая):"); float height = 0; do { Console.ForegroundColor = ConsoleColor.White; if (Single.TryParse(Console.ReadLine(), out height)) break; else { Console.ForegroundColor = ConsoleColor.Yellow; Console.WriteLine("Введенное значение не является дробным числом!\nПопробуйте еще раз!"); } } while (true); Console.ForegroundColor = ConsoleColor.Cyan; Console.WriteLine($"\nИндекс массы тела = {weight/(height*height)}"); Console.ReadLine(); } } } <file_sep>-- Найдите номера моделей и цены всех имеющихся в продаже продуктов (любого типа) производителя B (латинская буква). SELECT p.model, p.price FROM PC p JOIN Product pr ON pr.model = p.model AND pr.Maker = 'B' UNION SELECT l.model, l.price FROM Laptop l JOIN Product pr ON pr.model = l.model AND pr.Maker = 'B' UNION SELECT prin.model, prin.price FROM Printer prin JOIN Product pr ON pr.model = prin.model AND pr.Maker = 'B'<file_sep>using System; using System.Collections.Generic; using System.Drawing; using System.Windows.Forms; namespace WF_Udvoitel { public partial class Form1 : Form { Random r = new Random(); List<int> values = new List<int>(); // Записываем значение каждого шага int[] steps; // Изначально сделал при помощи List, но при быстром нажатии кнопок отрабатывало некорректно int i; public Form1() { InitializeComponent(); } #region События // Прибавляем 1 private void btnCommand1_Click(object sender, EventArgs e) { steps[i] = int.Parse(lblNumber.Text); lblNumber.Text = (int.Parse(lblNumber.Text) + 1).ToString(); lblCommandsCount.Text = (int.Parse(lblCommandsCount.Text) + 1).ToString(); i++; StepsCheck(); } // Умножаем на 2 private void btnCommand2_Click(object sender, EventArgs e) { steps[i] = int.Parse(lblNumber.Text); lblNumber.Text = (int.Parse(lblNumber.Text) * 2).ToString(); lblCommandsCount.Text = (int.Parse(lblCommandsCount.Text) + 1).ToString(); i++; StepsCheck(); } // Сбрасываем до 0 private void btnReset_Click(object sender, EventArgs e) { steps[i] = int.Parse(lblNumber.Text); lblNumber.Text = "0"; i++; lblCommandsCount.Text = (int.Parse(lblCommandsCount.Text) + 1).ToString(); } // Новая игра private void newGameToolStripMenuItem_Click(object sender, EventArgs e) { ResetControls(); } // Выход private void exitToolStripMenuItem_Click(object sender, EventArgs e) { if (MessageBox.Show("Вы точно уверены, что хотите выйти?", "Внимание!", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes) Application.Exit(); } // Отменить последний ход private void btnCancel_Click(object sender, EventArgs e) { if (i != 0) { lblNumber.Text = steps[--i].ToString(); lblCommandsCount.Text = (int.Parse(lblCommandsCount.Text) + 1).ToString(); } } // Загрузка формы private void Form1_Load(object sender, EventArgs e) { ResetControls(); } #endregion #region Вспомогательные методы // Сброс всех элементов private void ResetControls() { lblResultNum.Text = r.Next(0, 201).ToString(); lblCommandsCount.Text = "0"; lblNumber.Text = "0"; steps = new int[1000]; i = 0; //values.Add(int.Parse(lblNumber.Text)); } // Проверка на полученное значение private void StepsCheck() { // Проиграли if (int.Parse(lblNumber.Text) > int.Parse(lblResultNum.Text)) { lblNumber.ForeColor = Color.Red; if (MessageBox.Show("Полученное число больше необходимого!\nХотите сыграть еще?", "Перебор!", MessageBoxButtons.YesNo, MessageBoxIcon.Stop) == DialogResult.Yes) { lblNumber.ForeColor = Color.Black; ResetControls(); } else Application.Exit(); } // Выиграли if (int.Parse(lblNumber.Text) == int.Parse(lblResultNum.Text)) { lblNumber.ForeColor = Color.Green; if (MessageBox.Show("Вы выиграли!\nХотите сыграть еще?", "Поздравляем!", MessageBoxButtons.YesNo, MessageBoxIcon.Asterisk) == DialogResult.Yes) { lblNumber.ForeColor = Color.Black; ResetControls(); } else Application.Exit(); } } #endregion } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Lesson4 { /* * Исполнитель: * <NAME> * * Класс "Удвоитель" * Содерджит поля и методы для игры "Удвоитель" */ class Doubler { int current; int finish; #region Свойства public int Current { get { return current; } } public int Finish { get { return finish; } } #endregion #region Конструктор public Doubler(int min, int max, Random r) { if (min > max) CommonMethods.Swap(ref min, ref max); finish = r.Next(min, max); current = 1; } #endregion #region Методы public void Increase() { current++; } public void MultiTwice() { current *= 2; } public void Reset() { current = 1; } #endregion } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Lesson4 { /* * Исполнитель: * <NAME> * * Задание №5 * Существует алгоритмическая игра “Удвоитель”. * В этой игре человеку предлагается какое-то число, а человек должен, управляя роботом “Удвоитель”, достичь этого числа за минимальное число шагов. * Робот умеет выполнять несколько команд: увеличить число на 1, умножить число на 2 и сбросить число до 1. Начальное значение удвоителя равно 1. * Реализовать класс “Удвоитель”. Класс хранит в себе поле current - текущее значение, finish - число, которого нужно достичь, конструктор, в котором задается конечное число. * Методы: увеличить число на 1, увеличить число в два раза, сброс текущего до 1, свойство Current, которое возвращает текущее значение, свойство Finish,которое возвращает конечное значение. * Создать с помощью этого класса игру, в которой компьютер загадывает число, а человек. выбирая из меню на экране, отдает команды удвоителю и старается получить это число за наименьшее число ходов. * Если человек получает число больше положенного, игра прекращается. */ class Task5 { /// <summary> /// Игра "Удвоитель" /// </summary> public static void Go() { // Приветствие и печать правил игры CommonMethods.ColoredWriteLine(TasksDescription.Task5Description, ConsoleColor.Cyan); Random r = new Random(); bool exit = false; while (!exit) // Внешний цикл отвечает за выход из игры { bool restart = false; CommonMethods.ColoredWriteLine(TasksDescription.StartGame, ConsoleColor.Magenta); int count = 0; // Кол-во шагов Doubler d = new Doubler(0, 100, r); CommonMethods.ColoredWriteLine("Компьютер загадал число: " + d.Finish, ConsoleColor.Yellow); CommonMethods.ColoredWriteLine("Ваше число: " + d.Current, ConsoleColor.Cyan); bool skip = false; // Если для ответа введён некорректный символ, пропускаем ход while (!restart) // Цикл отвечает за рестарт игры { if (count == 0 && !skip) // Выводим список возможных действий только при новом старте CommonMethods.ColoredWriteLine(TasksDescription.Action, ConsoleColor.Yellow); skip = false; string choice = Console.ReadLine(); switch (choice) { case "+": // Прибавить единицу d.Increase(); break; case "*": // Удвоить d.MultiTwice(); break; case "r": // Сбросить до единицы d.Reset(); break; case "s": // Начать заново restart = true; break; case "q": // Выход из игры exit = true; break; default: CommonMethods.ColoredWriteLine("Непредвиденное действие!", ConsoleColor.Red); skip = true; break; } if (restart || exit) break; if (!skip) count++; if (d.Current == d.Finish) { CommonMethods.ColoredWriteLine("Поздравляем! Вы выиграли!\nКол-во шагов: " + count, ConsoleColor.Green); exit = !IsAnotherRound(); break; } else if (d.Current > d.Finish) { CommonMethods.ColoredWriteLine("Увы, но вы проиграли..!", ConsoleColor.Red); exit = !IsAnotherRound(); break; } else { if (!skip) { CommonMethods.ColoredWrite($"Ваше число {d.Current} всё еще недотягивает до ", ConsoleColor.Cyan); CommonMethods.ColoredWriteLine(d.Finish.ToString(), ConsoleColor.Magenta); } } } if (exit) break; } } /// <summary> /// Метод определяет, будет ли игрок участвовать в следующем раунде /// </summary> /// <returns>Да/Нет</returns> static bool IsAnotherRound() { CommonMethods.ColoredWriteLine("Жнлаете еще сыграть?\nВыберите \"+\", если хотите продолжить или нажмите любую клавишк, чтобы выйти.", ConsoleColor.Yellow); return Console.ReadLine().Equals("+"); } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Lesson2 { /* * Исполнитель: * <NAME> * * Задание №7 * a) Разработать рекурсивный метод, который выводит на экран числа от a до b(a<b); * б) *Разработать рекурсивный метод, который считает сумму чисел от a до b. */ class Task7 { public static void Go() { CommonMethods.ColoredWriteLine("Введите первое число:", ConsoleColor.Yellow); int a = CommonMethods.SetIntParametr(); CommonMethods.ColoredWriteLine("Введите второе число:", ConsoleColor.Yellow); int b = CommonMethods.SetIntParametr(); Swap(ref a, ref b); // На всякий случай (защита от "дурака") RecursivePrint(a, b); CommonMethods.ColoredWriteLine($"Сумма чисел от {a} до {b} = {RecursiveSum(a, b)}.", ConsoleColor.Cyan); } /// <summary> /// Рекурсивный метод, который выводит на экран числа от a до b(a<b) /// </summary> /// <param name="a">Первое число</param> /// <param name="b">Второе число</param> public static void RecursivePrint(int a, int b) { CommonMethods.ColoredWrite($"{a}{((a != b) ? ", " : "\n")}", ConsoleColor.Cyan); if (a == b) return; RecursivePrint(++a, b); } /// <summary> /// Рекурсивный метод, который считает сумму чисел от a до b /// </summary> /// <param name="a">Первое число</param> /// <param name="b">Второе число</param> /// <returns></returns> public static int RecursiveSum(int a, int b) { if (b == a) return a; return b + RecursiveSum(a, --b); } /// <summary> /// Функция смены значений местами в случае некорректного ввода /// </summary> /// <param name="a">Первый аргумент</param> /// <param name="b">Второй аргумент</param> public static void Swap(ref int a, ref int b) { if (a > b) { a += b; b = a - b; a -= b; } } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Lesson1 { class Start { static void Main(string[] args) { Console.WriteLine(Environment.UserName); Console.ReadLine(); //Console.ForegroundColor = ConsoleColor.Magenta; //Console.WriteLine("Приветствую!\n" + // "<NAME>!"); //bool exit = false; //while (!exit) //{ // Console.ForegroundColor = ConsoleColor.Magenta; // Console.WriteLine("Выберите задание для выполнения:\n- 1\n- 2\n- 3\n- 4\n- 5/6\nДля выхода нажмите 0."); // int choice = Additional.SetIntParametr(); // switch (choice) // { // case 0: // Console.ForegroundColor = ConsoleColor.Cyan; // Console.WriteLine("Всего доброго!"); // exit = true; // break; // #region Задание 1 // case 1: // Console.ForegroundColor = ConsoleColor.Cyan; // Console.WriteLine(Additional.task1Text); // Task1.Go(); // break; // #endregion // #region Задание 2 // case 2: // Console.ForegroundColor = ConsoleColor.Cyan; // Console.WriteLine(Additional.task2Text); // Task2.Go(); // break; // #endregion // #region Задание 3 // case 3: // Console.ForegroundColor = ConsoleColor.Cyan; // Console.WriteLine(Additional.task3Text); // Task3.Go(); // break; // #endregion // #region Задание 4 // case 4: // Console.ForegroundColor = ConsoleColor.Cyan; // Console.WriteLine(Additional.task4Text); // Task4.Go(); // break; // #endregion // #region Задание 5 и 6 // case 5: // Console.ForegroundColor = ConsoleColor.Cyan; // Console.WriteLine(Additional.task5Text); // Task5.Go(); // break; // case 6: // Console.ForegroundColor = ConsoleColor.Cyan; // Console.WriteLine(Additional.task5Text); // Task5.Go(); // break; // #endregion // default: // Console.WriteLine("Пункт не предусматривается системой!"); // break; // } //} } } }<file_sep>using System; using System.IO; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Lesson5 { /* * Исполнитель: * <NAME> * * Задание №4 * Задача ЕГЭ. * Требуется написать как можно более эффективную программу, которая будет выводить на экран фамилии и имена трех худших по среднему баллу учеников. * Если среди остальных есть ученики, набравшие тот же средний балл, что и один из трех худших, то следует вывести и их фамилии и имена. */ class Task4 { public static void Go() { if (File.Exists(TextConstants.FILE_NAME)) { CommonMethods.ColoredWriteLine(TextConstants.TASK4_DESCR, ConsoleColor.Yellow); DateTime start = DateTime.Now; StreamReader sr = new StreamReader(TextConstants.FILE_NAME); int.TryParse(sr.ReadLine(), out int n); // Кол-во строк в результатах экзаменов double[] avereges = new double[n]; // Массив, хранящий среднее значения для каждого ученика int[] minElementsIndexes = new int[n]; // Массив, хранящий индексы массива результатов экзаменов, у котрых среднее значение подходит под условие задачи double[] minElementsValues = new double[n]; // Массив значений минимальных средних значений string[] examsInfo = new string[n]; // Массив результатов экзаменов for (int i = 0; i < examsInfo.Length; i++) { examsInfo[i] = sr.ReadLine(); char [] marks = new char[3] { examsInfo[i][examsInfo[i].Length - 1], examsInfo[i][examsInfo[i].Length - 3], examsInfo[i][examsInfo[i].Length - 5] }; // Массив оценок avereges[i] = (double)(marks[0] + marks[1] + marks[2] - 48 * 3) / 3; } int k = 0; // Счетчик для массивов minElementsIndexes и minElementsValues for (int i = 0; i < 3; i++) // Согласно задания необходимо вывести три худших балла { double min = avereges.Min(); // Худший средний балл for (int j = 0; j < avereges.Length; j++) if (avereges[j] == min) { minElementsIndexes[k] = j; // Заполняем массив индексов минимальных элементов minElementsValues[k] = avereges[j]; // Заполняем массив значений минимальных элементов k++; avereges[j] = int.MaxValue; // Для того, чтобы элемент не вошел повторно, увеличиваем его значение } } minElementsIndexes[k] = -1; // -1 - как флаг окончания заполнения массива индексов StringBuilder sb = new StringBuilder(n * examsInfo[0].Length); // Выделяем память под максимально-возможное количество элементов for (int i = 0; i < minElementsIndexes.Length; i++) { if (minElementsIndexes[i] < 0) // Если встречаем флаг, завершаем заполнение break; string[] subAr = examsInfo[minElementsIndexes[i]].Split(' '); // Разбиваем элемент массива результатов экзаменов на массив элементов sb.Append(((i == 0) ? "" : "\n")).Append(subAr[0]).Append(" ").Append(subAr[1]).Append("\t- ").Append(String.Format("{0:F2}", minElementsValues[i])); // Формируем вывод } CommonMethods.ColoredWriteLine(sb.ToString(), ConsoleColor.Cyan); CommonMethods.ColoredWriteLine(TextConstants.EXEC_TIME, ConsoleColor.Yellow); CommonMethods.ColoredWriteLine((DateTime.Now - start).ToString(), ConsoleColor.Cyan); // Замеряем время работы } } } } <file_sep>WITH q AS ( SELECT point, [date], inc amount FROM Income UNION ALL SELECT point, date, -out FROM Outcome) SELECT point, CONVERT(VARCHAR(15), date, 103) date, ( SELECT SUM(q.amount) FROM q WHERE q.date <= w.date AND q.point = w.point ) amount FROM q w GROUP BY point, date;<file_sep>SELECT o.ship, c.displacement, c.numGuns FROM Outcomes o RIGHT JOIN Classes c ON o.ship=c.class WHERE o.battle = 'Guadalcanal' UNION SELECT o.ship, cl.displacement, cl.numGuns FROM Outcomes o LEFT JOIN Ships s ON o.ship = s.name LEFT JOIN Classes cl ON cl.class = s.class WHERE o.battle = 'Guadalcanal' AND o.ship NOT IN (SELECT o.ship FROM Outcomes o RIGHT JOIN Classes c ON o.ship=c.class WHERE o.battle = 'Guadalcanal') -- Variant 2 SELECT ship, displacement, numGuns FROM ( SELECT o.ship, COALESCE(s.class, o.ship) [class] FROM Outcomes o LEFT JOIN Ships s ON s.name = o.ship WHERE o.battle = 'Guadalcanal') q LEFT JOIN Classes cl ON cl.class = q.class<file_sep>SELECT pr3.maker, AVG(p.hd) hd FROM PC p JOIN Product pr3 ON pr3.model = p.model AND pr3.maker IN ( SELECT DISTINCT pr1.maker FROM Product pr1 JOIN Product pr2 ON pr1.maker = pr2.maker WHERE pr1.type = 'PC' AND pr2.type = 'Printer' ) GROUP BY pr3.maker; --- Var 2 SELECT maker, AVG(hd) FROM product pr, pc WHERE pr.model = pc.model AND maker IN ( SELECT maker FROM product WHERE type = 'printer' ) GROUP BY maker;<file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Lesson1 { class Task2 { public static void Go() { Console.ForegroundColor = ConsoleColor.Yellow; Console.WriteLine("Введите свой вес в килограммах:"); int w = Additional.SetIntParametr(); Console.ForegroundColor = ConsoleColor.Yellow; Console.WriteLine("Введите свой рост в метрах (разделитель - запятая):"); float h = Additional.SetFloatParametr(); Console.ForegroundColor = ConsoleColor.Yellow; Console.WriteLine($"\nИндекс массы тела = {w / (h * h):F}"); Console.ReadLine(); } } }<file_sep>SELECT name FROM Ships WHERE class IN ( SELECT class FROM Classes WHERE type = 'bb' AND displacement > 35000 ) AND launched >= 1922;<file_sep>-- (0.24489997327328) WITH sub AS (SELECT name, displacement, numGuns FROM ( SELECT name, class FROM Ships UNION SELECT DISTINCT ship, ship FROM Outcomes ) sh JOIN Classes c ON c.class = sh.class) SELECT name FROM sub q WHERE q.numGuns = ( SELECT TOP 1 numGuns FROM sub s WHERE s.displacement = q.displacement AND s.numGuns IS NOT NULL ORDER BY numGuns DESC ); -- Variant 2 (0.094840928912163) WITH sub AS (SELECT name, displacement, numGuns FROM ( SELECT name, class FROM Ships UNION SELECT ship, ship FROM Outcomes ) sh JOIN Classes c ON c.class = sh.class) SELECT name FROM sub q WHERE q.numGuns = ( SELECT MAX(numGuns) FROM sub s WHERE s.displacement = q.displacement );<file_sep>SELECT CAST(w.date AS DATETIME) [dt], COALESCE(q.trip_count, 0) trup_count FROM ( SELECT '20030401' [date] UNION ALL SELECT '20030402' UNION ALL SELECT '20030403' UNION ALL SELECT '20030404' UNION ALL SELECT '20030405' UNION ALL SELECT '20030406' UNION ALL SELECT '20030407' ) w LEFT JOIN ( SELECT pit.date, COUNT(DISTINCT pit.trip_no) trip_count FROM Pass_in_trip pit JOIN Trip t ON t.trip_no = pit.trip_no WHERE t.town_from = 'Rostov' GROUP BY pit.date ) q ON q.date = w.date;<file_sep>SELECT COALESCE(inc.[point], outc.[point]) point, COALESCE(inc.[date], outc.[date]) date, inc.inc, outc.out FROM Income_o inc FULL JOIN Outcome_o outc ON inc.point = outc.point AND inc.date = outc.date;<file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Task3 { class Task3 { static void Main(string[] args) { int x1, x2, y1, y2; Console.ForegroundColor = ConsoleColor.Yellow; Console.WriteLine("Введите точку x1:"); x1 = SetValue(); Console.ForegroundColor = ConsoleColor.Yellow; Console.WriteLine("Введите точку y1:"); y1 = SetValue(); Console.ForegroundColor = ConsoleColor.Yellow; Console.WriteLine("Введите точку x2:"); x2 = SetValue(); Console.ForegroundColor = ConsoleColor.Yellow; Console.WriteLine("Введите точку y2:"); y2 = SetValue(); Console.ForegroundColor = ConsoleColor.Yellow; Console.WriteLine($"Расстояние между точками = {PointsDistance(x1, y1, x2, y2):F}"); Console.ReadLine(); } static int SetValue() { do { int a = 0; Console.ForegroundColor = ConsoleColor.White; if (Int32.TryParse(Console.ReadLine(), out a)) return a; else { Console.ForegroundColor = ConsoleColor.Yellow; Console.WriteLine("Введенное значение не является целым числом!\nПопробуйте еще раз!"); } } while (true); } static double PointsDistance(int x1, int y1, int x2, int y2) { return Math.Sqrt(Math.Pow(x2 - x1, 2) + Math.Pow(y2 - y1, 2)); } } } <file_sep>SELECT sh.name FROM Ships sh WHERE name = class UNION SELECT o.ship FROM Outcomes o JOIN Classes cl ON cl.class = o.ship;<file_sep>using System; using System.Collections.Generic; using System.Linq; using CodeWars._3kyu; using CodeWars._4kyu; using CodeWars._5kyu; using CodeWars._6kyu; using CodeWars._7kyu; using CodeWars._8kyu; namespace CodeWars { class Program { public static void Main() { //Console.WriteLine(Calculator.Evaluate("-1-1")); Console.WriteLine(BallUpwards.MaxBall(85)); Console.ReadLine(); } } } <file_sep>SELECT maker, MAX(price) price FROM Product pr JOIN PC p ON pr.Model = p.model GROUP BY maker;<file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Lesson4 { /* * Исполнитель: * <NAME> * * Задание №1 * Дан целочисленный массив из 20 элементов. Элементы массива могут принимать целые значения от –10 000 до 10 000 включительно. * Написать программу, позволяющую найти и вывести количество пар элементов массива, в которых хотя бы одно число делится на 3. * В данной задаче под парой подразумевается два подряд идущих элемента массива. * Например, для массива из пяти элементов: 6; 2; 9; –3; 6 – ответ: 4. */ class Task1 { /// <summary> /// Вывод пар элементов массива, в которых хотя бы одно число делится на 3 /// </summary> public static void Go() { CommonMethods.ColoredWriteLine(TasksDescription.Task1Description, ConsoleColor.Cyan); int[] a = new int[20]; int min = -10000; int max = 10001; Random rnd = new Random(); for (int i = 0; i < a.Length; i++) a[i] = rnd.Next(min, max); CommonMethods.ColoredWriteLine("В массиве:", ConsoleColor.Yellow); CommonMethods.PrintArray(a, ConsoleColor.Cyan); CommonMethods.ColoredWriteLine("Пар элементов, кратных 3:", ConsoleColor.Yellow); CommonMethods.ColoredWriteLine(PairsSearch(a).ToString(), ConsoleColor.Cyan); } /// <summary> /// Поиск пар чисел /// </summary> /// <param name="a">Целочисленный массив</param> /// <returns>Количество пар</returns> static int PairsSearch(int[] a) { int count = 0; for (int i = 0; i < a.Length-1; i++) if (a[i] % 3 == 0 || a[i+1] % 3 == 0) count++; return count; } } }<file_sep>SELECT name, launched, battle FROM ( SELECT sh.name, sh.launched, b.name battle FROM Ships sh, Battles b WHERE b.date = (SELECT top 1 btl.date FROM Battles btl WHERE DATEPART(YEAR, btl.date) >= sh.launched ORDER BY btl.date ASC) AND sh.launched IS NOT NULL AND EXISTS (SELECT name FROM Battles WHERE DATEPART(YEAR, date) >= sh.launched) UNION SELECT shi.name, shi.launched, b.name FROM Ships shi LEFT JOIN Battles b ON DATEPART(YEAR, date) >= shi.launched WHERE NOT EXISTS (SELECT name FROM Battles WHERE DATEPART(YEAR, date) >= shi.launched) AND shi.launched IS NOT NULL UNION SELECT s.name, s.launched, b.name FROM Ships s, Battles b WHERE s.launched IS NULL AND b.date = (SELECT MAX(date) FROM Battles)) q ORDER BY name<file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Lesson6 { public class Support { static void Main(string[] args) { } /// <summary> /// Метод для получения целого числа, введённого пользователем в консоли /// </summary> /// <returns>Целое число</returns> public static int SetIntParametr() { do { String str = Console.ReadLine(); if (Int32.TryParse(str, out int a) && str.Length != 0) return a; else ColoredWriteLine("Введенное значение не является целым числом!\nПопробуйте еще раз!", ConsoleColor.Red); } while (true); } /// <summary> /// Метод для получения дробного числа, введённого пользователем в консоли /// </summary> /// <returns>Дробное число</returns> public static double SetDoubleParametr() { do { String str = Console.ReadLine(); if (Double.TryParse(str, out double a) && str.Length != 0) return a; else ColoredWriteLine("Введенное значение не является дробным числом!\nПопробуйте еще раз!", ConsoleColor.Red); } while (true); } /// <summary> /// Метод для вывода цветного текста в консоль с последующим переводом каретки на новую строку /// </summary> /// <param name="str">Текст, который необходимо вывести на экран</param> /// <param name="consoleColor">Цвет, который будет использоваться при выводе</param> public static void ColoredWriteLine(string str, ConsoleColor consoleColor) { Console.ForegroundColor = consoleColor; Console.WriteLine(str); Console.ForegroundColor = ConsoleColor.White; } /// <summary> /// Метод для вывода цветного текста в консоль без перевода каретки на новую строку /// </summary> /// <param name="str">Текст, который необходимо вывести на экран</param> /// <param name="consoleColor">Цвет, который будет использоваться при выводе</param> public static void ColoredWrite(string str, ConsoleColor consoleColor) { Console.ForegroundColor = consoleColor; Console.Write(str); Console.ForegroundColor = ConsoleColor.White; } } } <file_sep>-- Найти производителей, которые выпускают более одной модели, -- при этом все выпускаемые производителем модели являются продуктами одного типа. Вывести: maker, type SELECT DISTINCT p.Maker, p.type FROM Product p WHERE maker IN ( SELECT maker FROM Product GROUP BY maker HAVING COUNT(DISTINCT type) = 1 AND COUNT(model) > 1 ); --- Variant 2: SELECT p.Maker, p.type FROM Product p JOIN ( SELECT maker FROM Product GROUP BY maker HAVING COUNT(DISTINCT type) = 1 ) pr ON pr.maker = p.maker GROUP BY p.maker, type HAVING COUNT(p.model) > 1 <file_sep>SELECT name FROM Ships s LEFT JOIN Classes c ON c.class = s.class WHERE c.type = 'bb' AND country = 'Japan' AND COALESCE(numGuns, 9) >= 9 AND COALESCE(bore, 0) < 19 AND COALESCE(displacement, 0) <= 65000;<file_sep>SELECT DISTINCT battle FROM Outcomes o JOIN Ships s ON s.name = o.ship AND s.class = 'Kongo';<file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Lesson1 { class Task3 { public static void Go() { Console.ForegroundColor = ConsoleColor.Yellow; Console.WriteLine("Введите точку x1:"); int x1 = Additional.SetIntParametr(); Console.ForegroundColor = ConsoleColor.Yellow; Console.WriteLine("Введите точку y1:"); int y1 = Additional.SetIntParametr(); Console.ForegroundColor = ConsoleColor.Yellow; Console.WriteLine("Введите точку x2:"); int x2 = Additional.SetIntParametr(); Console.ForegroundColor = ConsoleColor.Yellow; Console.WriteLine("Введите точку y2:"); int y2 = Additional.SetIntParametr(); Console.ForegroundColor = ConsoleColor.Yellow; Console.WriteLine($"Расстояние между точками = {Additional.PointsDistance(x1, y1, x2, y2):F}"); Console.ReadLine(); } } }<file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Lesson5 { class Program { static void Main(string[] args) { CommonMethods.CenterOutput(); bool exit = false; while (!exit) { CommonMethods.ColoredWriteLine(TextConstants.TASK_LIST, ConsoleColor.Magenta); int choice = CommonMethods.SetIntParametr(); switch (choice) { case 0: exit = true; break; #region Задание 1 case 1: Task1.Go(); break; #endregion #region Задание 2 case 2: Task2.Go(); break; #endregion #region Задание 3 case 3: Task3.Go(); break; #endregion #region Задание 4 case 4: Task4.Go(); break; #endregion default: CommonMethods.ColoredWriteLine("Пункт не предусматривается системой!", ConsoleColor.Red); break; } } Console.ReadLine(); } } } <file_sep>-- Найдите номер модели, скорость и размер жесткого диска ПК, имеющих 12x или 24x CD и цену менее 600 дол. SELECT model, speed, hd FROM PC WHERE(cd LIKE '12x' OR cd LIKE '24x') AND (price < 600);<file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Lesson4 { /* * Исполнитель: * <NAME> * * Задание №4 * а) Реализовать класс для работы с двумерным массивом. Реализовать конструктор, заполняющий массив случайными числами. * Создать методы, которые возвращают сумму всех элементов массива, сумму всех элементов массива больше заданного, свойство, возвращающее минимальный элемент массива, * свойство, возвращающее максимальный элемент массива, метод, возвращающий номер максимального элемента массива (через параметры, используя модификатор ref или out) * б) Добавить конструктор и методы, которые загружают данные из файла и записывают данные в файл. */ class Task4 { /// <summary> /// Метод, демонстрирующий работу с двумерным массивом /// </summary> public static void Go() { CommonMethods.ColoredWriteLine(TasksDescription.Task4Description, ConsoleColor.Cyan); string fileName = "..\\..\\Data\\Task4Data.txt"; CommonMethods.ColoredWriteLine("Введите размерность массива:", ConsoleColor.Yellow); int n = CommonMethods.SetIntParametr(); CommonMethods.ColoredWriteLine("Введите значение минимального эл-та массива:", ConsoleColor.Yellow); int rangeMin = CommonMethods.SetIntParametr(); CommonMethods.ColoredWriteLine("Введите значение максимального эл-та массива:", ConsoleColor.Yellow); int rangeMax = CommonMethods.SetIntParametr(); if (rangeMax < rangeMin) CommonMethods.Swap(ref rangeMin, ref rangeMax); MyArrayTwoDim myArray = new MyArrayTwoDim(n, rangeMin, rangeMax); CommonMethods.ColoredWriteLine(myArray.ToString(), ConsoleColor.Cyan); CommonMethods.ColoredWriteLine($"Сумма эл-ов массива:\n{myArray.Sum()}", ConsoleColor.Cyan); CommonMethods.ColoredWriteLine("Введите нижнее ограничение элементов для подсчета суммы:", ConsoleColor.Yellow); int constraint = CommonMethods.SetIntParametr(); CommonMethods.ColoredWriteLine($"Сумма эл-ов массива, больше {constraint}:\n{myArray.Sum(constraint)}", ConsoleColor.Cyan); CommonMethods.ColoredWriteLine($"Минимальный элемент:\n{myArray.Min}", ConsoleColor.Cyan); CommonMethods.ColoredWriteLine($"Мксимальный элемент:\n{myArray.Max}", ConsoleColor.Cyan); myArray.IndexOfMax(out int[] iom); CommonMethods.ColoredWriteLine($"Номер максимального элемента:\n[{iom[0]}, {iom[1]}]", ConsoleColor.Cyan); CommonMethods.ColoredWriteLine("Чтение массива из файла:", ConsoleColor.Yellow); MyArrayTwoDim mySecArray = new MyArrayTwoDim(fileName); CommonMethods.ColoredWriteLine($"{mySecArray.ToString()}", ConsoleColor.Cyan); myArray.WriteToFile(fileName); CommonMethods.ColoredWriteLine("исходный массив успешно записан в файл!", ConsoleColor.Yellow); } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Lesson4 { class TasksDescription { public const string TaskList = "\nВыберите задание для выполнения:\n- 1\n- 2\n- 3\n- 4\n- 5\n- 6\nДля выхода нажмите 0."; public const string Task1Description = "Дан целочисленный массив из 20 элементов." + "\nЭлементы массива могут принимать целые значения от –10 000 до 10 000 включительно." + "\nНаписать программу, позволяющую найти и вывести количество пар элементов массива, в которых хотя бы одно число делится на 3." + "\nВ данной задаче под парой подразумевается два подряд идущих элемента массива." + "\nНапример, для массива из пяти элементов: 6; 2; 9; –3; 6 – ответ: 4."; public const string Task2Description = "а) Дописать класс для работы с одномерным массивом." + "\nРеализовать конструктор, создающий массив заданной размерности и заполняющий массив числами от начального значения с заданным шагом." + "\nСоздать свойство Sum, которые возвращают сумму элементов массива, метод Inverse, меняющий знаки у всех элементов массива," + "\nМетод Multi, умножающий каждый элемент массива на определенное число, свойство MaxCount, возвращающее количество максимальных элементов." + "\nВ Main продемонстрировать работу класса." + "\nб)*Добавить конструктор и методы, которые загружают данные из файла и записывают данные в файл."; public const string Task3Description = "Решить задачу с логинами из предыдущего урока, только логины и пароли считать из файла в массив."; public const string Task4Description = "а) Реализовать класс для работы с двумерным массивом." + "\nРеализовать конструктор, заполняющий массив случайными числами." + "\nСоздать методы, которые возвращают сумму всех элементов массива, сумму всех элементов массива больше заданного, свойство, возвращающее минимальный элемент массива," + "\nсвойство, возвращающее максимальный элемент массива, метод, возвращающий номер максимального элемента массива (через параметры, используя модификатор ref или out)" + "\nб) Добавить конструктор и методы, которые загружают данные из файла и записывают данные в файл."; public const string Task5Description = "Вас приветствет алгоритмическая игра \"Удвоитель\"!" + "\nПравила игры:" + "\nКомпьютер загадывает число, а игрок должен попытаться достичь его при помощи команд:" + "\n\t+: прибавить к текущему значению (первоначально 1) числа единицу;" + "\n\t*: увеличить текущее значение числа в два раза;" + "\n\tr: сброс текущего значения числа до единицы;" + "\n\ts: рестарт;" + "\n\tq: выход из игры." + "\nЕсли игрок получает число больше положенного, игра прекращается."; public const string StartGame = "******************************** ИГРА НАЧАЛАСЬ ********************************"; public const string Action = "выберите действие:\n\t+: прибавить к текущему значению (первоначально 1) числа единицу;" + "\n\t*: увеличить текущее значение числа в два раза;" + "\n\tr: сброс текущего значения числа до единицы;" + "\n\ts: рестарт;" + "\n\tq: выход из игры."; public const string Task6Description = "Вас приветствет игра \"Верю - Не верю\"!" + "\nПравила игры:" + "\nКомпьютер задаёт игроку 5 вопросов, игрок должен ответить на них при помощи команд:" + "\n\t+: \"Верю\" - игрок соглашается с заданным вопросом или утверждением;" + "\n\t-: \"Не верю\" - игрок не соглашается с заданным вопросом или утверждением;" + "\n\tr: - Начать заново;" + "\n\tq: - Выход из игры."; } } <file_sep>WITH q AS ( SELECT town_from, town_to, COUNT(trip_no) tr FROM Trip GROUP BY town_from, town_to) SELECT COUNT(*) cnt FROM q WHERE tr = ( SELECT MAX(tr) FROM q );<file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Lesson5 { class Task2 { /* * Исполнитель: * <NAME> * * Задание №3 * Разработать методы для решения следующих задач. Дано сообщение: * а) Вывести только те слова сообщения, которые содержат не более чем n букв; * б) Удалить из сообщения все слова, которые заканчиваются на заданный символ; * в) Найти самое длинное слово сообщения; * г) Найти все самые длинные слова сообщения. */ public static void Go() { CommonMethods.ColoredWriteLine(TextConstants.TASK2_DESCR, ConsoleColor.Cyan); CommonMethods.ColoredWriteLine(TextConstants.ENTER_MESSAGE, ConsoleColor.Yellow); MyString s = new MyString(Console.ReadLine()); #region а) Вывести только те слова сообщения, которые содержат не более чем n букв; CommonMethods.ColoredWriteLine(TextConstants.ENTER_LETTERS_COUNT, ConsoleColor.Yellow); int n = CommonMethods.SetIntParametr(); CommonMethods.ColoredWriteLine(String.Format("Слова сообщения, не длиннее {0} букв (Без использования регулярных выражений):", n), ConsoleColor.Yellow); CommonMethods.ColoredWriteLine(s.CheckWordsLength(n), ConsoleColor.Cyan); CommonMethods.ColoredWriteLine(String.Format("Слова сообщения, не длиннее {0} букв (С использованием регулярных выражений):", n), ConsoleColor.Yellow); CommonMethods.ColoredWriteLine(s.CheckWordsLength(n), ConsoleColor.Cyan); #endregion #region б) Удалить из сообщения все слова, которые заканчиваются на заданный символ; CommonMethods.ColoredWriteLine(TextConstants.ENTER_ENDING_SYMBOL, ConsoleColor.Yellow); string st = Console.ReadLine(); CommonMethods.ColoredWriteLine(String.Format("Слова сообщения, не заканчивающиеся на символ {0} (Без использования регулярных выражений):", st), ConsoleColor.Yellow); CommonMethods.ColoredWriteLine(s.DeleteWords(st), ConsoleColor.Cyan); CommonMethods.ColoredWriteLine(String.Format("Слова сообщения, не заканчивающиеся на символ {0} (С использованием регулярных выражений):", st), ConsoleColor.Yellow); CommonMethods.ColoredWriteLine(s.RegexDeleteWords(st), ConsoleColor.Cyan); #endregion #region в) Найти самое длинное слово сообщения; CommonMethods.ColoredWriteLine(TextConstants.LONGEST_WORD, ConsoleColor.Yellow); CommonMethods.ColoredWriteLine(s.FindLongestWord(), ConsoleColor.Cyan); #endregion #region г) Найти все самые длинные слова сообщения. CommonMethods.ColoredWriteLine(TextConstants.LONGEST_WORDS, ConsoleColor.Yellow); CommonMethods.ColoredWriteLine(s.FindAllLongestWords(), ConsoleColor.Cyan); #endregion } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.IO; using System.Text; using System.Threading.Tasks; namespace Task3 { class Task3 { /* * Исполнитель: * <NAME> * * Задание №3 * Подсчитать количество студентов: * а) учащихся на 5 и 6 курсах; * б) подсчитать сколько студентов в возрасте от 18 до 20 лет на каком курсе учатся(частотный массив); * в) отсортировать список по возрасту студента; * г) *отсортировать список по курсу и возрасту студента. */ static void Main(string[] args) { List<Student> list = new List<Student>(); StreamReader sr = new StreamReader("..\\..\\Data\\students.csv"); while (!sr.EndOfStream) { try { string[] s = sr.ReadLine().Split(';'); list.Add(new Student(s[1], s[0], s[2], s[3], int.Parse(s[6]), s[4], int.Parse(s[7]), s[8], int.Parse(s[5]))); } catch(Exception ex) { Lesson6.Support.ColoredWriteLine(ex.Message, ConsoleColor.Red); Lesson6.Support.ColoredWriteLine("Ошибка!ESC - прекратить выполнение программы.", ConsoleColor.Red); if (Console.ReadKey().Key == ConsoleKey.Escape) return; } } sr.Close(); // а) Lesson6.Support.ColoredWriteLine($"Учащихся на 5 и 6 курсах:\t{GetFiveAndSixCourseStudents(list)}", ConsoleColor.Cyan); // б) Lesson6.Support.ColoredWriteLine("Список студентов в возрасте от 18 до 20 лет:", ConsoleColor.Yellow); GetCurrCourseStudentsCount(list); // в) Lesson6.Support.ColoredWriteLine("Список студентов, отсортированнй по возрасту:", ConsoleColor.Yellow); AgeSort(list); AgePrint(list); // г) Lesson6.Support.ColoredWriteLine("Список студентов, отсортированнй по курсу возрасту:", ConsoleColor.Yellow); CourseAgeSort(list); CourseAgePrint(list); Console.ReadLine(); } /// <summary> /// Получаем кол-во учеников, учащихся на 5 и 6 курсах /// </summary> /// <param name="list">Коллекция учеников</param> /// <returns>Кол-во учеников</returns> static int GetFiveAndSixCourseStudents(List<Student> list) { return list.Where(l => l.Course > 4).Count(); } /// <summary> /// Подсчитываем сколько студентов в возрасте от 18 до 20 лет на каком курсе учатся /// </summary> /// <param name="list">Список студентов</param> static void GetCurrCourseStudentsCount(List<Student> list) { int[] arr = new int[6]; for (int i = 0; i < list.Count(); i++) if (list[i].Age >=18 && list[i].Age <= 20) arr[list[i].Course - 1]++; for (int i = 0; i < arr.Length; i++) Lesson6.Support.ColoredWriteLine($"На {i + 1} курсе учится {arr[i]}.", ConsoleColor.Cyan); } /// <summary> /// Сортировка студентов по возрасту /// </summary> /// <param name="list">Список студентов</param> static void AgeSort(List<Student> list) { list.Sort(delegate (Student s1, Student s2) { return s1.Age - s2.Age; }); } /// <summary> /// Еще один вариант сортировки по возрасту, при помощи Linq /// </summary> /// <param name="list">Список студентов</param> static void LinqAgeSort(List<Student> list) { list.OrderBy(l => l.Age).ToList(); } /// <summary> /// Сортировка по курсу и возрасту студента /// </summary> /// <param name="list">Список студентов</param> static void CourseAgeSort(List<Student> list) { list.Sort(Comparer); } /// <summary> /// Еще один вариант сортировки по курсу и возрасту, при помощи Linq /// </summary> /// <param name="list">Список студентов</param> static void LinqCourseAgeSort(List<Student> list) { list.OrderBy(l => l.Course).ThenBy(l => l.Age).ToList(); } /// <summary> /// Компаратор по курсу и возрасту студента /// </summary> /// <param name="s1">Студент 1</param> /// <param name="s2">Студент 2</param> /// <returns>Результат сравнения</returns> static int Comparer(Student s1, Student s2) { int res = s1.Course - s2.Course; if (res == 0) res = s1.Age - s2.Age; return res; } /// <summary> /// Печать списка для сортировки по возрасту /// </summary> /// <param name="list">Список студентов</param> static void AgePrint(List<Student> list) { foreach (var s in list) Lesson6.Support.ColoredWriteLine($"{s.FirstName} {s.LastName},\tвозраст: {s.Age}", ConsoleColor.Cyan); } /// <summary> /// Печвть списка для сортировки по курсу и возрасту /// </summary> /// <param name="list">Список студентов</param> static void CourseAgePrint(List<Student> list) { foreach (var s in list) Lesson6.Support.ColoredWriteLine($"{s.FirstName} {s.LastName},\tкурс: {s.Course}\tвозраст: {s.Age}", ConsoleColor.Cyan); } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Lesson3 { class TasksDescription { public const string TaskList = "\nВыберите задание для выполнения:\n- 1\n- 2\n- 3\nДля выхода нажмите 0."; public const string Task1Text= "а) Дописать структуру Complex, добавив метод вычитания комплексных чисел. Продемонстрировать работу структуры;" + "\nб) Дописать класс Complex, добавив методы вычитания и произведения чисел. Проверить работу класса."; public const string Task2Text = "а) С клавиатуры вводятся числа, пока не будет введен 0 (каждое число в новой строке)." + "\nТребуется подсчитать сумму всех нечетных положительных чисел." + "\nСами числа и сумму вывести на экран; Используя tryParse;" + "\nб) Добавить обработку исключительных ситуаций на то, что могут быть введены некорректные данные." + "\nПри возникновении ошибки вывести сообщение."; public const string Task3Text = "Описать класс дробей - рациональных чисел, являющихся отношением двух целых чисел." + "\nПредусмотреть методы сложения, вычитания, умножения и деления дробей." + "\nНаписать программу, демонстрирующую все разработанные элементы класса." + "\n* Добавить упрощение дробей."; } }<file_sep>using System; using System.IO; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Task5 { class Task5 { /* * Исполнитель: * <NAME> * * Задание №5 * Модифицировать задачу “Сложную задачу” ЕГЭ так, чтобы она решала задачу с 10 000 000 элементов менее чем за минуту. */ static void Main(string[] args) { Save("..\\..\\Data\\Task5.bin", 1000000); Load2("..\\..\\Data\\Task5.bin"); //Load("..\\..\\Data\\Task5.bin"); Console.ReadKey(); } static void Save(string fileName, int n) { Random rnd = new Random(); FileStream fs = new FileStream(fileName, FileMode.Create, FileAccess.Write); BinaryWriter bw = new BinaryWriter(fs); for (int i = 1; i < n; i++) { bw.Write(rnd.Next(0, 100000)); } fs.Close(); bw.Close(); } /// <summary> /// Решение сложной задачи ЕГЭ из методички /// </summary> /// <param name="fileName"></param> static void Load(string fileName) { DateTime d = DateTime.Now; FileStream fs = new FileStream(fileName, FileMode.Open, FileAccess.Read); BinaryReader br = new BinaryReader(fs); #region Для наглядности int maxElem1 = int.MinValue; int maxElem2 = int.MinValue; #endregion int[] a = new int[fs.Length / 4]; for (int i = 0; i < fs.Length / 4; i++) a[i] = br.ReadInt32(); br.Close(); fs.Close(); //int max = 0; // - max будет больше 2 * 10^9 long max = 0; for (int i = 0; i < a.Length; i++) for (int j = 0; j < a.Length; j++) //if (Math.Abs(i - j) >= 8 && a[i] * a[j] > max) // - некорректная проверка, т.к. a[i] * a[j] даст результат больше, чем умещается в тип int if (Math.Abs(i - j) >= 8) { long m = (long)a[i] * a[j]; if (m > max) { max = m; #region Для наглядности maxElem1 = a[i]; maxElem2 = a[j]; #endregion } } //Console.WriteLine(max); Lesson6.Support.ColoredWriteLine($"Максимальное произведение элеметов {maxElem1} и {maxElem2}: {max}", ConsoleColor.Cyan); Console.WriteLine(DateTime.Now - d); } /// <summary> /// Улучшенная версия метода решения сложной задачи ЕГЭ. /// 1. Избавляемся от массива. Работаем только с потоком. /// 2. Избавляемся от вложенного цикла. /// 3. Избавляемся от многократных вычислений произведений во внешнем цикле. /// </summary> /// <param name="fileName">Имя файла для считывания</param> static void Load2(string fileName) { DateTime d = DateTime.Now; FileStream fs = new FileStream(fileName, FileMode.Open, FileAccess.Read); BinaryReader br = new BinaryReader(fs); #region Для наглядности int maxElem1 = int.MinValue; int maxElem2 = int.MinValue; #endregion int[] a = new int[fs.Length / 4]; long maxMulti = int.MinValue; int maxPrevElem = int.MinValue; int backPos = sizeof(int) * 9; // Возвращаемся на 9 элементов назад. Записываем значение, чтобы не вычислять каждый раз в цикле fs.Seek(backPos - sizeof(int), SeekOrigin.Current); // Переходим на 8 элементов вперёд, чтобы начать читать поток с элемента №9 for (int i = 8; i < fs.Length / 4; i++) { int currentElem = br.ReadInt32(); fs.Seek(-backPos, SeekOrigin.Current); // Возвращаемся на 9 элементов назад, т.к. в строке выше был считан элемент и позиция в потоке сдвинулась на элемент вперёд int prevElem = br.ReadInt32(); if (prevElem > maxPrevElem) maxPrevElem = prevElem; long multi = (long)maxPrevElem * currentElem; if (multi > maxMulti) { maxMulti = multi; #region Для наглядности maxElem1 = maxPrevElem; maxElem2 = currentElem; #endregion } fs.Seek(backPos - sizeof(int), SeekOrigin.Current); // Возвращаемся позицию потока вперёд на 8 символов для чтения следующего значения } br.Close(); fs.Close(); Lesson6.Support.ColoredWriteLine($"Максимальное произведение элеметов {maxElem1} и {maxElem2}: {maxMulti}", ConsoleColor.Cyan); Console.WriteLine(DateTime.Now - d); } } } <file_sep>-- Найдите пары моделей PC, имеющих одинаковые скорость и RAM. -- В результате каждая пара указывается только один раз, т.е. (i,j), но не (j,i), -- Порядок вывода: модель с большим номером, модель с меньшим номером, скорость и RAM. SELECT DISTINCT p1.model model1, p2.model model2, p1.speed, p1.ram FROM pc p1, pc p2 WHERE p1.speed = p2.speed AND p1.ram = p2.ram AND p1.model > p2.model;<file_sep>using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Lesson4 { /* * Исполнитель: * <NAME> * * Класс для работы с одномерным массивом */ public class MyArray { int[] a; #region Свойства /// <summary> /// Максимальный элемент массива /// </summary> public int Max { get { int max = a[0]; for (int i = 0; i < a.Length; i++) if (a[i] > max) max = a[i]; return max; } } /// <summary> /// Минимальный элемент массива /// </summary> public int Min { get { int min = a[0]; for (int i = 0; i < a.Length; i++) if (a[i] < min) min = a[i]; return min; } } /// <summary> /// Количество чисел в массиве, больше ноля /// </summary> public int CountPositive { get { int count = 0; for (int i = 0; i < a.Length; i++) if (a[i] > 0) count++; return count; } } /// <summary> /// Сумма элементов массива /// </summary> public int Sum { get { int sum = 0; for (int i = 0; i < a.Length; i++) sum += a[i]; return sum; } } /// <summary> /// Количество максимальных элементов /// </summary> public int MaxCount { get { int max = Max; int count = 0; for (int i = 0; i < a.Length; i++) if (a[i] == max) count++; return count; } } #endregion #region Конструкторы /// <summary> /// Конструктор, заполняющий элементы массива указанным значением /// </summary> /// <param name="n">Размер массива</param> /// <param name="el">Значение элементов массива</param> public MyArray(int n, int el) { a = new int[n]; for (int i = 0; i < n; i++) a[i] = el; } /// <summary> /// Создание массива и заполнение его случайными числами от min до max /// </summary> /// <param name="n">Кол-во элементов массива</param> /// <param name="min">Минимальное значение элементов</param> /// <param name="max">Максимальное значение элементов</param> //public MyArray(int n, int min, int max) //{ // a = new int[n]; // Random r = new Random(); // for (int i = 0; i < n; i++) // a[i] = r.Next(min, max); //} /// <summary> /// Конструктор, создающий массив заданной размерности и заполняющий массив числами от начального значения с заданным шагом /// </summary> /// <param name="n">Размер массива</param> /// <param name="start">Значение начального элемента</param> /// <param name="step">Шаг изменения значений</param> public MyArray(int n, int startEl, int step) { a = new int[n]; if (n != 0) a[0] = startEl; for (int i = 1; i < a.Length; i++) a[i] = a[i - 1] + step; } /// <summary> /// Конструктор, создающий массив на основании данных, загруженных из файла /// </summary> /// <param name="fileName"></param> public MyArray(string fileName) { // Можно было бы записать в первую строку файла кол-во эл-ов массива, // Или переписать содержание файла в строку и потом работать с ней, // Но для разнообразия воспользуемся объектом List List<int> list = new List<int>(); if (!File.Exists(fileName)) CommonMethods.ColoredWriteLine("Файл не существует!", ConsoleColor.Red); else { StreamReader sr = new StreamReader(fileName); while (!sr.EndOfStream) if (int.TryParse(sr.ReadLine(), out int el)) list.Add(el); sr.Close(); if (list.Count != 0) a = list.ToArray(); } } #endregion #region Методы /// <summary> /// Запись массива в файл /// </summary> /// <param name="fileName">Полное имя файла</param> public void WriteToFile(string fileName) { if (a.Length != 0) { if (!File.Exists(fileName)) File.Create(fileName).Dispose(); StreamWriter sw = new StreamWriter(fileName, false); for (int i = 0; i < a.Length; i++) sw.WriteLine(a[i]); sw.Close(); } } /// <summary> /// Метод, меняющий знак у всех элементов массива /// </summary> public void Inverse() { for (int i = 0; i < a.Length; i++) a[i] = -a[i]; } /// <summary> /// Умножение каждого элемента массива на заданное число /// </summary> /// <param name="x"></param> public void Multi(int x) { for (int i = 0; i < a.Length; i++) a[i] *= x; } /// <summary> /// Вывод в строку /// </summary> /// <returns></returns> public override string ToString() { string s = ""; foreach (int v in a) s += v + " "; return s; } #endregion } }<file_sep>-- Найдите производителей ПК с процессором не менее 450 Мгц. Вывести: Maker SELECT DISTINCT maker FROM product pr JOIN pc p ON p.model = pr.Model AND p.speed >= 450;<file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Lesson2 { /* * Исполнитель: * <NAME> * * Задание №4 * Реализовать метод проверки логина и пароля. На вход подается логин и пароль. * На выходе истина, если прошел авторизацию, и ложь, если не прошел(Логин:root, Password:<PASSWORD>). * Используя метод проверки логина и пароля, написать программу: пользователь вводит логин и пароль, * программа пропускает его дальше или не пропускает. * С помощью цикла do while ограничить ввод пароля тремя попытками. */ class Task4 { const string LOGIN = "root"; const string PASSWORD = "<PASSWORD>"; /// <summary> /// Метод проверки корректности учетных данных пользователя. /// </summary> public static void Go() { int i = 0; bool isAuthorized; do { CommonMethods.ColoredWriteLine("Введите логин:", ConsoleColor.Yellow); string login = Console.ReadLine(); CommonMethods.ColoredWriteLine("Введите пароль:", ConsoleColor.Yellow); string password = Console.ReadLine(); isAuthorized = CheckCredentials(login, password, i); i++; } while (i < 3 && !isAuthorized); } /// <summary> /// Метод проверки логина и пароля. /// </summary> /// <param name="login">Логин</param> /// <param name="password"><PASSWORD></param> /// <returns>bool - значение Авторизации</returns> public static bool CheckCredentials(string login, string password, int trysCount) { if (login.Equals(LOGIN) && password.Equals(PASSWORD)) { CommonMethods.ColoredWriteLine("Авторизация выполнена успешно!", ConsoleColor.Green); return true; } else { CommonMethods.ColoredWriteLine($"Неверные логин или пароль!\nОсталось попыток: {2-trysCount}", ConsoleColor.Red); return false; } } } }<file_sep>SELECT DISTINCT battle FROM ( SELECT name, country FROM Ships s JOIN Classes c ON c.class = s.class UNION ALL SELECT class, country FROM Classes ) q JOIN Outcomes o ON o.ship = q.name GROUP BY country, battle HAVING COUNT(DISTINCT name) > 2;<file_sep>WITH summary AS (SELECT TOP 1 WITH TIES DATEPART(month, date) month_Val, DATEPART(year, date) year_Val, SUM(out) max_Sum FROM Outcome GROUP BY DATEPART(month, date), DATEPART(year, date) ORDER BY max_Sum DESC) SELECT o.code, o.point, o.date, o.out FROM Outcome o JOIN summary s ON s.month_Val = DATEPART(month, o.date) AND s.year_Val = DATEPART(year, date);<file_sep>-- Найдите номер модели, скорость и размер жесткого диска для всех ПК стоимостью менее 500 дол. Вывести: model, speed и hd SELECT model, speed, hd FROM PC WHERE price < 500;<file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Lesson5 { /* * Исполнитель: * <NAME> * * Задание №3 * *Для двух строк написать метод, определяющий, является ли одна строка перестановкой другой. Регистр можно не учитывать. * а) с использованием методов C# * б) *разработав собственный алгоритм */ class Task3 { public static void Go() { CommonMethods.ColoredWriteLine(TextConstants.TASK3_DESCR, ConsoleColor.Cyan); CommonMethods.ColoredWriteLine(TextConstants.ENTER_LINE1, ConsoleColor.Yellow); string s1 = Console.ReadLine(); CommonMethods.ColoredWriteLine(TextConstants.ENTER_LINE2, ConsoleColor.Yellow); string s2 = Console.ReadLine(); if (IsPermutation(s1, s2)) //if (MyIsPermutation(s1, s2)) CommonMethods.ColoredWriteLine(TextConstants.STR_IS_PERM, ConsoleColor.Cyan); else CommonMethods.ColoredWriteLine(TextConstants.STR_IS_NOT_PERM, ConsoleColor.Cyan); } /// <summary> /// Метод опеределяет, является ли одна строка перестановкой другой /// С использованием встроенных методов C# /// </summary> /// <param name="s1">Строка 1</param> /// <param name="s2">Строка 2</param> /// <returns>Результат сравнения</returns> static bool IsPermutation(string s1, string s2) { return String.Concat(s1.ToLower().OrderBy(ch => ch)).Equals(String.Concat(s2.ToLower().OrderBy(ch => ch))); } /// <summary> /// Метод определяет, является ли одна строка перестановкой другой /// Про помощи собственного алгоритма /// </summary> /// <param name="s1">Строка 1</param> /// <param name="s2">Строка 2</param> /// <returns>Результат</returns> static bool MyIsPermutation(string s1, string s2) { return ((s1.Length == s2.Length) && (BubbleSort(s1).Equals(BubbleSort(s2)))); } /// <summary> /// Сортировка строк методом Пузырька /// </summary> /// <param name="s">Строка</param> /// <returns>Отсортированная в порядке возрастания строка</returns> static string BubbleSort(string s) { bool swapped; char[] a = s.ToCharArray(); do { swapped = false; for (int i = 1; i < a.Length; i++) { if (a[i - 1].CompareTo(a[i]) > 0) { char temp = a[i - 1]; a[i - 1] = a[i]; a[i] = temp; swapped = true; } } } while (swapped); return new string(a); } } } <file_sep>SELECT name FROM Ships s JOIN Classes c ON c.class = s.class WHERE c.bore = 16 UNION SELECT ship FROM Outcomes o JOIN Classes c ON c.class = o.ship WHERE c.bore = 16; --Variant 2 SELECT DISTINCT ISNULL(name, ship) FROM Classes c LEFT JOIN Ships s ON s.class = c.class LEFT JOIN Outcomes o ON o.ship = c.class WHERE c.bore = 16 AND ISNULL(name, ship) IS NOT NULL;<file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Lesson2 { /* * Исполнитель: * <NAME> * * Класс предназначен для дополнительных методов, * которые используются в работе, как вспомогательные инструменты */ class CommonMethods { /// <summary> /// Метод для получения целого числа, введённого пользователем в консоли /// </summary> /// <returns>Целое число</returns> public static int SetIntParametr() { int a = 0; do { String str = Console.ReadLine(); if (Int32.TryParse(str, out a) && str.Length != 0) return a; else ColoredWriteLine("Введенное значение не является целым числом!\nПопробуйте еще раз!", ConsoleColor.Yellow); } while (true); } /// <summary> /// Метод для получения дробного числа, введённого пользователем в консоли /// </summary> /// <returns>Дробное число</returns> public static double SetDoubleParametr() { double a = 0; do { String str = Console.ReadLine(); if (Double.TryParse(str, out a) && str.Length != 0) return a; else ColoredWriteLine("Введенное значение не является дробным числом!\nПопробуйте еще раз!", ConsoleColor.Yellow); } while (true); } /// <summary> /// Метод для вывода цветного текста в консоль с последующим переводом каретки на новую строку /// </summary> /// <param name="str">Текст, который необходимо вывести на экран</param> /// <param name="consoleColor">Цвет, который будет использоваться при выводе</param> public static void ColoredWriteLine(string str, ConsoleColor consoleColor) { Console.ForegroundColor = consoleColor; Console.WriteLine(str); Console.ForegroundColor = ConsoleColor.White; } /// <summary> /// Метод для вывода цветного текста в консоль без перевода каретки на новую строку /// </summary> /// <param name="str">Текст, который необходимо вывести на экран</param> /// <param name="consoleColor">Цвет, который будет использоваться при выводе</param> public static void ColoredWrite(string str, ConsoleColor consoleColor) { Console.ForegroundColor = consoleColor; Console.Write(str); Console.ForegroundColor = ConsoleColor.White; } /// <summary> /// Приветсвие - вывод в центре экрана с паузой /// </summary> public static void CenterOutput() { string[] a = new string[] { $"Вэлкам, {(Environment.UserName.Equals(String.Empty) ? "Username" : Environment.UserName)}!", "Это второе ДЗ <NAME>!", "Нажми любую клавишу!", }; Console.Clear(); Console.SetCursorPosition(Console.WindowWidth / 2, Console.WindowHeight / 2); // Чтобы ниже получить позицию курсора по вертикали из буфера for (int i = 0; i < a.GetLength(0); i++) { Console.SetCursorPosition(Console.WindowWidth / 2 - a[i].Length / 2, Console.CursorTop); for (int j = 0; j < a[i].Length; j++) { ColoredWrite(a[i][j].ToString(), ConsoleColor.Magenta); System.Threading.Thread.Sleep(50); } Console.Write("\n"); } Console.ReadLine(); Console.Clear(); } } } <file_sep>-- Найдите производителя, выпускающего ПК, но не ПК-блокноты. SELECT maker FROM Product WHERE type LIKE 'PC' EXCEPT SELECT maker FROM Product WHERE type LIKE 'Laptop';<file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Lesson2 { class TasksText { public const string Task1Text = "Написать метод возвращающий минимальное из трех чисел."; public const string Task2Text = "Написать метод подсчета количества цифр числа."; public const string Task3Text = "С клавиатуры вводятся числа, пока не будет введен 0." + "\nПодсчитать сумму всех нечетных положительных чисел."; public const string Task4Text = "Реализовать метод проверки логина и пароля." + "\nНа вход подается логин и пароль. На выходе истина, если прошел авторизацию, и ложь, если не прошел(Логин:root, Password:<PASSWORD>)." + "\nИспользуя метод проверки логина и пароля, написать программу:" + "\nпользователь вводит логин и пароль, программа пропускает его дальше или не пропускает." + "\nС помощью цикла do while ограничить ввод пароля тремя попытками."; public const string Task5Text = "а) Написать программу, которая запрашивает массу и рост человека," + "\nвычисляет его индекс массы и сообщает, нужно ли человеку похудеть, набрать вес или все в норме;" + "\nб) *Рассчитать, на сколько кг похудеть или сколько кг набрать для нормализации веса."; public const string Task6Text = "*Написать программу подсчета количества “Хороших” чисел в диапазоне от 1 до 1 000 000 000." + "\nХорошим называется число, которое делится на сумму своих цифр." + "\nРеализовать подсчет времени выполнения программы, используя структуру DateTime."; public const string Task7Text = "a) Разработать рекурсивный метод, который выводит на экран числа от a до b(a<b);" + "\nб) *Разработать рекурсивный метод, который считает сумму чисел от a до b."; } } <file_sep>SELECT q.maker, type, CAST(tmQty * 100.0 / mQty AS NUMERIC(12, 2)) perc FROM ( SELECT w.type, w.maker, COALESCE(tmQty, 0) tmQty FROM ( SELECT type, maker, COUNT(model) tmQty FROM Product GROUP BY type, maker ) e RIGHT JOIN ( SELECT DISTINCT type, q.maker FROM Product CROSS JOIN ( SELECT DISTINCT maker FROM Product ) q ) w ON w.maker = e.maker AND w.type = e.type ) q LEFT JOIN ( SELECT maker, COUNT(model) mQty FROM Product GROUP BY maker ) w ON q.maker = w.maker;<file_sep>-- Найдите среднюю скорость ПК-блокнотов, цена которых превышает 1000 дол. SELECT AVG(speed) speed FROM Laptop WHERE price > 1000;<file_sep>WITH q AS ( SELECT class, COUNT(result) sunkedCount FROM ( SELECT class name, class FROM Classes cl UNION SELECT name, class FROM Ships s ) q LEFT JOIN Outcomes o ON o.ship = q.name AND o.result = 'sunk' GROUP BY class HAVING COUNT(result) > 0) SELECT e.class, q.sunkedCount FROM ( SELECT class, COUNT(name) shipCount FROM ( SELECT c.class, s.name FROM Classes c JOIN Ships s ON s.class = c.class UNION SELECT c.class, o.ship FROM Classes c JOIN Outcomes o ON o.ship = c.class ) w GROUP BY class HAVING COUNT(name) > 2 ) e JOIN q ON q.class = e.class;<file_sep>SELECT DISTINCT o.ship FROM Outcomes o JOIN Battles b ON b.name = o.battle JOIN ( SELECT ship, b.date FROM Outcomes o JOIN Battles b ON b.name = o.battle ) a ON a.ship = o.ship AND a.date > b.date WHERE o.result = 'damaged';<file_sep>using System; using System.IO; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Lesson4 { /* * Исполнитель: * <NAME> * * Задание №3 * Решить задачу с логинами из предыдущего урока, только логины и пароли считать из файла в массив. */ class Task3 { /// <summary> /// Проверка аутентификации /// </summary> public static void Go() { CommonMethods.ColoredWriteLine(TasksDescription.Task3Description, ConsoleColor.Cyan); string fileName = "..\\..\\Data\\Task3Data.txt"; if (File.Exists(fileName)) { if (Auth(fileName)) CommonMethods.ColoredWriteLine("Вы успешно авторизованы!", ConsoleColor.Green); else CommonMethods.ColoredWriteLine("Лимит попыток израсходован! Попробуйте позже.", ConsoleColor.Red); } else CommonMethods.ColoredWriteLine("Файл не существует!", ConsoleColor.Red); } /// <summary> /// Метод проверки корректности пары Логин - Пароль /// </summary> /// <param name="fileName">Полное имя файла с данными об аутентификации</param> /// <returns>Результат аутентификации</returns> static bool Auth(string fileName) { string[] s = File.ReadAllLines(fileName); CommonMethods.ColoredWriteLine("Выберите правильную пару Логин - Пароль, у вас 3 попытки (правильная пара №7):", ConsoleColor.Yellow); int trysCount = 3; while (trysCount > 0) { for (int i = 0; i < s.Length; i++) CommonMethods.ColoredWriteLine(((i + 1) + ": " + s[i].Split(' ')[0] + "-" + s[i].Split(' ')[1]), ConsoleColor.Magenta); int t = CommonMethods.SetIntParametr(); if (t == 7) return true; else if (--trysCount != 0) CommonMethods.ColoredWriteLine("Неправильный логин или пароль!\nКоличество попыток: " + trysCount, ConsoleColor.Red); } return false; } } }<file_sep>-- Найдите среднюю скорость ПК, выпущенных производителем A. SELECT AVG(speed) speed FROM PC pc JOIN Product pr ON pr.Model = pc.model AND pr.Maker = 'A';<file_sep>SELECT c.country, b.name FROM Classes c, Battles b EXCEPT ( SELECT c.country, o.battle FROM Outcomes o JOIN Ships s ON s.name = o.ship JOIN Classes c ON c.class = s.class UNION SELECT c.country, o.battle FROM Outcomes o JOIN Classes c ON c.class = o.ship );<file_sep>SELECT title, info FROM ( SELECT TOP 1 p.model, CAST(p.speed AS VARCHAR(50)) speed, CAST(p.ram AS VARCHAR(50)) ram, CAST(p.hd AS VARCHAR(50)) hd, CAST(p.cd AS VARCHAR(50)) cd, CAST(p.price AS VARCHAR(50)) price FROM PC p ORDER BY code DESC ) x UNPIVOT(info FOR title IN(model, speed, ram, hd, cd, price)) unpvt;<file_sep>SELECT pas.name, total_time_in_fly FROM ( SELECT TOP 1 WITH TIES p.ID_psg, SUM(CASE WHEN t.time_out > t.time_in THEN DATEDIFF(minute, t.time_out, t.time_in) + 24 * 60 ELSE DATEDIFF(minute, t.time_out, t.time_in) END) total_time_in_fly FROM Pass_in_trip p JOIN Trip t ON t.trip_no = p.trip_no GROUP BY p.ID_psg ORDER BY total_time_in_fly DESC ) q JOIN Passenger pas ON q.ID_psg = pas.ID_psg;<file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Lesson2 { /* * Исполнитель: * <NAME> * * Задание №1 * Написать метод, возвращающий минимальное из трех чисел. */ class Task1 { /// <summary> /// Метод, запрашивающий три числа и выводящий в консоль минимальное из этих чисел. /// </summary> public static void Go() { CommonMethods.ColoredWriteLine("Введите первое целое число:", ConsoleColor.Yellow); int a = CommonMethods.SetIntParametr(); CommonMethods.ColoredWriteLine("Введите второе целое число:", ConsoleColor.Yellow); int b = CommonMethods.SetIntParametr(); CommonMethods.ColoredWriteLine("Введите третье целое число:", ConsoleColor.Yellow); int c = CommonMethods.SetIntParametr(); CommonMethods.ColoredWriteLine($"Минимум из чисел {a}, {b} и {c}:\n{CompareThreeNum(a, b, c)}", ConsoleColor.Cyan); } /// <summary> /// Метод поиска минимума из трех целых чисел /// </summary> /// <param name="a">Первое число</param> /// <param name="b">Второе число</param> /// <param name="c">Третье число</param> /// <returns>Минимальное число</returns> public static int CompareThreeNum(int a, int b, int c) { return ((a > b) ? ((b > c) ? c : b) : ((a > c) ? c : a)); } } } <file_sep>SELECT c.class FROM Outcomes o JOIN Classes c ON c.class = o.ship WHERE o.result = 'sunk' UNION SELECT s.class FROM Outcomes o JOIN Ships s ON s.name = o.ship WHERE o.result = 'sunk';<file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Lesson3 { /* * Исполнитель: * <NAME> * * Задание №3 * * Описать класс дробей - рациональных чисел, являющихся отношением двух целых чисел. * Предусмотреть методы сложения, вычитания, умножения и деления дробей. * Написать программу, демонстрирующую все разработанные элементы класса. * * Добавить упрощение дробей. */ class Task3 { public class FractNumber { #region Описание класса int num; // Числитель int denom; // Знаменатель int integerPart; // Целая часть string sign=""; // Знак дроби /// <summary> /// Свойство числителя /// </summary> public int Num { get { return num; } set { if (value < 0) sign = (sign.Equals("-") ? sign = "" : sign = "-"); // проверяем знак дроби num = Math.Abs(value); } } /// <summary> /// Свойство знаменателя /// </summary> public int Denom { set { if (value < 0) sign = (sign.Equals("-") ? sign = "" : sign = "-"); // проверяем знак дроби if (denom != 0) denom = Math.Abs(value); } get { return denom; } } /// <summary> /// Свойство целой части дроби /// </summary> public int InegerPart { get; } /// <summary> /// Конструктор класса FractNumber /// </summary> /// <param name="num">Числитель</param> /// <param name="denom">Знаменатель</param> public FractNumber(int num, int denom) { // Определяем знак дроби if ((num < 0 && denom > 0) || (num > 0 && denom < 0)) sign = "-"; this.num = Math.Abs(num); if (denom != 0) this.denom = Math.Abs(denom); // Выделяем целую часть integerPart = this.num / this.denom; if (integerPart != 0) this.num -= this.num / this.denom * this.denom; // Упрощаем дробь int gcd = Gcd(this.num, this.denom); this.num /= gcd; this.denom /= gcd; } #endregion #region Методы арифметических операций с дробями /// <summary> /// Сложение дробей /// </summary> /// <param name="x"></param> /// <returns>Результат сложения дробей</returns> public FractNumber Sum(FractNumber x) { PrepairFractions(); x.PrepairFractions(); // Вычисление для дробей с одинаковым знаменателем if (x.denom == denom) return new FractNumber(num + x.num, denom); // Вычисление для дробей с разными знаменателями int lcm = Lcm(denom, x.denom); return new FractNumber(lcm / denom * num + lcm / x.denom * x.num, denom * lcm/denom); } /// <summary> /// Вычитание дробей реализуем через сложение с заменой знака /// </summary> /// <param name="x"></param> /// <returns>Разность дробей</returns> public FractNumber Subtraction(FractNumber x) { //x.Num = -x.num; тут была ошибка. После выполнения операции вычитания для второго числа менялся знак операции, т.к. программа крутится в цикле return Sum(new FractNumber(- x.num, x.denom)); } /// <summary> /// Умножение дробей /// </summary> /// <param name="x"></param> /// <returns>Произведение дробей</returns> public FractNumber Multiply(FractNumber x) { PrepairFractions(); x.PrepairFractions(); return new FractNumber(num * x.num, denom * x.denom); } /// <summary> /// Деление дробей (реализуем через умножение) /// </summary> /// <param name="x">Делитель</param> /// <returns>Частное</returns> public FractNumber Division(FractNumber x) { // Исключаем целую часть без учета знака дроби x.num += denom * x.integerPart; x.integerPart = 0; // Меняем числитель и знаменатель местами CommonMethods.Swap(ref x.num, ref x.denom); return Multiply(x); } #endregion #region Вспомогательные методы /// <summary> /// Подготовка дроби к вычислениям /// </summary> void PrepairFractions() { // Убираем целую часть, полность переводим в дробь num += denom * integerPart; integerPart = 0; // Определяемся со знаком дроби num = ((sign.Equals("-")) ? -num : num); sign = ""; } public override string ToString() { // тут тоже была ошибка, т.к. был неверно записан тернарный оператор if (num == 0 && integerPart == 0) return "0"; if (num == 0 && integerPart != 0) return integerPart.ToString(); return $"{sign}{((integerPart != 0) ? integerPart + ((integerPart.ToString()[integerPart.ToString().Length - 1] == '1') ? " целая " : " целых ") : "")}{num}/{denom}"; } /// <summary> /// Метод нахождения НОД двух чисел /// </summary> /// <param name="x"></param> /// <param name="y"></param> /// <returns>Значение НОД</returns> static int Gcd(int x, int y) { while (y != 0) { x %= y; CommonMethods.Swap(ref x, ref y); } return x; } /// <summary> /// Метод для нахождения НОК двух чисел /// </summary> /// <param name="x"></param> /// <param name="y"></param> /// <returns>Значение НОК</returns> static int Lcm(int x, int y) { return x * y / Gcd(x, y); } #endregion } public static void Go() { CommonMethods.ColoredWriteLine(TasksDescription.Task3Text, ConsoleColor.Cyan); CommonMethods.ColoredWriteLine("Введите числитель первой дроби:", ConsoleColor.Yellow); int a = CommonMethods.SetIntParametr(); CommonMethods.ColoredWriteLine("Введите знаменатель первой дроби:", ConsoleColor.Yellow); int b = CommonMethods.SetIntParametrExeptZero(); FractNumber fn1 = new FractNumber(a, b); CommonMethods.ColoredWriteLine("Введите числитель второй дроби:", ConsoleColor.Yellow); a = CommonMethods.SetIntParametr(); CommonMethods.ColoredWriteLine("Введите знаменатель второй дроби:", ConsoleColor.Yellow); b = CommonMethods.SetIntParametrExeptZero(); FractNumber fn2 = new FractNumber(a, b); bool exit = false; while (!exit) { CommonMethods.ColoredWriteLine("Выберите арифметическое действие:\n +\t: сложение;\n -\t: вычитание;\n *\t: умножение;\n /\t: деление;\n 0\t: завершить работу.", ConsoleColor.Magenta); string choice = Console.ReadLine(); switch (choice) { case "+": CommonMethods.ColoredWriteLine($"Результат выполнения операции сложения:\n{fn1.Sum(fn2)}", ConsoleColor.Cyan); break; case "-": CommonMethods.ColoredWriteLine($"Результат выполнения операции вычитания:\n{fn1.Subtraction(fn2)}", ConsoleColor.Cyan); break; case "*": CommonMethods.ColoredWriteLine($"Результат выполнения операции умножения:\n{fn1.Multiply(fn2)}", ConsoleColor.Cyan); break; case "/": CommonMethods.ColoredWriteLine($"Результат выполнения операции деления:\n{fn1.Division(fn2)}", ConsoleColor.Cyan); break; case "0": exit = true; break; default: CommonMethods.ColoredWriteLine("Пункт не предусматривается системой!", ConsoleColor.Red); break; } } } } }<file_sep>WITH q AS (SELECT DISTINCT town_from, town_to, ( SELECT COUNT(trip_no) qty FROM Trip tr WHERE(t.town_from = tr.town_from AND t.town_to = tr.town_to) OR (t.town_from = tr.town_to AND t.town_to = tr.town_from) ) trip_count FROM Trip t) SELECT CAST(SUM(trip_count) AS NUMERIC(2, 0)) trip_count FROM ( SELECT CASE WHEN EXISTS ( SELECT 1 FROM q WHERE q.town_from = w.town_to AND q.town_to = w.town_from ) THEN 0.5 ELSE 1 END trip_count FROM ( SELECT town_from, town_to, trip_count FROM q WHERE trip_count = ( SELECT MAX(trip_count) FROM q ) ) w ) e; -- var 2 WITH ordered_towns AS (SELECT CASE WHEN(town_from < town_to) THEN town_to ELSE town_from END town1, CASE WHEN town_from < town_to THEN town_from ELSE town_to END town2 FROM Trip), trip_counts AS (SELECT town1, town2, COUNT(*) cnt FROM ordered_towns GROUP BY town1, town2) SELECT COUNT(*) cnt FROM trip_counts WHERE cnt = ( SELECT MAX(cnt) FROM trip_counts );<file_sep>using System; using System.Linq; using System.Text.RegularExpressions; using System.Collections.Generic; using System.Text; using System.Threading.Tasks; namespace Lesson5 { /* * Исполнитель: * <NAME> * * Задание №1 * Создать программу, которая будет проверять корректность ввода логина. Корректным * логином будет строка от 2-х до 10-ти символов, содержащая только буквы или цифры, и при * этом цифра не может быть первой. * а) без использования регулярных выражений; * б) **с использованием регулярных выражений. */ class Task1 { public static void Go() { CommonMethods.ColoredWriteLine(TextConstants.TASK1_DESCR, ConsoleColor.Cyan); Authorization(); Console.ReadLine(); } /// <summary> /// Метод проверки логина без использования регулярных выражений. но с использованием Linq /// (что не запрещено, то разрешено) /// </summary> /// <param name="s">Строковое представление логина</param> /// <returns>Результат</returns> static bool Check(string s) { return !(s.Length == 0 || char.IsDigit(s[0]) || (s.Length < 2 || s.Length > 10)) && s.All(c => char.IsLetterOrDigit(c)); } /// <summary> /// Метод проверки логина с использованием регулярных выражений /// </summary> /// <param name="s">Строковое представление логина</param> /// <returns>Результат</returns> static bool RegexCheck(string s) { return new Regex("^[A-Za-z][A-Za-z0-9]{1,9}$").IsMatch(s); } /// <summary> /// Метод для повторных попыток ввода логина. Работа программы завершается, если 3 раза ввели некорректный логин. /// </summary> /// <returns>Результат</returns> static bool Authorization() { CommonMethods.ColoredWriteLine(TextConstants.ENTER_LOGIN, ConsoleColor.Yellow); int i = 0; while (i < 3) { if (Check(Console.ReadLine())) // без использования регулярных выражений //if (RegexCheck(Console.ReadLine())) // с использованием регулярных выражений { CommonMethods.ColoredWriteLine(TextConstants.LOGIN_CORRECT, ConsoleColor.Green); return true; } else { CommonMethods.ColoredWriteLine(TextConstants.LOGIN_NOT_CORRECT, ConsoleColor.Red); if (++i < 3) CommonMethods.ColoredWriteLine(TextConstants.TRYS_COUNT + (3 - i), ConsoleColor.Red); // Зачем предупреждать, если больше нет попыток? else CommonMethods.ColoredWriteLine(TextConstants.TRYS_COUNT_END, ConsoleColor.Red); } } return false; } } } <file_sep>SELECT class FROM ( SELECT class, name FROM Ships UNION SELECT DISTINCT o.ship, o.ship FROM Outcomes o JOIN Classes c ON c.class = o.ship ) a GROUP BY class HAVING COUNT(name) = 1;<file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Lesson1 { class Task4 { public static void Go() { Console.ForegroundColor = ConsoleColor.Yellow; Console.WriteLine("Введите первую переменную \"x\":"); int x = Additional.SetIntParametr(); Console.ForegroundColor = ConsoleColor.Yellow; Console.WriteLine("Введите вторую переменную \"y\":"); int y = Additional.SetIntParametr(); Console.ForegroundColor = ConsoleColor.Yellow; Console.WriteLine("Меняем местами первым способом:"); Additional.Swap1(ref x, ref y); Console.ForegroundColor = ConsoleColor.White; Console.WriteLine($"x = {x}\ny = {y}"); Console.ForegroundColor = ConsoleColor.Yellow; Console.WriteLine("Меняем обратно вторым способом:"); Additional.Swap1(ref x, ref y); Console.ForegroundColor = ConsoleColor.White; Console.WriteLine($"x = {x}\ny = {y}"); Console.ReadLine(); } } }<file_sep>using System; using System.IO; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Lesson4 { /* * Исполнитель: * <NAME> * * Класс для управления игрой "Верю - не верю" */ class BelieveOrNot { string question; bool answer; #region Свойства /// <summary> /// Вопрос /// </summary> public string Question { set { question = value; } get { return question; } } /// <summary> /// Ответ /// </summary> public bool Answer { set { answer = value; } get { return answer; } } #endregion #region Конструкторы /// <summary> /// Пустой конструктор /// </summary> BelieveOrNot() { } /// <summary> /// Конструктор объекта Пары /// </summary> /// <param name="question">Вопрос</param> /// <param name="answer">Ответ</param> public BelieveOrNot(string question, bool answer) { this.question = question; this.answer = answer; } #endregion #region Метод /// <summary> /// Получения массива пар вопрос-ответ из файла /// </summary> /// <param name="fileName">Полное имя файла</param> /// <returns>Массив объектов вопрос-ответ</returns> public static BelieveOrNot[] GenerateFromFile(string fileName) { string s = ""; if (!File.Exists(fileName)) { CommonMethods.ColoredWriteLine("Файл не существует!", ConsoleColor.Red); return null; } else { s = File.ReadAllText(fileName); string[] sa = s.Split('\n'); BelieveOrNot[] bon = new BelieveOrNot[sa.Length]; for (int i = 0; i < sa.Length; i++) bon[i] = new BelieveOrNot(sa[i].Split(';')[0], sa[i].Split(';')[1].Substring(0, 2) == "Да"); return bon; } } #endregion } } <file_sep>SELECT COALESCE(i.point, o.point) point, COALESCE(i.date, o.date) date, CASE WHEN o.point IS NULL THEN 'inc' WHEN i.point IS NULL THEN 'out' ELSE NULL END [type], COALESCE(inc, out) rem FROM ( SELECT point, date, SUM(inc) inc FROM Income GROUP BY point, date ) i FULL JOIN ( SELECT point, date, SUM(out) out FROM Outcome GROUP BY point, date ) o ON i.point = o.point AND i.date = o.date WHERE o.point IS NULL OR i.point IS NULL;<file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Lesson1 { class Additional { #region Текстовые констакты (это не точно) public static String task1Text = "Написать программу “Анкета”.\n" + "Последовательно задаются вопросы (имя, фамилия, возраст, рост, вес).\n" + "В результате вся информация выводится в одну строчку."; public static String task2Text = "Ввести вес и рост человека.\n" + "Рассчитать и вывести индекс массы тела(ИМТ) по формуле I=m/(h*h); где m-масса тела в килограммах, h - рост в метрах."; public static String task3Text = "Написать программу, которая подсчитывает расстояние между точками с координатами x1, y1 и x2,y2\n" + "по формуле r=Math.Sqrt(Math.Pow(x2-x1,2)+Math.Pow(y2-y1,2).\n" + "Вывести результат используя спецификатор формата .2f (с двумя знаками после запятой);"; public static String task4Text = "Написать программу обмена значениями двух переменных."; public static String task5Text = "Написать программу, которая выводит на экран ваше имя, фамилию и город проживания."; #endregion #region Методы для получения значений из консоли // целые public static int SetIntParametr() { do { int a = 0; Console.ForegroundColor = ConsoleColor.White; String str = Console.ReadLine(); if (Int32.TryParse(str, out a) && str.Length != 0) return a; else { Console.ForegroundColor = ConsoleColor.Yellow; Console.WriteLine("Введенное значение не является целым числом!\nПопробуйте еще раз!"); } } while (true); } // вещественные public static float SetFloatParametr() { float a = 0; do { Console.ForegroundColor = ConsoleColor.White; String str = Console.ReadLine(); if (Single.TryParse(str, out a) && str.Length != 0) return a; else { Console.ForegroundColor = ConsoleColor.Yellow; Console.WriteLine("Введенное значение не является дробным числом!\nПопробуйте еще раз!"); } } while (true); } #endregion #region Расстояние между точками public static double PointsDistance(int x1, int y1, int x2, int y2) { return Math.Sqrt(Math.Pow(x2 - x1, 2) + Math.Pow(y2 - y1, 2)); } #endregion #region Методы для смены значений двух переменных public static void Swap1(ref int a, ref int b) { a = a + b; b = a - b; a = a - b; } public static void Swap2(int a, int b) { a = a + b; b = a ^ b; a = a ^ b; } #endregion #region Вывод в центре экрана с паузой public static void CenterOutput() { string[] a = new string[] { "Приветствую!" , "<NAME>ут #username!", "Я проживаю в городе #city." }; Console.Clear(); Console.SetCursorPosition(Console.WindowWidth / 2, Console.WindowHeight / 2); Console.ForegroundColor = ConsoleColor.Yellow; for (int i = 0; i < a.GetLength(0); i++) { Console.SetCursorPosition(Console.WindowWidth / 2 - a[i].Length / 2, Console.CursorTop); for (int j = 0; j < a[i].Length; j++) { Console.Write(a[i][j]); System.Threading.Thread.Sleep(100); } Console.Write("\n"); } Console.ReadLine(); Console.Clear(); } #endregion } }<file_sep>SELECT CAST(AVG(numGuns * 1.0) AS NUMERIC(8, 2)) avg_numGuns FROM ( SELECT name, class FROM Ships UNION SELECT ship, ship FROM Outcomes ) q JOIN Classes c ON c.class = q.class WHERE type = 'bb';<file_sep>SELECT COUNT(*) qty FROM ( SELECT COUNT(maker) qty FROM Product GROUP BY maker HAVING COUNT(model) = 1 ) a;<file_sep>using System; using System.IO; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Task2 { /* * Исполнитель: * <NAME> * * Задание №2 * *Модифицировать программу нахождения минимума функции так, чтобы можно было * передавать функцию в виде делегата. Сделать меню с различными функциями и представьте * пользователю выбор для какой функции и на каком отрезке находить минимум. Используйте массив делегатов. */ public delegate double Func(double x); class Task2 { public static void Main(string[] args) { Lesson6.Support.ColoredWriteLine("Введите начальное значение аргумента для функции:", ConsoleColor.Yellow); double x1 = Lesson6.Support.SetDoubleParametr(); Lesson6.Support.ColoredWriteLine("Введите конечное значение аргумента для функции:", ConsoleColor.Yellow); double x2 = Lesson6.Support.SetDoubleParametr(); Lesson6.Support.ColoredWriteLine("Введите шаг увеличения аргумента:", ConsoleColor.Yellow); double h = Lesson6.Support.SetDoubleParametr(); Func[] arr = new Func[5] { Math.Sin, Math.Cos, delegate (double y) { return y * y; }, Math.Sqrt , delegate (double y) { return y * y / Math.Log(y); } }; // массив делегатов string fileName = "..\\..\\Data\\Task2.txt"; int i = 0; do { Lesson6.Support.ColoredWriteLine("Выберите функцию:\n- 1: Sin(x);\n- 2: Cos(x);\n- 3: x^2;\n- 4: Sqrt(x);\n- 5: x^2/Ln(x);\n- 0: Выход.", ConsoleColor.Yellow); int choice = Lesson6.Support.SetIntParametr(); switch (choice) { case 0: i = 0; break; case 1: i = 1; break; case 2: i = 2; break; case 3: i = 3; break; case 4: i = 4; break; case 5: i = 5; break; default: Lesson6.Support.ColoredWriteLine("Пункт не предусматривается системой!", ConsoleColor.Red); break; } if (i != 0) { SaveFunc(fileName, arr[i-1], x1, x2, h); Load(fileName, out double min, out double x); Table(arr[i - 1], x1, x2); Lesson6.Support.ColoredWriteLine(String.Format("Минимум:\n{0,0:0.000}", min), ConsoleColor.Cyan); Lesson6.Support.ColoredWriteLine("Значение x при минимуме функции:\n" + x, ConsoleColor.Cyan); } } while (i != 0); Console.ReadLine(); } /// <summary> /// Сохранение результатов выполнения функции в файл /// </summary> /// <param name="fileName">Имя файла</param> /// <param name="F">Делегат</param> /// <param name="a">Значение "от"</param> /// <param name="b">Значение "до"</param> /// <param name="h">Шаг аргумента функции</param> public static void SaveFunc(string fileName, Func F, double a, double b, double h) { FileStream fs = new FileStream(fileName, FileMode.Create, FileAccess.Write); BinaryWriter bw = new BinaryWriter(fs); double x = a; while (x <= b) { bw.Write(F(x)); bw.Write(x); // Значение аргумента функции x += h; } bw.Close(); fs.Close(); } /// <summary> /// Получение значений функции из файла, нахождение минимума /// </summary> /// <param name="fileName">Имя файла</param> /// <returns>Минимум функции</returns> public static void Load(string fileName, out double min, out double x) { FileStream fs = new FileStream(fileName, FileMode.Open, FileAccess.Read); BinaryReader bw = new BinaryReader(fs); min = double.MaxValue; x = 0; double d; for (int i = 0; i < fs.Length / sizeof(double); i += 2) { // Считываем значение и переходим к следующему d = bw.ReadDouble(); // считываем значение минимума if (d < min) { min = d; x = bw.ReadDouble(); // считываем значение аргумента, при котором получили минимум функции fs.Seek(-sizeof(double), SeekOrigin.Current); // возвращаем позицию в потоке назад } if (i != fs.Length / sizeof(double) - 1) fs.Seek(sizeof(double), SeekOrigin.Current); // Переходим к следующему значению минимума } bw.Close(); fs.Close(); } /// <summary> /// Функция табулирования /// </summary> /// <param name="F">Функция</param> /// <param name="a">Занчение x "от"</param> /// <param name="b">Значение x "до"</param> static void Table(Func F, double a, double b) { Console.WriteLine("----X----Y--------"); while (a <= b) Lesson6.Support.ColoredWriteLine(String.Format("|{0,8:0.000}|{1,8:0.000}", a, F(a++)), ConsoleColor.Cyan); Console.WriteLine("-------------------"); } } } <file_sep>SELECT class, ( SELECT COUNT(*) FROM ( SELECT ship, result FROM Outcomes WHERE ship NOT IN ( SELECT name FROM Ships ) UNION ALL SELECT s.class, o.result FROM Outcomes o JOIN Ships s ON s.name = o.ship ) q WHERE ship = c.class AND result = 'sunk' ) qty FROM Classes c; -- Variant 2 SELECT class, COUNT(result) qty FROM ( SELECT class name, class FROM Classes c UNION SELECT name, class FROM Ships ) q LEFT JOIN Outcomes o ON o.ship = q.name AND result = 'sunk' GROUP BY class;<file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Lesson3 { /* * Исполнитель: * <NAME> * * Класс предназначен для дополнительных методов, * которые используются в работе, как вспомогательные инструменты. */ class CommonMethods { /// <summary> /// Метод для получения целого числа, введённого пользователем в консоли /// </summary> /// <returns>Целое число</returns> public static int SetIntParametr() { do { String str = Console.ReadLine(); if (Int32.TryParse(str, out int a) && str.Length != 0) return a; else ColoredWriteLine("Введенное значение не является целым числом!\nПопробуйте еще раз!", ConsoleColor.Red); } while (true); } /// <summary> /// Метод для получения целого числа, неравного нулю, введённого пользователем в консоли /// </summary> /// <returns>Целое число</returns> public static int SetIntParametrExeptZero() { do { String str = Console.ReadLine(); if (Int32.TryParse(str,out int a) && str.Length != 0 && a != 0) return a; else ColoredWriteLine(((a != 0) ? "Введенное значение не является целым числом!\nПопробуйте еще раз!" : "Введенное значение не может быть равным нулю!"), ConsoleColor.Red); } while (true); } /// <summary> /// Метод для получения целого числа, введённого пользователем в консоли, /// с использованием try{ } catch{ } конструкции /// </summary> /// <returns>Целое число</returns> public static int SetIntParametrExProcessing() { int a = 0; bool isRepeat; do { try { isRepeat = false; a = Int32.Parse(Console.ReadLine()); } catch (Exception ex) { ColoredWriteLine(ex.Message, ConsoleColor.Red); isRepeat = true; } } while (isRepeat); return a; } /// <summary> /// Метод для получения дробного числа, введённого пользователем в консоли /// </summary> /// <returns>Дробное число</returns> public static double SetDoubleParametr() { do { String str = Console.ReadLine(); if (Double.TryParse(str, out double a) && str.Length != 0) return a; else ColoredWriteLine("Введенное значение не является дробным числом!\nПопробуйте еще раз!", ConsoleColor.Red); } while (true); } /// <summary> /// Метод для вывода цветного текста в консоль с последующим переводом каретки на новую строку /// </summary> /// <param name="str">Текст, который необходимо вывести на экран</param> /// <param name="consoleColor">Цвет, который будет использоваться при выводе</param> public static void ColoredWriteLine(string str, ConsoleColor consoleColor) { Console.ForegroundColor = consoleColor; Console.WriteLine(str); Console.ForegroundColor = ConsoleColor.White; } /// <summary> /// Метод для вывода цветного текста в консоль без перевода каретки на новую строку /// </summary> /// <param name="str">Текст, который необходимо вывести на экран</param> /// <param name="consoleColor">Цвет, который будет использоваться при выводе</param> public static void ColoredWrite(string str, ConsoleColor consoleColor) { Console.ForegroundColor = consoleColor; Console.Write(str); Console.ForegroundColor = ConsoleColor.White; } /// <summary> /// Приветсвие - вывод в центре экрана с паузой /// </summary> public static void CenterOutput() { string[] a = new string[] { $"Вэлкам, {(Environment.UserName.Equals(String.Empty) ? "Username" : Environment.UserName)}!", "Это третье Д<NAME>!", "Нажми любую клавишу!", }; Console.Clear(); Console.SetCursorPosition(Console.WindowWidth / 2, Console.WindowHeight / 2); // Чтобы ниже получить позицию курсора по вертикали из буфера for (int i = 0; i < a.GetLength(0); i++) { Console.SetCursorPosition(Console.WindowWidth / 2 - a[i].Length / 2, Console.CursorTop); for (int j = 0; j < a[i].Length; j++) { ColoredWrite(a[i][j].ToString(), ConsoleColor.Magenta); System.Threading.Thread.Sleep(30); } Console.Write("\n"); } Console.ReadLine(); Console.Clear(); } /// <summary> /// Функция смены значений местами в случае некорректного ввода /// </summary> /// <param name="a">Первый аргумент</param> /// <param name="b">Второй аргумент</param> public static void Swap(ref int a, ref int b) { a += b; b = a - b; a -= b; } } }<file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Lesson2 { /* * Исполнитель: * <NAME> * * Задание №5 * а) Написать программу, которая запрашивает массу и рост человека, вычисляет его индекс массы и сообщает, * нужно ли человеку похудеть, набрать вес или все в норме; * б) *Рассчитать, на сколько кг похудеть или сколько кг набрать для нормализации веса. */ class Task5 { /// <summary> /// Запрашивает рост человека в см и вес в кг. Вычесляет его ИМТ, сообщает, нужно ли человеку похудеть, набрать вес или всё в норме. /// При отклонении от нормы выдаёт информацию о том, сколько кг набрать или сколько кг скинуть для нормализации веса. /// </summary> public static void Go() { #region Инициализация констант, массивов ИМТ и их текстовых пояснений const int NORMAL_INDEX = 2; // Индекс верхенего значения нормы ИМТ в массиве indexes double[] indexes = new double[] {16, 18.5, 25, 30, 35, 40}; // показатели ИМТ string[,] stAr = new string[,] { // Двумерный массив текстовых описаний { "Выраженный дефицит массы тела.", "Надо срочно набирать" }, { "Недостаточная (дефицит) масса тела.", "Надо набирать вес!"}, {"Нома.","Ваш вес находится в норме!" }, {"Избыточная масса тела (предожирение).", "Не мешало бы похудеть на" }, { "Ожирение!", "Нужно сбросить" }, { "Ожирение резкое!", "Очень срочно нужно похудеть на" }, { "Очень резкое ожирение!", "Уже поздно, можно съесть еще пончик.\nШутка! Нужно худеть на"} }; #endregion CommonMethods.ColoredWriteLine("Введите свой вес в килограммах:", ConsoleColor.Yellow); int w = CommonMethods.SetIntParametr(); CommonMethods.ColoredWriteLine("Введите свой рост в сантиметрах:", ConsoleColor.Yellow); double h = CommonMethods.SetDoubleParametr() / 100; double index = w / (h * h); CommonMethods.ColoredWriteLine($"\nИндекс массы тела = {index:F}", ConsoleColor.Cyan); for(int i = 0; i < indexes.Length; i++) { if (index < indexes[i]) { if (i == NORMAL_INDEX) // если ИМТ в норме, нам не нужно указывать, на сколько кг худеть или сколько кг набирать CommonMethods.ColoredWriteLine($"{stAr[i, 0]}\n{stAr[i, 1]}", ConsoleColor.Cyan); else CommonMethods.ColoredWriteLine($"{stAr[i, 0]}\n{stAr[i, 1]} {GetWeightDiff(indexes[NORMAL_INDEX-1], indexes[NORMAL_INDEX], h, w):F} кг.", ConsoleColor.Cyan); break; } else if (i == indexes.Length - 1) // т.к. размерности массивов ИМТ и текстовых описаний не совпадают, делаем исключение для index > 40 { CommonMethods.ColoredWriteLine($"{stAr[i+1, 0]}\n{stAr[i+1, 1]} {GetWeightDiff(indexes[NORMAL_INDEX - 1], indexes[NORMAL_INDEX], h, w):F} кг.", ConsoleColor.Cyan); } } } /// <summary> /// Метод возвращает разницу в килограммах между текущим весом человека и рекомендуемыми ВОЗ показателями ИМТ для указанного роста /// </summary> /// <param name="minNormalIndex">Минимальный показатель нормы ИМТ по ВОЗ</param> /// <param name="maxNormalIndex">Максимальный показатель нормы ИМТ по ВОЗ</param> /// <param name="h">Рост человека в метрах</param> /// <param name="w">Вес человека в килограммах</param> /// <returns>Разница в килограммах</returns> public static double GetWeightDiff(double minNormalIndex, double maxNormalIndex, double h, double w) { return (w / (h * h) < minNormalIndex) ? (h * h * minNormalIndex - w) : w - h * h * maxNormalIndex; } } }<file_sep>SELECT c.class, s.name, c.country FROM Ships s, Classes c WHERE c.numGuns > 9 AND c.class = s.class;<file_sep>using System; using System.Text.RegularExpressions; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Task4 { /* * Исполнитель: * <NAME> * * Задание №4 * В файле могут встречаться номера телефонов, записанные в формате xx-xx-xx, xxx-xxx или xxx-xx-xx. * Вывести все номера телефонов, которые содержатся в файле. */ class Task4 { static void Main(string[] args) { Regex r = new Regex("\\b\\d{2,3}-\\d{2}-\\d{2}\\b|\\b\\d{3}-\\d{3}\\b"); do { Lesson6.Support.ColoredWriteLine("Введите номер телефона или 0 для выхода из программы:", ConsoleColor.Yellow); string check = Console.ReadLine(); if (check.Equals("0")) break; foreach (Match match in r.Matches(check)) Lesson6.Support.ColoredWriteLine(match.Value, ConsoleColor.Green); if (!r.IsMatch(check)) Lesson6.Support.ColoredWriteLine("Совпадений нет.", ConsoleColor.Red); } while (true); } } } <file_sep>SELECT speed, AVG(price) avg_price FROM PC GROUP BY speed HAVING speed > 600;<file_sep>using System.Collections.Generic; using System.Linq; using System.Text.RegularExpressions; namespace Lesson5 { class MyString { string message; string[] array; List<string> list; public string Message { get; set; } public string[] Array { get; set; } public List<string> List { get; set;} public MyString(string s) { message = s; array = message.Replace(", ", ",").Replace(". ", ".").Split(new char[] { ' ', ',', '.', ';', ':' }); // по сути нужно только для того, чтобы не делать дополнительные преобразования в методах list = new List<string>(message.Replace(", ", ",").Replace(". ", ".").Split(new char[] { ' ', ',', '.', ';', ':' })); // сразу создаём лист, для использования в дальнейшем } /// <summary> /// Вывод только тех слов сообщения, которые содержат не более чем n букв /// Пояснения: /// message.Replace(", ", ",").Replace(". ", ".") - если вдруг сообщение написано с разделителями, после которых идёт пробел /// Where(st => (st.Length <= n) - условие выборки /// </summary> /// <param name="n">Кол-во букв</param> /// <returns></returns> public string CheckWordsLength(int n) { return string.Join(" ", array.Where(st => st.Length <= n)); } /// <summary> /// Вывод только тех слов сообщения, которые содержат не более чем n букв при помощи регулярного выражения /// Пояснения: /// new Regex("[ ]{2, }").Replace - выбирает множественные пробелы, потом заменяем их на 1 пробел /// Cast<Match>().Select(m => m.Value) - преобразует MatchCollection в строковый массив /// </summary> /// <param name="n"></param> /// <returns></returns> public string RegexCheckWordsLength(int n) { return new Regex("\\b\\w{" +(++n) + ",}\\s?\\b").Replace(message, " "); } /// <summary> /// Удаление слов из сообщения, заканчивающихся на определенный символ /// </summary> /// <param name="symbol">Символ</param> /// <returns>Итоговое сообщение</returns> public string DeleteWords(string symbol) { return string.Join(" ", array.Except(message.Split(' ').Where(s => s.EndsWith(symbol)))).Replace(" ", " "); } /// <summary> /// Удаление слов из сообщения, заканчивающихся на определенный символ при помощи регулярного выражения /// </summary> /// <param name="symbol">Символ</param> /// <returns>Итоговое сообщение</returns> public string RegexDeleteWords(string symbol) { return new Regex("\\w*" + symbol + "\\s?\\b").Replace(message, ""); } /// <summary> /// Поиск самого длинного слова в сообщении /// </summary> /// <returns>Строка - самое длинное слово</returns> public string FindLongestWord() { //Способ №1 return array.OrderByDescending(s => s.Length).First(); // Способ №2 //return list.Aggregate("", (max, current) => max.Length > current.Length ? max : current); } /// <summary> /// Поиск всех самых длинных слов в сообщении. /// </summary> /// <returns>Строка - самые длинные слова сообщения</returns> public string FindAllLongestWords() { return string.Join(" ", list.Where(s => s.Length == list.Max(st => st.Length))); } } }<file_sep>SELECT COALESCE(i.point, o.point) point, (COALESCE(inc, 0) - COALESCE(out, 0)) res FROM ( SELECT point, SUM(inc) inc FROM Income_o GROUP BY point ) i FULL JOIN ( SELECT point, SUM(out) out FROM Outcome_o GROUP BY point ) o ON i.point = o.point;<file_sep>WITH q AS (SELECT CASE WHEN country LIKE 'Russia' THEN 1 ELSE 0 END val, country, class FROM Classes) SELECT TOP 1 WITH TIES country, class FROM q ORDER BY val DESC;<file_sep>WITH All_models AS ( SELECT model, price FROM PC UNION SELECT model, price FROM Laptop UNION SELECT model, price FROM Printer) SELECT TOP 1 WITH TIES model FROM All_models ORDER BY price DESC;<file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Lesson1 { class Task1 { public static void Go() { // name Console.ForegroundColor = ConsoleColor.Yellow; Console.WriteLine("Введите своё имя:"); Console.ForegroundColor = ConsoleColor.White; string name = Console.ReadLine(); // surname Console.ForegroundColor = ConsoleColor.Yellow; Console.WriteLine("Введите свою фамилию:"); Console.ForegroundColor = ConsoleColor.White; string surname = Console.ReadLine(); // age Console.ForegroundColor = ConsoleColor.Yellow; Console.WriteLine("Введите свой возраст:"); Console.ForegroundColor = ConsoleColor.White; int age = Additional.SetIntParametr(); // height Console.ForegroundColor = ConsoleColor.Yellow; Console.WriteLine("Введите свой рост (см):"); Console.ForegroundColor = ConsoleColor.White; int height = Additional.SetIntParametr(); // weight Console.ForegroundColor = ConsoleColor.Yellow; Console.WriteLine("Введите свой вес (кг):"); Console.ForegroundColor = ConsoleColor.White; int weight = Additional.SetIntParametr(); // output Console.WriteLine("\nВывод Склеиванием:"); Console.ForegroundColor = ConsoleColor.Yellow; Console.WriteLine("Приветствую, " + surname + " " + name + "!\nЭто программа \"Анкета\"!\nВаш возраст:\t" + age + "\nВаш рост:\t" + height + "\nВаш вес:\t" + weight); Console.ForegroundColor = ConsoleColor.White; Console.WriteLine("\nФорматированный вывод:"); Console.ForegroundColor = ConsoleColor.Cyan; Console.WriteLine("Приветствую, {0} {1}!\nЭто программа \"Анкета\"!\nВаш возраст:\t{2}\nВаш рост:\t{3} \nВаш вес:\t{4}", surname, name, age, height, weight); Console.ForegroundColor = ConsoleColor.White; Console.WriteLine("\nВывод со знаком $:"); Console.ForegroundColor = ConsoleColor.Red; Console.WriteLine($"Приветствую, {surname} {name}!\nЭто программа \"Анкета\"!\nВаш возраст:\t{age}\nВаш рост:\t{height} \nВаш вес:\t{weight}"); Console.ReadLine(); } } }<file_sep>SELECT DISTINCT maker FROM Product WHERE type = 'PC' EXCEPT SELECT maker FROM Product p1 WHERE type = 'PC' AND model NOT IN ( SELECT p2.model FROM Product p2 JOIN pc ON p2.model = pc.model WHERE p2.maker = p1.maker );<file_sep>SELECT name FROM Passenger p JOIN ( SELECT DISTINCT ID_psg FROM Pass_in_trip GROUP BY ID_psg, place HAVING COUNT(date) > 1 ) q ON q.ID_psg = p.ID_psg;<file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Lesson2 { class Program { static void Main(string[] args) { CommonMethods.CenterOutput(); bool exit = false; while (!exit) { CommonMethods.ColoredWriteLine("\nВыберите задание для выполнения:\n- 1\n- 2\n- 3\n- 4\n- 5\n- 6\n- 7\nДля выхода нажмите 0.", ConsoleColor.Magenta); int choice = CommonMethods.SetIntParametr(); switch (choice) { case 0: CommonMethods.ColoredWriteLine("Всего доброго!", ConsoleColor.Cyan); exit = true; break; #region Задание 1 case 1: CommonMethods.ColoredWriteLine(TasksText.Task1Text, ConsoleColor.Cyan); Task1.Go(); break; #endregion #region Задание 2 case 2: CommonMethods.ColoredWriteLine(TasksText.Task2Text, ConsoleColor.Cyan); Task2.Go(); break; #endregion #region Задание 3 case 3: CommonMethods.ColoredWriteLine(TasksText.Task3Text, ConsoleColor.Cyan); Task3.Go(); break; #endregion #region Задание 4 case 4: CommonMethods.ColoredWriteLine(TasksText.Task4Text, ConsoleColor.Cyan); Task4.Go(); break; #endregion #region Задание 5 case 5: CommonMethods.ColoredWriteLine(TasksText.Task5Text, ConsoleColor.Cyan); Task5.Go(); break; #endregion #region Задание 6 case 6: CommonMethods.ColoredWriteLine(TasksText.Task6Text, ConsoleColor.Cyan); Task6.Go(); break; #endregion #region Задание 7 case 7: CommonMethods.ColoredWriteLine(TasksText.Task7Text, ConsoleColor.Cyan); Task7.Go(); break; #endregion default: CommonMethods.ColoredWriteLine("Пункт не предусматривается системой!", ConsoleColor.Red); break; } } } } }<file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Lesson3 { /* * Исполнитель: * <NAME> * * Задание №1 * а) Дописать структуру Complex, добавив метод вычитания комплексных чисел. Продемонстрировать работу структуры; * б) Дописать класс Complex, добавив методы вычитания и произведения чисел. Проверить работу класса; */ class Task1 { #region Описание структуры ComplexStruct для работы с комплексными числами public struct ComplexStruct { double im; double re; public double Im { get { return im; } set { im = value; } } public double Re { get { return re; } set { re = value; } } /// <summary> /// Конструктор структуры ComplexStruct для инициализации экземпляра струтуры. /// </summary> /// <param name="im">Коэффициент мнимой единицы</param> /// <param name="re">Вещественная часть числа</param> public ComplexStruct(double im, double re) { this.im = im; this.re = re; } /// <summary> /// Метод сложения двух экземпляров структуры /// </summary> /// <param name="x">Второе слагаемое</param> /// <returns>Сумма двух экземпляров структуры</returns> public ComplexStruct Plus(ComplexStruct x) { return new ComplexStruct(this.im + x.im, this.re + x.re); } /// <summary> /// Метод умножения двух экземпляров структуры /// </summary> /// <param name="x">Множитель</param> /// <returns>Произведение двух экземпляров структуры</returns> public ComplexStruct Multi(ComplexStruct x) { return new ComplexStruct(this.im * x.im + this.re * x.im, this.re * x.im - this.im * x.re); } /// <summary> /// Метод вычитания двух экземпляров структуры /// </summary> /// <param name="x">Вычитаемое</param> /// <returns>Разница</returns> public ComplexStruct Subtraction(ComplexStruct x) { return new ComplexStruct(this.im - x.im, this.re - x.re); } /// <summary> /// Переопределение метода ToString() для структуры /// </summary> /// <returns>Строковое представление экземпляра структуры</returns> public override string ToString() { return re + ((im.ToString()[0] == '-') ? (" " + im.ToString()[0] + " " + ((im == 0) ? "" : (im.ToString().Substring(1)))) : (" + " + ((im==0) ? "" : im.ToString()))) + "i"; } } #endregion #region Описание класса ComplexClass для работы с комплексными числами public class ComplexClass { double im; double re; public double Im { get; set; } public double Re { get; set; } /// <summary> /// Конструктор класса ComplexClass для инициализации экземпляра класса. /// </summary> /// <param name="im">Коэффициент мнимой единицы</param> /// <param name="re">Вещественная часть числа</param> public ComplexClass(double im, double re) { this.im = im; this.re = re; } /// <summary> /// Метод сложения двух экземпляров класса /// </summary> /// <param name="x">Второе слагаемое</param> /// <returns>Сумма двух экземпляров класса</returns> public ComplexClass Plus(ComplexClass x) { return new ComplexClass(this.im + x.im, this.re + x.re); } /// <summary> /// Метод умножения двух экземпляров класса /// </summary> /// <param name="x">Множитель</param> /// <returns>Произведение двух экземпляров класса</returns> public ComplexClass Multi(ComplexClass x) { return new ComplexClass(this.im * x.im + this.re * x.im, this.re * x.im - this.im * x.re); } /// <summary> /// Метод вычитания двух экземпляров класса /// </summary> /// <param name="x">Вычитаемое</param> /// <returns>Разница</returns> public ComplexClass Subtraction(ComplexClass x) { return new ComplexClass(this.im - x.im, this.re - x.re); } /// <summary> /// Переопределение метода ToString() для класса /// </summary> /// <returns>Строковое представление экземпляра класса</returns> public override string ToString() { return re + ((im.ToString()[0] == '-') ? (" " + im.ToString()[0] + " " + ((im == 0) ? "" : (im.ToString().Substring(1)))) : (" + " + ((im == 0) ? "" : im.ToString()))) + "i"; } } #endregion public static void Go() { CommonMethods.ColoredWriteLine(TasksDescription.Task1Text, ConsoleColor.Cyan); #region Демонстрация работы структуры комплексных чисел CommonMethods.ColoredWriteLine("Демонстрация работы структуры.\nВведите вещественную часть первого комплексного числа:", ConsoleColor.Yellow); double cs1re = CommonMethods.SetDoubleParametr(); CommonMethods.ColoredWriteLine("Введите коэффициент мнимой единицы первого комплексного числа:", ConsoleColor.Yellow); double cs1im = CommonMethods.SetDoubleParametr(); ComplexStruct cs1 = new ComplexStruct(cs1im, cs1re); CommonMethods.ColoredWriteLine("Вы ввели комплексное число:", ConsoleColor.Yellow); CommonMethods.ColoredWriteLine(cs1.ToString(), ConsoleColor.White); CommonMethods.ColoredWriteLine("Введите вещественную часть второго комплексного числа:", ConsoleColor.Yellow); double cs2re = CommonMethods.SetDoubleParametr(); CommonMethods.ColoredWriteLine("Введите коэффициент мнимой единицы второго комплексного числа:", ConsoleColor.Yellow); double cs2im = CommonMethods.SetDoubleParametr(); ComplexStruct cs2 = new ComplexStruct(cs2im, cs2re); CommonMethods.ColoredWriteLine("Вы ввели комплексное число:", ConsoleColor.Yellow); CommonMethods.ColoredWriteLine(cs2.ToString(), ConsoleColor.White); CommonMethods.ColoredWriteLine("Сумма двух комплексных чисел:", ConsoleColor.Yellow); CommonMethods.ColoredWriteLine(cs1.Plus(cs2).ToString(), ConsoleColor.Cyan); CommonMethods.ColoredWriteLine("Разница двух комплексных чисел:", ConsoleColor.Yellow); CommonMethods.ColoredWriteLine(cs1.Subtraction(cs2).ToString(), ConsoleColor.Cyan); CommonMethods.ColoredWriteLine("Произведение двух комплексных чисел:", ConsoleColor.Yellow); CommonMethods.ColoredWriteLine(cs1.Multi(cs2).ToString(), ConsoleColor.Cyan); #endregion CommonMethods.ColoredWriteLine("Провести те же самые действия для демонстрации работы класса комплексных чисел?" + "\nВведите любой символ для подтверждения, либо нажмите Enter для отмены.", ConsoleColor.Yellow); if (Console.ReadLine() != "") { #region Демонстрация работы класса комплексных чисел CommonMethods.ColoredWriteLine("Демонстрация работы класса.\nВведите вещественную часть первого комплексного числа:", ConsoleColor.Yellow); double cc1re = CommonMethods.SetDoubleParametr(); CommonMethods.ColoredWriteLine("Введите коэффициент мнимой единицы первого комплексного числа:", ConsoleColor.Yellow); double cс1im = CommonMethods.SetDoubleParametr(); ComplexClass cc1 = new ComplexClass(cс1im, cc1re); CommonMethods.ColoredWriteLine("Вы ввели комплексное число:", ConsoleColor.Yellow); CommonMethods.ColoredWriteLine(cc1.ToString(), ConsoleColor.White); CommonMethods.ColoredWriteLine("Введите вещественную часть второго комплексного числа:", ConsoleColor.Yellow); double cc2re = CommonMethods.SetDoubleParametr(); CommonMethods.ColoredWriteLine("Введите коэффициент мнимой единицы второго комплексного числа:", ConsoleColor.Yellow); double cc2im = CommonMethods.SetDoubleParametr(); ComplexClass cc2 = new ComplexClass(cc2im, cc2re); CommonMethods.ColoredWriteLine("Вы ввели комплексное число:", ConsoleColor.Yellow); CommonMethods.ColoredWriteLine(cc2.ToString(), ConsoleColor.White); CommonMethods.ColoredWriteLine("Сумма двух комплексных чисел:", ConsoleColor.Yellow); CommonMethods.ColoredWriteLine(cc1.Plus(cc2).ToString(), ConsoleColor.Cyan); CommonMethods.ColoredWriteLine("Разница двух комплексных чисел:", ConsoleColor.Yellow); CommonMethods.ColoredWriteLine(cc1.Subtraction(cc2).ToString(), ConsoleColor.Cyan); CommonMethods.ColoredWriteLine("Произведение двух комплексных чисел:", ConsoleColor.Yellow); CommonMethods.ColoredWriteLine(cc1.Multi(cc2).ToString(), ConsoleColor.Cyan); #endregion } } } }<file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Lesson2 { /* * Исполнитель: * <NAME> * * Задание №2 * Написать метод подсчета количества цифр числа. */ class Task2 { /// <summary> /// Метод запрашивает любое число и выводит в консоль количество цифр, содержащихся в нем /// </summary> public static void Go() { CommonMethods.ColoredWriteLine("Введите число:", ConsoleColor.Yellow); double a = CommonMethods.SetDoubleParametr(); CommonMethods.ColoredWriteLine($"Кол-во цифр в числе {a}:\n{a.ToString().Replace(",", "").Length}", ConsoleColor.Cyan); } } } <file_sep>SELECT AVG(price) price FROM ( SELECT p.model, price FROM PC p UNION ALL SELECT l.model, price FROM Laptop l ) a JOIN Product pr ON pr.model = a.model AND pr.maker = 'A';<file_sep>SELECT name FROM Battles WHERE CAST(DATEPART(YEAR, date) AS VARCHAR(10)) NOT IN ( SELECT CAST(launched AS VARCHAR(10)) FROM Ships WHERE launched IS NOT NULL );<file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Lesson5 { class TextConstants { public const string TASK_LIST = "\nВыберите задание для выполнения:\n- 1\n- 2\n- 3\n- 4\nДля выхода нажмите 0."; public const string TASK1_DESCR = "Создать программу, которая будет проверять корректность ввода логина." + "Корректным логином будет строка от 2-х до 10-ти символов, содержащая только буквы или цифры, и при этом цифра не может быть первой." + "\nа) без использования регулярных выражений;" + "\nб) **с использованием регулярных выражений."; public const string TASK2_DESCR = "Разработать методы для решения следующих задач. Дано сообщение:" + "\nа) Вывести только те слова сообщения, которые содержат не более чем n букв;" + "\nб) Удалить из сообщения все слова, которые заканчиваются на заданный символ;" + "\nв) Найти самое длинное слово сообщения;" + "\nг) Найти все самые длинные слова сообщения."; public const string TASK3_DESCR = "*Для двух строк написать метод, определяющий, является ли одна строка перестановкой другой. Регистр можно не учитывать." + "\nа) с использованием методов C#" + "\nб) *разработав собственный алгоритм" + "\nНапример: badc являются перестановкой abcd"; public const string TASK4_DESCR = "4. *Задача ЕГЭ." + "\nНа вход программе подаются сведения о сдаче экзаменов учениками 9-х классов некоторой средней" + "\nшколы.В первой строке сообщается количество учеников N, которое не меньше 10, но не" + "\nпревосходит 100, каждая из следующих N строк имеет следующий формат:" + "\n<Фамилия>​​<Имя>​​<оценки>," + "\nгде<Фамилия> – строка, состоящая не более чем из 20 символов, <Имя> – строка, состоящая не" + "\nболее чем из 15 символов, <оценки> – через пробел три целых числа, соответствующие оценкам по" + "\nпятибалльной системе. <Фамилия> и<Имя>, а также<Имя> и<оценки> разделены одним пробелом." + "\nПример входной строки:" + "\n<NAME> 4 5 3" + "\nТребуется написать как можно более эффективную программу, которая будет выводить на экран" + "\nфамилии и имена трех худших по среднему баллу учеников. Если среди остальных есть ученики," + "\nнабравшие тот же средний балл, что и один из трех худших, то следует вывести и их фамилии иимена."; public const string ENTER_LOGIN = "Логин должен содержать от двух до десяти символов, только буквы или цифры и цифра не может быть первой." + "\nВведите логин:"; public const string LOGIN_CORRECT = "Логин введён корректно!"; public const string LOGIN_NOT_CORRECT = "Логин введён не корректно!"; public const string TRYS_COUNT = "Попыток осталось: "; public const string TRYS_COUNT_END = "Попробуйте позже!"; public const string ENTER_MESSAGE = "Введите сообщение:"; public const string ENTER_LETTERS_COUNT = "Введите кол-во букв, которое максимально может содержаться в слове сообщения:"; public const string ENTER_ENDING_SYMBOL = "Удалить из сообщения все слова, которе заканчиваются на заданный символ.\nВведите символ:"; public const string LONGEST_WORD = "Самое длинное слово сообщения:"; public const string LONGEST_WORDS = "Самые длинные слова сообщения:"; public const string ENTER_LINE1 = "Введите строку №1:"; public const string ENTER_LINE2 = "Введите строку №2:"; public const string STR_IS_PERM = "Строка является перестановкой второй строки!"; public const string STR_IS_NOT_PERM = "Строка не является перестановкой второй строки!"; public const string FILE_NAME = "..\\..\\Data\\Task4Data.txt"; public const string EXEC_TIME = "Время выполнения:"; } } <file_sep>-- Найдите производителей самых дешевых цветных принтеров. Вывести: maker, price SELECT DISTINCT TOP 1 WITH TIES pr.maker, price FROM Printer p, Product pr WHERE pr.model = p.model AND price IS NOT NULL AND p.color = 'y' ORDER BY price; SELECT DISTINCT TOP 1 WITH TIES pr.maker, price FROM ( SELECT model, price FROM Printer WHERE color = 'y' ) p, Product pr WHERE pr.model = p.model AND price IS NOT NULL ORDER BY price;<file_sep>-- Найдите модели ПК-блокнотов, скорость которых меньше скорости любого из ПК. -- Вывести: type, model, speed SELECT DISTINCT 'laptop' type, l.model, speed FROM Laptop l WHERE l.speed < ( SELECT MIN(speed) FROM PC )<file_sep>-- Для каждого производителя, имеющего модели в таблице Laptop, найдите средний размер экрана выпускаемых им ПК-блокнотов. -- Вывести: maker, средний размер экрана. SELECT maker, AVG(screen) size FROM Product pr JOIN Laptop l ON pr.Model = l.model GROUP BY maker;<file_sep>-- Для каждого производителя, выпускающего ПК-блокноты c объёмом жесткого диска не менее 10 Гбайт, -- найти скорости таких ПК-блокнотов. Вывод: производитель, скорость. SELECT DISTINCT pr.maker, l.speed FROM Laptop l JOIN Product pr ON pr.Model = l.model AND l.hd >= 10<file_sep>using System.Collections.Generic; using System.Drawing; namespace Asteroids { class Settings { #region Настройки игрового поля /// <summary> /// Ширина игрового поля /// </summary> public static int FieldWidth { get; set; } = 1000; /// <summary> /// Максимальная ширина игрового поля /// </summary> public static int FieldMaxWidth { get; set; } = 1000; /// <summary> /// Высота игрового поля /// </summary> public static int FieldMaxHeight { get; set; } = 667; /// <summary> /// Максимальная высота игрового поля /// </summary> public static int FieldHeight { get; set; } = 667; /// <summary> /// Размер кнопок /// </summary> public static Size ButtonSize { get; set; } = new Size(200, 50); /// <summary> /// Высота между кнопками /// </summary> public static int HeightBetweenButtons { get; } = 40; #endregion #region Настройки элементов игры /// <summary> /// Уровни сложности /// </summary> public static int MaxDiffLevels { get; } = 2; /// <summary> /// Минимальный размер звезды /// </summary> public static int MinStarSize { get; set; } = 1; /// <summary> /// Максимальный размер звезды /// </summary> public static int MaxStarSize { get; set; } = 1; /// <summary> /// Количество кораблей Империи на игровом поле /// </summary> public static int[] EmpireShipsCount { get; set; } = new int[] { 12, 15, 20 }; /// <summary> /// Усредненное значение высоты корабля Империи /// </summary> public static int EmpireShipAvgHeight { get; set; } = 75; /// <summary> /// Максимальный уровень урона корабля Империи /// </summary> public static int[] EmpireShipMaxDamage { get; set; } = new int[] { 40, 50, 60 }; /// <summary> /// Минимальный уровень урона у корабля Империи /// </summary> public static int[] EmpireShipMinDamage { get; set; } = new int[] { 20, 30, 40 }; /// <summary> /// Индекс изображения пули корабля Империи /// </summary> public static int EmpireShipBulletIndex { get; set; } = 1; /// <summary> /// Количество звезд на поле /// </summary> public static int StarsCount { get; } = 40; /// <summary> /// Стартовая позиция корабля /// </summary> public static Point SpaceShipStartPos { get; set; } = new Point(50, 300); /// <summary> /// Уровень жизни для Ship /// </summary> public static int SpaceShipMaxHealth { get; set; } = 100; /// <summary> /// Энергия корабля для выстрела /// </summary> public static int SpaceShipMaxEnergy { get; set; } = 100; /// <summary> /// Сдвиг корабля при нажатии на клавишу управления движением /// </summary> public static int SpaceShipStep { get; set; } = 7; /// <summary> /// Интервал таймера класса Game /// </summary> public static int TimerInterval { get; set; } = 100; /// <summary> /// Позиция Хелс бара /// </summary> public static Point HPBarPos { get; set; } = new Point(10, 10); /// <summary> /// Размер хелс бара /// </summary> public static Size HPBarSize { get; set; } = new Size(200, 12); /// <summary> /// Позиция энерджи бара /// </summary> public static Point EnergyBarPos { get; set; } = new Point(10, HPBarPos.Y + HPBarSize.Height + 20); /// <summary> /// Размер Energy бара /// </summary> public static Size EnergyBarSize { get; set; } = new Size(200, 12); /// <summary> /// Количество энергии, затраченной на выстрел /// </summary> public static int[] EnergyCostShoot { get; set; } = new int[] { 2, 4, 6 }; /// <summary> /// Шанс восстановления энергии колеблется в зависимости от уровня сложности /// </summary> public static int[] EnergyRecoveryChance { get; set; } = new int[] { 3, 6, 9 }; /// <summary> /// Шаг изменения позиции астероидов по уровням сложности /// </summary> public static Dictionary<int, int[]> AsteroidsDir { get; } = new Dictionary<int, int[]> { [0] = new int[] { -10, -5 }, [1] = new int[] { -10, 10 }, [2] = new int[] { 5, 15 } }; /// <summary> /// Скорость перемещения аптечек в зависимости от сложности /// </summary> public static int[] KitDir { get; } = new int[] { 3, 5, 7}; /// <summary> /// Кол-во аптечек на уровень, в зависимости от сложности /// </summary> public static int[] KitsCount { get; } = new int[] { 3, 2, 1 }; /// <summary> /// Шанс появления аптечки /// </summary> public static int KitAppearence { get; } = 150; #endregion #region Описания Элементов формы и исключительных ситуаций /// <summary> /// Шрифт кнопки приветсвия /// </summary> public static string MainFont { get; set; } = "Verdana"; /// <summary> /// Текст кнопки старта игры /// </summary> public static string GameStart { get; set; } = "Начать игру"; /// <summary> /// Перейти на новый уровень /// </summary> public static string GameNextLvl { get; set; } = "Новый уровень"; /// <summary> /// Сыграть еще раз /// </summary> public static string GamePlayOneMore { get; set; } = "Сыграть еще раз"; /// <summary> /// Текст сообщения при старте /// </summary> public static string GameRules { get; set; } = "Выстрел - пробел;\nУправление кораблём - стрелки."; /// <summary> /// Текст кнопки выход /// </summary> public static string GameEnd { get; set; } = "Выход"; /// <summary> /// Получение имени пользователя /// </summary> public static string UserName { get; set; } = (!System.Security.Principal.WindowsIdentity.GetCurrent().Name.Contains("\\") ? System.Security.Principal.WindowsIdentity.GetCurrent().Name : System.Security.Principal.WindowsIdentity.GetCurrent().Name. Substring(System.Security.Principal.WindowsIdentity.GetCurrent().Name.IndexOf("\\") + 1)); /// <summary> /// Текст ошибки установки некорректных значений размера экрана /// </summary> public static string WindowSizeException { get; } = "Некорректно задан размер экрана!"; /// <summary> /// Сообщение о проигрыше в диалоговом окне: /// Увы, Ваш корабль сбит! /// Выйти? /// </summary> public static string LooseMessage { get; } = "Увы, Ваш корабль сбит!\nВыйти?"; /// <summary> /// Заголовок для сообщения о проигрыше: /// Проиграли! /// </summary> public static string LooseMessageHeader { get; } = "Проиграли!"; /// <summary> /// Переход на новый уровень /// Вы сбили все астероиды! Перейти на новый уровень? /// </summary> public static string NewLevel { get; } = "Вы сбили все астероиды!\nПерейти на новый уровень?"; /// <summary> /// Поздравительное сообщение /// </summary> public static string Greetings { get; } = "Поздравляем!"; /// <summary> /// Конец игры /// Вы успешно завершили игру! Сыграть еще раз? /// </summary> public static string GameComplete { get; } = "Вы успешно завершили игру!\nСыграть еще раз?"; /// <summary> /// Конец игры /// Вы успешно завершили игру! Сыграть еще раз? /// </summary> public static string RestartOrQuit { get; } = "Сыграть еще раз или выйти?\nСыграть еще раз?"; #endregion } } <file_sep>SELECT ROW_NUMBER() OVER(ORDER BY models_qty DESC, maker, model), maker, model FROM ( SELECT models_qty, p.maker, p.model FROM Product p JOIN ( SELECT maker, COUNT(model) models_qty FROM Product GROUP BY maker ) q ON q.Maker = p.Maker ) sub; -- Variant 2 SELECT ROW_NUMBER() OVER(ORDER BY qty DESC, p.maker, p.model) [no], p.maker, p.model FROM Product p JOIN ( SELECT COUNT(model) qty, maker FROM Product GROUP BY maker ) q ON q.Maker = p.Maker;
2385872312435a255989b1af0ecab1ac86766137
[ "C#", "SQL" ]
122
SQL
fallingsappy/Edu
e6b92af471165d6b39c56f5c94d08d8c666cc76f
182558c9e373928d7b3655a974eca9d06d8e3bb0
refs/heads/master
<file_sep><?php include "_header.php"; require_once "_functions.php"; check_auth(); db_connect(); if (isset($_GET['email'])) $sql = "SELECT id, email, firstname, lastname, status, relationship_status, profile_image_url, location FROM users WHERE email = ?"; else $sql = "SELECT id, email, firstname, lastname, status, relationship_status, profile_image_url, location FROM users WHERE id = ?"; $statement = $connection->prepare($sql); if (isset($_GET['email'])) $statement->bind_param('s', $_GET['email']); else $statement->bind_param('s', $_SESSION['user_id']); $statement->execute(); $statement->store_result(); $statement->bind_result($id, $email, $firstname, $lastname, $status, $relationship_status, $profile_image_url, $location); $statement->fetch(); if (!isset($id)) // In case the email isn't in the db redirect_to("/home.php"); ?> <!-- Main --> <main class="container"> <div class="row"> <div class="col-md-3"> <!-- edit profile --> <div class="panel panel-default"> <div class="panel-body"> <?php if (!isset($_GET['email'])) { ?> <h4>Update your profile</h4> <form method="post" action="php/edit-profile.php"> <label>Status: </label> <div class="form-group"> <input class="form-control" type="text" name="status" placeholder="Status" value="<?php echo $status; ?>"> </div> <label>Location: </label> <div class="form-group"> <input class="form-control" type="text" name="location" placeholder="Location" value="<?php echo $location; ?>"> </div> <label>Relationship Status: </label> <div class="form-group"> <input class="form-control" type="text" name="relationship_status" placeholder="Relationship Status" value="<?php echo isset($relationship_status) ? $relationship_status : ' '; ?>"> </div> <label>Profile Photo (URL): </label> <div class="form-group"> <input class="form-control" type="text" name="profile_image_url" placeholder="Relationship Status" value="<?php echo $profile_image_url; ?>"> </div> <div class="form-group"> <input class="btn btn-primary" type="submit" value="Save"> </div> </form> <?php } ?> <?php if (isset($_GET['email'])) { ?> <h4>Send <?php echo $firstname . " " . $lastname; ?> a friend request</h4> <form method="get" action="php/add-friend.php"> <input class="form-control" type="hidden" name="email" value="<?php echo $email;?>"> <div class="input-group"> <span class="input-group-btn"> <button class="btn btn-primary" type="submit" name="post">Send</button> </span> </div> </form> <?php } ?> </div> </div> </div> <!-- ./Edit profile --> <div class="col-md-6"> <!-- User profile --> <div class="media"> <div class="media-left"> <img src="<?php echo $profile_image_url; ?>" class="media-object" style="width: auto; height: 128px;"> </div> <div class="media-body"> <h2 class="media-heading"><?php echo $firstname . " " . $lastname; ?></h2> <p>Status: <?php echo $status; ?> <br> Relationship Status: <?php echo $relationship_status; ?> <br> Location: <?php echo $location; ?> </p> </div> </div> <!-- User profile --> <hr> <!-- Timeline --> <div> <form method="post" action="php/create-post.php?from=profile"> <div class="input-group"> <input class="form-control" type="text" name="content" placeholder="Make a post…"> <span class="input-group-btn"> <button class="btn btn-primary" type="submit" name="post">Post</button> </span> </div> </form> <br> <!-- Post --> <?php $sql = "SELECT * FROM posts WHERE posts.user_id = {$id} ORDER BY created_at DESC"; $result = $connection->query($sql); if ($result->num_rows > 0) { while ($post = $result->fetch_assoc()) { ?> <div class="panel panel-default"> <div class="panel-body"> <p style="width: auto; height-max: 400px;"><?php echo $post['content']; ?></p> </div> <div class="panel-footer"> <span>Posted <?php echo $post['created_at']; ?> by <?php echo $post['firstname']; ?></span> <span class="pull-right"><a class="text-danger" href="php/delete-post.php?id=<?php echo $post['id']; ?>&from=profile">[delete]</a></span> </div> </div> <?php } } else { ?> <p class="text-center">No posts yet!</p> <?php } ?> <!-- ./Post --> </div> <!-- ./Timeline --> </div> <div class="col-md-3"> <!-- Add friend --> <div class="panel panel-default"> <div class="panel-body"> <h4>Send friend request</h4> <form method="get" action="php/add-friend.php"> <div class="input-group"> <input class="form-control" type="text" name="email" placeholder="Enter e-mail"> <span class="input-group-btn"> <button class="btn btn-primary" type="submit">Send</button> </span> </div> </form> </div> </div> <!-- ./Add friend --> <!-- Friends --> <div class="panel panel-default"> <div class="panel-body"> <h4>Friends</h4> <?php $sql = "SELECT * FROM friends WHERE friend_id = {$_SESSION['user_id']}"; $result = $connection->query($sql); if ($result->num_rows > 0) { ?> <ul><?php while ($friend = $result->fetch_assoc()) { ?> <li> <?php $u_sql = "SELECT * FROM users WHERE id = {$friend['user_id']} LIMIT 1"; $u_result = $connection->query($u_sql); $fr_user = $u_result->fetch_assoc(); ?> <a href="profile.php?email=<?php echo $fr_user['email']; ?>"><?php echo $fr_user['firstname'] . " " . $fr_user['lastname']; ?></a> <a class="text-danger" href="php/remove-request.php?uid=<?php echo $fr_user['id']; ?>">[unfriend]</a> </li> <?php } ?></ul><?php } else { ?> <p class="text-center">No pending friend requests!</p> <?php } ?> </div> </div> <!-- ./Friends --> <div class="panel panel-default"> <div class="panel-body"> <h4>Pending Friend Requests</h4> <?php $sql = "SELECT * FROM friend_requests WHERE friend_id = {$_SESSION['user_id']}"; $result = $connection->query($sql); if ($result->num_rows > 0) { ?> <ul><?php while ($friend = $result->fetch_assoc()) { ?> <li> <?php $u_sql = "SELECT * FROM users WHERE id = {$friend['user_id']} LIMIT 1"; $u_result = $connection->query($u_sql); $fr_user = $u_result->fetch_assoc(); ?> <a href="profile.php?email=<?php echo $fr_user['email']; ?>"><?php echo $fr_user['firstname'] . " " . $fr_user['lastname']; ?></a> <a class="text-success" href="php/accept-request.php?uid=<?php echo $fr_user['id']; ?>">[accept]</a> <a class="text-danger" href="php/remove-request.php?uid=<?php echo $fr_user['id']; ?>">[decline]</a> </li> <?php } ?></ul><?php } else { ?> <p class="text-center">No pending friend requests!</p> <?php } ?> </div> </div> </div> </div> </main> <!-- ./Main --> <?php include "_footer.php" ?> <script type="text/javascript" src="js/bootstrap.min.js"></script> <script type="text/javascript" src="js/script.js"></script> </body> </html> <file_sep>-- phpMyAdmin SQL Dump -- version 4.9.5deb2 -- https://www.phpmyadmin.net/ -- -- Host: localhost:3306 -- Generation Time: Feb 04, 2021 at 07:00 PM -- Server version: 8.0.23-0ubuntu0.20.04.1 -- PHP Version: 7.4.3 SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO"; SET AUTOCOMMIT = 0; START TRANSACTION; SET time_zone = "+00:00"; /*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */; /*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */; /*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */; /*!40101 SET NAMES utf8mb4 */; -- -- Database: `theFacebookDB` -- -- -------------------------------------------------------- -- -- Table structure for table `friends` -- CREATE TABLE `friends` ( `id` int NOT NULL, `user_id` int NOT NULL, `friend_id` int NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=latin1; -- -- Dumping data for table `friends` -- INSERT INTO `friends` (`id`, `user_id`, `friend_id`) VALUES (1, 4, 1), (3, 1, 4), (4, 1, 3), (5, 3, 1); -- -------------------------------------------------------- -- -- Table structure for table `friend_requests` -- CREATE TABLE `friend_requests` ( `id` int NOT NULL, `user_id` int NOT NULL, `friend_id` int NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=latin1; -- -------------------------------------------------------- -- -- Table structure for table `posts` -- CREATE TABLE `posts` ( `id` int NOT NULL, `content` text NOT NULL, `user_id` int NOT NULL, `firstname` varchar(35) NOT NULL, `created_at` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP ) ENGINE=InnoDB DEFAULT CHARSET=latin1; -- -- Dumping data for table `posts` -- INSERT INTO `posts` (`id`, `content`, `user_id`, `firstname`, `created_at`) VALUES (5, 'Remember, remember! The fifth of November, The Gunpowder treason and plot; I know of no reason Why the Gunpowder treason Should ever be forgot!', 1, 'Andrej', '2021-02-04 12:51:58'), (12, '<img src=\"https://cutt.ly/4kjZ0cN\" style=\"height: auto; width: 58vh\">', 1, 'Andrej', '2021-02-04 14:43:11'); -- -------------------------------------------------------- -- -- Table structure for table `users` -- CREATE TABLE `users` ( `id` int NOT NULL, `email` varchar(60) CHARACTER SET latin1 COLLATE latin1_swedish_ci NOT NULL, `firstname` varchar(50) NOT NULL, `lastname` varchar(50) NOT NULL, `password` varchar(255) NOT NULL, `status` varchar(150) CHARACTER SET latin1 COLLATE latin1_swedish_ci DEFAULT NULL, `relationship_status` varchar(255) CHARACTER SET latin1 COLLATE latin1_swedish_ci DEFAULT NULL, `profile_image_url` varchar(255) CHARACTER SET latin1 COLLATE latin1_swedish_ci NOT NULL DEFAULT 'https://www.improvutopia.com/wp-content/uploads/2016/02/empty.png.jpeg', `location` varchar(30) NOT NULL, `is_friend` tinyint NOT NULL DEFAULT '0' ) ENGINE=InnoDB DEFAULT CHARSET=latin1; -- -- Dumping data for table `users` -- INSERT INTO `users` (`id`, `email`, `firstname`, `lastname`, `password`, `status`, `relationship_status`, `profile_image_url`, `location`, `is_friend`) VALUES (1, '<EMAIL>', 'Andrej', 'Ilievski', '$2y$10$aYYdkOwdVXKl5rmTQlg12.2Xe/EEqrg5R7sxINkNZNlhOauSPXDKC', 'Full stack development like a boss', ' Single', 'https://cutt.ly/HkjZyZG', 'Harvard', 0), (2, '<EMAIL>', 'Mark', 'Zuckerberg', '$2y$10$aYYdkOwdVXKl5rmTQlg12.2Xe/EEqrg5R7sxINkNZNlhOauSPXDKC', NULL, NULL, 'https://www.improvutopia.com/wp-content/uploads/2016/02/empty.png.jpeg', 'Harvard', 0), (3, '<EMAIL>', 'Eduardo', 'Saverin', '$2y$10$aYYdkOwdVXKl5rmTQlg12.2Xe/EEqrg5R7sxINkNZNlhOauSPXDKC', NULL, NULL, 'https://www.improvutopia.com/wp-content/uploads/2016/02/empty.png.jpeg', 'Harvard', 0), (4, '<EMAIL>', 'David', 'Smith', '$2y$10$aYYdkOwdVXKl5rmTQlg12.2Xe/EEqrg5R7sxINkNZNlhOauSPXDKC', NULL, NULL, 'https://www.improvutopia.com/wp-content/uploads/2016/02/empty.png.jpeg', 'Harvard', 0); -- -- Indexes for dumped tables -- -- -- Indexes for table `friends` -- ALTER TABLE `friends` ADD PRIMARY KEY (`id`); -- -- Indexes for table `friend_requests` -- ALTER TABLE `friend_requests` ADD PRIMARY KEY (`id`); -- -- Indexes for table `posts` -- ALTER TABLE `posts` ADD PRIMARY KEY (`id`); -- -- Indexes for table `users` -- ALTER TABLE `users` ADD PRIMARY KEY (`id`); -- -- AUTO_INCREMENT for dumped tables -- -- -- AUTO_INCREMENT for table `friends` -- ALTER TABLE `friends` MODIFY `id` int NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=6; -- -- AUTO_INCREMENT for table `friend_requests` -- ALTER TABLE `friend_requests` MODIFY `id` int NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=4; -- -- AUTO_INCREMENT for table `posts` -- ALTER TABLE `posts` MODIFY `id` int NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=14; -- -- AUTO_INCREMENT for table `users` -- ALTER TABLE `users` MODIFY `id` int NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=5; COMMIT; /*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */; /*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */; /*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */; <file_sep><?php require_once "../_functions.php"; db_connect(); $sql = "DELETE FROM posts WHERE id = ?"; $statement = $connection->prepare($sql); $statement->bind_param('i', $_GET['id']); if ($statement->execute()) { if ($_GET['from'] === 'profile') redirect_to("/profile.php"); else redirect_to("/home.php"); } else { echo "Error: " . $connection->error; } <file_sep><?php require_once "../_functions.php"; db_connect(); $sql = "INSERT INTO friend_requests (user_id, friend_id) VALUES (?, ?)"; // If the redirection happened from the button to the left of a person, use that // If the redirection happened from the email input, use the function to find the desired ID // TODO: Show "you're already friends" if the person is already a friend if (isset($_GET['email'])) { $targetID = $connection->query("SELECT `id` FROM users WHERE email='" . $_GET['email'] . "'")->fetch_object()->id; } else $targetID = $_GET['uid']; if (!isset($targetID)) // In case the user entered an email that doesn't exist in the DB redirect_to("/home.php"); $statement = $connection->prepare($sql); $statement->bind_param('ii', $_SESSION['user_id'], $targetID); if ($statement->execute()) redirect_to("/home.php?request_sent=true"); else echo "Error: " . $connection->error; <file_sep><?php require_once "../_functions.php"; session_destroy(); redirect_to("/index.php"); <file_sep><?php session_start(); function db_connect() { global $connection; $db_server = "localhost"; $username = "mrandrej"; $password = "<PASSWORD>"; $db_name = "theFacebookDB"; $connection = new mysqli($db_server, $username, $password, $db_name); if ($connection->connect_error) die("Error: " . $connection->connect_error); } function redirect_to($url) { header("Location: " . $url); exit(); } function is_auth() { return isset($_SESSION['user_id']); } function check_auth() { if (!is_auth()) redirect_to("/index.php?logged_in=false"); } <file_sep><?php require_once "../_functions.php"; db_connect(); $sql = "INSERT INTO friends (user_id, friend_id) VALUES (?, ?), (?, ?)"; $statement = $connection->prepare($sql); $statement->bind_param('iiii', $_SESSION['user_id'], $_GET['uid'], $_GET['uid'], $_SESSION['user_id']); if ($statement->execute()) redirect_to("/php/remove-request.php?uid=" . $_GET['uid']); else echo "Error: " . $connection->error; <file_sep><?php require_once "../_functions.php"; db_connect(); $sql = "INSERT INTO posts (content, user_id, firstname) VALUES (?, ?, ?)"; $statement = $connection->prepare($sql); $statement->bind_param('sis', $_POST['content'], $_SESSION['user_id'], $_SESSION['firstname']); if ($statement->execute()) { if ($_GET['from'] === 'profile') redirect_to("/profile.php"); else redirect_to("/home.php"); } else { echo "Error: " . $connection->error; } <file_sep><?php require_once "../_functions.php"; db_connect(); $sql = "DELETE FROM friends WHERE (user_id = ? AND friend_id = ?) OR (user_id = ? AND friend_id = ?)"; // Honestly I can't decide whether a PDO connection is better, I like this more $statement = $connection->prepare($sql); $statement->bind_param('iiii', $_GET['uid'], $_SESSION['user_id'], $_SESSION['user_id'], $_GET['uid']); if ($statement->execute()) redirect_to("/profile.php?email=" . $_SESSION['user_email']); else echo "Error: " . $connection->error; <file_sep><?php require_once "_functions.php"; db_connect(); ?> <!DOCTYPE html> <html> <head> <title>[thefacebook]</title> <link rel="stylesheet" type="text/css" href="css/bootstrap.min.css"> <link rel="stylesheet" type="text/css" href="css/style.css"> <link rel="icon" type="image/png" href="/img/favicon.png"/> </head> <body> <!-- Nav --> <nav class="navbar navbar-default"> <div class="container-fluid"> <div class="navbar-header"> <a class="navbar-brand" href="index.php"><strong>[thefacebook]</strong></a> </div> </div> </nav> <!-- ./Nav --> <!-- Main --> <main class="container"> <h1 class="text-center">Welcome to <strong>[thefacebook]</strong> <br><br></h1> <?php if (isset($_GET['registered'])): ?> <div class="alert alert-success"> <p>Account created successfully! Use your email and password to login.</p> </div> <?php endif; ?> <div class="row"> <div class="col-md-6"><br> <h4>Login to start enjoying unlimited fun!</h4> <!-- Login form --> <form method="post" action="php/login.php"> <div class="form-group"> <input class="form-control" type="text" name="email" placeholder="E-mail"> </div> <div class="form-group"> <input class="form-control" type="<PASSWORD>" name="password" placeholder="<PASSWORD>"> </div> <div class="form-group"> <input class="btn btn-primary" type="submit" name="login" value="Login"> </div> </form> <!-- ./Login form --> </div> <br> <div class="col-md-6"> <h4>Don't have an account yet? Register!</h4> <!-- TODO: Copy the style of the original TheFacebook index page --> <!-- Register form --> <form method="post" action="php/register.php"> <div class="form-group"> <input class="form-control" type="text" name="email" placeholder="E-mail"> </div> <div class="form-group"> <input class="form-control" type="text" name="firstname" placeholder="<NAME>"> </div> <div class="form-group"> <input class="form-control" type="text" name="lastname" placeholder="<NAME>"> </div> <div class="form-group"> <input class="form-control" type="text" name="location" placeholder="Location"> </div> <div class="form-group"> <input class="form-control" type="<PASSWORD>" name="password" placeholder="<PASSWORD>"> </div> <div class="form-group"> <input class="btn btn-success" type="submit" name="register" value="Register"> </div> </form> <!-- ./Register form --> </div> </div> </main> <!-- ./Main --> <?php include "_footer.php" ?> <script type="text/javascript" src="js/bootstrap.min.js"></script> <script type="text/javascript" src="js/script.js"></script> </body> </html> <file_sep><?php require_once "../_functions.php"; db_connect(); $sql = "DELETE FROM friend_requests WHERE user_id = ? AND friend_id = ?"; $statement = $connection->prepare($sql); $statement->bind_param('ii', intval($_GET['uid']), $_SESSION['user_id']); if ($statement->execute()) redirect_to("/profile.php"); else echo "Error: " . $connection->error; <file_sep><?php require_once "../_functions.php"; db_connect(); $sql = "INSERT INTO users (email, firstname, lastname, password, location) values (?, ?, ?, ?, ?)"; $statement = $connection->prepare($sql); $statement->bind_param("sssss", $_POST["email"], $_POST["firstname"], $_POST["lastname"], password_hash($_POST['password'], PASSWORD_DEFAULT), $_POST['location']); if ($statement->execute()) { redirect_to("/index.php?registered=true"); } else { echo "Error: " . $connection->error; } <file_sep><?php include "_header.php" ?> <?php require_once "_functions.php"; check_auth(); db_connect(); $sql = "SELECT id, email, firstname, lastname, status, relationship_status, profile_image_url, location FROM users WHERE id = ?"; $statement = $connection->prepare($sql); // Get the info of the current user $statement->bind_param('s', $_SESSION['user_id']); $statement->execute(); $statement->store_result(); $statement->bind_result($id, $email, $firstname, $lastname, $status, $relationship_status, $profile_image_url, $location); $statement->fetch(); ?> <!-- Main --> <main class="container"> <div class="row"> <div class="col-md-3"> <!-- Profile brief --> <div class="panel panel-default"> <div class="panel-body"> <h4><?php echo $firstname . " " . $lastname; ?></h4> <p><i><?php echo $status; ?></i></p> <div style="text-align: right"> <small><?php echo $location; ?></small> </div> </div> </div> <!-- ./Profile brief --> </div> <div class="col-md-6"> <!-- Post form --> <form method="post" action="php/create-post.php"> <div class="input-group"> <input class="form-control" type="text" name="content" placeholder="Make a post…"> <span class="input-group-btn"> <button class="btn btn-primary" type="submit" name="post">Post</button> </span> </div> </form> <hr> <!-- ./Post form --> <!-- Feed --> <div> <!-- Post --> <?php $sql = "SELECT * FROM posts ORDER BY created_at DESC"; $result = $connection->query($sql); if ($result->num_rows > 0) { while ($post = $result->fetch_assoc()) { ?> <div class="panel panel-default"> <div class="panel-body"> <p><?php echo $post['content']; ?></p> </div> <div class="panel-footer"> <span>Posted <?php echo $post['created_at']; ?> by <?php echo $post['firstname']; ?></span> <span class="pull-right"><a class="text-danger" href="php/delete-post.php?id=<?php echo $post['id']; ?>">[delete]</a></span> </div> </div> <?php } } else { ?> <p class="text-center">No posts yet!</p> <?php } ?> <!-- ./Post --> </div> <!-- ./Feed --> </div> <div class="col-md-3"> <!-- Add friend --> <div class="panel panel-default"> <div class="panel-body"> <h4>Send friend request</h4> <form method="get" action="php/add-friend.php"> <div class="input-group"> <input class="form-control" type="text" name="email" placeholder="Enter e-mail"> <span class="input-group-btn"> <button class="btn btn-primary" type="submit">Send</button> </span> </div> </form> </div> </div> <!-- ./Add friend --> <!-- Friends --> <div class="panel panel-default"> <div class="panel-body"> <h4>Friends</h4> <?php $sql = "SELECT * FROM friends WHERE friend_id = {$_SESSION['user_id']}"; $result = $connection->query($sql); if ($result->num_rows > 0) { ?> <ul><?php while ($friend = $result->fetch_assoc()) { ?> <li> <?php $u_sql = "SELECT * FROM users WHERE id = {$friend['user_id']} LIMIT 1"; $u_result = $connection->query($u_sql); $fr_user = $u_result->fetch_assoc(); ?> <a href="profile.php?email=<?php echo $fr_user['email']; ?>"><?php echo $fr_user['firstname'] . " " . $fr_user['lastname']; ?></a> <a class="text-danger" href="php/remove-request.php?uid=<?php echo $fr_user['id']; ?>">[unfriend]</a> </li> <?php } ?></ul><?php } else { ?> <p class="text-center">No pending friend requests!</p> <?php } ?> </div> </div> <!-- ./Friends --> <div class="panel panel-default"> <div class="panel-body"> <h4>Pending Friend Requests</h4> <?php $sql = "SELECT * FROM friend_requests WHERE friend_id = {$_SESSION['user_id']}"; $result = $connection->query($sql); if ($result->num_rows > 0) { ?> <ul><?php while ($friend = $result->fetch_assoc()) { ?> <li> <?php $u_sql = "SELECT * FROM users WHERE id = {$friend['user_id']} LIMIT 1"; $u_result = $connection->query($u_sql); $fr_user = $u_result->fetch_assoc(); ?> <a href="profile.php?email=<?php echo $fr_user['email']; ?>"><?php echo $fr_user['email']; ?></a> <a class="text-success" href="php/accept-request.php?uid=<?php echo $fr_user['id']; ?>">[accept]</a> <a class="text-danger" href="php/remove-request.php?uid=<?php echo $fr_user['id']; ?>">[decline]</a> </li> <?php } ?></ul><?php } else { ?> <p class="text-center">No pending friend requests!</p> <?php } ?> </div> </div> </div> </div> </main> <!-- ./Main --> <?php include "_footer.php" ?> <script type="text/javascript" src="js/bootstrap.min.js"></script> <script type="text/javascript" src="js/script.js"></script> </body> </html> <file_sep><?php require_once "../_functions.php"; db_connect(); $sql = "SELECT id, email, firstname, lastname, password FROM users WHERE email = ?"; $statement = $connection->prepare($sql); $statement->bind_param("s", $_POST['email']); $statement->execute(); $statement->store_result(); $statement->bind_result($id, $email, $firstname, $lastname, $password); $statement->fetch(); if ($statement->execute()) { if (password_verify($_POST['password'], $password)) { $_SESSION['user_id'] = $id; $_SESSION['user_email'] = $email; $_SESSION['firstname'] = $firstname; redirect_to("/home.php"); } else { redirect_to("/index.php?login_error=true"); } } else { echo "Error: " . $connection->error; } <file_sep><?php require_once "../_functions.php"; db_connect(); $sql = "UPDATE users SET status = ?, location = ?, relationship_status = ?, profile_image_url = ? WHERE id = ?"; $statement = $connection->prepare($sql); $statement->bind_param('ssssi', $_POST['status'], $_POST['location'], $_POST['relationship_status'], $_POST['profile_image_url'], $_SESSION['user_id']); if ($statement->execute()) redirect_to("/profile.php?"); else echo "Error: " . $connection->error;
739c431701a79726c2ceae0a3ef88834e9cb4c8b
[ "SQL", "PHP" ]
15
PHP
mr-andrej/thefacebook
4adb7bd48f3617efa28e977e8ec0dad99ea6ff3c
545d53f74d6dcad0748dada11af04f8d6452543a
refs/heads/master
<file_sep><?php namespace App\Http\Controllers; use App\Models\Role; use App\Models\User; use App\Models\Semester; use App\Models\Department; use App\Models\Permission; use App\Models\UserDetails; use Illuminate\Support\Str; use Illuminate\Http\Request; use Illuminate\Support\Facades\Auth; use Illuminate\Support\Facades\Hash; class HomeController extends Controller { /** * Create a new controller instance. * * @return void */ public function __construct() { $this->middleware('auth'); } /** * Show the application dashboard. * * @return \Illuminate\Contracts\Support\Renderable */ public function index() { $user = Auth::user(); foreach($user->roles as $role) { $role = $role->role_name; } foreach($user->permissions as $permission) { $permission = $permission->permission_name; } if($role == 'admin') { $totaluser = User::count(); $data['totaluser'] = $totaluser; } $data['role'] = $role; // $data['permission'] = $permission; return view('dashboard.home', $data); } public function viewRoles() { $roles = Role::with('permissions')->get(); $perm = Permission::all(); $data['roles'] = $roles; $data['permissions'] = $perm; return view('dashboard.add-roles', $data); } public function addRoles(Request $request) { $rolename = strtolower($request->role_name); $perms = $request->permname; if($request->action == 'create') { $role = Role::create(['role_name' => $rolename]); foreach($perms as $p) { $permcheck = Permission::where('permission_name', $p)->firstOrFail(); $role->permissions()->attach($permcheck); } } elseif($request->action == 'update') { Role::where('id', $request->roleid)->update(['role_name' => $rolename]); } elseif($request->action == 'delete') { Role::where('id', $request->roleid)->delete(); } return redirect()->route('viewroles'); } public function viewPermissions() { $permissions = Permission::all(); $data['permissions'] = $permissions; return view('dashboard.add-permissions', $data); } public function addPermissions(Request $request) { $permission = Str::slug($request->permission_name); if($request->action == 'create') { Permission::create(['permission_name' => $permission]); } elseif($request->action == 'update') { Permission::where('id', $request->permissionid)->update(['permission_name' => $permission]); } elseif($request->action == 'delete') { Permission::where('id', $request->permissionid)->delete(); } return redirect()->route('viewpermissions'); } public function viewUser() { $users = User::with('userdetails', 'roles', 'permissions')->get(); $data['users'] = $users; return view('dashboard.add-user', $data); } public function viewUserDetails() { $dept = Department::all(); $sem = Semester::all(); $perm = Permission::all(); $role = Role::all(); $data['departments'] = $dept; $data['semesters'] = $sem; $data['permissions'] = $perm; $data['roles'] = $role; return view('dashboard.add-user-details', $data); } public function addUserDetails(Request $request) { $this->validate($request,[ 'name' => 'required|string', 'email' => 'required', 'contact_no' => 'required', ]); $passval = time(); $name = $request->name; $email = $request->email; $pwd = $request->session()->put('userpwd', $passval); $contno = $request->contact_no; $department = $request->department; $role = $request->rolename; $perms = $request->permname; $adduser = new User(); $adduser->name = $name; $adduser->email = $email; $adduser->password = <PASSWORD>($passval); $adduser->save(); $adduserdetails = new UserDetails(); $adduserdetails->contact_no = $contno; $adduserdetails->department = $department; $adduser->userdetails()->save($adduserdetails); $rolecheck = Role::where('role_name', $role)->first(); $adduser->roles()->attach($rolecheck); foreach($perms as $val) { $permcheck = Permission::where('permission_name', $val)->firstOrFail(); $adduser->permissions()->attach($permcheck); } return redirect()->route('viewuser'); } } <file_sep><?php use Illuminate\Support\Facades\Route; /* |-------------------------------------------------------------------------- | Web Routes |-------------------------------------------------------------------------- | | Here is where you can register web routes for your application. These | routes are loaded by the RouteServiceProvider within a group which | contains the "web" middleware group. Now create something great! | */ // Route::get('/login', 'Admin\LoginController@showLogin')->name('login'); // Route::post('/login', 'Admin\LoginController@loginCheck'); // Route::get('/register', 'MainController@showRegister')->name('register'); // Route::get('/home', 'MainController@index')->name('home'); Auth::routes(); Route::get('/dashboard', 'HomeController@index')->name('home'); Route::get('/add-roles', 'HomeController@viewRoles')->name('viewroles'); Route::post('/add-roles', 'HomeController@addRoles'); Route::post('/update-roles', 'HomeController@addRoles'); Route::post('/delete-roles', 'HomeController@addRoles'); Route::get('/add-permissions', 'HomeController@viewPermissions')->name('viewpermissions'); Route::post('/add-permissions', 'HomeController@addPermissions'); Route::post('/update-permissions', 'HomeController@addPermissions'); Route::post('/delete-permissions', 'HomeController@addPermissions'); Route::get('/add-user', 'HomeController@viewUser')->name('viewuser'); Route::get('/add-user-details', 'HomeController@viewUserDetails')->name('adduserdetails'); Route::post('/add-user-details', 'HomeController@addUserDetails');
6cdfed5e8e2b22ee3dd99af46cce5b52dc331336
[ "PHP" ]
2
PHP
amitr-cn/rolemgmt
05092b39d44ec1fc971ff5c5ff468ac9db6b6209
8becdeb7876772cbe0f454b22da0daed47de48c3
refs/heads/main
<file_sep># BreezeAdmin 这是一个基于flask的后端管理模板。他实现了用户登陆验证与菜单权限管理。他的优势是结构简单,没有数据库,菜单是存在json中。用户可以根据自己的需要对接其他用户管理系统,只要传session过来就可以。 在 static/files/menu.json 中有json文件,用于保存菜单。 session['username']保存用户名,用于验证是否登陆 session['usermenu']该用户的菜单,以'01010'形式,对应菜单的id,0表示无权限,1表示有权限 <file_sep>import os import datetime DEBUG=True SECRET_KEY =os.urandom(24) PERMANENT_SESSION_LIFETIME = datetime.timedelta(minutes=20) UPLOAD_FOLDER='static\\files\\'
245cf1e4582ffc9228e8c807e7ed4c015479cb4b
[ "Markdown", "Python" ]
2
Markdown
lyclqq/BreezeAdmin
9e0169f9add79ee74f1fb50f2c84fdd3b97e797f
006511dbd1fd0e5c24cc9fd6b5f29070a505402e
refs/heads/master
<repo_name>VijayReddy119/LeetCode<file_sep>/Stringtoint(atoi).cpp #include<iostream> #include<string> #include<cmath> using namespace std; int main(){ //string str = "42"; // ----(42) //string str = "-42"; //-----(-42) //string str = " -42"; //---- (-42) //string str = "4193 with words"; //---- (4193) //string str = "words and 987"; //---- (0) //string str = "-91283472332"; //---- (INT_MIN) int i = 0, n = str.size(); while (i < n && str[i] == ' ') i++; if (i >= n) return 0; int sign = 1; if (str[i] == '+') i++; else if (str[i] == '-') { sign = -1; i++; } if (i >= n || !isdigit(str[i])) return 0; long res = 0; while (i < n && isdigit(str[i])) { res = res * 10 + str[i++] - '0'; if (res * sign > INT_MAX) return INT_MAX; else if (res * sign < INT_MIN) return INT_MIN; } return (int)(res * sign); }<file_sep>/Jewels_Stone.cpp #include<iostream> #include<unordered_set> #include<map> using namespace std; int main(){ string J ="evr"; string S ="fsdelqgvwn"; /* int freq_stones[58] = {0}; int freq_jewels[58] = {0}; for(int i=0;i<S.size();i++) freq_stones[S[i]-'A']++; for(int i=0;i<J.size();i++) freq_jewels[J[i]-'A']++; int sum=0; for(int i=0; i<58; i++){ if(freq_stones[i]!=0 && freq_jewels[i]!=0){ sum += freq_stones[i]; } } cout<<sum; */ /* unordered_set<char> hs; for(char x : J) hs.insert(x); int count=0; for(int i=0;i<S.size();i++){ if(hs.find(S[i])!=hs.end()){ count++; } } cout<<count; */ map<char,int>m; for(auto it: S) m[it]++; int ans = 0; for(auto it: J) ans += m[it]; cout<<ans; return 0; }<file_sep>/NumberComplement.cpp #include<iostream> #include<bits/stdc++.h> using namespace std; int main(){ int n=2147483647; int mask = 1; while(mask < n) mask = (mask<<1)+1; cout<< (n^mask); return 0; }<file_sep>/Check_if_it_is_straight_line.cpp #include<iostream> #include <vector> using namespace std; int main(){ //vector<vector<int>> coordinates{{1,2}, {2,3}, {3,4}}; //vector<vector<int>> coordinates{{-3,-2}, {-1,-2}, {2,-2}, {-2,-2}, {0,-2}}; vector<vector<int>> coordinates{{-5,1}, {-4,-1}, {-7,4}, {-7,7}, {5,-7}, {-3,2}, {2,-5}}; int slope=0; if((coordinates[0][1] - coordinates[1][1])!=0) slope = (coordinates[0][0]-coordinates[1][0])/(coordinates[0][1] - coordinates[1][1]); for(int i=1; i <coordinates.size()-1; i++) { int next_slope = 0; if((coordinates[i][1] - coordinates[i+1][1])!=0) next_slope = (coordinates[i][0]-coordinates[i+1][0])/(coordinates[i][1] - coordinates[i+1][1]); cout<<slope<<" "<<next_slope<<" \n"; if(slope!=next_slope){ cout<<"Not a St.Line"; }else{ slope = next_slope; } } cout<<"\nSt. Line"; return 0; }<file_sep>/SortElementsByFrequency.cpp #include<iostream> #include<climits> #include<vector> using namespace std; int main(){ string s = "Aabb"; int freq_count[52]={0}; int max_idx = 0; vector<string> v; for(int i=0; i<s.size(); i++) freq_count[s[i]-'a']++; int j=0; for(int i=0; i<s.size(); i++){ if(freq_count[s[i]-'a'] > max_idx){ } } for(string x: v){ cout<<x; } return 0; }<file_sep>/Pow-fn_Implementation.cpp #include <iostream> #include<climits> #include <cmath> using namespace std; double myPow(double x, int n) { if(n==0) return 1; else if(n==1) return x; else if(n<0) { if(n==INT_MIN) { n=INT_MAX; return x/(myPow(x,n)); } else { n = n*-1; return 1/myPow(x,n); } } int t = n/2; double temp = myPow(x,t); if(n%2==0) return temp*temp; else return x*temp*temp; } int main(){ double x =2.00000; int n = -2147483648; //cout<< pow(x, n); cout<<myPow(x,n); return 0; }<file_sep>/leetcode_bulbSwitch.cpp #include<iostream> #include<cmath> #include<vector> using namespace std; int main(){ int n; std::cin>>n; std::cout<<(int)sqrt(n); /*vector<bool> v; for(int i=0;i<n;i++){ v.push_back(true); } for(int i=2;i<n;i++){ for(int j=0;j<n;){ if(v[j]) v[j] = false; else v[j]= true; j += i; cout<<i<<" "; } cout<<"\n"; } int count=0; for(int i=0;i<n;i++){ if(v[i]){ count++; } } cout<<count<<" "<<sqrt(n);*/ return 0; }<file_sep>/RemoveK.cpp #include<iostream> #include<string> #include<stack> using namespace std; int main(){ string str = "10200"; int k=1, n=str.size(); stack<char> mystack; for(char x: str){ while(!mystack.empty() && k>0 && mystack.top()>x){ mystack.pop(); k--; } if(!mystack.empty() || x!='0') mystack.push(x); } while(!mystack.empty() && k--) mystack.pop(); if(mystack.empty()) cout<<"0"; while(!mystack.empty()){ str[n-1] = mystack.top(); mystack.pop(); n-=1; } cout<<str.substr(n); return 0; }<file_sep>/IntervalListIntersection.cpp class Solution { public: vector<vector<int>> intervalIntersection(vector<vector<int>>& A, vector<vector<int>>& B) { vector<vector<int>> results; auto ai = A.cbegin(); auto bi = B.cbegin(); while (ai != A.cend() && bi != B.cend()) { auto& a = *ai; auto& b = *bi; if (a[1] < b[0]) { ++ai; continue; } if (a[0] > b[1]) { ++bi; continue; } results.push_back(intersect(a, b)); if (a[1] <= b[1]) { ++ai; } if (a[1] >= b[1]) { ++bi; } } return results; } private: static inline vector<int> intersect(const vector<int>& a, const vector<int>& b) { int lo = max(a[0], b[0]); int hi = min(a[1], b[1]); return vector<int>{lo, hi}; } }; static auto optimize = [](){ std::ios::sync_with_stdio(false); std::cin.tie(nullptr); std::cout.tie(nullptr); return nullptr; }();<file_sep>/SetMismatch.cpp #include<iostream> #include<vector> #include<unordered_map> using namespace std; int main(){ vector<int> nums{1,2,2,4}; unordered_map<int,int> hm; for(int i=1; i<=nums.size(); i++) hm.insert({i,0}); int num=0; for(int i=0; i<=nums.size(); i++){ hm[nums[i]]++; if(hm[nums[i]] == 2) num = nums[i]; } for(auto it : hm){ if(it.second==0){ cout<<num<<" "<<it.first; break; } } return 0; }<file_sep>/Nimgame.cpp #include<iostream> using namespace std; int main() { int n; cin>>n; int x = n%4; cout<<x; return 0; }<file_sep>/RansomeNote.cpp #include<iostream> #include<unordered_map> using namespace std; static auto _______ = [](){ std::ios::sync_with_stdio(false); std::cin.tie(nullptr); return 0; }(); int main(){ string ransomNote = "aa"; string magazine = "aab"; /* unordered_map<char, int> hm; for(int i=0; i<magazine.size(); i++){ hm[magazine[i]]++; } for(int i=0; i<ransomNote.size(); i++){ --hm[ransomNote[i]]; if(hm[ransomNote[i]] < 0){ cout<<"False"<<"\n"; return 0; } } cout<<"True"; */ int freq_count[128]={0}; for(int i=0; i<magazine.size(); i++){ freq_count[magazine[i]]++; } for(int i=0; i<ransomNote.size(); i++){ --freq_count[ransomNote[i]]; if(freq_count[ransomNote[i]] < 0){ cout<<"False"; } } cout<<"True"; return 0; }
4cc01bb450a264037c0852a6b0772000a6a8058f
[ "C++" ]
12
C++
VijayReddy119/LeetCode
59f5d50b4bf3d2ac4bd8f6ec686e2cd5f1b1883e
d759763df6295618421c7bf029ccd4c550da7a50
refs/heads/main
<file_sep>// import createGlobalStyle import { createGlobalStyle } from 'styled-components'; //create global style const GlobalStyle = createGlobalStyle` font-family: sans-serif; text-align: center; `; export default GlobalStyle;<file_sep>//import everything as firebase import * as firebase from 'firebase/app'; //import firestore import 'firebase/firestore'; // Initialize Firebase firebase.initializeApp({ apiKey: "<KEY>", authDomain: "todo-app-ccfa8.firebaseapp.com", databaseURL: "https://todo-app-ccfa8.firebaseio.com", projectId: "todo-app-ccfa8", storageBucket: "todo-app-ccfa8.appspot.com", messagingSenderId: "49304441043", appId: "1:49304441043:web:5c8b5509195e5f31d4c426" }); export const getTime = firebase.firestore.FieldValue.serverTimestamp; export const db = firebase.firestore(); <file_sep>//import react import React from 'react'; //import conext import { Context } from '../../utils/Context'; //import components from material import List from '@material-ui/core/List'; import ListItem from '@material-ui/core/ListItem'; import ListItemSecondaryAction from '@material-ui/core/ListItemSecondaryAction'; import ListItemText from '@material-ui/core/ListItemText'; import Checkbox from '@material-ui/core/Checkbox'; import IconButton from '@material-ui/core/IconButton'; import DeleteIcon from '@material-ui/icons/Delete'; const TodoList = () => { //react use Context hook const { todos, deleteTodo } = React.useContext(Context); return ( <List> {todos.map((todo, index) => ( <ListItem key={index.toString()} dense button> <Checkbox tabIndex={-1} disableRipple /> <ListItemText primary={todo.info} /> <ListItemSecondaryAction> <IconButton style={{paddingLeft:'1rem'}} aria-label='Delete' onClick={() => { deleteTodo(todo.id); }}> <DeleteIcon/> </IconButton> </ListItemSecondaryAction> </ListItem> ))} </List> ); }; export default TodoList; <file_sep>//import react import React, { useState } from 'react'; //import text field from material ui import TextField from '@material-ui/core/TextField'; const TodoForm = ({ saveTodo }) => { const [value, setValue] = useState(''); return ( <form onSubmit={(event) => { event.preventDefault(); saveTodo(value); setValue(''); }}> <TextField variant='outlined' placeholder='Add todo' margin='normal' onChange={(event) => { setValue(event.target.value); }} value={value} /> </form> ); }; export default TodoForm; <file_sep>//import react import React, { useState } from 'react'; //import material import Typography from '@material-ui/core/Typography'; //import styles import GlobalStyle from '../../styles/GlobalStyles'; import { Container } from './styles'; //import formS import TodoForm from '../TodoForm'; //import todolist import TodoList from '../TodoList'; //import the context import { Context } from '../../utils/Context'; export const App = () => { //use context hook const { addTodo } = React.useContext(Context); return ( <Container> <GlobalStyle /> <Typography component='h1' variant='h2'> Todos </Typography> <TodoForm saveTodo={(todoText) => { const trimmedText = todoText.trim(); if (trimmedText.length > 0) { addTodo(todoText); } }} /> <TodoList /> </Container> ); };
24c656b9d0ec0aa578618f9bed1891b5c02df628
[ "JavaScript" ]
5
JavaScript
BernardoAguayoOrtega/todo-app
cfd43a4e794c8177f1f8503ff1f42e7053d79fbd
e49881a28518ada15ef6f51c307cb33595a439c4
refs/heads/master
<file_sep>import React from 'react'; import { Link } from 'react-router'; export default () => <Link className="" to={`/executor-info`} title="Executor Information"> Executors </Link> ; <file_sep>package io.jenkins.blueocean.rest.impl.pipeline; import com.google.common.collect.Iterators; import com.google.common.collect.Lists; import hudson.model.Cause; import hudson.model.CauseAction; import hudson.model.Item; import hudson.model.Queue; import io.jenkins.blueocean.commons.ServiceException; import io.jenkins.blueocean.rest.Utils; import io.jenkins.blueocean.rest.hal.Link; import io.jenkins.blueocean.rest.model.BluePipeline; import io.jenkins.blueocean.rest.model.BlueRun; import io.jenkins.blueocean.rest.model.BlueRunContainer; import io.jenkins.blueocean.service.embedded.rest.QueueItemImpl; import org.apache.commons.lang.StringUtils; import org.kohsuke.stapler.Stapler; import org.kohsuke.stapler.StaplerRequest; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.Iterator; import java.util.List; import static io.jenkins.blueocean.rest.impl.pipeline.PipelineRunImpl.LATEST_RUN_START_TIME_COMPARATOR; /** * @author <NAME> */ public class MultibranchPipelineRunContainer extends BlueRunContainer{ private static final int MAX_MBP_RUNS_ROWS = Integer.getInteger("MAX_MBP_RUNS_ROWS", 250); private final MultiBranchPipelineImpl blueMbPipeline; private final Link self; public MultibranchPipelineRunContainer(MultiBranchPipelineImpl pipeline) { this.blueMbPipeline = pipeline; this.self = pipeline.getLink().rel("runs"); } @Override public Link getLink() { return self; } @Override public BlueRun get(String name) { return null; } @Override public Iterator<BlueRun> iterator() { throw new ServiceException.NotImplementedException("Not implemented"); } /** * Fetches maximum up to MAX_MBP_RUNS_ROWS rows from each branch and does pagination on that. * * JVM property MAX_MBP_RUNS_ROWS can be used to tune this value to optimize performance for given setup */ @Override public Iterator<BlueRun> iterator(int start, int limit) { List<BlueRun> c = new ArrayList<>(); List<BluePipeline> branches; // Check for branch filter StaplerRequest req = Stapler.getCurrentRequest(); String branchFilter = null; if (req != null) { branchFilter = req.getParameter("branch"); } if (!StringUtils.isEmpty(branchFilter)) { BluePipeline pipeline = blueMbPipeline.getBranches().get(branchFilter); if (pipeline != null) { branches = Collections.singletonList(pipeline); } else { branches = Collections.emptyList(); } } else { branches = Lists.newArrayList(blueMbPipeline.getBranches().list()); sortBranchesByLatestRun(branches); } for (final BluePipeline b : branches) { BlueRunContainer blueRunContainer = b.getRuns(); if(blueRunContainer==null){ continue; } Iterator<BlueRun> it = blueRunContainer.iterator(0, MAX_MBP_RUNS_ROWS); int count = 0; Utils.skip(it, start); while (it.hasNext() && count++ < limit) { c.add(it.next()); } } Collections.sort(c, LATEST_RUN_START_TIME_COMPARATOR); return Iterators.limit(c.iterator(), limit); } static void sortBranchesByLatestRun(List<BluePipeline> branches) { Collections.sort(branches, ( o1, o2 ) -> LATEST_RUN_START_TIME_COMPARATOR.compare(o1.getLatestRun(), o2.getLatestRun())); } private boolean retry(boolean[] retries) { //if at least one of the branch needs retry we will retry it for (boolean r : retries) { if (r) { return true; } } return false; } private int computeLimit(boolean[] retries, int limit) { //if at least one of the branch needs retry we will retry it int count = 0; for (boolean r : retries) { if (r) { count++; } } if (count == 0) { return 0; } return limit / count > 0 ? limit / count : 1; } private int collectRuns(List<BluePipeline> branches, List<BlueRun> runs, boolean[] retries, int remainingCount, int[] startIndexes, int[] limits) { int count = 0; for (int i = 0; i < branches.size(); i++) { BluePipeline b = branches.get(i); if (!retries[i]) { continue; } BlueRunContainer blueRunContainer = b.getRuns(); if(blueRunContainer==null){ continue; } Iterator<BlueRun> it = blueRunContainer.iterator(startIndexes[i], limits[i]); int lcount = 0; while (it.hasNext() && count < remainingCount) { lcount++; count++; runs.add(it.next()); } if (lcount < limits[i]) { //if its less than l retries[i] = false; //iterator already exhausted so lets not retry next time } else { startIndexes[i] = startIndexes[i] + lcount; //set the new start index for next time } } return count; } @Override public BlueRun create(StaplerRequest request) { blueMbPipeline.mbp.checkPermission(Item.BUILD); Queue.Item queueItem = blueMbPipeline.mbp.scheduleBuild2(0, new CauseAction(new Cause.UserIdCause())); if(queueItem == null){ // possible mbp.isBuildable() was false due to no sources fetched yet return null; } return new QueueItemImpl( blueMbPipeline.getOrganization(), queueItem, blueMbPipeline, 1 ).toRun(); } } <file_sep>import React from 'react'; import executorInfoService from './ExecutorInfoService'; import { observer } from 'mobx-react'; import { JTable, TableHeaderRow, TableRow, TableCell, StatusIndicator, Icon } from '@jenkins-cd/design-language'; const columns = [ JTable.column(10, '', false), JTable.column(60, 'Computers', true), ]; @observer export class ExecutorInfoPage extends React.Component { render() { return ( <JTable columns={columns} className="executor-info-table"> <TableHeaderRow /> {executorInfoService.computers && executorInfoService.computers.map(computer => [ <TableRow> <TableCell> <Icon size={24} icon="HardwareComputer" color="rgba(53, 64, 82, 0.5)" /> </TableCell> <TableCell> {computer.displayName} </TableCell> </TableRow>].concat(computer.executors.map(executor => <TableRow> <TableCell> {!executor.idle && <StatusIndicator result="running" percentage={1000} />} </TableCell> <TableCell className="executor-info-cell"> <Icon size={18} icon="NavigationSubdirectoryArrowRight" color="rgba(53, 64, 82, 0.5)" /> {executor.displayName} </TableCell> </TableRow>)) )} </JTable> ); } }; <file_sep>FROM ubuntu:16.04 ENV MAVEN_VERSION 3.5.4 ENV NODE_VERSION 10.13.0 ENV PHANTOMJS_VERSION 2.1.1 ARG UID=1000 ARG GID=1000 USER root RUN apt-get update #======================== # Miscellaneous packages #======================== RUN apt-get update -qqy \ && apt-get -qqy --no-install-recommends install \ sudo \ openjdk-8-jdk \ tar \ zip xz-utils \ curl wget \ git \ build-essential \ python \ iputils-ping \ net-tools \ locales \ libsass-dev \ && rm -rf /var/lib/apt/lists/* \ && sed -i 's/securerandom\.source=file:\/dev\/random/securerandom\.source=file:\/dev\/urandom/' ./usr/lib/jvm/java-8-openjdk-amd64/jre/lib/security/java.security # Set utf-8 locale RUN locale-gen en_US.UTF-8 ENV LANG en_US.UTF-8 ENV LC_ALL en_US.UTF-8 #========== # Maven #========== RUN curl -fsSL http://repo.maven.apache.org/maven2/org/apache/maven/apache-maven/$MAVEN_VERSION/apache-maven-$MAVEN_VERSION-bin.tar.gz | tar xzf - -C /usr/share \ && mv /usr/share/apache-maven-$MAVEN_VERSION /usr/share/maven \ && ln -s /usr/share/maven/bin/mvn /usr/bin/mvn ENV MAVEN_HOME /usr/share/maven #=============== # Node and NPM #=============== RUN wget --no-verbose https://nodejs.org/dist/v$NODE_VERSION/node-v$NODE_VERSION-linux-x64.tar.xz -O /opt/nodejs.tar.xz RUN tar -C /usr/local --strip-components 1 -xJf /opt/nodejs.tar.xz RUN mkdir /.npm && chmod 777 /.npm #============================================= # Misc packages needed by the ATH #============================================= RUN apt-get update -qqy \ && apt-get -qqy --no-install-recommends install \ libxml2-utils \ libssl-dev \ && rm -rf /var/lib/apt/lists/* #============================================= # Phantom JS #============================================= RUN wget --no-verbose -O - -L https://bitbucket.org/ariya/phantomjs/downloads/phantomjs-2.1.1-linux-x86_64.tar.bz2 \ | tar -xj --strip-components=1 -C /usr/local #======================================== # Add normal user with passwordless sudo #======================================== RUN sudo groupadd -r -g $GID bouser \ && sudo useradd bouser -g $GID -u $UID --shell /bin/bash --create-home \ && sudo usermod -a -G sudo bouser \ && echo 'ALL ALL = (ALL) NOPASSWD: ALL' >> /etc/sudoers \ && echo 'bouser:secret' | chpasswd USER bouser WORKDIR /home/bouser #======================================== # Configure the local git user. #======================================== RUN git config --global user.name "<NAME>" RUN git config --global user.email <EMAIL> #======================================== # Need ssh #======================================== RUN sudo apt-get update -qqy && sudo apt-get install -y ssh <file_sep>/** * Created by cmeyers on 7/11/16. */ /** * Determine whether the URL for the supplied favorite and pipeline/branch match. * * @param favoriteUrl * @param pipelineOrBranchUrl * @returns {boolean} */ export const checkMatchingFavoriteUrls = (favoriteUrl, pipelineOrBranchUrl) => { if (favoriteUrl === pipelineOrBranchUrl) { return true; } // A favorite can point to a pipeline or a specific branch of a multi-branch pipeline. // This logic handles the special case where a multi-branch pipeline was favorited - // implicitly favoriting the 'master' branch - but the URL to the pipeline itself is supplied. // We watch this to count as a match, even though the URL's are actually different. return favoriteUrl === `${pipelineOrBranchUrl}branches/master` || favoriteUrl === `${pipelineOrBranchUrl}branches/master/`; }; <file_sep>package io.blueocean.ath.offline.personalization; import io.blueocean.ath.ATHJUnitRunner; import io.blueocean.ath.BaseUrl; import io.blueocean.ath.GitRepositoryRule; import io.blueocean.ath.Login; import io.blueocean.ath.ResourceResolver; import io.blueocean.ath.WebDriverMixin; import io.blueocean.ath.api.classic.ClassicJobApi; import io.blueocean.ath.factory.ClassicPipelineFactory; import io.blueocean.ath.factory.FreestyleJobFactory; import io.blueocean.ath.factory.MultiBranchPipelineFactory; import io.blueocean.ath.model.Folder; import io.blueocean.ath.pages.blue.FavoritesDashboardPage; import org.apache.log4j.Logger; import org.glassfish.jersey.client.authentication.HttpAuthenticationFeature; import org.junit.After; import org.junit.Before; import org.junit.Rule; import org.junit.runner.RunWith; import javax.inject.Inject; import javax.ws.rs.client.Client; import javax.ws.rs.client.ClientBuilder; import java.io.IOException; /** * @author cliffmeyers */ @Login @RunWith(ATHJUnitRunner.class) abstract public class AbstractFavoritesTest implements WebDriverMixin { static final Folder FOLDER = new Folder("personalization-folder"); @Rule @Inject public GitRepositoryRule git; @Inject @BaseUrl String base; @Inject ClassicJobApi jobApi; @Inject FreestyleJobFactory freestyleFactory; @Inject ClassicPipelineFactory pipelineFactory; @Inject MultiBranchPipelineFactory multibranchFactory; @Inject FavoritesDashboardPage dashboardPage; protected ResourceResolver resources; abstract protected Logger getLogger(); @Before public void setUp() throws IOException { resources = new ResourceResolver(getClass()); String user = "alice"; getLogger().info(String.format("deleting any existing favorites for %s", user)); Client restClient = ClientBuilder.newClient().register(HttpAuthenticationFeature.basic(user, user)); restClient.target(base + "/users/" + user + "/favorites/").request().delete(); } @After public void tearDown() throws IOException { // wipe out all jobs to avoid causing issues w/ SearchTest jobApi.deleteFolder(FOLDER); } } <file_sep>import React, {PropTypes} from 'react'; import {observer} from 'mobx-react'; import {FilterableList, FormElement} from '@jenkins-cd/design-language'; import FlowStep from '../../flow2/FlowStep'; import {i18nTranslator} from '@jenkins-cd/blueocean-core-js'; const t = i18nTranslator('blueocean-dashboard'); @observer export default class PerforceProjectListStep extends React.Component { selectProject(proj) { this.props.flowManager.selectProject(proj); } beginCreation() { this.props.flowManager.saveRepo(); } render() { const {flowManager, title = 'creation.p4.project_step.title'} = this.props; const titleString = t(title); const disabled = flowManager.stepsDisabled; const buttonDisabled = !flowManager.selectedProject; return ( <FlowStep {...this.props} className="github-repo-list-step" title={titleString} disabled={disabled}> <FormElement title={t('creation.p4.project_step.subtitle')}/> <div className="container"> <FilterableList className="repo-list" data={flowManager.projects} onItemSelect={(idx, proj) => this.selectProject(proj)} labelFunction={proj => proj} filterFunction={(text, proj) => proj.toLowerCase().indexOf(text.toLowerCase()) !== -1} /> <button className="button-create" onClick={(proj) => this.beginCreation(proj)} disabled={buttonDisabled}> {t('creation.core.header.title')} </button> </div> </FlowStep> ); } } PerforceProjectListStep.propTypes = { flowManager: PropTypes.object, title: PropTypes.string, }; <file_sep>package io.jenkins.blueocean.commons; import com.google.common.base.CharMatcher; import javax.annotation.Nonnull; /** JSON Utility */ public class JSON { /** * Sanitises string by removing any ISO control characters, tabs and line breaks * @param input string * @return sanitized string */ public static String sanitizeString(@Nonnull String input) { return CharMatcher.JAVA_ISO_CONTROL.and(CharMatcher.anyOf("\r\n\t")).removeFrom(input); } private JSON() {} } <file_sep>#!/bin/bash SCRIPT_DIR=$(dirname $0) $SCRIPT_DIR/stop-selenium.sh echo "" echo " Starting Selenium Docker container..." echo "" docker run -d --name blueo-selenium \ --net=host \ -e no_proxy=localhost \ -v /dev/shm:/dev/shm \ selenium/standalone-chrome-debug:3.141.5 # Output the containers bridge network IP to file SELENIUM_IP=`docker inspect -f '{{ .NetworkSettings.IPAddress }}' blueo-selenium` mkdir -p ./target echo $SELENIUM_IP > ./target/.selenium_ip echo "" echo "**************************************************************" echo "**** Docker container with Selenium, browser and VNC running." echo "**** Selenium server listening on $SELENIUM_IP:4444" echo "**** " echo "**** To connect and view with VNC, run:" echo "**** $ open vnc://:secret@localhost:15900" echo "**************************************************************" <file_sep>import React, {PropTypes} from 'react'; import {observer} from 'mobx-react'; import FlowStep from '../../flow2/FlowStep'; @observer export default class PerforceUnknownErrorStep extends React.Component { render() { return ( <FlowStep {...this.props} title="Unknown Error" error> <div className="instructions">An unknown error has occurred. You may try again.</div> <p className="instructions">Message: {this.props.message}</p> </FlowStep> ); } } PerforceUnknownErrorStep.propTypes = { flowManager: PropTypes.object, message: PropTypes.string, }; <file_sep>package io.jenkins.blueocean.service.embedded; import com.google.common.base.Predicate; import hudson.model.FreeStyleProject; import hudson.model.Item; import hudson.model.ItemGroup; import hudson.model.Project; import io.jenkins.blueocean.service.embedded.rest.ContainerFilter; import org.junit.Test; import org.junit.runner.RunWith; import org.jvnet.hudson.test.MockFolder; import org.jvnet.hudson.test.TestExtension; import org.kohsuke.stapler.Stapler; import org.kohsuke.stapler.StaplerRequest; import org.powermock.core.classloader.annotations.PowerMockIgnore; import org.powermock.core.classloader.annotations.PrepareForTest; import org.powermock.modules.junit4.PowerMockRunner; import java.io.IOException; import java.util.ArrayList; import java.util.Collection; import java.util.List; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; import static org.powermock.api.mockito.PowerMockito.*; /** * @author <NAME> */ @RunWith(PowerMockRunner.class) @PowerMockIgnore({"javax.crypto.*", "javax.security.*", "javax.net.ssl.*", "com.sun.org.apache.xerces.*", "javax.xml.*", "org.xml.*", "org.w3c.dom.*"}) @PrepareForTest(Stapler.class) public class ContainerFilterTest extends BaseTest{ @Test public void testPagedFilter() throws IOException { StaplerRequest request = mock(StaplerRequest.class); when(request.getParameter("filter")).thenReturn("itemgroup-only"); mockStatic(Stapler.class); when(Stapler.getCurrentRequest()).thenReturn(request); List<Item> items = new ArrayList<>(); MockFolder folder = j.createFolder("folder"); for(int i=0; i<50; i++){ FreeStyleProject job = folder.createProject(FreeStyleProject.class, "job"+i); items.add(folder.createProject(MockFolder.class, "subFolder"+i)); items.add(job); } assertEquals(100, items.size()); //there are total 50 folders in items, we want 25 of them starting 25th ending at 49th. Collection<Item> jobs = ContainerFilter.filter(items, 25, 25); assertEquals(25, jobs.size()); int i = 25; for(Item item: jobs){ assertTrue(item instanceof ItemGroup); assertEquals("subFolder"+i++, item.getName()); } } @Test public void customFilter() throws IOException { MockFolder folder = j.createFolder("folder1"); Project p = folder.createProject(FreeStyleProject.class, "test1"); Collection<Item> items = ContainerFilter.filter(j.getInstance().getAllItems(), "itemgroup-only"); assertEquals(1, items.size()); assertEquals(folder.getFullName(), items.iterator().next().getFullName()); } @TestExtension public static class ItemGroupFilter extends ContainerFilter { private final Predicate<Item> filter = new Predicate<Item>() { @Override public boolean apply(Item job) { return (job instanceof ItemGroup); } }; @Override public String getName() { return "itemgroup-only"; } @Override public Predicate<Item> getFilter() { return filter; } } } <file_sep>#!/bin/bash SCRIPT_DIR=$(dirname $0) $SCRIPT_DIR/stop-sc.sh echo "" echo " Starting Sauce Connect container..." echo "" docker run \ -d \ --name blueo-selenium \ --net host \ -e SAUCE_ACCESS_KEY \ -e SAUCE_USERNAME \ -e BUILD_TAG \ --rm \ blueocean/sauceconnect:4.5.3 <file_sep>package io.jenkins.blueocean.preload; import hudson.Extension; import hudson.model.User; import hudson.plugins.favorite.user.FavoriteUserProperty; import io.jenkins.blueocean.commons.PageStatePreloader; import net.sf.json.JSONArray; import javax.annotation.CheckForNull; import javax.annotation.Nonnull; import java.util.Set; /** * Loads the list of item full names for favorites */ @Extension public class FavoriteListStatePreloader extends PageStatePreloader { @Nonnull @Override public String getStatePropertyPath() { return "favoritesList"; } @CheckForNull @Override public String getStateJson() { User jenkinsUser = User.current(); if (jenkinsUser == null) { return null; } FavoriteUserProperty fup = jenkinsUser.getProperty(FavoriteUserProperty.class); if (fup == null) { return null; } Set<String> favorites = fup.getAllFavorites(); if (favorites == null) { return null; } return JSONArray.fromObject(favorites).toString(); } } <file_sep>import React, { PropTypes } from 'react'; import { observer } from 'mobx-react'; import FlowStep from '../../flow2/FlowStep'; @observer export default class GithubLoadingStep extends React.Component { render() { return <FlowStep {...this.props} title="Loading..." loading scrollOnActive={false} />; } } GithubLoadingStep.propTypes = { flowManager: PropTypes.object, }; <file_sep>BlueOceanCredentialsProvider.DisplayName=BlueOcean Folder Credentials BlueOceanCredentialsProvider.DomainDescription=Blue Ocean Folder Credentials domain<file_sep>import { observable, action } from 'mobx'; import { Fetch, UrlConfig, AppConfig, sseConnection } from '@jenkins-cd/blueocean-core-js'; import throttle from 'lodash.throttle'; const FETCH_TIMEOUT_MS = 30 /* seconds */ * 1000 /* milliseconds */; export class ExecutorInfoService { @observable computers; constructor() { this.fetchExecutorInfo(); sseConnection.subscribe('pipeline', event => { switch (event.jenkins_event) { case 'pipeline_block_start': case 'pipeline_block_end': { throttle(this.fetchExecutorInfo.bind(this), FETCH_TIMEOUT_MS)(); } } }); } @action setComputers(computers) { this.computers = computers; } fetchExecutorInfo() { Fetch.fetchJSON(`${UrlConfig.getRestBaseURL()}/organizations/${AppConfig.getOrganizationName()}/computers/`) .then(response => { this.setComputers(response.computers); }); } } // Export an instance to be shared so sseConnection.subscribe // not called multiple times export default new ExecutorInfoService(); <file_sep>import React from 'react'; import ScmProvider from '../ScmProvider'; import PerforceDefaultOption from './PerforceDefaultOption'; import PerforceCreationApi from '../perforce/api/PerforceCreationApi'; import PerforceFlowManager from './PerforceFlowManager'; import PerforceCredentialsApi from "../../credentials/perforce/PerforceCredentialsApi"; /** * Provides the impl of FlowManager and the button for starting the Perforce flow. */ export default class PerforceScmProvider extends ScmProvider { getDefaultOption() { return <PerforceDefaultOption/>; } getFlowManager() { //TODO Remove perforce hardcoding const createApi = new PerforceCreationApi('perforce'); const credentialApi = new PerforceCredentialsApi('perforce'); return new PerforceFlowManager(createApi, credentialApi); } destroyFlowManager() { } } <file_sep>import {Fetch, UrlConfig, Utils, AppConfig} from '@jenkins-cd/blueocean-core-js'; import {TypedError} from '../TypedError'; export const LoadError = { CRED_NOT_FOUND: 'TOKEN_NOT_FOUND', TOKEN_REVOKED: 'TOKEN_REVOKED', TOKEN_MISSING_SCOPES: 'TOKEN_MISSING_SCOPES', }; export const SaveError = { TOKEN_INVALID: 'TOKEN_INVALID', TOKEN_MISSING_SCOPES: 'TOKEN_MISSING_SCOPES', API_URL_INVALID: 'API_URL_INVALID', }; // TODO: temporary until we get more structured errors const INVALID_TOKEN = 'Invalid accessToken'; const INVALID_SCOPES = 'missing scopes'; /** * Handles lookup, validation and creation the Github access token credential. */ class PerforceCredentialsApi { constructor(scmId) { this._fetch = Fetch.fetchJSON; this.organization = AppConfig.getOrganizationName(); this.scmId = scmId || 'perforce'; } findExistingCredential() { const path = UrlConfig.getJenkinsRootURL(); // Value is /jenkins const credUrl = Utils.cleanSlashes(`${path}/credentials/store/system/domain/_/api/json?tree=credentials[id,typeName]`); const fetchOptions = { method: 'GET', headers: { 'Content-Type': 'application/json', }, }; return this._fetch(credUrl, {fetchOptions}).then(result => this._findExistingCredentialSuccess(result), error => this._findExistingCredentialFailure(error)); } _findExistingCredentialSuccess(credential) { if (credential && credential.credentials) { return credential.credentials; } throw new TypedError(LoadError.TOKEN_NOT_FOUND); } _findExistingCredentialFailure(error) { const {responseBody} = error; const {message} = responseBody; if (message.indexOf(INVALID_TOKEN) !== -1) { throw new TypedError(LoadError.TOKEN_REVOKED, responseBody); } else if (message.indexOf(INVALID_SCOPES) !== -1) { throw new TypedError(LoadError.TOKEN_MISSING_SCOPES, responseBody); } throw error; } } export default PerforceCredentialsApi; <file_sep>package io.jenkins.blueocean.executor; import hudson.Extension; import hudson.model.AbstractBuild; import hudson.model.Computer; import hudson.model.Executor; import hudson.model.Item; import hudson.model.Queue; import hudson.model.Run; import hudson.model.queue.SubTask; import io.jenkins.blueocean.rest.OrganizationRoute; import io.jenkins.blueocean.rest.factory.BluePipelineFactory; import io.jenkins.blueocean.rest.factory.BlueRunFactory; import io.jenkins.blueocean.rest.hal.Link; import io.jenkins.blueocean.rest.model.BlueOrganization; import io.jenkins.blueocean.rest.model.BluePipeline; import io.jenkins.blueocean.rest.model.BlueRun; import io.jenkins.blueocean.rest.model.Container; import io.jenkins.blueocean.rest.model.Resource; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import jenkins.model.Jenkins; import org.jenkinsci.plugins.workflow.job.WorkflowRun; import org.jenkinsci.plugins.workflow.support.steps.ExecutorStepExecution; import org.kohsuke.stapler.Ancestor; import org.kohsuke.stapler.Stapler; import org.kohsuke.stapler.export.Exported; import org.kohsuke.stapler.export.ExportedBean; /** * @author kzantow */ @Extension @ExportedBean public class Computers extends Resource implements OrganizationRoute { @Override public String getUrlName() { return "computers"; } @Override public Link getLink() { return getOrganization().getLink().rel(getUrlName()); } private static BlueOrganization getOrganization() { // This should always have an organization as a parent, as it's an OrganizationRoute Ancestor ancestor = Stapler.getCurrentRequest().findAncestor(BlueOrganization.class); BlueOrganization organization = (BlueOrganization)ancestor.getObject(); return organization; } @Exported(inline=true) public ComputerInfo[] getComputers() throws Exception { List<ComputerInfo> info = new ArrayList<>(); Jenkins j = Jenkins.getInstance(); for (Computer c : j.getComputers()) { info.add(new ComputerInfo(getLink(), c)); } return info.toArray(new ComputerInfo[info.size()]); } @ExportedBean public static class ComputerInfo extends Resource { final Link parent; Computer computer; public ComputerInfo(Link parent, Computer computer) { this.parent = parent; this.computer = computer; } @Exported public String getDisplayName() { return computer.getDisplayName(); } @Exported(inline=true) public Container<ExecutorInfo> getExecutors() { final List<ExecutorInfo> out = new ArrayList<>(); if (computer != null) { for (Executor e : computer.getExecutors()) { out.add(new ExecutorInfo(this, e)); } } return new Container() { @Override public Object get(String string) { throw new UnsupportedOperationException("Not supported."); } @Override public Iterator iterator() { return out.iterator(); } @Override public Link getLink() { return parent.rel("executors"); } }; } @Override public Link getLink() { return parent.rel("computer"); } } @ExportedBean public static class ExecutorInfo extends Resource { final Resource parent; final Executor executor; private ExecutorInfo(Resource parent, Executor executor) { this.parent = parent; this.executor = executor; } @Override public Link getLink() { return parent.getLink().rel("executor"); } @Exported public String getDisplayName() { return executor.getDisplayName(); } @Exported public boolean isIdle() { return executor.isIdle(); } @Exported(inline=true) public BlueRun getRun() { Queue.Executable e = executor.getCurrentExecutable(); if (e == null) { return null; } Run r = null; SubTask subTask = e.getParent(); if (subTask instanceof ExecutorStepExecution.PlaceholderTask) { ExecutorStepExecution.PlaceholderTask task = (ExecutorStepExecution.PlaceholderTask)subTask; r = task.run(); } if (e instanceof WorkflowRun) { r = (WorkflowRun)e; } if (e instanceof AbstractBuild) { r = (AbstractBuild)e; } if (r != null) { Item pipelineJobItem = r.getParent(); BluePipeline pipeline = (BluePipeline)BluePipelineFactory.resolve(pipelineJobItem); //BluePipelineFactory.getPipelineInstance(item, getOrganization()); return BlueRunFactory.getRun(r, pipeline); } return null; } } } <file_sep>package io.jenkins.blueocean.blueocean_github_pipeline; import com.cloudbees.plugins.credentials.CredentialsMatcher; import com.cloudbees.plugins.credentials.CredentialsMatchers; import com.cloudbees.plugins.credentials.CredentialsProvider; import com.cloudbees.plugins.credentials.CredentialsStore; import com.cloudbees.plugins.credentials.common.StandardUsernamePasswordCredentials; import com.cloudbees.plugins.credentials.domains.Domain; import com.cloudbees.plugins.credentials.impl.UsernamePasswordCredentialsImpl; import com.google.common.collect.Lists; import hudson.model.User; import hudson.security.SecurityRealm; import hudson.tasks.Mailer; import hudson.util.Secret; import io.jenkins.blueocean.rest.Reachable; import io.jenkins.blueocean.rest.hal.Link; import io.jenkins.blueocean.rest.impl.pipeline.credential.BlueOceanDomainRequirement; import jenkins.model.Jenkins; import net.sf.json.JSONObject; import org.acegisecurity.Authentication; import org.acegisecurity.GrantedAuthority; import org.jenkinsci.plugins.github_branch_source.GitHubSCMSource; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.kohsuke.stapler.Stapler; import org.kohsuke.stapler.StaplerRequest; import org.mockito.ArgumentCaptor; import org.mockito.Mock; import org.mockito.Mockito; import org.mockito.verification.VerificationMode; import org.powermock.core.classloader.annotations.PowerMockIgnore; import org.powermock.core.classloader.annotations.PrepareForTest; import org.powermock.modules.junit4.PowerMockRunner; import java.io.ByteArrayInputStream; import java.net.HttpURLConnection; import java.net.Proxy; import java.net.URL; import static io.jenkins.blueocean.rest.impl.pipeline.scm.Scm.CREDENTIAL_ID; import static org.powermock.api.mockito.PowerMockito.*; /** * @author <NAME> */ @RunWith(PowerMockRunner.class) @PrepareForTest({GithubScm.class, Jenkins.class, Authentication.class, User.class, Secret.class, CredentialsMatchers.class, CredentialsProvider.class, Stapler.class, HttpRequest.class}) @PowerMockIgnore({"javax.crypto.*", "javax.security.*", "javax.net.ssl.*", "com.sun.org.apache.xerces.*", "javax.xml.*", "org.xml.*", "org.w3c.dom.*"}) public class GithubScmTest { @Mock Jenkins jenkins; @Mock Authentication authentication; @Mock User user; @Before public void setup() throws Exception { mockStatic(Jenkins.class); when(Jenkins.getInstance()).thenReturn(jenkins); when(Jenkins.getInstanceOrNull()).thenReturn(jenkins); when(Jenkins.getAuthentication()).thenReturn(authentication); GrantedAuthority[] grantedAuthorities = Lists.newArrayList(SecurityRealm.AUTHENTICATED_AUTHORITY).toArray(new GrantedAuthority[1]); Mockito.when(authentication.getAuthorities()).thenReturn(grantedAuthorities); Mockito.when(authentication.getPrincipal()).thenReturn("joe"); mockStatic(User.class); when(user.getId()).thenReturn("joe"); when(user.getFullName()).thenReturn("<NAME>"); when(user.getDisplayName()).thenReturn("<NAME>"); when(User.class, method(User.class, "get", Authentication.class)).withArguments(authentication).thenReturn(user); when(User.current()).thenReturn(user); } @Test public void validateAccessTokenScopes() throws Exception { HttpURLConnection httpURLConnectionMock = mock(HttpURLConnection.class); doNothing().when(httpURLConnectionMock).connect(); URL urlMock = mock(URL.class); whenNew(URL.class).withAnyArguments().thenReturn(urlMock); when(urlMock.openConnection(Proxy.NO_PROXY)).thenReturn(httpURLConnectionMock); when(httpURLConnectionMock.getHeaderField("X-OAuth-Scopes")).thenReturn("user:email,repo"); when(httpURLConnectionMock.getResponseCode()).thenReturn(200); HttpURLConnection httpURLConnection = GithubScm.connect(GitHubSCMSource.GITHUB_URL, "abcd"); GithubScm.validateAccessTokenScopes(httpURLConnection); } @Test public void validateAndCreate() throws Exception { validateAndCreate("12345"); } @Test public void validateAndCreatePaddedToken() throws Exception { validateAndCreate(" 12345 "); } protected void validateAndCreate(String accessToken) throws Exception { Mailer.UserProperty userProperty = mock(Mailer.UserProperty.class); when(userProperty.getAddress()).thenReturn("<EMAIL>"); JSONObject req = new JSONObject().element("accessToken", accessToken); GithubScm githubScm = new GithubScm(new Reachable() { @Override public Link getLink() { return new Link("/blue/organizations/jenkins/scm/"); } }); mockCredentials("joe", accessToken, githubScm.getId(), GithubScm.DOMAIN_NAME); mockStatic(HttpRequest.class); HttpRequest httpRequestMock = mock(HttpRequest.class); ArgumentCaptor<String> urlStringCaptor = ArgumentCaptor.forClass(String.class); when(HttpRequest.get(urlStringCaptor.capture())).thenReturn(httpRequestMock); ArgumentCaptor<String> tokenCaptor = ArgumentCaptor.forClass(String.class); when(httpRequestMock.withAuthorizationToken(tokenCaptor.capture())).thenReturn(httpRequestMock); HttpURLConnection httpURLConnectionMock = mock(HttpURLConnection.class); doNothing().when(httpURLConnectionMock).connect(); when(httpRequestMock.connect()).thenReturn(httpURLConnectionMock); when(httpURLConnectionMock.getHeaderField("X-OAuth-Scopes")).thenReturn("user:email,repo"); when(httpURLConnectionMock.getResponseCode()).thenReturn(200); String guser = "{\n \"login\": \"joe\",\n \"id\": 1, \"email\": \"<EMAIL>\", \"created_at\": \"2008-01-14T04:33:35Z\"}"; mockStatic(Stapler.class); StaplerRequest request = mock(StaplerRequest.class); when(Stapler.getCurrentRequest()).thenReturn(request); when(HttpRequest.getInputStream(httpURLConnectionMock)).thenReturn(new ByteArrayInputStream(guser.getBytes("UTF-8"))); githubScm.validateAndCreate(req); String id = githubScm.getCredentialId(); Assert.assertEquals(githubScm.getId(), id); Assert.assertEquals("constructed url", "https://api.github.com/user", urlStringCaptor.getValue()); Assert.assertEquals("access token passed to github", accessToken.trim(), tokenCaptor.getValue()); } @Test public void getOrganizations() { mockStatic(Stapler.class); StaplerRequest staplerRequest = mock(StaplerRequest.class); when(Stapler.getCurrentRequest()).thenReturn(staplerRequest); when(staplerRequest.getParameter(CREDENTIAL_ID)).thenReturn("12345"); } void mockCredentials(String userId, String accessToken, String credentialId, String domainName) throws Exception { //Mock Credentials UsernamePasswordCredentialsImpl credentials = mock(UsernamePasswordCredentialsImpl.class); whenNew(UsernamePasswordCredentialsImpl.class).withAnyArguments().thenReturn(credentials); when(credentials.getId()).thenReturn(credentialId); when(credentials.getUsername()).thenReturn(userId); Secret secret = mock(Secret.class); when(secret.getPlainText()).thenReturn(accessToken); when(credentials.getPassword()).thenReturn(secret); CredentialsMatcher credentialsMatcher = mock(CredentialsMatcher.class); mockStatic(CredentialsMatchers.class); mockStatic(CredentialsProvider.class); when(CredentialsMatchers.withId( credentialId)).thenReturn(credentialsMatcher); BlueOceanDomainRequirement blueOceanDomainRequirement = mock(BlueOceanDomainRequirement.class); whenNew(BlueOceanDomainRequirement.class).withNoArguments().thenReturn(blueOceanDomainRequirement); when(CredentialsProvider.class, "lookupCredentials", StandardUsernamePasswordCredentials.class, jenkins, authentication, blueOceanDomainRequirement) .thenReturn(Lists.newArrayList(credentials)); when(CredentialsMatchers.class, "firstOrNull", Lists.newArrayList(credentials), credentialsMatcher).thenReturn(credentials); when(CredentialsMatchers.allOf(credentialsMatcher)).thenReturn(credentialsMatcher); //Mock credentials Domain Domain domain = mock(Domain.class); when(domain.getName()).thenReturn(domainName); //Mock credentials Store CredentialsStore credentialsStore = mock(CredentialsStore.class); when(credentialsStore.hasPermission(CredentialsProvider.CREATE)).thenReturn(true); when(credentialsStore.hasPermission(CredentialsProvider.UPDATE)).thenReturn(true); when(credentialsStore.getDomainByName(domainName)).thenReturn(domain); when(CredentialsProvider.class, "lookupStores", user).thenReturn(Lists.newArrayList(credentialsStore)); when(credentialsStore.updateCredentials(domain, credentials, credentials)).thenReturn(true); } } <file_sep>package io.jenkins.blueocean.rest.impl.pipeline.scm; import com.google.common.collect.ImmutableMap; import hudson.model.User; import io.jenkins.blueocean.commons.JsonConverter; import io.jenkins.blueocean.commons.ServiceException; import org.kohsuke.stapler.HttpResponse; import org.kohsuke.stapler.StaplerRequest; import org.kohsuke.stapler.StaplerResponse; import javax.annotation.CheckForNull; import javax.annotation.Nonnull; import javax.servlet.ServletException; import java.io.IOException; /** * @author <NAME> */ public abstract class AbstractScm extends Scm { /** * Gives authenticated user * @return logged in {@link User} * @throws ServiceException.UnauthorizedException */ protected User getAuthenticatedUser(){ User authenticatedUser = User.current(); if(authenticatedUser == null){ throw new ServiceException.UnauthorizedException("No logged in user found"); } return authenticatedUser; } protected HttpResponse createResponse(final String credentialId) { return new HttpResponse() { @Override public void generateResponse(StaplerRequest req, StaplerResponse rsp, Object node) throws IOException, ServletException { rsp.setStatus(200); rsp.getWriter().print(JsonConverter.toJson(ImmutableMap.of("credentialId", credentialId))); } }; } protected static @CheckForNull String getCredentialIdFromRequest(@Nonnull StaplerRequest request){ String credentialId = request.getParameter(CREDENTIAL_ID); if(credentialId == null){ credentialId = request.getHeader(X_CREDENTIAL_ID); } return credentialId; } } <file_sep>import React, {PropTypes} from 'react'; import {observer} from 'mobx-react'; import FlowStep from '../../flow2/FlowStep'; import {i18nTranslator} from "@jenkins-cd/blueocean-core-js"; const t = i18nTranslator('blueocean-dashboard'); @observer export default class PerforceLoadingStep extends React.Component { render() { return <FlowStep {...this.props} title={t('common.pager.loading')} loading scrollOnActive={false}/>; } } PerforceLoadingStep.propTypes = { flowManager: PropTypes.object, }; <file_sep>import {mockExtensionsForI18n} from '../../mock-extensions-i18n'; import PerforceCredentialsManager from '../../../../main/js/credentials/perforce/PerforceCredentialsManager'; import {TypedError} from "../../../../main/js/credentials/TypedError"; import {LoadError} from "../../../../main/js/credentials/perforce/PerforceCredentialsApi"; import Promise from "bluebird"; mockExtensionsForI18n(); describe('PerforceCredentialsManager', () => { let manager; //instance of this class: PerforceCredentialsManager let credApi; //mock of PerforceCredentialsApi beforeEach(() => { credApi = new PerforceCredentialsApiMock(); manager = new PerforceCredentialsManager(credApi); }); describe('findExistingCredential', () => { it('behaves when found', () => { expect.assertions(4); credApi.findExistingCredentialShouldSucceed = true; credApi.credentials = [ { "id": "p4poke", "typeName": "Perforce Password Credential" }, { "id": "otherNonPerforce", "typeName": "Password Credential" }, ]; return manager.findExistingCredential() .then(creds => { expect(creds).toBeDefined(); expect(creds[0].id).toBe("p4poke"); expect(creds[0].typeName).toBe("Perforce Password Credential"); expect(creds[1]).toBeUndefined(); //PerforceCredentialsManager is expected to filter non-perforce credentials }); }); }); }); // Helpers function later(promiseResolver) { return new Promise((resolve, reject) => { process.nextTick(() => { try { resolve(promiseResolver()); } catch (err) { reject(err); } }); }); } class PerforceCredentialsApiMock { findExistingCredentialShouldSucceed = false; credentials = []; findExistingCredential() { return later(() => { if (this.findExistingCredentialShouldSucceed) { return this.credentials; } throw new TypedError(LoadError.TOKEN_NOT_FOUND); }); } } <file_sep>import React, {PropTypes} from 'react'; import {observer} from 'mobx-react'; import {Dropdown, FormElement} from '@jenkins-cd/design-language'; import FlowStep from '../../flow2/FlowStep'; let t = null; @observer class PerforceCredentialsStep extends React.Component { constructor(props) { super(props); this.dropdown = null; this.credManager = props.flowManager.credManager; } componentWillMount() { t = this.props.flowManager.translate; } render() { const title = t('creation.p4.step1.title'); //TODO Change the below github title return ( <FlowStep {...this.props} className="credentials-picker-perforce" title={title}> <FormElement title={t('creation.p4.step1.instructions')}> <Dropdown ref={dropdown => { this.dropdown = dropdown; }} options={this.credManager.credentials} labelField="id" onChange={option => this._onChangeDropdown(option)} /> </FormElement> </FlowStep> ); //return ("","",""); } _onChangeDropdown(option) { //TODO may want to do validation later //serverManager.validateVersion(option.id).then(success => this._onValidateVersion(success), error => this._onValidateVersion(error)); this.props.flowManager.selectCredential(option.id); } } PerforceCredentialsStep.propTypes = { flowManager: PropTypes.object, }; export default PerforceCredentialsStep; <file_sep>package io.jenkins.blueocean.blueocean_github_pipeline; import com.google.common.base.Charsets; import com.google.common.hash.Hashing; import io.jenkins.blueocean.rest.hal.Link; import io.jenkins.blueocean.rest.impl.pipeline.scm.ScmServerEndpoint; import org.jenkinsci.plugins.github_branch_source.Endpoint; public class GithubServer extends ScmServerEndpoint { private final Endpoint endpoint; private final Link parent; GithubServer(Endpoint endpoint, Link parent) { this.endpoint = endpoint; this.parent = parent; } @Override public String getId() { return Hashing.sha256().hashString(endpoint.getApiUri(), Charsets.UTF_8).toString(); } @Override public String getName() { return endpoint.getName(); } @Override public String getApiUrl() { return endpoint.getApiUri(); } @Override public Link getLink() { return parent.rel(getId()); } } <file_sep>import React from 'react'; import {action, computed, observable} from 'mobx'; import {i18nTranslator, logging, sseService} from '@jenkins-cd/blueocean-core-js'; const translate = i18nTranslator('blueocean-dashboard'); import FlowManager from '../CreationFlowManager'; import waitAtLeast from '../flow2/waitAtLeast'; import STATE from "../perforce/PerforceCreationState"; import PerforceLoadingStep from "./steps/PerforceLoadingStep"; import PerforceCredentialsStep from "./steps/PerforceCredentialStep"; import PerforceCredentialsManager from "../../credentials/perforce/PerforceCredentialsManager"; import {ListProjectsOutcome} from './api/PerforceCreationApi'; import PerforceProjectListStep from './steps/PerforceProjectListStep'; import PerforceCompleteStep from './steps/PerforceCompleteStep'; import {CreateMbpOutcome} from "./api/PerforceCreationApi"; import PerforceRenameStep from "./steps/PerforceRenameStep"; import PerforceUnknownErrorStep from "./steps/PerforceUnknownErrorStep"; const LOGGER = logging.logger('io.jenkins.blueocean.p4-pipeline'); const MIN_DELAY = 500; const SSE_TIMEOUT_DELAY = 1000 * 60; /** * Impl of FlowManager for perforce creation flow. */ export default class PerforceFlowManager extends FlowManager { selectedCred = null; pipelineName = null; pipeline = null; _sseSubscribeId = null; _sseTimeoutId = null; @observable projects = []; @observable selectedProject = null; @computed get stepsDisabled() { return ( this.stateId === STATE.STEP_COMPLETE_EVENT_ERROR || this.stateId === STATE.STEP_COMPLETE_EVENT_TIMEOUT || this.stateId === STATE.STEP_COMPLETE_MISSING_JENKINSFILE || this.stateId === STATE.PENDING_CREATION_SAVING || this.stateId === STATE.PENDING_CREATION_EVENTS || this.stateId === STATE.STEP_COMPLETE_SUCCESS ); } constructor(creationApi, credentialApi) { super(); this._creationApi = creationApi; this.credManager = new PerforceCredentialsManager(credentialApi); } translate(key, opts) { return translate(key, opts); } getScmId() { return 'perforce'; } getState() { return STATE; } getStates() { return STATE.values(); } getInitialStep() { return { stateId: STATE.PENDING_LOADING_CREDS, stepElement: <PerforceLoadingStep/>, }; } onInitialized() { this._loadCredentialsList(); this.setPlaceholders(translate('creation.core.status.completed')); } _loadCredentialsList() { return this.credManager .findExistingCredential() .then(waitAtLeast(MIN_DELAY)) .then(success => this._loadCredentialsComplete(success)); } //TODO response is not used at the moment. Will be used when handling bad credentials later. _loadCredentialsComplete(response) { //this.credentials = response; this.renderStep({ stateId: STATE.STEP_CHOOSE_CREDENTIAL, stepElement: <PerforceCredentialsStep/>, afterStateId: null, }); } selectCredential(credential) { this.selectedCred = credential; this._renderLoadingProjects(); } _renderLoadingProjects() { this.renderStep({ stateId: STATE.PENDING_LOADING_PROJECTS, stepElement: <PerforceLoadingStep/>, afterStateId: this._getProjectsStepAfterStateId(), }); this.listProjects(); } _getProjectsStepAfterStateId() { return STATE.STEP_CHOOSE_CREDENTIAL; } @action listProjects() { this._creationApi .listProjects(this.selectedCred) .then(waitAtLeast(MIN_DELAY)) .then(projects => this._listProjectsSuccess(projects)); } @action _listProjectsSuccess(response) { if (response.outcome === ListProjectsOutcome.SUCCESS) { this.projects = response.projects; this._renderChooseProject(); } else if (response.outcome === ListProjectsOutcome.INVALID_CREDENTIAL_ID) { this.renderStep({ stateId: STATE.STEP_CHOOSE_CREDENTIAL, stepElement: <PerforceCredentialsStep/>, afterStateId: null, }); } else { this.renderStep({ stateId: STATE.ERROR_UNKNOWN, stepElement: <PerforceUnknownErrorStep message={response.error}/>, }); } } _renderChooseProject() { this.renderStep({ stateId: STATE.STEP_CHOOSE_PROJECT, stepElement: <PerforceProjectListStep/>, afterStateId: this._getProjectsStepAfterStateId(), }); } @action selectProject(project) { this.selectedProject = project; this.pipelineName = project; } saveRepo() { this._saveRepo(); } @action _saveRepo() { const afterStateId = this.isStateAdded(STATE.STEP_RENAME) ? STATE.STEP_RENAME : STATE.STEP_CHOOSE_PROJECT; this.renderStep({ stateId: STATE.PENDING_CREATION_SAVING, stepElement: <PerforceCompleteStep/>, afterStateId, }); this.setPlaceholders(); this._initListeners(); this._creationApi.createMbp(this.selectedCred, this.selectedProject, this.pipelineName) .then(waitAtLeast(MIN_DELAY * 2)) .then(result => this._createPipelineComplete(result)); } saveRenamedPipeline(pipelineName) { this.pipelineName = pipelineName; return this._saveRepo(); } @action _createPipelineComplete(result) { this.outcome = result.outcome; if (result.outcome === CreateMbpOutcome.SUCCESS) { //TODO Assumption here is Jenkinsfile is present. So not checking for it. this._checkForBranchCreation( result.pipeline.name, true, ({ isFound, hasError, pipeline }) => { if (!hasError && isFound) { this._finishListening(STATE.STEP_COMPLETE_SUCCESS); this.pipeline = pipeline; this.pipelineName = pipeline.name; } }, this.redirectTimeout ); } else if (result.outcome === CreateMbpOutcome.INVALID_NAME) { this.renderStep({ stateId: STATE.STEP_RENAME, stepElement: <PerforceRenameStep pipelineName={this.pipelineName}/>, afterStateId: STATE.STEP_CHOOSE_PROJECT, }); this._showPlaceholder(); } else if (result.outcome === CreateMbpOutcome.INVALID_URI || result.outcome === CreateMbpOutcome.INVALID_CREDENTIAL) { this.removeSteps({afterStateId: STATE.STEP_CREDENTIAL}); this._showPlaceholder(); } else if (result.outcome === CreateMbpOutcome.ERROR) { const afterStateId = this.isStateAdded(STATE.STEP_RENAME) ? STATE.STEP_RENAME : STATE.STEP_CHOOSE_PROJECT; this.renderStep({ stateId: STATE.ERROR, stepElement: <PerforceUnknownErrorStep error={result.error}/>, afterStateId, }); } } _showPlaceholder() { this.setPlaceholders([ this.translate('creation.core.status.completed'), ]); } _checkForBranchCreation(pipelineName, multiBranchIndexingComplete, onComplete, delay = 500) { if (multiBranchIndexingComplete) { LOGGER.debug(`multibranch indexing for ${pipelineName} completed`); } LOGGER.debug(`will check for branches of ${pipelineName} in ${delay}ms`); setTimeout(() => { this._creationApi.findBranches(pipelineName).then(data => { LOGGER.debug(`check for pipeline complete. created? ${data.isFound}`); onComplete(data); }); }, delay); } checkPipelineNameAvailable(name) { if (!name) { return new Promise(resolve => resolve(false)); } return this._creationApi.checkPipelineNameAvailable(name); } @action setPlaceholders(placeholders) { let array = []; if (typeof placeholders === 'string') { array.push(placeholders); } else if (placeholders) { array = placeholders; } this.placeholders.replace(array); } _initListeners() { this._cleanupListeners(); LOGGER.info('P4: listening for project folder and multi-branch indexing events...'); this._sseSubscribeId = sseService.registerHandler(event => this._onSseEvent(event)); this._sseTimeoutId = setTimeout(() => { this._onSseTimeout(); }, SSE_TIMEOUT_DELAY); } _cleanupListeners() { if (this._sseSubscribeId || this._sseTimeoutId) { LOGGER.debug('cleaning up existing SSE listeners'); } if (this._sseSubscribeId) { sseService.removeHandler(this._sseSubscribeId); this._sseSubscribeId = null; } if (this._sseTimeoutId) { clearTimeout(this._sseTimeoutId); this._sseTimeoutId = null; } } _onSseTimeout() { LOGGER.debug(`wait for events timed out after ${SSE_TIMEOUT_DELAY}ms`); this.changeState(STATE.STEP_COMPLETE_EVENT_TIMEOUT); this._cleanupListeners(); } _onSseEvent(event) { if (LOGGER.isDebugEnabled()) { this._logEvent(event); } if ( event.blueocean_job_pipeline_name === this.pipelineName && event.jenkins_object_type === 'org.jenkinsci.plugins.workflow.job.WorkflowRun' && (event.job_run_status === 'ALLOCATED' || event.job_run_status === 'RUNNING' || event.job_run_status === 'SUCCESS' || event.job_run_status === 'FAILURE') ) { // set pipeline details that are needed later on in PerforceCompleteStep.navigatePipeline() this.pipeline = { organization: event.jenkins_org, fullName: this.pipelineName }; this._finishListening(STATE.STEP_COMPLETE_SUCCESS); return; } const multiBranchIndexingComplete = event.job_multibranch_indexing_result === 'SUCCESS' && event.blueocean_job_pipeline_name === this.pipelineName; if (multiBranchIndexingComplete) { LOGGER.info(`creation succeeded for ${this.pipelineName}`); if (event.jenkinsfile_present === 'false') { this._finishListening(STATE.STEP_COMPLETE_MISSING_JENKINSFILE); } } else if (event.job_multibranch_indexing_result === 'FAILURE') { this._finishListening(STATE.STEP_COMPLETE_EVENT_ERROR); } else { this._checkForBranchCreation(event.blueocean_job_pipeline_name, false, ({ isFound, hasError, pipeline }) => { if (isFound && !hasError) { this._finishListening(STATE.STEP_COMPLETE_SUCCESS); this.pipeline = pipeline; this.pipelineName = pipeline.name; } }); } } _finishListening(stateId) { console.log('PerforceFlowManager: finishListening()', stateId); this.changeState(stateId); this._cleanupListeners(); } } <file_sep>package io.jenkins.blueocean.blueocean_github_pipeline; import com.fasterxml.jackson.annotation.JsonProperty; import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; import org.kohsuke.github.GHRepository; /** * Expose github repository 'private' field * * GHRepository defines _private but doesn't get deserialized reliably with Jackson * * @author <NAME> */ @SuppressFBWarnings(value = "EQ_DOESNT_OVERRIDE_EQUALS", justification = "no extra state added to affect superclass equality") public class GHRepoEx extends GHRepository { @JsonProperty("private") private boolean _private; @Override public boolean isPrivate() { return _private; } } <file_sep>import {action, observable} from 'mobx'; /** * Manages retrieving, validating and saving the Perforce credentials. * Also holds the state of the credential for use in PerforceCredentialStep. */ class PerforceCredentialsManager { @observable credentials = []; constructor(credentialsApi) { this.credentialsApi = credentialsApi; } @action findExistingCredential() { return this.credentialsApi.findExistingCredential().then(credentials => this._onfindCredSuccess(credentials)); } @action _onfindCredSuccess(creds) { // We need only perforce credentials, so filter the non Perforce credentials out //TODO Is there a better way of doing this? const length = creds.length; for (let i = 0; i < length; i++) { const obj = creds[i]; if (obj.typeName.startsWith("Perforce")) { this.credentials.push(obj); } } return this.credentials; } } export default PerforceCredentialsManager; <file_sep>window.addEventListener('load', function() { var eventData = { name: 'pageview', properties: { mode: 'classic' } }; new Ajax.Request(rootURL + '/blue/rest/analytics/track', { method: 'POST', contentType: 'application/json', postBody: JSON.stringify(eventData), onFailure: function() { console.error('Could not send pageview event'); }, }); }); <file_sep>#!/bin/bash download() { pushd runner if [ ! -d bin ]; then mkdir bin fi URL=$1 DOWNTO=$2 if [ -f "$DOWNTO" ]; then echo "" echo "***** ${DOWNTO} already downloaded. Skipping download." echo "" popd return fi echo "" echo "Downloading ${URL} to ${DOWNTO} ..." echo "" # Try for curl, then wget, or fail if hash curl 2>/dev/null; then curl -o $DOWNTO -L $URL elif hash wget 2>/dev/null; then wget -O $DOWNTO $URL else popd echo "curl or wget must be installed." exit 1 fi if [ $? != 0 ] then popd echo " ************************************" echo " **** ${DOWNTO} download failed." echo " ************************************" exit 1 fi popd } <file_sep>package io.jenkins.blueocean.rest.impl.pipeline; import io.jenkins.blueocean.service.embedded.rest.QueueUtil; import org.jenkinsci.plugins.workflow.job.WorkflowJob; import org.jenkinsci.plugins.workflow.job.WorkflowRun; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mock; import org.mockito.internal.verification.VerificationModeFactory; import org.powermock.api.mockito.PowerMockito; import org.powermock.core.classloader.annotations.PowerMockIgnore; import org.powermock.core.classloader.annotations.PrepareForTest; import org.powermock.modules.junit4.PowerMockRunner; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNull; @RunWith(PowerMockRunner.class) @PrepareForTest({ WorkflowRun.class, WorkflowJob.class, QueueUtil.class }) @PowerMockIgnore({"javax.crypto.*", "javax.security.*", "javax.net.ssl.*"}) public class PipelineNodeImplTest { @Mock WorkflowJob job; @Mock WorkflowRun run; @Test public void getRun_NeverFound() throws Exception { PowerMockito.mockStatic(QueueUtil.class); PowerMockito.when(QueueUtil.getRun(job, 1)).thenReturn(null); WorkflowRun workflowRun = PipelineNodeImpl.getRun(job, 1); assertNull(workflowRun); PowerMockito.verifyStatic(QueueUtil.class, VerificationModeFactory.atLeastOnce()); QueueUtil.getRun(job, 1); // need to call again to handle verify } @Test public void getRun_FirstFound() throws Exception { PowerMockito.mockStatic(QueueUtil.class); PowerMockito.when(QueueUtil.getRun(job, 1)).thenReturn(run); WorkflowRun workflowRun = PipelineNodeImpl.getRun(job, 1); assertEquals(workflowRun, run); PowerMockito.verifyStatic(QueueUtil.class, VerificationModeFactory.times(1)); QueueUtil.getRun(job, 1); // need to call again to handle verify } @Test public void getRun_EventuallyFound() throws Exception { PowerMockito.mockStatic(QueueUtil.class); PowerMockito.when(QueueUtil.getRun(job, 1)).thenReturn(null).thenReturn(null).thenReturn(null).thenReturn(run); WorkflowRun workflowRun = PipelineNodeImpl.getRun(job, 1); assertEquals(workflowRun, run); PowerMockito.verifyStatic(QueueUtil.class, VerificationModeFactory.times(4)); QueueUtil.getRun(job, 1); // need to call again to handle verify } }
f0128302da5a8ee184eb57be061a961edbab5188
[ "JavaScript", "INI", "Java", "Dockerfile", "Shell" ]
31
JavaScript
p4charu/blueocean-plugin
c4c05961d109b30bb9d4d3a056e2ce70db9eaac5
156e896fe0e172e7c1ee72f2c82999d3f95d1ea4
refs/heads/master
<file_sep>def square_array(array) array1 = [] array.each do |numbers| array1 << numbers**2 end array1 end
9c2e0f9e8ab8d23f0f56e343af760f7f7744acc0
[ "Ruby" ]
1
Ruby
tgrosch91/square_array-ruby-apply-000
36125ac741cb1a150ccc4af60cb512ee9f4f9d1b
76fcf1669f35eaa8609f640f7fb553b71ef8b573
refs/heads/master
<repo_name>tudarmstadt-lt/jwatson<file_sep>/README.md jwatson ======= A Java wrapper for the IBM Watson DQA service. Getting started --------------- The latest release is [jwatson 1.0](https://github.com/tudarmstadt-lt/jwatson/releases/tag/1.0.0). Build --------------- Use `sbt clean compile assembly` to build the project. The fat `jar` file can be found in the `/target` folder. Usage - In a Nutshell ----- ```java public static void main(String[] args) throws IOException { // Create a Watson instance with your URL and credentials JWatson watson = new JWatson("username", "password", "https://url/instance/xxxxx/deepqa/"); // Query Watson to retrieve answers for a specific question // WatsonAnswer answer = watson.askQuestion("Who is <NAME>?"); // ... or use the QuestionBuilder to construct complex questions for Watson WatsonQuestion question = new WatsonQuestion.QuestionBuilder("Who is <NAME>?") .setNumberOfAnswers(3) // Provide three possible answers .formatAnswer() // Instruct Watson to deliver answers in HTML .create(); WatsonAnswer answer = watson.askQuestion(question); System.out.println(answer); } ``` #### Note * Make sure that the URL contains a trailing slash at the end. Known bugs and issues ---------------- * Ping and Feedback endpoints are not implemented yet. * To use JWatson with the Bluemix QA service instead of an university (private-) instance, you need make slightly modifications in the JSON structure. License ------- ``` Copyright 2016 Technische Universität Darmstadt. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ``` See also -------- [IBM Watson Developer Cloud API Reference](http://www.ibm.com/smarterplanet/us/en/ibmwatson/developercloud/apis/#!/Question_Answer) <file_sep>/src/main/java/jwatson/JWatson.java /* * Copyright 2016 Technische Universität Darmstadt * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * Contributors: * - <NAME> * */ package jwatson; import jwatson.answer.WatsonAnswer; import jwatson.feedback.Feedback; import jwatson.question.WatsonQuestion; import java.io.*; import java.net.*; import java.util.logging.Level; import java.util.logging.Logger; /** * The Watson API adapter class. * * @author <NAME> */ public class JWatson implements IWatsonRestService { private static Logger logger = Logger.getLogger(JWatson.class.getName()); private final URL url; private final String username; private final String password; public JWatson(String username, String password, String url) throws MalformedURLException { this.username = username; this.password = <PASSWORD>; this.url = new URL(url); setAuthentication(); } private void setAuthentication() { Authenticator.setDefault(new Authenticator() { protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication(JWatson.this.username, JWatson.this.password.toCharArray()); } }); } /** * Pings the service to verify that it is available. * * @return <code>true</code> if the service is available. Otherwise <code>false</code>. */ public boolean ping() { // HttpResponse response = null; // try { // Executor executor = Executor.newInstance().auth(username, password); // URI serviceURI = new URI(url + "/v1/ping").normalize(); // // System.out.print(serviceURI.toString()); // // response = executor.execute(Request.Get(serviceURI) // .addHeader("X-SyncTimeout", "30")).returnResponse(); // // } catch (Exception ex) { // logger.log(Level.SEVERE, "Got the following error: " + ex.getMessage(), ex); // } // int statusCode = response.getStatusLine().getStatusCode(); // // //200: Service is available, 500: Server error // return (statusCode == 200); return false; } /** * Ask Watson a question via the Question and Answer API. * * @param questionText question to ask Watson * @return WatsonAnswer * @throws IOException */ public WatsonAnswer askQuestion(String questionText) throws IOException { WatsonQuestion question = new WatsonQuestion.QuestionBuilder(questionText).create(); return queryService(question); } public WatsonAnswer askQuestion(WatsonQuestion question) throws IOException { return queryService(question); } public boolean sendFeedback(Feedback feedback) { // HttpResponse response = null; // try { // Executor executor = Executor.newInstance().auth(username, password); // URI serviceURI = new URI(url + "/v1/feedback").normalize(); // // response = executor.execute(Request.Put(serviceURI) // .addHeader("Accept", "application/json") // .addHeader("X-SyncTimeout", "30") // .bodyString(feedback.toJson().toString(), ContentType.APPLICATION_JSON)).returnResponse(); // // // } catch (Exception ex) { // logger.log(Level.SEVERE, "Got the following error: " + ex.getMessage(), ex); // } // // int statusCode = response.getStatusLine().getStatusCode(); // // // 201 - Accepted, 400 - Bad request. Most likely the result of a missing required parameter. // return (statusCode == 201); return false; } private WatsonAnswer queryService(WatsonQuestion question) throws IOException { HttpURLConnection urlConnection; WatsonAnswer answer; URL queryUrl = new URL(url, "v1/question/"); logger.log(Level.INFO, "Connecting to: " + queryUrl.toString()); urlConnection = (HttpURLConnection) queryUrl.openConnection(); // Connect urlConnection.setDoOutput(true); urlConnection.setRequestProperty("Accept", "application/json"); urlConnection.setRequestProperty("X-SyncTimeout", "30"); urlConnection.setRequestMethod("POST"); urlConnection.setRequestProperty("Content-Type", "APPLICATION/JSON"); urlConnection.connect(); // Write OutputStream out = urlConnection.getOutputStream(); OutputStreamWriter writer = new OutputStreamWriter(out); writer.write(question.toJsonString()); writer.close(); out.close(); logger.log(Level.INFO, "Sending Query: " + question.toJsonString()); int status = urlConnection.getResponseCode(); logger.log(Level.INFO, "Response Code " + status); // Read InputStream in = (status >= HttpURLConnection.HTTP_BAD_REQUEST) ? urlConnection.getErrorStream(): urlConnection.getInputStream(); String content = convertStreamToString(in); in.close(); if (status >= HttpURLConnection.HTTP_BAD_REQUEST) { logger.log(Level.SEVERE, content); throw new IOException(String.format("%d : %s", status, in)); } else { answer = WatsonAnswer.createAnswerFromContent(content); } urlConnection.disconnect(); return answer; } private String convertStreamToString(InputStream is) throws IOException { BufferedReader reader = new BufferedReader(new InputStreamReader(is)); StringBuilder sb = new StringBuilder(); String line; while ((line = reader.readLine()) != null) { sb.append(line); } is.close(); return sb.toString(); } } <file_sep>/src/main/java/jwatson/answer/Answer.java /* * Copyright 2016 Technische Universität Darmstadt * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * Contributors: * - <NAME> * */ package jwatson.answer; public class Answer { /** * An integer that uniquely identifies an answer in the context of the question. */ private int id; /** * A string that contains an answer to the question in the form of text. */ private String text; /** * (optional) * The HTML-formatted version of the answer text that is returned when you set formattedAnswer * to true when you submit a question. The formatted answer includes content from the tag of the answer. */ private String formattedText; /** * A decimal percentage that represents the confidence that Watson has in this answer. * Higher values represent higher confidences. */ private float confidence; /** * ??? */ private String pipeline; public int getId() { return id; } public String getText() { return text; } public String getFormattedText() { return formattedText; } public float getConfidence() { return confidence; } public String getPipeline() { return pipeline; } @Override public String toString() { return "Answer{" + "id=" + id + ", text='" + text + '\'' + ", formattedText='" + formattedText + '\'' + ", confidence=" + confidence + ", pipeline='" + pipeline + '\'' + '}'; } } <file_sep>/src/main/java/jwatson/answer/Synonymlist.java /* * Copyright 2016 Technische Universität Darmstadt * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * Contributors: * - <NAME> * */ package jwatson.answer; import java.util.List; public class Synonymlist { private String partOfSpeech; private String value; private String lemma; /** * The set that represents the source (such as wordnet or wikiredirect) of the synonyms. */ private List<Synset> synSet; public String getPartOfSpeech() { return partOfSpeech; } public String getValue() { return value; } public String getLemma() { return lemma; } public List<Synset> getSynset() { return synSet; } @Override public String toString() { return "Synonymlist{" + "partOfSpeech='" + partOfSpeech + '\'' + ", value='" + value + '\'' + ", lemma='" + lemma + '\'' + ", synset=" + synSet + '}'; } } <file_sep>/src/main/java/jwatson/question/WatsonQuestion.java /* * Copyright 2016 Technische Universität Darmstadt * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * Contributors: * - <NAME> * */ package jwatson.question; import com.google.gson.Gson; public class WatsonQuestion { private QuestionInformation question; private WatsonQuestion(QuestionBuilder builder) { this.question = new QuestionInformation(builder.questionText, builder.items, builder.category, builder.context, builder.formattedAnswer); } public QuestionInformation getQuestion() { return question; } public String toJsonString() { return new Gson().toJson(this).toString(); } @Override public String toString() { return "WatsonQuestion{" + "question=" + question + '}'; } public static class QuestionBuilder { private final String questionText; private int items; private boolean formattedAnswer; private String category; private String context; public QuestionBuilder(String questionText) { this.questionText = questionText; this.items = 5; } public QuestionBuilder setNumberOfAnswers(int num) { this.items = num; return this; } public QuestionBuilder formatAnswer() { this.formattedAnswer = true; return this; } public QuestionBuilder setCategory(String category) { this.category = category; return this; } public QuestionBuilder setContext(String context) { this.context = context; return this; } public WatsonQuestion create() { return new WatsonQuestion(this); } } } <file_sep>/src/main/java/jwatson/feedback/Feedback.java /* * Copyright 2016 Technische Universität Darmstadt * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * Contributors: * - <NAME> * */ package jwatson.feedback; import com.google.gson.Gson; import com.google.gson.JsonElement; import com.google.gson.JsonObject; import com.google.gson.JsonParser; import jwatson.answer.Answer; import jwatson.question.QuestionInformation; public class Feedback { /** * The question ID, obtained from the QA API result. */ private String questionId; /** * The question text obtained from the QA API result. */ private String questionText; /** * The answer ID to provide feedback on. The Answer ID is obtained from the QA API result. */ private String answerId; /** * The answer text to provide feedback on. The answer text is obtained from the QA API result. */ private String answerText; /** * (optional) * The name of the user submitting the feedback. */ private String userName; /** * (optional) * The Watson mode used to obtain the QA API result. */ private WatsonMode mode; /** * (optional) * The confidence of the answer obtained from the QA API result. */ private String confidence; /** * (optional) * If the answer was shown to the user. */ private boolean shown; /** * (optional) * If the evidence was viewed by the user. */ private boolean evidenceViewed; /** * (optional) * Representation of the feedback. */ private FeedbackRating feedback; /** * (optional) * User comment. */ private String comment; private Feedback(FeedbackBuilder builder) { this.questionId = builder.questionId; this.questionText = builder.questionText; this.answerId = builder.answerId; this.answerText = builder.answerText; this.feedback = builder.feedback; this.confidence = builder.confidence; this.comment = builder.comment; } public JsonObject toJson() { Gson gson = new Gson(); JsonElement data = new JsonParser().parse(gson.toJson(this)); return data.getAsJsonObject(); } public static class FeedbackBuilder { private final String questionId; private final String questionText; private final String answerId; private final String answerText; private FeedbackRating feedback; private String confidence; private String comment; public FeedbackBuilder(String id, QuestionInformation question, Answer answer) { this(id, question.getQuestionText(), answer.getId(), answer.getText()); } private FeedbackBuilder(String questionId, String questionText, int answerId, String answerText) { this.questionId = questionId; this.questionText = questionText; //weird api answer id is an integer and feedback call wants it as string this.answerId = Integer.toString(answerId); this.answerText = answerText; } public FeedbackBuilder addRating(FeedbackRating rating) { this.feedback = rating; return this; } public FeedbackBuilder addComment(String comment) { this.comment = comment; return this; } public FeedbackBuilder withConfidence(int confidence) { this.confidence = Integer.toString(confidence); return this; } public Feedback create() { return new Feedback(this); } } } <file_sep>/src/main/java/jwatson/question/QuestionInformation.java /* * Copyright 2016 Technische Universität Darmstadt * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * Contributors: * - <NAME> * */ package jwatson.question; import java.util.List; /** * A question to ask Watson. * See "IBM Watson Developer Cloud" for more details * IBM Watson Developer Cloud: http://www.ibm.com/smarterplanet/us/en/ibmwatson/developercloud/apis/#!/Question_Answer/question * * @author <NAME> */ public class QuestionInformation { /** * The text of the question to be answered. */ private String questionText; /** * An integer in the range 1 – 10 that represents the number of possible answers to be returned. * If you do not specify the number of items, the request assumes five answers. */ private int items; /** * Specifies that you want Watson to return supporting evidence * for each answer in the answers/answer/evidence section of the answer response. */ private EvidenceRequest evidenceRequest; /** * (optional) * Specify an answer to receive the supporting evidence passages for that answer. Without this element, * Watson searches for answers from the questionText. When you assert an answer, Watson uses that answer * instead to search for supporting evidence passages. * * If you configured your pipeline to support a ranked list of evidence, the supporting evidence appears * in the question/evidencelist section. If you include the evidenceRequest element with the question, the * supporting evidence appears in the answers/answer/evidence section. If no supporting passages are returned * for the asserted answer, the API returns a message that no answers were found. * * Restriction: Your processing pipeline must be configured to support AnswerAssertionPrimarySearch. * Otherwise, the element is ignored. */ private String answerAssertion; /** * The category of the question in terms of a constraint on the possible answers. */ private String category; /** * (optional) * A natural language string that is composed of words that provide extra information for Watson to * consider when it determines answers. The maximum length of this element is 1024 characters. * * The context element can have one of the following values: * <ul> * <li>Plain text: * The context is provided as text in the context element: <context>Fauna</context> * </li> * <li>Url: * A valid URL that points to the context string. The service accepts text and HTML in the * response. * * <context>http://www.example.com/fauna.txt</context> * * The first 1024 characters of the contents in the file that is identified by the URL are used as * the context value. If the file is not found (HTTP 404), the service returns an error and the * question is not submitted to Watson. * </li> * </ul> */ private String context; /** * Requests Watson to return the formatted answer. */ private boolean formattedAnswer; /** * Specifies a string that you include with the question. The passthru data is not submitted with the * pipeline but does pass through to the answer. */ //Todo: Add to answer private String passthru; /** * The lexical answer type (LAT) of the question. The LAT is a word or noun phrase that appears in the * question, or is implied by it. LATs are terms in the question that indicate what type of entity is * being asked for. The headword of the focus is generally a LAT, but questions often contain additional * LATs. LATs are used by Watson’s type coercion components to determine whether a candidate answer * is an instance of the answer types. */ private String lat; /** * Supports the use of metadata to restrict answers to specific documents. */ //Todo: Filter add own builder? private List<Filter> filters; public QuestionInformation(String questionText, int items, String category, String context, boolean formattedAnswer) { this.questionText = questionText; this.items = items; this.category = category; this.context = context; this.formattedAnswer = formattedAnswer; //TODO: Init rest } public String getQuestionText() { return questionText; } public int getNumberOfAnswers() { return items; } public boolean isFormattedAnswer() { return formattedAnswer; } @Override public String toString() { return "QuestionInformation{" + "questionText='" + questionText + '\'' + ", items=" + items + ", evidenceRequest=" + evidenceRequest + ", answerAssertion='" + answerAssertion + '\'' + ", category='" + category + '\'' + ", context='" + context + '\'' + ", formattedAnswer=" + formattedAnswer + ", passthru='" + passthru + '\'' + ", lat='" + lat + '\'' + ", filters=" + filters + '}'; } } <file_sep>/src/main/java/jwatson/answer/AnswerInformation.java /* * Copyright 2016 Technische Universität Darmstadt * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * Contributors: * - <NAME> * */ package jwatson.answer; import java.util.ArrayList; import java.util.List; public class AnswerInformation { /** * An integer that is assigned by the service to * identify this question and its answers. */ private String id; /** * The response status of the request e.g 'Complete', * 'Timeout' or 'Failed'. */ private String status; /** * The category of the question that was submitted with * the question. When no category was submitted with the * question, an empty category element is returned in the * response. */ private String category; /** * The internal ID that is assigned for the final answer CAS. * This element contains the internal CAS ID that is assigned * after the question is answered. You can use this ID to identify * the question with the internal data structures that Watson uses. */ private String pipelineid; /** * The container for a list of question classes that are determined * by the pipeline for the final answer. */ private List<Qclasslist> qclasslist; /** * The collection of focus elements that are determined by the pipeline * for the final answer. */ private List<Focuslist> focuslist; /** * The collection of lexical answer types (LATs) that the pipeline determined for * the final answer. The WatsonQuestion.lat is submitted in the POST when the question * was submitted. The WatsonQuestion.latlist contains the LATs that were determined * by the pipeline when it processed the answer. */ private List<Latlist> latlist; /** * The collection of synonyms for terms in the question. */ private List<Synonymlist> synonymList; /** * The collection of recoverable errors, if any. */ private List<ErrorNotification> errorNotifications; /** * The collection of evidence used to support the answer(s). */ private List<Evidencelist> evidencelist; /** * The collection of answers. */ private List<Answer> answers; public AnswerInformation() { this.focuslist = new ArrayList<Focuslist>(); this.latlist = new ArrayList<Latlist>(); this.evidencelist = new ArrayList<Evidencelist>(); } public String getId() { return id; } public String getStatus() { return status; } public String getCategory() { return category; } public String getPipelineid() { return pipelineid; } public List<Qclasslist> getQclasslist() { return qclasslist; } public List<Focuslist> getFocuslist() { return focuslist; } public List<Latlist> getLatlist() { return latlist; } public List<Synonymlist> getSynonymList() { return synonymList; } public List<ErrorNotification> getErrorNotifications() { return errorNotifications; } public List<Evidencelist> getEvidencelist() { return evidencelist; } public List<Answer> getAnswers() { return answers; } @Override public String toString() { return "WatsonAnswer{" + "id='" + id + '\'' + ", status='" + status + '\'' + ", category='" + category + '\'' + ", pipelineid='" + pipelineid + '\'' + ", qclasslist=" + qclasslist + ", focuslist=" + focuslist + ", latlist=" + latlist + ", synonymList=" + synonymList + ", errorNotifications=" + errorNotifications + ", evidencelist=" + evidencelist + ", answers=" + answers + '}'; } } <file_sep>/src/main/java/jwatson/feedback/WatsonMode.java /* * Copyright 2016 Technische Universität Darmstadt * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * Contributors: * - <NAME> * */ package jwatson.feedback; import com.google.gson.annotations.SerializedName; public enum WatsonMode { @SerializedName("prod") PRODUCTION, @SerializedName("m_prod") M_PRODUCTION, @SerializedName("test") TESTING, @SerializedName("M_TESTING") M_TESTING, }
07e88f4fd439e66b20e9f39b7c3968fe9060f288
[ "Markdown", "Java" ]
9
Markdown
tudarmstadt-lt/jwatson
6f71268ab7dcdd50084c9e42636a8c2f8fa2b606
dedf29d5b669c4cc3125bfa843f18baf0c640418
refs/heads/master
<repo_name>cpfriend1721994/fastlane-plugin-mattermost<file_sep>/lib/fastlane/plugin/mattermost/actions/mattermost_action.rb require 'fastlane/action' require_relative '../helper/mattermost_helper' DEFAULT_USERNAME = "Fastlane Mattermost" DEFAULT_ICON_URL = "https://www.mattermost.org/wp-content/uploads/2016/04/icon.png" def is_set variable str_variable = variable str_variable = variable.strip if variable.class.to_s == "String" variable && !(str_variable.nil? || str_variable.empty?) end module Fastlane module Actions class MattermostAction < Action def self.run(params) require 'net/http' require 'uri' require 'json' begin uri = URI.parse(params[:url]) header = { 'Content-Type': 'application/json' } body = { 'username': (is_set(params[:username]) ? params[:username] : DEFAULT_USERNAME), 'icon_url': (is_set(params[:icon_url]) ? params[:icon_url] : DEFAULT_ICON_URL) } if !is_set(params[:text]) && !is_set(params[:attachments]) UI.error("You need to set either 'text' or 'attachments'") return end body.merge!('text': params[:text]) if is_set(params[:text]) body.merge!('channel': params[:channel]) if is_set(params[:channel]) body.merge!('icon_emoji': params[:icon_emoji]) if is_set(params[:icon_emoji]) body.merge!('attachments': params[:attachments]) if is_set(params[:attachments]) body.merge!('props': params[:props]) if is_set(params[:props]) body.merge!('type': params[:type]) if is_set(params[:type]) http = Net::HTTP.new(uri.host, uri.port) http.use_ssl = (uri.scheme == 'https') request = Net::HTTP::Post.new(uri.request_uri, header) request.body = body.to_json response = http.request(request) rescue => exception UI.error("Exception: #{exception}") return end UI.success('Successfully push messages to Mattermost') end def self.description "Fastlane plugin for push messages to Mattermost" end def self.authors ["cpfriend1721994"] end def self.return_value # If your method provides a return value, you can describe here what it does end def self.details # Optional: "Fastlane plugin for push messages to Mattermost" end def self.available_options [ FastlaneCore::ConfigItem.new(key: :url, env_name: "MATTERMOST_WEBHOOKS_URL", sensitive: true, description: "Mattermost Incoming Webhooks URL"), FastlaneCore::ConfigItem.new(key: :text, env_name: "MATTERMOST_WEBHOOKS_TEXT", optional: true, description: "Mattermost Incoming Webhooks Text"), FastlaneCore::ConfigItem.new(key: :username, env_name: "MATTERMOST_WEBHOOKS_USERNAME", optional: true, description: "Mattermost Incoming Webhooks Username"), FastlaneCore::ConfigItem.new(key: :icon_url, env_name: "MATTERMOST_WEBHOOKS_ICON_URL", optional: true, description: "Mattermost Incoming Webhooks Icon URL"), FastlaneCore::ConfigItem.new(key: :channel, env_name: "MATTERMOST_WEBHOOKS_CHANNEL", optional: true, description: "Mattermost Incoming Webhooks Channel"), FastlaneCore::ConfigItem.new(key: :icon_emoji, env_name: "MATTERMOST_WEBHOOKS_ICON_EMOJI", optional: true, description: "Mattermost Incoming Webhooks Icon Emoji"), FastlaneCore::ConfigItem.new(key: :attachments, env_name: "MATTERMOST_WEBHOOKS_ATTACHMENTS", optional: true, skip_type_validation: true, description: "Mattermost Incoming Webhooks Attachments"), FastlaneCore::ConfigItem.new(key: :props, env_name: "MATTERMOST_WEBHOOKS_PROPS", optional: true, description: "Mattermost Incoming Webhooks Properties"), FastlaneCore::ConfigItem.new(key: :type, env_name: "MATTERMOST_WEBHOOKS_TYPE", optional: true, description: "Mattermost Incoming Webhooks Type") ] end def self.is_supported?(platform) # Adjust this if your plugin only works for a particular platform (iOS vs. Android, for example) # See: https://docs.fastlane.tools/advanced/#control-configuration-by-lane-and-by-platform # # [:ios, :mac, :android].include?(platform) true end def self.example_code [ 'mattermost( url: "https://example.mattermost.com/hooks/xxx-generatedkey-xxx", text: "Hello, this is some text\nThis is more text. :tada:", username: "<NAME>", icon_url: "https://www.mattermost.org/wp-content/uploads/2016/04/icon.png" )', 'mattermost( url: "https://example.mattermost.com/hooks/xxx-generatedkey-xxx", text: "Hello, this is some text\nThis is more text. :tada:", username: "<NAME>", icon_url: "https://www.mattermost.org/wp-content/uploads/2016/04/icon.png", channel: ... , icon_emoji: ... , attachments: ... , props: ... , type: ... )' ] end end end end <file_sep>/fastlane/Fastfile lane :test do mattermost end <file_sep>/README.md # mattermost plugin [![fastlane Plugin Badge](https://rawcdn.githack.com/fastlane/fastlane/master/fastlane/assets/plugin-badge.svg)](https://rubygems.org/gems/fastlane-plugin-mattermost) ## Getting Started 1. Generate `Mattermost Incoming Webhook` - From your Mattermost organization page, go to `Integrations` -> `Incoming Webhooks` -> `Add Incoming Webhooks` - Configurate Incoming Webhooks - Get Webhooks URL 2. Add plugin to `fastlane` ```bash fastlane add_plugin mattermost ``` 3. Add `mattermost` to your lane in `Fastfile`, for more infomations about incoming webhook's fields read: https://developers.mattermost.com/integrate/incoming-webhooks/ ```bash lane :build_android do ... # Push messages to Mattermost # Minimum params example mattermost( url: "https://example.mattermost.com/hooks/xxx-generatedkey-xxx", # mandatory text: "Hello, this is some text\nThis is more text. :tada:", # mandatory if 'attachments' is not set username: "Fastlane Mattermost", # optional icon_url: "https://www.mattermost.org/wp-content/uploads/2016/04/icon.png" # optional ) # Full params example mattermost( url: "https://example.mattermost.com/hooks/xxx-generatedkey-xxx", # mandatory text: "Hello, this is some text\nThis is more text. :tada:", # mandatory username: "Fastlane Mattermost", # optional icon_url: "https://www.mattermost.org/wp-content/uploads/2016/04/icon.png", # optional channel: ... , # optional icon_emoji: ... , # optional attachments: [...] , # optional props: ... , # optional type: ... # optional ) ``` ## About mattermost Fastlane plugin for push messages to Mattermost **Note to author:** Add a more detailed description about this plugin here. If your plugin contains multiple actions, make sure to mention them here. ## Example Check out the [example `Fastfile`](fastlane/Fastfile) to see how to use this plugin. Try it by cloning the repo, running `fastlane install_plugins` and `bundle exec fastlane test`. **Note to author:** Please set up a sample project to make it easy for users to explore what your plugin does. Provide everything that is necessary to try out the plugin in this project (including a sample Xcode/Android project if necessary) ## Run tests for this plugin To run both the tests, and code style validation, run ``` rake ``` To automatically fix many of the styling issues, use ``` rubocop -a ``` ## Issues and Feedback For any other issues and feedback about this plugin, please submit it to this repository. ## Troubleshooting If you have trouble using plugins, check out the [Plugins Troubleshooting](https://docs.fastlane.tools/plugins/plugins-troubleshooting/) guide. ## Using _fastlane_ Plugins For more information about how the `fastlane` plugin system works, check out the [Plugins documentation](https://docs.fastlane.tools/plugins/create-plugin/). ## About _fastlane_ _fastlane_ is the easiest way to automate beta deployments and releases for your iOS and Android apps. To learn more, check out [fastlane.tools](https://fastlane.tools). <file_sep>/lib/fastlane/plugin/mattermost/version.rb module Fastlane module Mattermost VERSION = "1.3.2" end end
0f5e5c10cf40490b914ceba5c06f5785088d3eba
[ "Markdown", "Ruby" ]
4
Ruby
cpfriend1721994/fastlane-plugin-mattermost
4cdc750bfcb63741a98bb0b04c392cc02bf020e5
b5fdb2642b2f1b265cafba3b17be3e532b0231cd
refs/heads/main
<repo_name>Dbishop-web/project-8-host-3<file_sep>/routes/books.js const express = require('express'); const router = express.Router(); const Book = require('../models').Book; //asyncHandler wraps each route in this function and is taken as the callback function asyncHandler(callback){ return async(req, res, next) => { try { await callback(req, res, next) } catch(error){ res.status(500).render('error'); } } } // Shows the full list of books. router.get('/', asyncHandler(async (req, res, next) => { const books = await Book.findAll({ order: [['createdAt', 'DESC']]}); res.render('index', { books, title: 'Book list' }); console.log('Rendering books'); })); // Shows the create new book form. router.get('/new', asyncHandler(async (req, res) => { res.render('new-book', {book: {}, title: 'New Book'}); })); // Posts a new book to the database and redirects to the new route. router.post('/', asyncHandler(async (req, res) => { let book ; try { book = await Book.create({ title: req.body.title, author: req.body.author, genre: req.body.genre, year: req.body.year }) res.redirect('/books/' + book.id); } catch (error) { if (error.name === 'SequelizeValidationError') { book = await Book.build(req.body); res.render('update-book', { book, errors: error.errors, title: "New Book" }) } else { throw error; } } })); // Shows book detail form. router.get('/:id', asyncHandler(async (req, res) => { const book = await Book.findByPk(req.params.id); if(book) { res.render('update-book', { book, title: book.title }); } else { throw error; } })); // Updates book info in the database. router.post('/:id', asyncHandler(async (req, res) => { let book; try { book = await Book.findByPk(req.params.id); if(book) { await book.update(req.body); res.redirect('/'); } else { res.sendStatus(404); } } catch (error) { if(error.name === 'SequelizeValidationError') { book = await Book.build(req.body); book.id = req.params.id; res.render('book/' + book.id, { book, errors: error.errors, title: 'Edit Book' }) } else { throw error; } } })); // Deletes a book. router.post('/:id/delete', asyncHandler(async (req ,res) => { const book = await Book.findByPk(req.params.id) await book.destroy(); res.redirect('/books'); })); module.exports = router;
24abd17edd1802535130ed337d3af656ab3c2266
[ "JavaScript" ]
1
JavaScript
Dbishop-web/project-8-host-3
3e05749b83e7644cbd6a270761c97343875c0776
4315debde606879232efb1c57dc1c3a420810d4b
refs/heads/master
<file_sep>package admin; import java.io.IOException; import java.util.Scanner; import main.View; import member.MemberController; import movie.MovieController; public class Admin { final String AdminPw = "<PASSWORD>"; Scanner sc = new Scanner(System.in); public void AdminLogin(MovieController mc, MemberController memc) { while(true){ System.out.println("관리자 비밀번호를 입력해주세요 : "); String AdminPw = sc.nextLine(); if (AdminPw.equals(this.AdminPw)) { return; }else { System.out.println("비밀번호를 잘못입력하셨습니다."); } } } } <file_sep>package main; import java.io.IOException; import java.util.ArrayList; import java.util.Scanner; import admin.Admin; import admin.MemberAd; import admin.MovieAd; import member.Member; import member.MemberController; import member.Reservation; import movie.MovieController; import movie.MovieInfo; public class View { Scanner sc = new Scanner(System.in); MemberAd memAd = new MemberAd(); // 추가_연희 MovieAd moAd = new MovieAd(); // 추가_연희 Admin ad = new Admin(); // 추가_연희 public View() { } public void mainview(MovieController mc, MemberController memc) throws Exception { Reservation res = new Reservation(mc,memc); label: while (true) { System.out.println("=========="); System.out.println("1.로그인"); System.out.println("2.회원가입"); System.out.println("0.종료"); System.out.println("=========="); System.out.print("메뉴를 선택하여 주십시오. "); int ch = sc.nextInt(); switch (ch) { case 1: loginView(res, memc); break; case 2: joinMember(memc); break; case 0: break label; case 3: ad.AdminLogin(mc, memc); // 추가_연희 mainAd(mc, memc); default: break; } } } public void joinMember(MemberController memc) throws IOException { FileSave fs = new FileSave(); System.out.println("이름을 입력하여 주세요."); String id = sc.next(); System.out.println("비밀번호를 입력하여 주세요."); String password = sc.next(); System.out.println("카드번호를 입력하여 주세요."); String card = sc.next(); Member member = new Member(id,password,card); memc.insert(member); fs.memListWriter(memc); System.out.println("회원가입 되었습니다!"); } void loginView(Reservation res, MemberController memc) throws Exception { System.out.print("아이디:"); String id = sc.next(); System.out.print("비밀번호:"); String pass = sc.next(); boolean dec = findId(id, pass, memc); while (dec) { System.out.println("회원 서비스 입니다."); System.out.println("==============="); System.out.println("1.예매하기"); System.out.println("2.나의 예매 확인하기"); System.out.println("0.상위메뉴"); System.out.println("==============="); System.out.print("메뉴를 선택하여 주세요. "); int ch = sc.nextInt(); switch (ch) { case 1: res.service(id,memc); break; case 2: myReserve(res,id,memc); break; case 0: return; default: System.out.println("다시 입력하여 주세요"); break; } } } public boolean findId(String id, String pass, MemberController memc) { if (memc.memList != null) { for (int i = 0; i < memc.memList.size(); i++) { if (id.equals(memc.getLocate(i).getId()) && pass.equals(memc.getLocate(i).getPassword())) { System.out.println("[" + memc.memList.get(i).getId() + "]님 로그인 되었습니다!"); return true; } } } return false; } void myReserve(Reservation res,String id,MemberController memc) throws Exception { System.out.println("나의 예매"); memc.getLocate(memc.findId(id)).getSelectMovie(); System.out.println("------------"); System.out.println("1.다시 예매"); System.out.println("2.예매 취소"); System.out.println("0.상위메뉴"); System.out.println("------------"); System.out.println("메뉴를 선택하여 주십시오."); int ch = sc.nextInt(); switch (ch) { case 1: res.cancel(id, memc); res.service(id, memc); break; case 2: res.cancel(id, memc); // 에매취소 호출 break; case 0: return; } } public void mainAd(MovieController mc, MemberController memc) throws IOException { while (true) { System.out.println("관리자 메뉴입니다."); System.out.println("1.영화 관리"); System.out.println("2.회원 관리"); System.out.println("0.돌아가기"); System.out.println("메뉴를 선택하여 주십시오."); int ch = sc.nextInt(); switch (ch) { case 1: movieAd(mc); // Admin.MovieAd 호출_연희 break; case 2: memberAd(memc); // Admin.MovieAd 호출_연희 break; case 0: return; default: System.out.println("잘못입력하셨습니다."); break; } } } public void movieAd(MovieController mc) throws IOException { while (true) { System.out.println("영화 관리 메뉴입니다."); System.out.println("1.영화 목록"); System.out.println("2.영화 추가"); System.out.println("3.영화 수정"); System.out.println("4.영화 삭제"); System.out.println("0.돌아가기"); System.out.println("메뉴를 선택하여 주십시오."); int ch = sc.nextInt(); switch (ch) { case 1: moAd.MPrint(mc); // Admin.MovieAd.MovieAdd 호출_연희 break; case 2: moAd.MAdd(mc); // Admin.MovieAd.MovieAdd 호출_연희 break; case 3: moAd.MUpdate(mc); // Admin.MovieAd.MovieUpdate 호출_연희 break; case 4: moAd.MRemove(mc); // Admin.MovieAd.MovieRemove 호출_연희 break; case 0: return; default: System.out.println("잘못입력하셨습니다."); break; } } } public void memberAd(MemberController mem) { System.out.println("회원 관리 메뉴입니다."); System.out.println("1.회원 전체 목록"); System.out.println("2.회원 검색"); System.out.println("0.돌아가기"); System.out.println("메뉴를 선택하여 주십시오."); int ch = sc.nextInt(); switch (ch) { case 1: memAd.MemPrint(mem); // Admin.memberAd.MemberList 호출_연희 break; case 2: memAd.MemSearch(mem); // Admin.memberAd.MemberSearch 호출_연희 break; case 0: return; default: System.out.println("잘못입력하셨습니다."); break; } } }<file_sep>package member; import java.io.IOException; import java.io.Serializable; import java.util.ArrayList; import java.util.List; import java.util.Scanner; import main.FileSave; public class MemberController implements Serializable { public ArrayList<Member> memList; public MemberController() { } public MemberController(ArrayList<Member> memList) { this.memList = memList; } public int getSize() { return memList.size(); } public void insert(Member a) { memList.add(a); } public Member getLocate(int num) { return memList.get(num); } public int findId(String id) { for (int i = 0; i < memList.size(); i++) { if (memList.get(i).getId().equalsIgnoreCase(id)) return (i); } return -1; } }
10b1db3edad17132cff513e5dc4fbd368ac57628
[ "Java" ]
3
Java
DongheeL/movie
76a9d290882211b066dfe890316e323af8ca52d6
7588f8408386978d71eaa4f2d01993919c5aa860
refs/heads/master
<file_sep>### Workflow Steps - create-react-app typescript; - bootstrap; - reducer functional/class component example; - combineReducers; - thunk; - useDispatch/useSelector - simple Saga & middleware example <file_sep>import { AlertActionTypes } from "./alertReducer/types/types"; import { AppActionTypes } from "./appReducer/types/types"; import { PostActionTypes } from "./postsReducer/types/types"; export type AppActions = PostActionTypes | AppActionTypes | AlertActionTypes; <file_sep>import { CREATE_POST, FETCH_POSTS, PostActionTypes } from "./types/types"; const initialState: any = { posts: [], fetchedPosts: [], }; export default function postsReducer(state = initialState, action: PostActionTypes) { switch (action.type) { case CREATE_POST: return { ...state, posts: [...state.posts, action.payload] }; case FETCH_POSTS: return { ...state, fetchedPosts: action.payload }; default: return state; } } <file_sep>import { Alert } from "./types/Alert"; import { AlertActionTypes, HIDE_ALERT, SHOW_ALERT } from "./types/types"; const initialState: Alert = { alert: null, }; export default function alertReducer(state = initialState, action: AlertActionTypes) { switch (action.type) { case SHOW_ALERT: return { ...state, alert: action.payload }; case HIDE_ALERT: return { ...state, alert: false }; default: return state; } } <file_sep>import { Alert } from "./Alert"; const SHOW_ALERT = "APP/SHOW_ALERT"; const HIDE_ALERT = "APP/HIDE_ALERT"; export interface ShowAlertAction { type: typeof SHOW_ALERT; payload: Alert; } export interface HideAlertAction { type: typeof HIDE_ALERT; } export type AlertActionTypes = ShowAlertAction | HideAlertAction; export { SHOW_ALERT, HIDE_ALERT }; <file_sep>import { Post } from "./Post"; const CREATE_POST = "POST/CREATE_POST"; const FETCH_POSTS = "POST/FETCH_POSTS"; const FETCH_SAGA_POSTS = "POST/FETCH_SAGA_POSTS"; export interface CreatePostAction { type: typeof CREATE_POST; payload: Post; } export interface FetchPostsAction { type: typeof FETCH_POSTS; payload: Post[]; } export interface FetchSagaPostsAction { type: typeof FETCH_SAGA_POSTS; payload: Post[]; } export type PostActionTypes = CreatePostAction | FetchPostsAction | FetchSagaPostsAction; export { CREATE_POST, FETCH_POSTS, FETCH_SAGA_POSTS }; <file_sep>import { combineReducers, createStore, compose, applyMiddleware } from "redux"; import thunk from "redux-thunk"; import alertReducer from "./alertReducer/alertReducer"; import appReducer from "./appReducer/appReducer"; import { forbiddenWordsMiddleware } from "./middleware/middleware"; import postsReducer from "./postsReducer/postsReducer"; import createSagaMiddleware from "redux-saga"; import { sagaWatcher } from "./sagas/sagas"; export const rootReducer = combineReducers({ posts: postsReducer, app: appReducer, alert: alertReducer, }); export type AppState = ReturnType<typeof rootReducer>; const saga = createSagaMiddleware(); export const store = createStore(rootReducer, compose(applyMiddleware(thunk, forbiddenWordsMiddleware, saga))); saga.run(sagaWatcher); <file_sep>import { Dispatch } from "redux"; import { showAlert } from "../../alertReducer/actions/actions"; import { Alert } from "../../alertReducer/types/Alert"; import { hideLoader, showLoader } from "../../appReducer/actions/actions"; import { AppActions } from "../../rootTypes"; import { Post } from "../types/Post"; import { CREATE_POST, FETCH_POSTS } from "../types/types"; export function createPost(post: Post): AppActions { return { type: CREATE_POST, payload: post, }; } export function fetchPosts(): (dispatch: Dispatch<AppActions>) => void { return async (dispatch: Dispatch<AppActions>) => { try { dispatch(showLoader()); const response = await fetch("https://jsonplaceholder.typicode.com/posts?_limit=5"); const json = await response.json(); dispatch({ type: FETCH_POSTS, payload: json, }); dispatch(hideLoader()); } catch (e) { dispatch(hideLoader()); dispatch(showAlert(("ddd" as unknown) as Alert) as any); } }; } export function fetchSagaPosts() { return { type: "FETCH_SAGA_POSTS", }; } <file_sep>import { takeEvery, put, call } from "redux-saga/effects"; import { hideLoader, showLoader } from "../appReducer/actions/actions"; import { fetchSagaPosts } from "../postsReducer/actions/actions"; import { FETCH_SAGA_POSTS } from "../postsReducer/types/types"; export function* sagaWatcher(): any { yield takeEvery(FETCH_SAGA_POSTS, sagaWorker); } function* sagaWorker() { yield put(showLoader()); const payload = yield call(fetchPosts); yield put({ type: FETCH_SAGA_POSTS, payload, }); yield put(hideLoader()); } async function fetchPosts(): Promise<any> { const response = await fetch("https://jsonplaceholder.typicode.com/posts?_limit=5"); return await response.json(); } <file_sep>import { AnyAction, CombinedState, Dispatch, Middleware } from "redux"; import { showAlert } from "../alertReducer/actions/actions"; import { Alert } from "../alertReducer/types/Alert"; import { Loader } from "../appReducer/types/Loader"; import { Post } from "../postsReducer/types/Post"; import { CREATE_POST } from "../postsReducer/types/types"; const forbidden: string[] = ["fuck", "spam", "pht"]; export function forbiddenWordsMiddleware({ dispatch, }: any): ({ dispatch, }: any) => Middleware<{}, CombinedState<{ posts: Post[]; app: Loader; alert: Alert }>, Dispatch<AnyAction>> { return function (next: any) { return function (action: any) { if (action.type === CREATE_POST) { const found = forbidden.filter((element) => action.payload.title.includes(element)); if (found.length) { dispatch(showAlert(("SPAM" as unknown) as Alert)); } } return next(action); }; }; } <file_sep>import { Dispatch } from "redux"; import { AppActions } from "../../rootTypes"; import { Alert } from "../types/Alert"; import { HIDE_ALERT, SHOW_ALERT } from "../types/types"; export function showAlert(text: Alert): (dispatch: Dispatch<AppActions>) => void { return (dispatch: Dispatch<AppActions>) => { dispatch({ type: SHOW_ALERT, payload: text, }); setTimeout(() => { dispatch(hideAlert()); }, 2000); }; } export function hideAlert(): AppActions { return { type: HIDE_ALERT, }; }
15f0f85d89db4c94636d69046eaaca5280fb6dec
[ "Markdown", "TypeScript" ]
11
Markdown
marheva/typescript_redux
6532a3c48949c5f18e58eef9ffba547d1cb0ee1c
74fdf2639dfdfae8bf6d3317086c9321c35ce921
refs/heads/master
<repo_name>resoluteCoder/ash-knives<file_sep>/README.md <h1><NAME></h1> <p>A landing page for a made-up company.</p> <h2>Purpose</h2> <p>Beginning project that was created to help me learn more about design and CSS frameworks like Bootstrap.</p> <file_sep>/script.js const navLinks = document.querySelectorAll('.nav-link'); for (let i = 0; i < navLinks.length; i++) { navLinks[i].addEventListener('click', function(){ // get attribute from navLinks const id = navLinks[i].getAttribute('data-link'); console.log(id); const ele = document.querySelector('#' + id); console.log(ele); ele.scrollIntoView({ behavior:"smooth", block: "start", inline: "nearest" }); }); }
6ed8a7a9a3ca9311325bfc2912d8ecaa7e88ea50
[ "Markdown", "JavaScript" ]
2
Markdown
resoluteCoder/ash-knives
ddce51a08c1a07bdc35ea49d507ae3f0e25e8ad8
13975d2a2e4bc75f1b8c7f30c283cf05397896ae
refs/heads/master
<file_sep>#pragma once #include "geometry/bounding_box.hpp" #include "geometry/point2d.hpp" namespace m2 { // Bounding box for a set of points on the plane, rotated by 45 // degrees. class DiamondBox { public: void Add(PointD const & p) { return Add(p.x, p.y); } void Add(double x, double y) { return m_box.Add(x + y, x - y); } bool HasPoint(PointD const & p) const { return HasPoint(p.x, p.y); } bool HasPoint(double x, double y) const { return m_box.HasPoint(x + y, x - y); } private: BoundingBox m_box; }; } // namespace m2 <file_sep>#pragma once #include "geometry/point2d.hpp" #include <limits> #include <vector> namespace m2 { class BoundingBox { public: BoundingBox() = default; BoundingBox(std::vector<PointD> const & points); void Add(PointD const & p) { return Add(p.x, p.y); } void Add(double x, double y); bool HasPoint(PointD const & p) const { return HasPoint(p.x, p.y); } bool HasPoint(double x, double y) const; PointD Min() const { return PointD(m_minX, m_minY); } PointD Max() const { return PointD(m_maxX, m_maxY); } private: static_assert(std::numeric_limits<double>::has_infinity, ""); static double constexpr kPositiveInfinity = std::numeric_limits<double>::infinity(); static double constexpr kNegativeInfinity = -kPositiveInfinity; double m_minX = kPositiveInfinity; double m_minY = kPositiveInfinity; double m_maxX = kNegativeInfinity; double m_maxY = kNegativeInfinity; }; } // namespace m2 <file_sep>#include "geometry/bounding_box.hpp" #include <algorithm> using namespace std; namespace m2 { BoundingBox::BoundingBox(vector<PointD> const & points) { for (auto const & p : points) Add(p); } void BoundingBox::Add(double x, double y) { m_minX = min(m_minX, x); m_minY = min(m_minY, y); m_maxX = max(m_maxX, x); m_maxY = max(m_maxY, y); } bool BoundingBox::HasPoint(double x, double y) const { return x >= m_minX && x <= m_maxX && y >= m_minY && y <= m_maxY; } } // namespace m2
ee2f33c52b13f98e8eadb05e2a1998dde64a8fed
[ "C++" ]
3
C++
xblonde/omim
d940a4761786c994884d2488a469635a4ac76d28
3a4b5181b0b3a0072c3642726e0c981e4514ff61
refs/heads/master
<repo_name>djdavidi/code-challenges<file_sep>/septa-fare-calculator/app.js 'use strict'; // in an actual project with more data I would modularize this // for reviewing purposes however, this is easier to take in I think window.app = angular.module('FareWidget', []); // I would have put this in a resolve, because if this was actually async this wouldnt work app.controller('FareWidgetCtrl', function($scope, JsonFactory) { $scope.fares = JsonFactory.getJsonData(); $scope.finalCost=5; $scope.times = ['weekday','evening_weekend','anytime'] $scope.where; $scope.when; $scope.amount =1; $scope.purchaseLocation; var calculatePrice = function() { var val; if ($scope.where && $scope.when) { $scope.where.fares.forEach(function(fare) { console.log("fare type"+fare.type) console.log("fare purchase"+fare.purchase) console.log("scope when"+$scope.when) console.log("scope purchase"+$scope.purchaseLocation) if (fare.type === $scope.when && fare.purchase === $scope.purchaseLocation){ val =fare.price * $scope.amount console.log("in") } }) } return val; } $scope.$watchCollection('[amount,where,when, purchaseLocation]', function(newValues){ $scope.finalCost =calculatePrice() }); }) // If this was a full application and I had a backend, I would have a static route set up // to serve the files up so I could access them like this, so this would work in that case. app.factory('JsonFactory', function($http) { return { getJsonData: function() { // return $http.get('/fares.json').then(function(response) { // return response.data // }) return { "info": { "anytime": "Valid anytime", "weekday": "Valid Monday through Friday, 4:00 a.m. - 7:00 p.m. On trains arriving or departing 30th Street Station, Suburban and Jefferson Station", "evening_weekend": "Valid weekdays after 7:00 p.m.; all day Saturday, Sunday and major holidays. On trains arriving or departing 30th Street Station, Suburban and Jefferson Station", "advance_purchase": "Tickets available for purchase at all SEPTA offices.", "onboard_purchase": "Tickets available for purchase from a train conductor aboard SEPTA regional rail trains." }, "zones": [{ "name": "CCP/1", "zone": 1, "fares": [{ "type": "weekday", "purchase": "advance_purchase", "trips": 1, "price": 4.75 }, { "type": "weekday", "purchase": "onboard_purchase", "trips": 1, "price": 6.00 }, { "type": "evening_weekend", "purchase": "advance_purchase", "trips": 1, "price": 3.75 }, { "type": "evening_weekend", "purchase": "onboard_purchase", "trips": 1, "price": 5.00 }, { "type": "anytime", "purchase": "advance_purchase", "trips": 10, "price": 38.00 }] }, { "name": "Zone 2", "zone": 2, "fares": [{ "type": "weekday", "purchase": "advance_purchase", "trips": 1, "price": 4.75 }, { "type": "weekday", "purchase": "onboard_purchase", "trips": 1, "price": 6.00 }, { "type": "evening_weekend", "purchase": "advance_purchase", "trips": 1, "price": 3.75 }, { "type": "evening_weekend", "purchase": "onboard_purchase", "trips": 1, "price": 5.00 }, { "type": "anytime", "purchase": "advance_purchase", "trips": 10, "price": 45.00 }] }, { "name": "Zone 3", "zone": 3, "fares": [{ "type": "weekday", "purchase": "advance_purchase", "trips": 1, "price": 5.75 }, { "type": "weekday", "purchase": "onboard_purchase", "trips": 1, "price": 7.00 }, { "type": "evening_weekend", "purchase": "advance_purchase", "trips": 1, "price": 5.00 }, { "type": "evening_weekend", "purchase": "onboard_purchase", "trips": 1, "price": 7.00 }, { "type": "anytime", "purchase": "advance_purchase", "trips": 10, "price": 54.50 }] }, { "name": "Zone 4", "zone": 4, "fares": [{ "type": "weekday", "purchase": "advance_purchase", "trips": 1, "price": 6.50 }, { "type": "weekday", "purchase": "onboard_purchase", "trips": 1, "price": 8.00 }, { "type": "evening_weekend", "purchase": "advance_purchase", "trips": 1, "price": 5.00 }, { "type": "evening_weekend", "purchase": "onboard_purchase", "trips": 1, "price": 7.00 }, { "type": "anytime", "purchase": "advance_purchase", "trips": 10, "price": 62.50 }] }, { "name": "NJ", "zone": 5, "fares": [{ "type": "weekday", "purchase": "advance_purchase", "trips": 1, "price": 9.00 }, { "type": "weekday", "purchase": "onboard_purchase", "trips": 1, "price": 10.00 }, { "type": "evening_weekend", "purchase": "advance_purchase", "trips": 1, "price": 9.00 }, { "type": "evening_weekend", "purchase": "onboard_purchase", "trips": 1, "price": 10.00 }, { "type": "anytime", "purchase": "advance_purchase", "trips": 10, "price": 80.00 }] }] } } } });
7a611f3d76f87219363f8cfed51324f2968b8efb
[ "JavaScript" ]
1
JavaScript
djdavidi/code-challenges
aa1d134110f6aff998028a9f7b1b88fb305c786c
7918898367cfa4d14acbc8fcf8570bfc434e6aa6
refs/heads/master
<repo_name>Howardyangyixuan/OpenGL-Learning<file_sep>/OpenGL-Learning/main.cpp #include <glad/glad.h> #include <GLFW/glfw3.h> #include <math.h> #include <stdio.h> #include <stdlib.h> #include <iostream> #include "Shader.hpp" #define STB_IMAGE_IMPLEMENTATION #include "stb_image.h" #include <glm/glm.hpp> #include <glm/gtc/matrix_transform.hpp> #include <glm/gtc/type_ptr.hpp> #include "Camera.hpp" const unsigned int SCR_WIDTH = 800; const unsigned int SCR_HEIGHT = 600; GLfloat mixPercent=0.5f; glm::vec3 cameraPos = glm::vec3(0.0f,0.0f,0.3f); glm::vec3 cameraFront = glm::vec3(0.0f,0.0f,-1.0f); glm::vec3 cameraUp = glm::vec3(0.0f,1.0f,0.0f); float deltaTime = 0.0f; float lastTime = 0.0f; float cameraSpeed = 0.05f; float lastX = 400; float lastY = 300; float pitch = 0.0f; float yaw = 0.0f; float fov = 45.0f; Camera ourCamera(glm::vec3(0.0f,0.0f,0.3f)); using namespace std; void framebuffer_size_callback(GLFWwindow* window, int width, int height); void processInput(GLFWwindow *window); void key_callback(GLFWwindow *window, int key, int scancode, int action, int mode); void mouse_callback(GLFWwindow* window, double xpos, double ypos); void scroll_callback(GLFWwindow* window, double xoffset, double yoffset); int main() { // glfw实例化 glfwInit(); glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 4); glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 1); glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE); glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT,GL_TRUE); cout<<"完成glfw实例化"<<endl; GLFWwindow* window = glfwCreateWindow(SCR_WIDTH, SCR_HEIGHT, "Hello OpenGL", NULL, NULL); //隐藏光标 glfwSetInputMode(window, GLFW_CURSOR, GLFW_CURSOR_DISABLED); //添加滚轮回调 glfwSetScrollCallback(window, scroll_callback); //添加鼠标回调函数 glfwSetCursorPosCallback(window, mouse_callback); //添加键盘回调函数 glfwSetKeyCallback(window, key_callback); if(window==NULL){ cout<<"创建glfw窗口失败"<<endl; glfwTerminate(); return -1; } glfwMakeContextCurrent(window); cout<<"完成窗口对象创建"<<endl; if(!gladLoadGLLoader((GLADloadproc)glfwGetProcAddress)){ cout<<"初始化GLAD失败"<<endl; return -1; } cout<<"初始化GLAD"<<endl; //这一句会影响三角形的初始位置,不知道为什么!!! // glViewport(0,0,800,600); cout<<"初始化视口"<<endl; glfwSetFramebufferSizeCallback(window, framebuffer_size_callback); cout<<"设置回调"<<endl; //创建并编译顶点着色器 Shader ourShader("../3.3.shader.vs", "../3.3.shader.fs"); //三角形 float vertices[] = { -0.5f, -0.5f, -0.5f, 0.0f, 0.0f, 0.5f, -0.5f, -0.5f, 1.0f, 0.0f, 0.5f, 0.5f, -0.5f, 1.0f, 1.0f, 0.5f, 0.5f, -0.5f, 1.0f, 1.0f, -0.5f, 0.5f, -0.5f, 0.0f, 1.0f, -0.5f, -0.5f, -0.5f, 0.0f, 0.0f, -0.5f, -0.5f, 0.5f, 0.0f, 0.0f, 0.5f, -0.5f, 0.5f, 1.0f, 0.0f, 0.5f, 0.5f, 0.5f, 1.0f, 1.0f, 0.5f, 0.5f, 0.5f, 1.0f, 1.0f, -0.5f, 0.5f, 0.5f, 0.0f, 1.0f, -0.5f, -0.5f, 0.5f, 0.0f, 0.0f, -0.5f, 0.5f, 0.5f, 1.0f, 0.0f, -0.5f, 0.5f, -0.5f, 1.0f, 1.0f, -0.5f, -0.5f, -0.5f, 0.0f, 1.0f, -0.5f, -0.5f, -0.5f, 0.0f, 1.0f, -0.5f, -0.5f, 0.5f, 0.0f, 0.0f, -0.5f, 0.5f, 0.5f, 1.0f, 0.0f, 0.5f, 0.5f, 0.5f, 1.0f, 0.0f, 0.5f, 0.5f, -0.5f, 1.0f, 1.0f, 0.5f, -0.5f, -0.5f, 0.0f, 1.0f, 0.5f, -0.5f, -0.5f, 0.0f, 1.0f, 0.5f, -0.5f, 0.5f, 0.0f, 0.0f, 0.5f, 0.5f, 0.5f, 1.0f, 0.0f, -0.5f, -0.5f, -0.5f, 0.0f, 1.0f, 0.5f, -0.5f, -0.5f, 1.0f, 1.0f, 0.5f, -0.5f, 0.5f, 1.0f, 0.0f, 0.5f, -0.5f, 0.5f, 1.0f, 0.0f, -0.5f, -0.5f, 0.5f, 0.0f, 0.0f, -0.5f, -0.5f, -0.5f, 0.0f, 1.0f, -0.5f, 0.5f, -0.5f, 0.0f, 1.0f, 0.5f, 0.5f, -0.5f, 1.0f, 1.0f, 0.5f, 0.5f, 0.5f, 1.0f, 0.0f, 0.5f, 0.5f, 0.5f, 1.0f, 0.0f, -0.5f, 0.5f, 0.5f, 0.0f, 0.0f, -0.5f, 0.5f, -0.5f, 0.0f, 1.0f }; //10个位移向量 glm::vec3 cubePositions[] = { glm::vec3( 0.0f, 0.0f, 0.0f), glm::vec3( 2.0f, 5.0f, -15.0f), glm::vec3(-1.5f, -2.2f, -2.5f), glm::vec3(-3.8f, -2.0f, -12.3f), glm::vec3( 2.4f, -0.4f, -3.5f), glm::vec3(-1.7f, 3.0f, -7.5f), glm::vec3( 1.3f, -2.0f, -2.5f), glm::vec3( 1.5f, 2.0f, -2.5f), glm::vec3( 1.5f, 0.2f, -1.5f), glm::vec3(-1.3f, 1.0f, -1.5f) }; //创建纹理 unsigned int texture1,texture2; glad_glGenTextures(1,&texture1); glad_glBindTexture(GL_TEXTURE_2D, texture1); //设置环绕和过滤 glad_glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_WRAP_S,GL_CLAMP_TO_EDGE); glad_glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_WRAP_T,GL_CLAMP_TO_BORDER); glTexParameterfv(GL_TEXTURE_2D,GL_CLAMP_TO_BORDER,(float []){1.0f,1.0f,1.0f,1.0f}); glad_glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MIN_FILTER,GL_LINEAR); glad_glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MAG_FILTER,GL_LINEAR); //加载纹理 int width, height, nrChannels; unsigned char *data = stbi_load("../wall.jpg", &width, &height, &nrChannels, 0); if(data){ glad_glTexImage2D(GL_TEXTURE_2D,0,GL_RGB,width,height,0,GL_RGB,GL_UNSIGNED_BYTE,data); glad_glGenerateMipmap(GL_TEXTURE_2D); }else{ std::cout<<"加载纹理失败"<<std::endl; } stbi_image_free(data); //第二个纹理 glad_glGenTextures(1,&texture2); glad_glBindTexture(GL_TEXTURE_2D, texture2); //设置环绕和过滤 glad_glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_WRAP_S,GL_REPEAT); glad_glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_WRAP_T,GL_REPEAT); glad_glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MIN_FILTER,GL_LINEAR); glad_glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MAG_FILTER,GL_NEAREST); //加载纹理 stbi_set_flip_vertically_on_load(true); data = stbi_load("../awesomeface.png", &width, &height, &nrChannels, 0); if(data){ glad_glTexImage2D(GL_TEXTURE_2D,0,GL_RGBA,width,height,0,GL_RGBA,GL_UNSIGNED_BYTE,data); glad_glGenerateMipmap(GL_TEXTURE_2D); }else{ std::cout<<"加载纹理失败"<<std::endl; } stbi_image_free(data); //绑定纹理到着色器 ourShader.use(); glad_glUniform1i(glad_glGetUniformLocation(ourShader.ID,"ourTexture1"),0); ourShader.setInt("ourTexture2", 1); //创建顶点缓冲对象 unsigned int VBO; glGenBuffers(1,&VBO); //创建VAO unsigned int VAO; glGenVertexArrays(1, &VAO); // 1. 绑定VAO glBindVertexArray(VAO); // 2. 把顶点数组复制到缓冲中供OpenGL使用 glBindBuffer(GL_ARRAY_BUFFER, VBO); glBufferData(GL_ARRAY_BUFFER, sizeof(vertices), vertices, GL_STATIC_DRAW); // 3. 设置顶点属性指针 glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 5 * sizeof(float), (void*)0); glEnableVertexAttribArray(0); glVertexAttribPointer(1, 2, GL_FLOAT, GL_FALSE, 5 * sizeof(float), (void*)(3*sizeof(float))); glEnableVertexAttribArray(1); //开启Z缓冲,即深度测试 glad_glEnable(GL_DEPTH_TEST); //构造摄影机 while(!glfwWindowShouldClose(window)){ float currentTime = glfwGetTime(); deltaTime = currentTime - lastTime; lastTime = currentTime; cameraSpeed = 2.5f * deltaTime; processInput(window); //绘制三角形 glClearColor(0.2f,0.3f,0.3f,1.0f); glClear(GL_COLOR_BUFFER_BIT); //清除颜色缓冲 glClear(GL_DEPTH_BUFFER_BIT); // ourShader.use(); glActiveTexture(GL_TEXTURE0); glBindTexture(GL_TEXTURE_2D, texture1); glad_glUniform1i(glad_glGetUniformLocation(ourShader.ID,"ourTexture1"),0); glActiveTexture(GL_TEXTURE1); glBindTexture(GL_TEXTURE_2D, texture2); ourShader.setInt("ourTexture2", 1); // 译注:下面就是矩阵初始化的一个例子,如果使用的是0.9.9及以上版本 // glm::mat4 trans; // 这行代码就需要改为: glm::mat4 view = ourCamera.getViewMatrix(); glm::mat4 projection = glm::mat4(1.0f); projection = glm::perspective(glm::radians(ourCamera.Zoom),float(SCR_WIDTH / SCR_HEIGHT), 0.1f, 100.0f); ourShader.setMat4("view", view); ourShader.setMat4("projection", projection); ourShader.setFloat("mixPercent", mixPercent); glBindVertexArray(VAO); for(int i=0;i<10;i++){ glm::mat4 model = glm::mat4(1.0f); model = glm::translate(model, cubePositions[i]); model = glm::rotate(model,(float)20*i,glm::vec3(0.5f,1.0f,0.0f)); if(i%3==0) model = glm::rotate(model,(float)glfwGetTime()*glm::radians(-55.0f),glm::vec3(0.5f,1.0f,0.0f)); ourShader.setMat4("model", model); glDrawArrays(GL_TRIANGLES, 0, 36); } //解绑 glBindVertexArray(0); //绘制颜色 // glad_glClearColor(0.2f,0.3f,0.3f,1.0f); // glad_glClear(GL_COLOR_BUFFER_BIT); glfwSwapBuffers(window); glfwPollEvents(); } cout<<"循环渲染"<<endl; glDeleteVertexArrays(1, &VAO); glDeleteBuffers(1, &VBO); glfwTerminate(); // getchar(); return 0; } void framebuffer_size_callback(GLFWwindow* window, int width, int height) { glViewport(0, 0, width, height); } void processInput(GLFWwindow *window) { if(glfwGetKey(window, GLFW_KEY_ESCAPE) == GLFW_PRESS) glfwSetWindowShouldClose(window, true); } void key_callback(GLFWwindow *window, int key, int scancode, int action, int mode){ if(key == GLFW_KEY_ESCAPE && action == GLFW_PRESS) glfwSetWindowShouldClose(window, GL_TRUE); if(key == GLFW_KEY_UP && action == GLFW_PRESS){ if(mixPercent<1.0f)mixPercent+=0.1f; } if(key == GLFW_KEY_DOWN && action == GLFW_PRESS){ if(mixPercent>0.0f)mixPercent-=0.1f; } if(glfwGetKey(window, GLFW_KEY_W) == GLFW_PRESS){ ourCamera.processKeyboard(FORWARD, deltaTime); } if(glfwGetKey(window, GLFW_KEY_S) == GLFW_PRESS){ ourCamera.processKeyboard(BACKWARD, deltaTime); } if(glfwGetKey(window, GLFW_KEY_A) == GLFW_PRESS){ ourCamera.processKeyboard(LEFT, deltaTime); } if(glfwGetKey(window, GLFW_KEY_D) == GLFW_PRESS){ ourCamera.processKeyboard(RIGHT, deltaTime); } } void mouse_callback(GLFWwindow* window, double xpos, double ypos){ float offsetX = xpos - lastX; float offsetY = lastY - ypos ; lastX = xpos; lastY = ypos; ourCamera.processMouseMovement(offsetX, offsetY); } void scroll_callback(GLFWwindow* window, double xoffset, double yoffset){ ourCamera.processMouseScroll(yoffset); } <file_sep>/OpenGL-Learning/Shader.cpp // // Shader.cpp // OpenGL-Learning // // Created by 杨义轩 on 2020/8/3. // Copyright © 2020 杨义轩. All rights reserved. // #include "Shader.hpp" Shader::Shader(const char* vertexPath, const char* fragmentPath) { // 1. retrieve the vertex/fragment source code from filePath std::string vertexCode; std::string fragmentCode; std::ifstream vShaderFile; std::ifstream fShaderFile; // ensure ifstream objects can throw exceptions: vShaderFile.exceptions(std::ifstream::failbit|std::ifstream::badbit); fShaderFile.exceptions(std::ifstream::failbit|std::ifstream::badbit); try{ // 打开文件 vShaderFile.open(vertexPath); fShaderFile.open(fragmentPath); std::stringstream vShaderStream, fShaderStream; // 读取文件的缓冲内容到数据流中 vShaderStream << vShaderFile.rdbuf(); fShaderStream << fShaderFile.rdbuf(); //关闭文件 vShaderFile.close(); fShaderFile.close(); //转换数据流到string vertexCode = vShaderStream.str(); fragmentCode = fShaderStream.str(); }catch(std::ifstream::failure e){ std::cout<<"ERROR::SHADER::文件未能成功读取" << std::endl; } const char* vShaderCode = vertexCode.c_str(); const char* fShaderCode = fragmentCode.c_str(); //2.编译着色器 unsigned int vertex, fragment; int success; char infoLog[512]; //顶点着色器 vertex = glad_glCreateShader(GL_VERTEX_SHADER); glad_glShaderSource(vertex,1,&vShaderCode,NULL); glad_glCompileShader(vertex); glad_glGetShaderiv(vertex,GL_COMPILE_STATUS,&success); if(!success){ glad_glGetShaderInfoLog(vertex,512,NULL,infoLog); std::cout<<"ERROR::SHADER::顶点着色器编译失败\n"<<infoLog<<std::endl; }; fragment = glad_glCreateShader(GL_FRAGMENT_SHADER); glad_glShaderSource(fragment,1,&fShaderCode,NULL); glad_glCompileShader(fragment); glad_glGetShaderiv(fragment,GL_COMPILE_STATUS,&success); if(!success){ glad_glGetShaderInfoLog(fragment,512,NULL,infoLog); std::cout<<"ERROR::SHADER::片段着色器编译失败\n"<<infoLog<<std::endl; }; ID = glad_glCreateProgram(); glad_glAttachShader(ID,vertex); glad_glAttachShader(ID,fragment); glad_glLinkProgram(ID); glad_glGetProgramiv(ID,GL_LINK_STATUS,&success); if(!success){ glad_glGetProgramInfoLog(ID,512,NULL,infoLog); std::cout<<"ERROR::SHADER::着色器链接失败\n"<<infoLog<<std::endl; }; glad_glDeleteShader(vertex); glad_glDeleteShader(fragment); } void Shader::use(){ glad_glUseProgram(ID); } void Shader::setBool(const std::string &name, bool value)const{ glad_glUniform1i(glad_glGetUniformLocation(ID,name.c_str()),(int)value); } void Shader::setInt(const std::string &name, int value)const{ glad_glUniform1i(glad_glGetUniformLocation(ID,name.c_str()),value); } void Shader::setFloat(const std::string &name, float value)const{ glad_glUniform1f(glad_glGetUniformLocation(ID,name.c_str()),value); } void Shader::setMat4(const std::string &name, glm::mat4 value)const{ int location = glGetUniformLocation(ID, name.c_str()); glUniformMatrix4fv(location, 1, GL_FALSE, glm::value_ptr(value)); }
e5c2b5d320c8566f9d1ffcdd5725b493897d8e97
[ "C++" ]
2
C++
Howardyangyixuan/OpenGL-Learning
ae9edff68d988868161559a1cf4c718f0cce2006
94457b9539422c02017d367352908742a16e3d8c
refs/heads/master
<repo_name>tvaliasek/cookie-notice<file_sep>/Gruntfile.js module.exports = function (grunt) { grunt.initConfig({ pkg: grunt.file.readJSON('package.json'), compass: { build: { options: { sassDir: 'scss', cssDir: 'css', force: true, outputStyle: 'compact' } } }, watch: { build: { files: ['js/*.js', 'scss/*.scss', 'scss/*/*.scss'], tasks: ['build'], options: { spawn: false } } }, cssmin: { options: { sourceMap: true }, target: { files: [{ expand: true, cwd: 'css', src: ['*.css', '!*.min.css'], dest: 'build', ext: '.min.css' }, ] } }, uglify: { options: { preserveComments: false, quoteStyle: 3, screwIE8: true }, build: { files: { 'build/eu-notice.min.js': ['js/eu-notice.js'], 'wp-plugin-src/js/cookie-notice.min.js': ['js/wp-eu-notice.js'], 'wp-plugin-src/js/cookie-notice-admin.min.js': ['js/wp-eu-notice-admin.js'] } } }, compress: { main: { options: { archive: 'build/cookie-notice-wp-plugin.zip' }, files: [ {expand: true, cwd: 'wp-plugin-src', src: ['**'], dest: 'tvaliasek-cookie-notice/'}, // makes all src relative to cwd ] } }, copy: { main: { files: [ {expand: false, flatten: true, src: ['build/eu-notice.min.css'], dest: 'wp-plugin-src/css/cookie-notice.min.css', filter: 'isFile'}, {expand: false, flatten: true, src: ['build/eu-notice.min.css.map'], dest: 'wp-plugin-src/css/cookie-notice.min.css.map', filter: 'isFile'}, {expand: false, flatten: true, src: ['build/admin.min.css'], dest: 'wp-plugin-src/css/cookie-notice-admin.min.css', filter: 'isFile'}, {expand: false, flatten: true, src: ['build/admin.min.css.map'], dest: 'wp-plugin-src/css/cookie-notice-admin.min.css.map', filter: 'isFile'}, ] } }, clean: { build:{ src: [ 'build/admin.min.css', 'build/admin.min.css.map' ] }, buildWp: { src: [ 'build/eu-notice.min.css', 'build/eu-notice.min.css.map', 'build/admin.min.css', 'build/admin.min.css.map', 'build/eu-notice.min.js' ] }, all:{ src: ['build/*'] } } }); grunt.loadNpmTasks('grunt-contrib-watch'); grunt.loadNpmTasks('grunt-contrib-uglify'); grunt.loadNpmTasks('grunt-contrib-cssmin'); grunt.loadNpmTasks('grunt-contrib-compass'); grunt.loadNpmTasks('grunt-contrib-copy'); grunt.loadNpmTasks('grunt-contrib-compress'); grunt.loadNpmTasks('grunt-contrib-clean'); grunt.registerTask('build', ['clean:all','compass:build', 'uglify:build', 'cssmin', 'clean:build']); grunt.registerTask('build-wp-plugin', ['clean:all','compass:build', 'uglify:build', 'cssmin', 'copy', 'compress', 'clean:buildWp']); }; <file_sep>/README.md # EU cookie notice Simple javascript library for integration of EU cookie notice, just link the JS and CSS files from build folder. Agreement information is saved in cookie with expiration after one year. Demo page: http://cookie-notice.valiasek.cz ## Usage Simply link needed files: ```html <!DOCTYPE html> <html> <head> <title>EU Cookie Notice Demo</title> <!-- link stylesheet for message in head section --> <link href="/build/eu-notice.min.css" rel="stylesheet" /> </head> <body> <!-- link main script before end of body --> <script type="text/javascript" src="/build/eu-notice.min.js"></script> </body> </html> ``` ## Build process and customization Build process is based on standard Gruntfile.js, you can watch your changes with `grunt watch` command or build it with `grunt build`. All scss and js files are automaticaly compiled, minified and saved in /build folder. If you want to build this library as Wordpress plugin, use command `grunt build-wp-plugin`. ### Disabling automatic display If you want to disable automatic display of message, delete lines 93 - 99 from /js/eu-notice.js. ```javascript //init -- delete it if you want custom display behavior var euNotice = window.EUNotice(); if(euNotice.wasAgreed() !== true){ euNotice.displayMessage(); } //init END ``` ### Canceling approval Just call `notice.cancelAgreed();` Example: ```html <!DOCTYPE html> <html> <head> <title>EU Cookie Notice Demo</title> <meta charset="UTF-8" /> <link href="/build/eu-notice.min.css" rel="stylesheet" /> </head> <body> <a href="javascript:void(0);" target="_self" title="cancel message approval" id="cancelApproval">Cancel cookie notice approval</a> <script type="text/javascript" src="/build/eu-notice.min.js"></script> <script type="text/javascript"> //cancel agreement by clicking on link #cancelApproval and reload current page var btn = document.getElementById('cancelApproval'); btn.addEventListener('click', function(e){ e.preventDefault(); var notice = window.EUNotice(); notice.cancelAgreed(); window.location.reload(); }, false); </script> </body> </html> ``` ### HTML structure of displayed message All texts can be customized directly in source on line 11 - 14, or by assigning string value to object property before the display of message. ```html <div id="__EUNotice"> <div class="__EUNotice--inner"> <p> <!-- Text of message: notice.messageText --> notice.messageText <!-- More Info link: notice.googleLinkText, notice.googleLinkHref --> <a class="__EUNotice--glink" target="_blank" title="notice.googleLinkText" href="notice.googleLinkHref">notice.googleLinkText</a> </p> <!-- Agree button: notice.okBtnText --> <a class="__EUNotice--okBtn" target="_self" title="notice.okBtnText" href="javascript:void(0);">notice.okBtnText</a> </div> </div> ```<file_sep>/wp-plugin-src/cookie-notice-admin.php <?php add_action('admin_menu', 'eucn_add_admin_menu'); add_action('admin_init', 'eucn_settings_init'); function eucn_admin_enqueue($hook) { if ( $_GET['page']!=='eu_cookie_notice') { return; } wp_register_script('cookie-notice-admin-js', plugins_url('/js/cookie-notice-admin.min.js', __FILE__), array(), '20150329', true); wp_register_style('cookie-notice-css', plugins_url('/css/cookie-notice.min.css', __FILE__)); wp_enqueue_style('cookie-notice-css'); wp_localize_script('cookie-notice-admin-js', 'notice_strings', get_eucn_option() ); wp_enqueue_script('cookie-notice-admin-js'); wp_enqueue_style('eucn_admin_scripts', plugin_dir_url( __FILE__ ) . 'css/admin.min.css' ); } add_action( 'admin_enqueue_scripts', 'eucn_admin_enqueue' ); function eucn_add_admin_menu() { add_options_page('EU Cookie notice', 'EU Cookie notice', 'manage_options', 'eu_cookie_notice', 'eucn_settings_page'); } function eucn_settings_init() { register_setting('pluginPage', 'eucn_settings'); add_settings_section( 'eucn_pluginPage_section', __('Settings', 'wordpress'), 'eucn_settings_section_callback', 'pluginPage' ); add_settings_field( 'eucn_enabled', __('Enable display of cookie notice:', 'wordpress'), 'eucn_enabled_render', 'pluginPage', 'eucn_pluginPage_section' ); add_settings_field( 'eucn_message_text', __('Cookie notice text:', 'wordpress'), 'eucn_message_text_render', 'pluginPage', 'eucn_pluginPage_section' ); add_settings_field( 'eucn_google_link_text', __('Text description of link to google info page:', 'wordpress'), 'eucn_google_link_text_render', 'pluginPage', 'eucn_pluginPage_section' ); add_settings_field( 'eucn_google_link_href', __('Link to google info page:', 'wordpress'), 'eucn_google_link_href_render', 'pluginPage', 'eucn_pluginPage_section' ); add_settings_field( 'eucn_ok_btn_text', __('Agree button text:', 'wordpress'), 'eucn_ok_btn_text_render', 'pluginPage', 'eucn_pluginPage_section' ); } function get_eucn_option(){ return get_option('eucn_settings', array( 'eucn_enabled'=>0, 'eucn_message_text'=>'This site uses cookies from Google to deliver its services, to personalize ads and to analyze traffic. information about your use of this site is shared with google. By using this site, you agree to its use of cookies.', 'eucn_google_link_text'=>'Learn More', 'eucn_google_link_href'=>'https://www.google.com/intl/cs/policies/technologies/cookies/', 'eucn_ok_btn_text'=>'Got it')); } function eucn_enabled_render() { $options = get_eucn_option(); ?> <select name='eucn_settings[eucn_enabled]'> <option value='0' <?php selected($options['eucn_enabled'], 0); ?>>Disabled</option> <option value='1' <?php selected($options['eucn_enabled'], 1); ?>>Enabled</option> </select> <?php } function eucn_message_text_render() { $options = get_eucn_option(); ?> <textarea class="eucn_input eucn_textarea" name='eucn_settings[eucn_message_text]'><?php echo $options['eucn_message_text']; ?></textarea> <?php } function eucn_google_link_text_render() { $options = get_eucn_option(); ?> <input type='text' class="eucn_input eucn_text" name='eucn_settings[eucn_google_link_text]' value='<?php echo $options['eucn_google_link_text']; ?>'> <?php } function eucn_google_link_href_render() { $options = get_eucn_option(); ?> <input type='text' class="eucn_input eucn_text" name='eucn_settings[eucn_google_link_href]' value='<?php echo $options['eucn_google_link_href']; ?>'> <?php } function eucn_ok_btn_text_render() { $options = get_eucn_option(); ?> <input type='text' class="eucn_input eucn_text" name='eucn_settings[eucn_ok_btn_text]' value='<?php echo $options['eucn_ok_btn_text']; ?>'> <?php } function eucn_settings_section_callback() { echo __('', 'wordpress'); } function eucn_settings_page() { ?> <form action='options.php' method='post'> <h2>EU Cookie notice</h2> <?php settings_fields('pluginPage'); do_settings_sections('pluginPage'); submit_button(); ?> </form> <hr/> <p> <span id="eucn_cookie_status" data-status="0">Cookie notice was not agreed.</span> <a href="javascript:void(0);" id="eucn_btn_test" target="_self" title="Test message">Test message display</a> <a href="javascript:void(0);" id="eucn_btn_cancel" target="_self" title="Cancel agreement cookie">Cancel agreement cookie</a> </p> <?php } ?><file_sep>/wp-plugin-src/cookie-notice.php <?php /* Plugin Name: EU Cookie Notice by tvaliasek Plugin URI: https://github.com/tvaliasek/cookie-notice Description: Custom plugin for integration of EU cookie notice. Version: 1.0.0 Author: <NAME> Author URI: http://www.valiasek.cz License: MIT */ defined( 'ABSPATH' ) or die( 'B)' ); //*************** // admin scripts //*************** include_once __DIR__.'/cookie-notice-admin.php'; //*************** // scripts for frontend //*************** function register_cookie_notice_scripts(){ wp_register_script('cookie-notice-js', plugins_url('/js/cookie-notice.min.js', __FILE__), array(), '20150329', true); wp_register_style('cookie-notice-css', plugins_url('/css/cookie-notice.min.css', __FILE__)); wp_enqueue_style('cookie-notice-css'); wp_localize_script('cookie-notice-js', 'notice_strings', get_eucn_option() ); wp_enqueue_script('cookie-notice-js'); } $options = get_eucn_option(); if( $options['eucn_enabled'] === "1"){ add_action('wp_enqueue_scripts', 'register_cookie_notice_scripts'); } <file_sep>/wp-plugin-src/readme.txt === Plugin Name === Contributors: tvaliasek Donate link: Tags: tvaliasek-cookie-notice Requires at least: Tested up to: Stable tag: License: MIT == Description == == Installation == == Changelog == = 1.0 =
a08229200eff548ca44f6de46cd21bdd6ba2afe8
[ "JavaScript", "PHP", "Text", "Markdown" ]
5
JavaScript
tvaliasek/cookie-notice
529c388d61e07b0a64c9338273c6275e5b668c4b
5db96494fd74b0be98348a878387ece9d1c945ea
refs/heads/master
<file_sep>class Profile: MAX_AGE = 20 EDU_MULTIPLIER = { 1: 1.0, 2: 1.12, 3: 1.25 } def __init__(self, userid, age, education, baseiq, basemidx): self.__id = userid self.__age = age self.__education = education self.__baseiq = baseiq self.__basemidx = basemidx @property def id(self): return self.__id @property def age(self): return self.__age @property def education(self): return self.__education @property def current_iq(self): deterioration_rate = 0.003 age_diff = abs(self.age - Profile.MAX_AGE) iq = self.__baseiq * pow(1 - deterioration_rate, age_diff) return iq @property def current_midx(self): deterioration_rate = 0.005 age_diff = abs(self.age - Profile.MAX_AGE) midx = self.__basemidx * pow(1 - deterioration_rate, age_diff) return midx @property def compound_index(self): cls = type(self) total = cls.EDU_MULTIPLIER[self.education] * (self.current_iq + self.current_midx) cpd_max = max(cls.EDU_MULTIPLIER.values()) * (150 + 150) return total / cpd_max <file_sep>from enum import Enum class OptionDiffLevel(Enum): EASY = 0 MEDIUM = 1 HARD = 2 def __ge__(self, other): return self.value > other.value<file_sep>from random import choice, randint, random, choices from datetime import datetime, timedelta import json from common import OptionDiffLevel from exprcontr import expr_pcontr # Each record of a user consists of the following info # Record = ConceptIDs, DifficultyLevel, CorrectAnswer, UserAnswer, TimeSpent, SubmitTimeStamp class RecordDB: def __init__(self, profiles, concepts, questions): self.__profiles = profiles self.__concepts = concepts self.__questions = questions self.__profile_dict = { p.id: p for p in profiles } self.__question_dict = { q[0]: q for q in questions } self.__record_database = { p.id: {} for p in self.__profiles } # key=question id, value=Records self.__concept_database = { p.id: {} for p in self.__profiles } # key=concept id, value=[True/False, ...] self.__time_database = { p.id: None for p in self.__profiles } # value=timestamp of the last time the user solving a question self.__concept_correlations = dict() # key=concept id, value= {concept id, correlation value} @staticmethod def answering(correctness, answer): if correctness: return answer else: option_set = list('ABCD') option_set.remove(answer) return choice(option_set) def concept_correlate(self, cpt_a, cpt_b, cv): if cpt_a not in self.__concepts: raise ValueError(f"Concept {repr(cpt_a)} does not exist in RecordDB") if cpt_b not in self.__concepts: raise ValueError(f"Concept {repr(cpt_b)} does not exist in RecordDB") if not isinstance(cv, float) or cv < -1 or cv > 1: raise ValueError("Correlation value needs to be a float number within range [-1, 1]") if cpt_a not in self.__concept_correlations: self.__concept_correlations[cpt_a] = {} if cpt_b not in self.__concept_correlations: self.__concept_correlations[cpt_b] = {} self.__concept_correlations[cpt_a][cpt_b] = cv self.__concept_correlations[cpt_b][cpt_a] = cv def dump_records(self, filename): with open(filename, 'w') as f: for userid, user_records in self.__record_database.items(): for question_id, question_records in user_records.items(): for qrecord in question_records: concepts, difflevel, correct_ans, user_ans, tspent, tstamp = qrecord obj = { 'UserID': userid, 'QuestionID': question_id, 'ConceptIDs': list(concepts), 'DifficultyLevel': difflevel.name, 'CorrectAnswer': correct_ans, 'UserAnswer': user_ans, 'TimeSpent': tspent, 'TimeStamp': tstamp } f.write(json.dumps(obj) + '\n') def gen_record(self, userid): if userid not in self.__profile_dict: raise ValueError(f"User profile ID={userid} does not exist") # Select a question question = choice(self.__questions) question_id, linked_concepts, answers = question # Check how many times a user has answered correctly or wrongly to a specific concepts concept_records = [self.__concept_database[userid][lcpt] for lcpt in linked_concepts if lcpt in self.__concept_database[userid]] # Select a time to do the question time_to_submit = None if self.__time_database[userid] is None: # Get current time time_to_submit = datetime.now() else: continuous = random() < 0.9 # If the user is in the process of doing multiple exercises last_time = datetime.fromtimestamp(self.__time_database[userid]) microseconds_apart = randint(15, 45) if continuous: minutes_apart = randint(1, 10) seconds_apart = randint(1, 59) time_to_submit = last_time + timedelta(0, minutes_apart * 60 + seconds_apart, microseconds_apart) else: days_apart = randint(1, 30) hours_apart = randint(1, 23) minutes_apart = randint(1, 59) seconds_apart = randint(1, 59) time_to_submit = last_time + timedelta( days_apart, hours_apart * 60 * 60 + minutes_apart * 60 + seconds_apart, microseconds_apart ) to_submit_timestamp = datetime.timestamp(time_to_submit) to_submit_timespent = randint(0, 15) * 60 + randint(1, 59) # in seconds to_submit_difflevel = choice(list(OptionDiffLevel)) to_submit_correct_answer = answers[to_submit_difflevel] to_submit_user_answer = None # This version does not take into account when the user does the question last time # It only cares about how many times the user has done questions related to a specific # concept and whether s/he has answered correctly or not prob_contr = 0 if len(concept_records) != 0: # Iterate over each concept and calculate its probability contribution for cr in concept_records: prob_contr += expr_pcontr(cr) prob_contr /= len(concept_records) cmpindex = self.__profile_dict[userid].compound_index # base: 25% => pure guess # experience: 25% => the more times the user has done questions with similar concepts, # the more likely s/he would successfully solve it # compound index: 40% => the higher level of education the user has received, # the more likely s/he would be able to solve it # luck: 10% => whether or not the user is lucky enough to guess out the right answer tot_prob = 0.25 * 1 + 0.25 * prob_contr + 0.40 * cmpindex + 0.10 * randint(0, 1) to_submit_correct = choices([True, False], weights=[tot_prob, 1 - tot_prob])[0] to_submit_user_answer = RecordDB.answering(to_submit_correct, to_submit_correct_answer) new_record = ( linked_concepts, to_submit_difflevel, to_submit_correct_answer, to_submit_user_answer, to_submit_timespent, to_submit_timestamp ) if question_id not in self.__record_database[userid]: self.__record_database[userid][question_id] = [] self.__record_database[userid][question_id].append(new_record) for lcpt in linked_concepts: if lcpt not in self.__concept_database[userid]: self.__concept_database[userid][lcpt] = [] self.__concept_database[userid][lcpt].append(True if to_submit_correct else False) self.__time_database[userid] = to_submit_timestamp <file_sep>from uuid import uuid4 from scipy.stats import beta, norm import random from profile import Profile # User ID, Age, Education Level, Base IQ, Base Memory Index class ProfileGenerator: @staticmethod def gen_profile(): userid = ProfileGenerator.gen_userid() age = ProfileGenerator.gen_age() education = ProfileGenerator.gen_education() baseiq = ProfileGenerator.gen_baseiq() basemidx = ProfileGenerator.gen_basemidx() profile = Profile(userid, age, education, baseiq, basemidx) return profile @staticmethod def gen_userid(): return str(uuid4()) @staticmethod def gen_age(): age_min, age_max = 15, 60 # Assume that the RV Age is a beta continuous random variable a, b = 2, 5 v = beta.rvs(a, b) return int(v * (age_max - age_min) + age_min) @staticmethod def gen_education(): # There are 3 education levels: # college, grad school, phd # Each education level corresponds to one integer, from 1 to 3 # Each education level has a different probability # College = 0.55 # Grad School = 0.35 # PhD = 0.10 return random.choices((1, 2, 3), (0.55, 0.35, 0.10))[0] @staticmethod def gen_baseiq(): # According to Wikipedia, the IQ distribution across the world has mean=100 and standard deviation=15 iq_mean, iq_std = 100, 15 return int(norm.rvs(iq_mean, iq_std)) @staticmethod def gen_basemidx(): mm_mean, mm_std = 100, 20 return int(norm.rvs(mm_mean, mm_std)) <file_sep> import numpy as np from scipy.stats import poisson def learning_contr(records): """Generate the contribution of doing each question to learning its corresponding concept. Args: records (np.ndarray): A numpy array of boolean values. True means the user has correctly answered the question; False otherwise. return: A list of contribution values each of which corresponds to the contribution of each question. """ if len(records) == 0: return [] contrs = np.zeros(len(records)) for i, vc in enumerate(records): if i == 0: # First attempt if vc: contrs[i] = .5 # Previous=None & Current=Success => 0.50 else: contrs[i] = .25 # Previous=None & Current=Failure => 0.25 else: # Starting from the second attempt if vp: if vc: contrs[i] = 1. # Previous=Success & Current=Success => 1.0 else: contrs[i] = .25 # Previous=Success & Current=Failure => 0.25 else: if vc: contrs[i] = .5 # Previous=Failure & Current=Success => 0.5 else: k = i - 2 if k < 0: contrs[i] = 0. else: if contrs[k]: contrs[i] = 0. else: contrs[i] = -.25 vp = vc return contrs def descending_weight(nfold): """Generate the weight of contribution for doing each question. Args: nfold (int): Number of attempts. returns: A list of weights each of which corresponds to the weight of contribution for a specific attempt. Later attempts are given more weights. """ if not isinstance(nfold, int) or nfold <= 0: raise ValueError("nfold must be a positive integer.") denom = nfold * (nfold + 1) / 2 return np.array([(i + 1) / denom for i in range(nfold)]) def expr_pcontr(records): """Calculate the probability of a user correctly answering the next question from a specific concept given the his/her records of doing other questions from the same concept. Args: records (np.ndarray): A numpy array of boolean values. True means the user has correctly answered the question; False otherwise. returns: The probability of a user correctly answering the next question only considering his/her records and nothing else. Note that this probability is an extra probability that will be added to other probabilities to make up the true probability of the user correctly solving the next question. """ if len(records) == 0: return 0 contrs = learning_contr(records) weights = descending_weight(len(records)) tot = np.dot(contrs, weights) # If we would produce probabily and generate fake records based only on the previous records, # in the case when the user fails to answer the first few question, the probability would become # extremely low and lower after. Hence, we need to add an extra part to it. We can assume that # the more questions the user has done in this concept, the more likely s/he would answer the # question correctly. Here, to achieve this effect, we introduce the CDF of poisson distribution. lam = 5 return 1/3 * tot + 2/3 * poisson.cdf(len(records), lam) def main(): import matplotlib.pyplot as plt import random nqs, nc = (10, 50, 100, 1000), 5 figure, axes = plt.subplots(nrows=len(nqs), ncols=nc) cols = [f'sim #{c+1}' for c in range(nc)] rows = [f'{nq} trials' for nq in nqs] for ax, col in zip(axes[0], cols): ax.set_title(col) for ax, row in zip(axes[:,0], rows): ax.set_ylabel(row, rotation=90, size='large') for r, nq in enumerate(nqs): for c in range(nc): count = 0 user_records = np.empty(nq, dtype=bool) user_probs = np.empty(nq) accuracy = np.empty(nq) for i in range(nq): p = .25 + .65 * expr_pcontr(user_records[:nq+1]) + .1 * random.randint(0, 1) a = random.choices([True, False], weights=[p, 1-p], k=1)[0] if a: count += 1 user_probs[i] = p user_records[i] = a accuracy[i] = count / (i + 1) axes[r, c].plot([i+1 for i in range(nq)], accuracy) axes[r, c].set_ylim(0, 1.2) plt.xlabel("number of trials") plt.ylabel("accuracy") figure.suptitle("Accuracy Simulation for Different Trial Numbers") plt.show() if __name__ == '__main__': main()<file_sep># This file provides some easy-to-use API functions for generating learning curves from profile_generate import ProfileGenerator as PGen from exprcontr import expr_pcontr from random import randint from random import choices def gen_synthetic_anshist(n_question): """Generate synthetic answering history for a user with regard to questions belonging to a specific concept. Args: n_question (int): Number of questions the user has done. """ assert(n_question > 0) # Generate a synthetic user profile profile = PGen.gen_profile() records = [] for _ in range(n_question): prob_contr = expr_pcontr(records) cmpindex = profile.compound_index # base: 25% => pure guess # experience: 25% => the more times the user has done questions with similar concepts, # the more likely s/he would successfully solve it # compound index: 40% => the higher level of education the user has received, # the more likely s/he would be able to solve it # luck: 10% => whether or not the user is lucky enough to guess out the right answer tot_prob = 0.25 * 1 + 0.25 * prob_contr + 0.40 * cmpindex + 0.10 * randint(0, 1) ans_correct = choices([True, False], weights=[tot_prob, 1 - tot_prob])[0] records.append(ans_correct) return records, profile def main(): n_trial = 10 n_question = 20 for i in range(n_trial): records, profile = gen_synthetic_anshist(n_question) records_fh = records[:n_question // 2] records_lh = records[n_question // 2:] score = len(list(filter(lambda r: r, records))) / len(records) score_fh = len(list(filter(lambda r: r, records_fh))) / len(records_fh) score_lh = len(list(filter(lambda r: r, records_lh))) / len(records_lh) print(f"{'>' * 25} Iteration {i+1} {'<' * 25}") print(f"profile: {profile.__dict__}") print(f"cmpindex: {profile.compound_index}") print(f"records: {records}") print(f"score: {score}") print(f"score (first half): {score_fh}") print(f"score (last half): {score_lh}") print() if __name__ == '__main__': main()<file_sep>from uuid import uuid4 from random import randint, sample, choice from profile_generate import ProfileGenerator as PGen from common import OptionDiffLevel from record_db import RecordDB NUM_USERS = 10 NUM_CONCEPTS = 1000 NUM_QUESTIONS = 5000 QUESTION_OPTIONS = 'ABCD' # Generate user profiles user_profiles = tuple(PGen.gen_profile() for _ in range(NUM_USERS)) # Generate concepts dummy_prefix = "DM - " concepts = list(f"concept-{uuid4()}" for _ in range(NUM_CONCEPTS)) bfs = f"{dummy_prefix}Banking Financial Statement" mfs = f"{dummy_prefix}Market Financial Statement" netin = f"{dummy_prefix}Net Income" exps = f"{dummy_prefix}Expenditure" # Add some dummy concepts concepts.extend([bfs, mfs, netin, exps]) concepts = tuple(concepts) # Generate questions questions = tuple( ( f"question-{uuid4()}", # Question ID set(sample(concepts, randint(1, 3))), # Linked concepts { OptionDiffLevel.EASY: choice(QUESTION_OPTIONS), OptionDiffLevel.MEDIUM: choice(QUESTION_OPTIONS), # Answer for each difficulty level OptionDiffLevel.HARD: choice(QUESTION_OPTIONS) } ) for _ in range(NUM_QUESTIONS) ) rdb = RecordDB(user_profiles, concepts, questions) for i in range(1000): userid = choice(user_profiles).id rdb.gen_record(userid) rdb.concept_correlate(bfs, mfs, 0.7) rdb.concept_correlate(netin, exps, -0.6) rdb.dump_records('output.json')
6af9197d214c98b9b1a93a68c1952f0712517f31
[ "Python" ]
7
Python
neuricos/KGBaseRecord
a976d6704977ca882f47f3eb4798ca9c3be14464
d6a7369af3ba8caa07b809d3a4bb8d91769329f5
refs/heads/master
<file_sep>index.file=index.php url=http://localhost/laradoka/ <file_sep><?php /* * Что бы разгрузить логику в route * для этого можно использовать контроллер */ /* * Можно указывать дополнительные проверки */ Route::get('/create', 'imagesController@create')->middleware('user'); /* * Что бы быстро сделать типичный контроллер * для этого можно использовать композер с командой * php artisan make:controller CategoriesController --resource * он создаст типичный CRUD */ class CategoriesController extends Controller { public function index() { } public function create() { } public function store() { } public function edit() { } public function update() { } public function destroy() { } } ///////////////////////////////////////////// /* * Контроллер может автоматически создавать объекты * с помощью инъекции в конструкторе */ class ImagesController extends Controller { private $imageClass; private $role; public function __construct(Image $imageClass, User $role) { $this->imageClass = $imageClass; $this->role = $role; } public function index() { $userRole = $this->role->isRole(); return view('welcome', [ 'userRole' => $userRole ]); } } //////////////////////////////// /* * Ещё имеются методы: post, put и delete */ /*post используется для отправки форм*/ Route::post('/store', 'imagesController@store'); /*put используется для обновления*/ Route::put('/posts/update/{d}', 'PostsController@update')->name('posts.update'); /*delete используется для удаления*/ Route::delete('users/destroy/{d}', 'UsersController@destroy')->name('users.destroy'); <file_sep><?php /* * helpers - помошники, их можно вызывать откуда угодно * без подключения классов * их очень много */ /* Те, которые я использую*/ /* auth() - проверяет, авторизирован ли пользователь */ $user = auth()->user(); //Если пользователь авторизирован, //то вернёт объект пользователя //иначе null //Можно вызвать таким способом Auth::user()->name ////////////////////////////////////////////// /* Это надо обязательно добавлять при отправке форм*/ // образуется скрытое поле input с токеном csrf_field(); //а так образуется только токен, без поля csrf_token() ///////////////////////////////////////////////////////// /* Самая частоиспользуемая функция, для просмотра данных*/ dd(); /*То же самое, только работа не прекращается*/ dump(); ///////////////////////////////////////////////////////////// /* old - подставляет старое значение в форму, * если форма была отправлена */ //value="{{ old('description') }} ////////////////////////////////////// /* redirect - перенапрвляет, на указанную страницу*/ return redirect('/'); ///////////////////////////////////// /* request возвращает текущий экземпляр запроса */ $request = request(); $value = request('key', $default); ///////////////////////////////////////// /* route создаёт адресс для именовонного маршрута в контроллере*/ {{route('admin.posts.update', ['id' => $post->id])}} ///////////////////////////////////// /* abort выведет ошибку, если что-то пошло не так*/ abort(404); ////////////////////////////////////// /* view - возвращает экземпляр вида*/ return view('auth.login'); // папка auth, файл login.blade.php <file_sep># laradoka # lara-documentation <file_sep><?php /* faker - модель для быстрого заполенеия БД информацией*/ <?php use Faker\Generator as Faker; /* Здесь указывается модель, * в которой будет взята таблица из бд * и будет работа с ней */ $factory->define(App\Services\Image::class, function ($faker) { return [ 'description' => $faker->title, 'image' => $faker->title, 'id_user' => function () { return App\User::all()->random()->id; } ]; }); /* * И потом можно в роуте вызвать */ factory(App\Services\Image::class, 5)->create() <file_sep><?php /* Request - отправленные данные с формы */ /* * Что бы получить данные нужного поля * можно использовать метод input * у экземпляра Request */ public function store(Request $request) { $name = $request->input('name'); /* другой способ */ $name = $request->name; } /* Получение всех данных, кроме файлов */ $input = $request->all(); ////////////////////////////////////////////// /* Проверить, отправились ли данные нужного поля*/ if ($request->has('name')) { } if ($request->has(['name', 'email'])) { } /////////////////////////////////////////// /* Получение старого ввода */ $username = $request->old('username'); ////////////////////////////////////////////////////// <file_sep><?php /** Route - путиводитель */ /** У этого компонента, есть метод get * который отрабатывает по адресу (URL). * Первый аргумент, должен быть адресом, * второй функцией */ Route::get('/', 'imagesController@index'); /* * Ещё можно передавать аргументы, * которые будут находиться в скобках */ Route::get('/edit/{id}', 'imagesController@edit'); ////////////////////////////////////////////////////// /* * Ещё можно именовать маршруты, для того, что бы * использовать хелпер route */ Route::get('/posts/create', 'PostsController@create')->name('posts.create'); /* * <a href="{{route('posts.create')}}" class="btn btn-success">Добавить</a> */ /////////////////////////////////////////////////////// /* * Если есть много маршрутов * у которых название начинается одинаково * их можно группировать */ Route::group(['as' => 'admin.', 'namespace'=>'Admin', 'prefix' => 'admin'], function() { Route::get('/', 'HomeController@index'); Route::get('/posts', 'PostsController@index')->name('posts'); Route::delete('/posts/{d}', 'PostsController@destroy'); }); <file_sep><?php /* * Данные из базы, помещаются в коллекцию */ /* * Сохранение методом save() */ public function add($image, $description) { $fileName = $image->store('uploads'); $this->image = $fileName; $this->description = $description; $this->id_user = Auth::id(); } $this->imageClass->add($image, $description); $this->imageClass->save(); $idNewImage = $this->imageClass->id; /* * Тут будет добавление в то поле * которое указано ($this->description) */ ///////////////////////////////////////// /* * Для того что бы использовать метод create * обязательно нужно заполнить массив fillable * это обязательный поля для заполнения */ protected $fillable = ['image', 'description', 'id_user']; public function add($image, $description) { $fileName = $image->store('uploads'); $post = self::create([ 'image' => $fileName, 'description' => $description, 'id_user' => Auth::id() ]); return $post->id; } $idNewImage = $this->imageClass->add($image, $description); dd($idNewImage ) //сюда вернётся id; ////////////////////////////////////////////////// /* * Если использовать метод create * то Eloquent будет автоматически вставлять в бд строки * created_at и updated_at * Если эти данные не нужны, то можно их отменить * свойством $timestamps */ protected $fillable = ['name']; public $timestamps = false; Category::create($request->all()); ///////////////////////////////////// /* * Найти нужную запись */ $post = Image::find($id); /* * Найти все записи */ $category = Category::all(); /* * Удалить запись */ $image = Image::find($id); $this->destroy($image->id); //////////////////////////////////// Category::find($id)->delete(); ///////////////////////////////////////////// DB::table('category_image')->where('image_id', $image->id)->delete(); //////////////////////////////////////// /* Обновление */ $category = Category::find($id); $category->update(['name' => $request->name]); /* Можно просто перезаписать*/ public function update(Request $request, $id) { $imgOld = $this->imageClass::find($id); $imgOld->description = $request->description; $imgOld->save(); } <file_sep><?php /* Collections - коллекции*/ /* * коллекции это класс для работы с массивами (Обёртка laravel) */ public function addRelation($categories, $id) { $categoryId = []; //создаёт коллекцию из обычного массива $collection = collect($categories); //В коллекции будет массив, но он не подходит для этой задачи //потому что не сработает метод insert //и что бы он сработал, надо взять все //элементы коллекции и из каждого сделать //отдельную коллекцию $collection = $collection->chunk(1); /* each метод выполняет итерацию по элементам коллекции и передает каждому элементу обратный вызов: */ /*Что бы не добавлять в базу при каждом цикле * сначала создам массив со значениями * и потом добавлю одним запросом */ $collection->each(function ($item, $key) use (&$categoryId, $id){ $categoryId[] = [ 'image_id' => $id, 'category_id' => $item->first() ] ; } ); DB::table('category_image')->insert($categoryId); } /////////////////////////////////////////// /* Выбрать случайного пользователя * Использую при сздание фейковых данных */ App\User::all()->random()->id; <file_sep><?php /* Middleware - дополнительный проверки*/ /* Создание - php artisan make:middleware CheckAge * Создаться в папке app/Http/Middleware */ namespace App\Http\Middleware; use Closure; use Illuminate\Support\Facades\Auth; class UserMiddleware { public function handle($request, Closure $next) { if(Auth::check()) { return $next($request); } abort(404); //Вызов ошибки } } /*Что бы добавить эту проверку, для конкретного роута * надо этот класс добавить в массив $routeMiddleware (app/Http/Kernel.php) */ protected $routeMiddleware = [ 'auth' => \Illuminate\Auth\Middleware\Authenticate::class, 'user' => \App\Http\Middleware\UserMiddleware::class, ]; /* Вызов */ /* Теперь страница для создания статьи, * откроется только для авторизированнного пользователя */ Route::get('/create', 'imagesController@create')->middleware('user'); ///////////////////////////////////////////// /* Ещё пример, проверка на админа */ class AdminOnlyMiddleware { /** * Handle an incoming request. * * @param \Illuminate\Http\Request $request * @param \Closure $next * @return mixed */ public function handle($request, Closure $next) { $user = Auth::user(); if($user == null){ abort(404); } if($user != null){ if ($user->role !== "admin") { abort(404); } } return $next($request); } } /* protected $routeMiddleware */ 'admin' => \App\Http\Middleware\AdminOnlyMiddleware::class /* Вызов */ Route::group(['as' => 'admin.', 'namespace'=>'Admin', 'prefix' => 'admin', 'middleware' => ['admin']], function() { Route::get('categories/edit/{d}', 'CategoriesController@edit')->name('categories.edit'); Route::put('categories/update/{d}', 'CategoriesController@update')->name('categories.update'); Route::delete('categories/destroy/{d}', 'CategoriesController@destroy')->name('categories.destroy'); }); } <file_sep><?php /* *Одна модель данных соответствует лишь одной таблице. * *Модель данных называется в единственном числе, в * ВерхнейВерблюжейНотации: Category, ShopCategory * *Таблица данных называется во множественном числе в * нижней_змеиной_нотации: categories, shop_categories * *В отношениях типа "один ко многим/одному", Название * полей, являющихся внешними ключами, ссылающимися * на определитель во внешней таблице, пишутся в нижней_змеиной_нотации, * единственном числе по имени вызывающего * метода и постфиксом _id: categоry_id, product_id. * *Пивотные (стержневые) таблицы, выражающие отношение "Многие ко многим", * называются в единственном числе, нижней змеиной нотации по именам * связанных моедлей, в алфавитном порядке: role_user, но не user_role, . * *В отношениях типа "многие ко многим", внешние ключи называютсяв * единственном числе, нижней змеиной нотации, * по именам моделей и постфиксом _id. * *Таблица данных должна содержать поля: *id(int, unsigned, auto-increment) *created_at(timestamp) опционально, при использовании таймштампов *updated_at(timestamp) опционально, при использовании таймштампов *deleted_at(timestamp) опционально, при использовании трейта "мягкого удаления" */ /* Многие ко многим */ /* Для этого отношения обязательно * нужна промежуточная таблица (пивотная) * и для этой таблицы модель не нужна */ /* * метод belongsToMany, обязательно обратится к трём таблицам * * Например, есть таблицы images, categories и category_image (пивотная). * И этот метод будет искать классы Image и Category и когда найдёт, * то потом будет искать таблицы в базе с таким же название и * автоматически преобразует их во множественное число * * В пивотоной таблице будут столбцы image_id, category_id */ class Image extends Model { public function categories() { return $this->belongsToMany(Category::class); } } class Category extends Model { public function article() { return $this->belongsToMany('App\Services\Image'); } } /* * Вывести все стать и указанной категории */ $targetCateory = Category::find($id)->article()->paginate(2); <file_sep><?php /* *в yield подгрузиться шаблон с названием * и в этом подгрузившемся шаблоном * содержимое должно быть в @section * * extends определяет, что этот шаблон расширяется (от этого) */ </nav> @yield('content') //будет искать шаблон, который назван content в аргументе @section </body> </html> //////////////////////////// @extends('layout') @section('content') <div class="container"> <h1 align="center">My Gallery</h1> </div> @endsection /////////////////////////////////////////////// /* * В фигурных скобках обрабатыввается * php код для его вывода * обрабатываются атак XSS * например, что бы такой код не сработал * <script>alert(1111)</alert> * теги заменятся на символы */ Hello, {{ $name }}. Вы можете создавать инструкции if с помощью @if, @elseif, @else и @endif . Эти директивы работают одинаково с их PHP-образцами: <ul class = "navbar-nav mr-auto"> @if (Auth::check()) <li class = "nav-item"> <a class = "nav-link" href = ""> {{ Auth::user()->name}} вы находитель в группе {{$userRole}} </a> </li> <li class = "nav-item"> <a class = "nav-link" href = "/create">Добавить картинку</a> </li> <li class = "nav-item"> <a href = "/logout" onclick = "event.preventDefault(); document.getElementById('logout-form').submit(); "class = "nav-link"> Выйти </a> <form id = "logout-form" action = "{{route('logout')}}" method = "POST" style = "display: none;"> {{csrf_field()}} </form> </li> @else Привет {{$userRole}} <li class = "nav-item"> <a class = "nav-link" href = "/login">Войти</a> </li> @endif </ul> //////////////////////////////////////// /* Можно использовать цикл */ @foreach($imagesInView as $image) <div class="col-sm-3 gallery-item"> <div> <img src="/{{$image->image}}" class="img-thumbnail"> <p style="text-align: center;">{{$image->description}}<p> </div> <a href="/show/{{$image->id}}" class="btn btn-info my-button">Show</a> <a href="/edit/{{$image->id}}" class="btn btn-warning my-button">Edit</a> <a href="/delete/{{$image->id}}" onclick="return confirm('Точно удалить?')"class="btn btn-danger my-button">Delete</a> </div> @endforeach <file_sep><?php /* Migrations - класс для работы с базой*/ /*Создание php artisan make:migration create_users_table */ /* * Класс миграции содержит два метода: up и down . * Метод up используется для добавления новых таблиц, * столбцов или индексов в вашу базу данных, тогда как * метод down должен отменить операции, выполняемые методом up */ public function up() { Schema::create('images', function (Blueprint $table) { $table->increments('id'); $table->string('image'); $table->timestamps(); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::dropIfExists('images'); } /* Запуск миграции - php artisan migrate */ /////////////////////////////////////////// /* * Чтобы отменить последнюю операцию миграции, * вы можете использовать команду rollback . * Эта команда откатывает последнюю «пакетную» миграции, * которая может включать в себя несколько файлов миграции: */ php artisan migrate:rollback ////////////////////////////// /* откатить несколько миграций */ php artisan migrate:rollback --step=5 ////////////////////////////////// /* Откатить все миграции */ php artisan migrate:reset ////////////////////////////////////////////////////// Для добавление столбцов, используется метод table вместо create class AddDesciptionToImages extends Migration { public function up() { Schema::table('images', function($table) { $table->string('description'); }); } public function down() { Schema::table('images', function($table) { $table->dropColumn('description'); }); } } /* * Значение по умолчанию */ $table->string('image')->default('uploads/users/ava.png');
40088fcdabc261f0ed29a93afc6318d3b925cd47
[ "Markdown", "PHP", "INI" ]
13
INI
Div-Man/lara-documentation
6cffb19b8611a7c2f9734718bd941f5963b540c6
768c0ea07beeb4235bfcc4bd81bd4a75ad8e2a7c
refs/heads/master
<file_sep><?php use Illuminate\Http\Request; /* |-------------------------------------------------------------------------- | API Routes |-------------------------------------------------------------------------- | | Here is where you can register API routes for your application. These | routes are loaded by the RouteServiceProvider within a group which | is assigned the "api" middleware group. Enjoy building your API! | */ Route::middleware('auth:api')->get('/user', function (Request $request) { return $request->user(); }); Route::get('/', function () { $result = ['result' => 'OK', 'data' => 'No Data Yet']; $response = \Response::json($result)->setStatusCode(200, 'Success'); return $response; }); Route::post('signup', function(Request $request){ // [1] // [2] $name = \Request::get('name'); $email = \Request::get('email'); $password = \Request::get('password'); $password_bcrypt = <PASSWORD>($password); // [3] $validator = Validator::make( [ 'name' => $name, 'email' => $email, 'password' => $password ], [ 'name' => 'required', 'email' => 'required|email|unique:users', 'password' => '<PASSWORD>' ] ); // [4] if ($validator->fails()){ $result = ['result' => 'Failed', 'message' => 'Some of the requirements are not met']; $response = \Response::json($result)->setStatusCode(400, 'Fail'); // [5] return $response; } else { // [6] $user = new \App\User; $user->name = $name; $user->email = $email; $user->password = $<PASSWORD>; $user->save(); $result = ['result' => 'Success', 'message' => 'Account '. $name . ' with email '. $email . ' was created']; $response = \Response::json($result)->setStatusCode(200, 'Success'); return $response; } }); Route::post('login', function(Request $request){ $email = \Request::get('email'); $password = \Request::get('password'); // [1] $user = \App\User::where('email','=', $email)->first(); // IF THE THERE IS EMAIL MATCHED if ($user != null){ if (Hash::check($password, $user->password)){ $result = ['result' => 'Success', 'message' => 'Password correct', 'user_id' => $user->id]; $response = \Response::json($result)->setStatusCode(200, 'Success'); return $response; }else{ $result = ['result' => 'Failed', 'message' => 'Password Incorrect']; $response = \Response::json($result)->setStatusCode(201, 'Failed'); return $response; } // NOT MATCHED }else{ $result = ['result' => 'Failed', 'message' => 'User with email not found.Create New Account']; $response = \Response::json($result)->setStatusCode(202, 'Failed'); return $response; } }); <file_sep><?php /* |-------------------------------------------------------------------------- | Web Routes |-------------------------------------------------------------------------- | | */ Route::get('/', function () { return view('welcome'); }); Route::resource('products','ProductController'); Route::resource('students','StudentController'); Auth::routes(); Route::get('/home', 'HomeController@index')->name('home'); Route::prefix('admin')->group(function() { Route::get('/login', 'Auth\AdminLoginController@showLoginForm')->name('admin.login'); Route::post('/login', 'Auth\AdminLoginController@login')->name('admin.login.submit'); Route::get('/home', 'AdminController@index')->name('admin.home'); });
95523c8bc68e3bc369058eccff5d8f46a3ecaea0
[ "PHP" ]
2
PHP
deyrupam/tut_laravel
3d5b2c07728b3b390bd1788c5bb10981381d5850
82466b48d5747573bd4cf85f97b43dc439304e02
refs/heads/main
<repo_name>Qabas-al-ani/Personal-Protfolio-2<file_sep>/readme.md # Personal Portfolio 2 --- [![License](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT) ## Table of Contents - [Description](#description) - [Technologies](#Technologies) - [Usage](#usage) - [Questions](#questions) ## Description: I updated my personal portfolio and added second page for contact information and also to be used further on if i want to add and extra page. ``` ## Technologies - Html. - Css. - Javascript. - Materialize. - Scroll.js. ``` ### Usage to have a look for my work and projects that i've created ### A Screenshot of my deployed personal portfolio ![ScreenShots](./Assets/images/screenshots/screenshot1q.png) ![ScreenShots](./Assets/images/screenshots/screenshot2q.png) ![ScreenShots](./Assets/images/screenshots/screenshot3q.png) ![ScreenShots](./Assets/images/screenshots/screenshot4q.png) [Click here to see the running app!](https://qabas-al-ani.github.io/Personal-Protfolio-2/) ### Questions? For any questions, please contact me with the information below: <EMAIL> [LinkedIn Profile]( https://www.linkedin.com/in/qabas-al-ani-7b858863/ ) [Github Profile]( https://github.com/Qabas-al-ani ) <file_sep>/js/scroll.js const sr = ScrollReveal({ distance: "100px", duration: 1000, mobile: true, }); sr.reveal(`.landing-title`, { delay: 200, origin: "left", }); sr.reveal(`.landing-description`, { delay: 200, origin: "right", }); sr.reveal(`.language-1`, { delay: 200, origin: "right", }); sr.reveal(`.language-2`, { delay: 200, origin: "right", }); sr.reveal(`.language-3`, { delay: 200, origin: "right", }); sr.reveal(`.language-4`, { delay: 200, origin: "right", }); sr.reveal(`.language-5`, { delay: 200, origin: "right", }); sr.reveal(`.language-6`, { delay: 200, origin: "right", }); sr.reveal(`.language-7`, { delay: 200, origin: "right", }); sr.reveal(`.language-8`, { delay: 200, origin: "right", }); sr.reveal(`.language-9`, { delay: 200, origin: "right", }); $(document).ready(function () { $(".sidenav").sidenav(); });
2d494b688fb28f67e994490f505d5d0d279b7796
[ "Markdown", "JavaScript" ]
2
Markdown
Qabas-al-ani/Personal-Protfolio-2
e5b3ea3e66728cc5d6baaa745ec03d69ef5ad11d
6338d6297ef54920fda617324eaf56633222b2f5
refs/heads/master
<repo_name>terzeron/GoTest<file_sep>/server/server.go package main import "github.com/go-martini/martini" func main() { m := martini.Classic() m.Get("/", func() string { return "Hello, world!" }) m.Get("/error", func() (int, string) { return 301, "I'm a kettle" }) m.Run() } <file_sep>/GrammarTest/32.channel.go package main import "fmt" func main() { // channel (like pipe) messages := make(chan string) // <-를 이용하여 메시지를 채널에 송신 go func() { messages <- "ping" }() // <-를 이용하여 채널에서 메시지를 수신 msg := <-messages fmt.Println(msg) } <file_sep>/GrammarTest/45.atomic_counter.go package main import ( "fmt" "sync/atomic" "time" ) func main() { var ops uint64 = 0 for i := 0; i < 50; i++ { // 고루틴 50개 동시 실행 go func() { for { // atomic한 add 연산 atomic.AddUint64(&ops, 1) time.Sleep(time.Millisecond) } }() } time.Sleep(time.Second) opsFinal := atomic.LoadUint64(&ops) fmt.Println("ops:", opsFinal) fmt.Println("ops original:", ops) } <file_sep>/GrammarTest/33.channel_buffering.go package main import "fmt" func main() { // 기본적으로 채널은 unbuffered 상태 // 수신준비가 안 되어 있으면 block되거나 유실됨 // 버퍼 크기 지정 가능 messages := make(chan string, 2) messages <- "buffered" messages <- "channel" fmt.Println(<-messages) fmt.Println(<-messages) } <file_sep>/GrammarTest/41.timer.go package main import ( "fmt" "time" ) func main() { // 타이머는 채널을 만들어서 반환함 timer1 := time.NewTimer(time.Second * 2) <-timer1.C // blocking fmt.Println("Timer 1 expired") timer2 := time.NewTimer(time.Second) go func() { <-timer2.C fmt.Println("Timer 2 expired") }() // 타이머는 단순 sleep과 달리 중간에 취소가 가능함 // 타이머 채널에 대한 blocking은 고루틴에서 비동기적으로 실행 중이기 때문에 메인 루틴은 다음의 취소 로직을 실행함 stop2 := timer2.Stop() if stop2 { fmt.Println("Timer 2 stopped") } } <file_sep>/GrammarTest/47.stateful_goroutine.go package main import ( "fmt" "math/rand" "sync/atomic" "time" ) type readMsgStruct struct { key int resp chan int } type writeMsgStruct struct { key int val int resp chan bool } func main() { var readOps uint64 = 0 var writeOps uint64 = 0 readChannel := make(chan *readMsgStruct) writeChannel := make(chan *writeMsgStruct) go func() { // state는 하나의 고루틴이 독점 사용함 (lock 불필요함) var state = make(map[int]int) for { select { // 읽기채널로 메시지가 오면 응답채널로 map의 특정 키가 가리키는 요소의 값을 보냄 case readMsg := <-readChannel: readMsg.resp <- state[readMsg.key] // 쓰기채널로 메시지가 오면 데이터를 map에 저장하고 응답채널로 true를 보냄 case writeMsg := <-writeChannel: state[writeMsg.key] = writeMsg.val writeMsg.resp <- true } } }() for r := 0; r < 100; r++ { // 100개의 읽기 고루틴 go func() { for { readMsg := &readMsgStruct{ key: rand.Intn(5), resp: make(chan int)} readChannel <- readMsg <-readMsg.resp atomic.AddUint64(&readOps, 1) time.Sleep(time.Millisecond) } }() } for w := 0; w < 10; w++ { // 10개의 쓰기 고루틴 go func() { for { writeMSg := &writeMsgStruct{ key: rand.Intn(5), val: rand.Intn(100), resp: make(chan bool)} writeChannel <- writeMSg <-writeMSg.resp atomic.AddUint64(&writeOps, 1) time.Sleep(time.Millisecond) } }() } time.Sleep(time.Second) readOpsFinal := atomic.LoadUint64(&readOps) fmt.Println("readOps:", readOpsFinal) writeOpsFinal := atomic.LoadUint64(&writeOps) fmt.Println("writeOps:", writeOpsFinal) } <file_sep>/README.md # 실행 방법 * `go run myapp1.go` * or * `go build myapp1.go && ./myapp1` <file_sep>/GrammarTest/39.closing_channel.go package main import "fmt" func main() { jobs := make(chan int, 5) done := make(chan bool) // ------jobs------- // 1 2 3 // worker <- ----------------- <- main // ------done------ // true // main <- ---------------- <- worker // worker go func() { for { j, more := <-jobs if more { fmt.Println("received job", j) } else { fmt.Println("received all jobs") done <- true return } } }() // 수신 for j := 1; j <= 3; j++ { jobs <- j fmt.Println("sent job", j) } // 채널 종료 // 채널을 닫지 않으면 계속 수신하겠다고 열어두는 것이므로 // 송신쪽과 짝이 맞지 않아서 에러 발생함 //close(jobs) fmt.Println("sent all jobs") // worker 대기 (동기화) <-done } <file_sep>/GrammarTest/34.channel_synchronization.go package main import ( "fmt" "time" ) func worker(done chan bool) { fmt.Print("working...") time.Sleep(time.Second) fmt.Println("done") // 1초 대기후 true 메시지 전송 done <- true } func main() { // 채널 생성 done := make(chan bool, 1) // 고루틴 실행 go worker(done) // 수신 대기 <-done }
ecd53ab3417a5af32df5d9f49dad37e5b00fa208
[ "Markdown", "Go" ]
9
Go
terzeron/GoTest
d31b27070463d333555a153c13d17dcbd2c3c01a
6b36c6c01424e423889ca6c38beb58f945b950e8
refs/heads/main
<repo_name>luqmanazeq/Sukui<file_sep>/sukuinote/plugins/cat.py import html import tempfile from pyrogram import Client, filters from .. import config, help_dict, log_errors, session, progress_callback, public_log_errors @Client.on_message(~filters.sticker & ~filters.via_bot & ~filters.edited & filters.me & filters.command('cat', prefixes=config['config']['prefixes'])) @log_errors @public_log_errors async def cat(client, message): media = message.document if not media and not getattr(message.reply_to_message, 'empty', True): media = message.reply_to_message.document if not media: await message.reply_text('Document required') return done = False with tempfile.NamedTemporaryFile() as file: reply = await message.reply_text('Downloading...') await client.download_media(media, file_name=file.name, progress=progress_callback, progress_args=(reply, 'Downloading...', False)) with open(file.name) as nfile: while True: chunk = nfile.read(4096) if not chunk: break chunk = f'<code>{html.escape(chunk)}</code>' if done: await message.reply_text(chunk, quote=False) else: await reply.edit_text(chunk) done = True help_dict['cat'] = ('cat', '{prefix}cat <i>(as caption of text file or reply)</i> - Outputs file\'s text to Telegram') <file_sep>/sukuinote/plugins/translate.py import time import html import googletrans from pyrogram import Client, filters from .. import config, help_dict, log_errors, public_log_errors PROBLEM_CODES = set(i for i in googletrans.LANGUAGES if '-' in i) @Client.on_message(~filters.sticker & ~filters.via_bot & ~filters.edited & filters.me & filters.command(['tr', 'translate'], prefixes=config['config']['prefixes'])) @log_errors @public_log_errors async def translate(client, message): reply = message.reply_to_message if getattr(reply, 'empty', True): await message.reply_text('Reply required') return text = reply.text or reply.caption if not text: await message.reply_text('Text required') return src_lang = 'auto' dest_lang = 'en' lang = ' '.join(message.command[1:]).lower() for i in PROBLEM_CODES: if lang.startswith(i): lang = lang[len(i) + 1:] if lang: src_lang = i dest_lang = lang else: dest_lang = i break else: lang = lang.split('-', 1) if len(lang) == 1 or not lang[-1]: dest_lang = lang.pop(0) or dest_lang else: src_lang, dest_lang = lang def _translate(): while True: try: return googletrans.Translator().translate(text, src=src_lang, dest=dest_lang) except AttributeError: time.sleep(0.5) result = await client.loop.run_in_executor(None, _translate) if result.text == text: text = 'They\'re the same' else: text = f'Translated from {result.src} to {result.dest}:\n{result.text[:4000]}' await message.reply_text(text, parse_mode=None) help_dict['translate'] = ('Translate', '''{prefix}translate <i>(as reply to text)</i> <i>[src]-[dest]</i> - Translates text and stuff Aliases: {prefix}tr''') <file_sep>/sukuinote/plugins/delete.py import html from pyrogram import Client, filters from .. import config, help_dict, log_errors, public_log_errors @Client.on_message(~filters.sticker & ~filters.via_bot & ~filters.edited & filters.me & filters.command(['d', 'del', 'delete'], prefixes=config['config']['prefixes'])) @log_errors @public_log_errors async def delete(client, message): messages = set((message.message_id,)) reply = message.reply_to_message if not getattr(reply, 'empty', True): messages.add(reply.message_id) else: async for i in client.iter_history(message.chat.id, offset=1): if i.outgoing: messages.add(i.message_id) break await client.delete_messages(message.chat.id, messages) @Client.on_message(~filters.sticker & ~filters.via_bot & ~filters.edited & filters.me & filters.command(['p', 'purge', 'sp', 'selfpurge'], prefixes=config['config']['prefixes'])) @log_errors @public_log_errors async def purge(client, message): command = message.command selfpurge = 's' in command.pop(0) command = ' '.join(command) ids = set((message.message_id,)) reply = message.reply_to_message if command.isnumeric(): command = int(command) if selfpurge: async for i in client.iter_history(message.chat.id, offset=1): if not (selfpurge and not i.outgoing): ids.add(i.message_id) command -= 1 if command <= 0: break else: async for i in client.iter_history(message.chat.id, offset=1, limit=command): ids.add(i.message_id) elif not getattr(reply, 'empty', True): if not (selfpurge and not reply.outgoing): ids.add(reply.message_id) async for i in client.iter_history(message.chat.id, offset=1): if not (selfpurge and not i.outgoing): ids.add(i.message_id) if reply.message_id + 1 >= i.message_id: break await client.delete_messages(message.chat.id, ids) yeetpurge_info = {True: dict(), False: dict()} @Client.on_message(~filters.sticker & ~filters.via_bot & ~filters.edited & filters.me & filters.command(['yp', 'yeetpurge', 'syp', 'selfyeetpurge'], prefixes=config['config']['prefixes'])) @log_errors @public_log_errors async def yeetpurge(client, message): reply = message.reply_to_message if getattr(reply, 'empty', True): await message.delete() return info = yeetpurge_info['s' in message.command[0]] if message.chat.id not in info: resp = await message.reply_text('Reply to end destination') info[message.chat.id] = (message.message_id, resp.message_id, reply.message_id, reply.outgoing) return og_message, og_resp, og_reply, og_reply_outgoing = info.pop(message.chat.id) messages = set((og_message, og_resp, message.message_id)) thing = [og_reply, reply.message_id] thing.sort() thing0, thing1 = thing if not ('s' in message.command[0] and not og_reply_outgoing): messages.add(og_reply) async for i in client.iter_history(message.chat.id, offset_id=thing1 + 1): if not ('s' in message.command[0] and not i.outgoing): messages.add(i.message_id) if thing0 + 1 >= i.message_id: break await client.delete_messages(message.chat.id, messages) help_dict['delete'] = ('Delete', '''{prefix}delete <i>(maybe reply to a message)</i> - Deletes the replied to message, or your latest message Aliases: {prefix}d, {prefix}del {prefix}purge <i>(as reply to a message)</i> - Purges the messages between the one you replied (and including the one you replied) Aliases: {prefix}p {prefix}selfpurge <i>(as reply to a message)</i> - {prefix}p but only your messages Aliases: {prefix}sp {prefix}yeetpurge <i>(as reply to a message)</i> - Purges messages in between Aliases: {prefix}yp {prefix}selfyeetpurge <i>(as reply to a message)</i> - {prefix}yp but only your messages Aliases: {prefix}syp''') <file_sep>/sukuinote/plugins/shell.py import re import html import asyncio from pyrogram import Client, filters from .. import config, help_dict, log_errors, public_log_errors @Client.on_message(~filters.sticker & ~filters.via_bot & ~filters.edited & filters.me & filters.regex('^(?:' + '|'.join(map(re.escape, config['config']['prefixes'])) + r')(?:(?:ba)?sh|shell|term(?:inal)?)\s+(.+)(?:\n([\s\S]+))?$')) @log_errors @public_log_errors async def shell(client, message): command = message.matches[0].group(1) stdin = message.matches[0].group(2) reply = await message.reply_text('Executing...') process = await asyncio.create_subprocess_shell(command, stdin=asyncio.subprocess.PIPE if stdin else None, stdout=asyncio.subprocess.PIPE, stderr=asyncio.subprocess.PIPE) stdout, stderr = await process.communicate(stdin.encode() if stdin else None) returncode = process.returncode text = f'<b>Exit Code:</b> <code>{returncode}</code>\n' stdout = stdout.decode().replace('\r', '').strip('\n') stderr = stderr.decode().replace('\r', '').strip('\n') if stderr: text += f'<code>{html.escape(stderr)}</code>\n' if stdout: text += f'<code>{html.escape(stdout)}</code>' await reply.edit_text(text) help_dict['shell'] = ('Shell', '''{prefix}sh <i>&lt;command&gt;</i> \\n <i>[stdin]</i> - Executes <i>&lt;command&gt;</i> in shell Aliases: {prefix}bash, {prefix}shell, {prefix}term, {prefix}terminal''') <file_sep>/requirements.txt googletrans pyrogram tgcrypto requests aiohttp>=3.7.1 PyYAML
e3cab00bfef7de384110769e9df7f1a6aaf11063
[ "Python", "Text" ]
5
Python
luqmanazeq/Sukui
1b5c21a2397985a08b2ab45713f0475d0743c672
9f05c28a2b8d1a66de494a070dc4475ea95e069d
refs/heads/master
<repo_name>Julia-Ku2000/lab3<file_sep>/UserCode.java package by.mail.bookShop; public interface UserCode { String generateCode(String email); } <file_sep>/Purchase.java package by.mail.bookShop; public interface Purchase { double discount = 0; double buy(double amount,double discount); } <file_sep>/Book.java package by.mail.bookShop; import java.sql.SQLOutput; import java.util.ArrayList; import java.util.Collection; import java.util.List; public class Book { private String name; private String author; private double price; private int count; static List<Book> books = new ArrayList<>(); public Book(String name, String author, double price) { this.name = name; this.author = author; this.price = price; } public static void showCatalog() { books.add(new Book("Война ии мир", "<NAME>", 25)); books.add(new Book("Маленькая хозяйка большого дома", "<NAME>", 36)); books.add(new Book("Палата №6", "<NAME>", 46)); books.add(new Book("Великий Гетсби", "<NAME>", 54.6)); for (int i = 0; i < books.size(); i++) { System.out.println((i + 1) + " " + books.get(i)); } } public static double chooseItem(int userChoice) { return books.get(userChoice).getPrice(); } public double getPrice() { return price; } @Override public String toString() { return name + " " + author + " " + price; } }<file_sep>/User.java package by.mail.bookShop; public abstract class User implements Purchase { String email; String name; String surname; String password; String iii; } <file_sep>/Delivery.java package by.mail.bookShop; public interface Delivery { final int delivery = 5; int amountWithPayDelivery = 20; int amountWithFreeDelivery = 50; double calculateDelivery(double amount, int delivery); } <file_sep>/Check.java package by.mail.bookShop; import java.io.BufferedReader; import java.io.FileReader; import java.io.IOException; public class Check implements Delivery, UserCode { Book book; public static double countFromFile() { double[] array = null; try (BufferedReader in = new BufferedReader(new FileReader("D:\\02_Study\\java-project\\variables\\src\\by\\mail\\bookShop\\file"))) { array = in.lines().mapToDouble(Double::parseDouble).toArray(); } catch (IOException | NumberFormatException e) { e.printStackTrace(); } double summa = 0; if (array != null) { for (int i = 0; i < array.length; i++) { summa +=array[i]; } } return summa; } @Override public double calculateDelivery(double amount, int delivery) { if (amount < amountWithPayDelivery) { return delivery; } if (amount > amountWithPayDelivery && amount < amountWithFreeDelivery) { return delivery / 2; } return 0; } @Override public String generateCode(String email) { Integer buffer = (100 + (int) Math.random() * 999); String code = buffer.toString(); return code; } } <file_sep>/Main.java package by.mail.bookShop; import java.io.*; import java.nio.file.Files; import java.nio.file.Paths; import java.nio.file.StandardOpenOption; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Date; import java.util.Locale; import java.util.Scanner; import static by.mail.bookShop.Book.chooseItem; import static by.mail.bookShop.Book.showCatalog; public class Main { public static void main(String[] args) throws IOException, ParseException { Buyer buyer = new Buyer(); showCatalog(); System.out.println("Выберете товар"); Scanner scanner = new Scanner(System.in); int choice; do { choice = scanner.nextInt(); if (choice > 0 && choice <= 4) { try { Files.write(Paths.get("D:\\02_Study\\java-project\\variables\\src\\by\\mail\\bookShop\\file") , (String.valueOf(chooseItem(choice - 1)) + "\n").getBytes(), StandardOpenOption.APPEND); } catch (IOException e) { e.printStackTrace(); } } } while (choice != 0); System.out.println("К оплате: "); buyer.buy(buyer.getAmountSpend(), 2); System.out.println(readCheckFromFile()); System.out.println("Выберете способ оплаты:"); int wayOfPay; String cardInfo; int CVC; String date; System.out.println("1. Наличные"); System.out.println("2. Карта"); wayOfPay = scanner.nextInt(); if (wayOfPay == 1) { System.out.println("Оплата будет совершена при получении"); } else if (wayOfPay == 2) { System.out.println("Заполните данные банковской карты"); CreditCard creditCard = new CreditCard(); System.out.println("Номер банковской карты"); while (scanner.hasNext()) { cardInfo = scanner.nextLine(); creditCard.setCardNumber(cardInfo); } //date = scanner.nextLine(); //SimpleDateFormat s = new SimpleDateFormat("yyyy-MM-dd"); //Date date1 = s.parse(date); //scanner.close(); //SimpleDateFormat smd = new SimpleDateFormat("MMM dd, yyyy", Locale.ENGLISH); ///creditCard.setTerm(smd.format(date1).toUpperCase()); } else if (wayOfPay != 1 || wayOfPay != 2) { System.out.println("error"); } } public static double readCheckFromFile() { double[] array = null; try (BufferedReader in = new BufferedReader(new FileReader("D:\\02_Study\\java-project\\variables\\src\\by\\mail\\bookShop\\fileCheck"))) { array = in.lines().mapToDouble(Double::parseDouble).toArray(); } catch (IOException | NumberFormatException e) { e.printStackTrace(); } double summa = 0; if (array != null) { for (int i = 0; i < array.length; i++) { summa += array[i]; } } return summa; } } <file_sep>/Admin.java package by.mail.bookShop; import java.io.BufferedReader; import java.io.FileReader; import java.io.IOException; public class Admin extends User { @Override public double buy(double amount, double discount) { double[] array = null; try (BufferedReader in = new BufferedReader(new FileReader("D:\\02_Study\\java-project\\variables\\src\\by\\mail\\bookShop\\file"))) { array = in.lines().mapToDouble(Double::parseDouble).toArray(); } catch (IOException | NumberFormatException e) { e.printStackTrace(); } double summa = 0; if (array != null) { for (int i = 0; i < array.length; i++) { summa +=array[i]; } } return summa; } }
b10b2f7db7336b357ca2c52277ea9f25b9923927
[ "Java" ]
8
Java
Julia-Ku2000/lab3
fffda8c8772ce6c7c22a0c637ce0ed157e7f8951
5a93fdc27b9fea3d4a0a7456a91ed2d646ae4447
refs/heads/main
<repo_name>stushar12/CPP-253<file_sep>/one.cpp Node *reverse(Node *head) { Node *prev = NULL; Node *curr = head; while(curr != NULL) { Node *next = curr->next; curr->next = prev; prev = curr; curr = next; } return prev; } struct Node* addTwoLists(struct Node* first, struct Node* second) { first=reverse(first); second=reverse(second); int carry = 0, sum = 0; Node* start = NULL; Node* end = NULL; while(first != NULL || second != NULL) { int a = (first != NULL)?first -> data:0; int b = (second != NULL)?second -> data:0; sum = carry + (a + b); carry = (sum >= 10)?1:0; sum = sum % 10; if(start == NULL) { start = new Node(sum); end = start; } else { end -> next = new Node(sum); end = end -> next; } if(first != NULL) first = first -> next; if(second != NULL) second = second -> next; } if(carry > 0) end -> next = new Node(carry); start = reverse(start); return start; }<file_sep>/README.md # CPP-253 Add two numbers represented by linked lists https://practice.geeksforgeeks.org/problems/add-two-numbers-represented-by-linked-lists/1
e4f69eec9b2041350844755dde62b2b636ac72de
[ "Markdown", "C++" ]
2
C++
stushar12/CPP-253
fcd860882cf5e09f07e8de4d33c65d6689bccd11
af8fd29fbbceea2d770622754c40e739da98d428
refs/heads/master
<repo_name>ChiliMonanta/terraform-template<file_sep>/makefile ifeq ($(env),global) TFVARS="global.tfvars" STATE=output base="environments/global" else ifeq ($(env),prod) TFVARS="prod.tfvars" STATE=output base="environments/production" else ifeq ($(env),stage) TFVARS="staging.tfvars" STATE=output base="environments/staging" else TFVARS="dev.tfvars" STATE=output base="environments/development" endif get: cd $(base) && terraform get plan: get cd $(base) && terraform plan -var-file=$(TFVARS) -state="$(STATE)/$(env).tfstate" destroy: get cd $(base) && terraform destroy -var-file=$(TFVARS) -state="$(STATE)/$(env).tfstate" apply: get cd $(base) && terraform apply -var-file=$(TFVARS) -state="$(STATE)/$(env).tfstate" clean: cd $(base) && rm -rf output <file_sep>/README.md # Terraform template A terraform template for a vpc with app server and load balancer. Access logs are sent to s3 every 60 minutes. Execute global before app specific infrastructure ## Prerequisites 1. Setup yor aws profile [docs](http://docs.aws.amazon.com/cli/latest/userguide/cli-chap-getting-started.html#cli-quick-configuration) aws configure --profile user2 2. Create key pair [docs](http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ec2-key-pairs.html#having-ec2-create-your-key-pair) ## Actions: Parameters: - env: prod, stage, dev, global Plan make env=dev plan Apply make env=dev apply Destroy make env=dev destroy Clean make clean Note: Problem with bootstrap (user_data), see /var/log/cloud-init-output.log<file_sep>/modules/web-server/bootstrap/user_data.sh #!/bin/bash echo "Initialize user data..." curl --silent --location https://rpm.nodesource.com/setup_7.x | bash - yum install -y nodejs cat <<EOT >> app.js var express = require('express'); \ var app = express(); \ app.get('/', function (req, res) { \ res.send('Hello World says ${app_name}!'); \ }); \ app.listen(80, function () { console.log('Example app listening on port 80!'); }); EOT npm install express nohup node app.js & echo "Initialize user data - complete"
57d6a0f6ea29a7d7292e840eb86e04b3b631fba7
[ "Markdown", "Makefile", "Shell" ]
3
Makefile
ChiliMonanta/terraform-template
a82d8c0cce40d51912d5d031a4a3be2c81a677b4
fbed2ac54cd0286648cfbdb2c138cebfa0c6de6f
refs/heads/master
<repo_name>vinegar17/testcode<file_sep>/demo.py print("hello word") print(23333) print(2.33) print({}) print("干活干活干活"+"xixixix") print("哈哈哈哈") name = "连续性" print(name) res = (2*3/3+4)%3 print(res) a = int(input("请输入",)) a/2 == 0 print("偶数")
93ca53021a2182eee7fe3d9d85c4509d01001cd3
[ "Python" ]
1
Python
vinegar17/testcode
bec6cc5b4050291c36f97e3af9a0971e2fefe935
579b1f033070fe5637d020468147903945091507
refs/heads/master
<repo_name>HEDMU-2015/PTE<file_sep>/PTE/Implemenation/Logic/PTEController.java package Logic; import java.util.List; public interface PTEController { public final static String PTE_FOLDER = "PTECalculator"; public void vaelgProfil(Profil profil); public void tilmeldObserver(Observer observer); public void notifyObservers(List<Tilstand> tilstande); public double getForskydningkraft(); public void setForskydningskraft(double forskydningskraft); public double getTyngdekraft(); public void setTyngdekraft(double tyngdekraft); public void setVinkel(double vinkel); public double getVinkel(); public void setProfil(Profil profil); public Profil getProfil(); public double getVaegt(); public void setVaegt(double vaegt); public double getNormalkraft(); public void setNormalkraft(double normalkraft); public double getDimensionerendeKraft(); public void setDimensioneredndeKraft(double dimensioneredndeKraft); public void setLaengdeRetning(LaengdeRetning laengdeRetning); public double getTau_ForskydningsSpaending(); public void setTau_ForskydningsSpaending(double tau_ForskydningsSpaending); public void nulstil(); public LaengdeRetning getLaengdeRetning(); public double getLaengde(); public void setLaengde(double laengde); public double getBoejningsMoment(); public void setBoejningsMoment(double boejningsMoment); public double getSigmaN(); public void setSigmaN(double sigmaN); public double getForskydningspunkt(); public void setForskydningspunkt(double forskydningspunkt); public double getInertimoment(); public void setInertimoment(double inertimoment); public double getSigmaB(); public void setSigmaB(double sigmaRef); public double getSigmaRef(); public void setSigmaRef(double sigmaRef); public double getBredde(); public void setBredde(double bredde); public double getDiameter(); public void setDiameter(double diameter); public double getHoejde(); public void setHoejde(double hoejde); public double getGodstykkelse(); public void setGodstykkelse(double godstykkelse); public double getAreal(); public void setAreal(double areal); public ProfilType getProfilType(); public void setProfilType(ProfilType profilType); public double getIndtastAreal(); public void setIndtastAreal(double indtastAreal); public double getFlydespaending(); public void setFlydespaending(double flydespaending); public void setSikkerhedsfaktor(double sikkerhedsfaktor); public double getSikkerhedsfaktor(); public boolean erSikkerhedsfaktorForLavt(); } <file_sep>/PTE/Implemenation/gui/PTEPane.java package gui; import Logic.Observer; import Logic.PTEController; public abstract class PTEPane implements Observer{ protected PTEController pteController; public void setPTEController(PTEController pteController){ this.pteController = pteController; this.pteController.tilmeldObserver(this); } } <file_sep>/PTE/Test/Logic/BreddeTest.java package Logic; import static org.junit.Assert.*; import org.junit.Before; import org.junit.Test; import Exceptions.BreddeException; public class BreddeTest { BreddeImpl bredde; @Before public void setUp() throws Exception { bredde = new BreddeImpl(); } @Test public void breddeNulstilTest() { bredde.setBredde(5); bredde.nulstil(); assertEquals(Double.NaN, bredde.getBredde(), 0.001); } @Test public void breddeNulTest() { bredde.setBredde(0); assertEquals(0, bredde.getBredde(), 0.001); } @Test public void breddeNormalTest() { bredde.setBredde(4); assertEquals(4, bredde.getBredde(), 0.001); } @Test public void breddeNegativTest() { try { bredde.setBredde(-4); } catch (BreddeException e) { // Success } } @Test public void breddeKommaTest() { bredde.setBredde(5.5555); assertEquals(5.556, bredde.getBredde(), 0.001); } } <file_sep>/PTE/Test/Logic/HoejdeTest.java package Logic; import static org.junit.Assert.assertEquals; import org.junit.Before; import org.junit.Test; import Exceptions.HoejdeException; public class HoejdeTest { HoejdeImpl hoejde; @Before public void setUp() throws Exception { hoejde = new HoejdeImpl(); } @Test public void hoejdeNulstilTest() { hoejde.setHoejde(5); hoejde.nulstil(); assertEquals(Double.NaN, hoejde.getHoejde(), 0.001); } @Test public void hoejdeNulTest() { hoejde.setHoejde(0); assertEquals(0, hoejde.getHoejde(), 0.001); } @Test public void hoejdeNormalTest() { hoejde.setHoejde(4); assertEquals(4, hoejde.getHoejde(), 0.001); } @Test public void hoejdeNegativTest() { hoejde.setHoejde(-4); try { hoejde.getHoejde(); } catch (HoejdeException e) { // Success } } @Test public void hoejdeKommaTest() { hoejde.setHoejde(5.5555); assertEquals(5.556, hoejde.getHoejde(), 0.001); } } <file_sep>/PTE/Implemenation/Logic/Godstykkelse.java package Logic; public interface Godstykkelse extends PTEEntity { public void setGodstykkelse(double godstykkelse); public double getGodstykkelse(); public void nulstil(); } <file_sep>/PTE/Implemenation/Logic/Tilstand.java package Logic; public enum Tilstand { VAEGT, PROFIL, VINKEL, TYNGDEKRAFT, DIMENSIONERENDE_KRAFT, NORMALKRAFT, FORSKYDNINGSKRAFT, BOEJNINGSMOMENT, LAENGDE, AREAL, TAU_FORSKYDNINGSSPAENDING, SIGMAN, FORSKYDNINGSPUNKT, INERTIMOMENT, SIGMAB, SIGMA_REF, FLYDESPAENDING, SIKKERHEDSFAKTOR, BREDDE, HOEJDE, DIAMETER, GODSTYKKELSE, PROFIL_TYPE, INDTAST_AREAL; } <file_sep>/PTE/Implemenation/Exceptions/UdefineretProfilException.java package Exceptions; public class UdefineretProfilException extends RuntimeException { /** * */ private static final long serialVersionUID = 1L; public UdefineretProfilException(String besked){ super(besked); } } <file_sep>/PTE/Implemenation/Logic/IndtastAreal.java package Logic; public interface IndtastAreal extends PTEEntity { public void setIndtastAreal(double areal); public double getIndtastAreal(); public void nulstil(); } <file_sep>/PTE/Implemenation/Logic/DimensionerendeKraft.java package Logic; interface DimensionerendeKraft extends PTEEntity { public double getDimensionerendeKraft(); public void setDimensionerendeKraft(double dimensionerendeKraft); public double dimensionerendeKraftTilVaegt(); public void nulstil(); } <file_sep>/PTE/Implemenation/gui/UdregningTilPdf.java package gui; import java.text.DecimalFormat; import java.util.ArrayList; import java.util.List; import Logic.LaengdeRetning; import Logic.PTEController; import Logic.Profil; public class UdregningTilPdf { private DecimalFormat format = new DecimalFormat("#.###"); public final static String FDIM = "Fdim"; public static final String FN = "Fn"; public final static String FT = "Ft"; public static final String TAU = "Tau"; public final static String BOEJNINGSMOMENT = "MB"; public final static String INTERTIMOMENT = "i"; public final static String FORSKYDNINGSPUNKT = "e"; public static final String AREAL = "A"; public static final String SIGMA_N = "SigmaN"; public static final String SIGMA_REF = "SigmaRef"; public static final String SIGMA_B = "SigmaB"; public static final String SF = "SF"; public final static String VAEGT = "vægt"; public final static String TYNGDEKRAFT = "Tyngdekraft"; public final static String FLYDESPAENDING = "SigmaTill"; public final static String LAENGDE = "l"; public static final String INGEN_RESULTAT = "?"; private String resultat; private PTEController pteController; private List<String> hoejreListe; private List<String> underListe; public UdregningTilPdf(PTEController pteController) { this.pteController = pteController; hoejreListe = new ArrayList<String>(); hoejreListe.add(normalkraftTilPdf()); hoejreListe.add(forskydningskraftTilPdf()); hoejreListe.add(dimensionerendeKraftTilPdf()); hoejreListe.add(boejningsmomentTilPdf()); underListe = new ArrayList<String>(); underListe.add(foskydningsspaendingTilPdf()); underListe.add(normalspaendingTilPdf()); underListe.add(boejningsspaendingTilPdf()); underListe.add(referencespaendingTilPdf()); underListe.add(sikkerhedsfaktorTilPdf()); } public List<String> getHoejreListe() { return hoejreListe; } public List<String> getUnderListe() { return underListe; } private String createStringFromDouble(double value) { return format.format(value); } private String boejningsmomentTilPdf() { String laengde = ""; String kraft = ""; if(Double.isNaN(pteController.getLaengde())) { laengde = LAENGDE; } else { laengde = createStringFromDouble(pteController.getLaengde()); } if (pteController.getLaengdeRetning() == LaengdeRetning.VINKELRET_TIL_FDIM) { if (Double.isNaN(pteController.getDimensionerendeKraft())) { kraft = FDIM; } else { kraft = createStringFromDouble(pteController.getDimensionerendeKraft()); } } else { if (Double.isNaN(pteController.getForskydningkraft())) { kraft = FT; } else { kraft = createStringFromDouble(pteController.getForskydningkraft()); } } if (Double.isNaN(pteController.getBoejningsMoment())) { resultat = INGEN_RESULTAT; } else { resultat = createStringFromDouble(pteController.getBoejningsMoment()); } return BOEJNINGSMOMENT + " = " + laengde + " * " + kraft + " = " + resultat; } private String boejningsspaendingTilPdf() { String boejningsMoment = createStringFromDouble(pteController.getBoejningsMoment()); if (Double.isNaN(pteController.getBoejningsMoment())) { boejningsMoment = BOEJNINGSMOMENT; } String forskydningspunkt = createStringFromDouble(pteController.getForskydningspunkt()); if (Double.isNaN(pteController.getForskydningspunkt())) { forskydningspunkt = FORSKYDNINGSPUNKT; } String inertimoment = createStringFromDouble(pteController.getInertimoment()); if (Double.isNaN(pteController.getInertimoment())) { inertimoment = INTERTIMOMENT; } if (Double.isNaN(pteController.getSigmaB())) { resultat = INGEN_RESULTAT; } else { resultat = createStringFromDouble(pteController.getSigmaB()); } return SIGMA_B + " = " + boejningsMoment + " * " + forskydningspunkt + " / " + inertimoment + " = " + resultat; } private String dimensionerendeKraftTilPdf() { String vaegt = createStringFromDouble(pteController.getVaegt()); if (Double.isNaN(pteController.getVaegt())) { vaegt = VAEGT; } String tyngdekraft = createStringFromDouble(pteController.getTyngdekraft()); if (Double.isNaN(pteController.getDimensionerendeKraft())) { tyngdekraft = TYNGDEKRAFT; } if (Double.isNaN(pteController.getDimensionerendeKraft())) { resultat = INGEN_RESULTAT; } else { resultat = createStringFromDouble(pteController.getDimensionerendeKraft()); } return FDIM + " = " + vaegt + " * " + tyngdekraft + " = " + resultat + " [N]"; } private String forskydningskraftTilPdf() { String vinkel = createStringFromDouble(pteController.getVinkel()); if (pteController.getProfil() == Profil.VANDRET) { vinkel = "cos(" + vinkel + ")"; } if (pteController.getProfil() == Profil.LODRET) { vinkel = "sin(" + vinkel + ")"; } String fdim = createStringFromDouble(pteController.getDimensionerendeKraft()); if (Double.isNaN(pteController.getDimensionerendeKraft())) { fdim = FDIM; } if (Double.isNaN(pteController.getForskydningkraft())) { resultat = INGEN_RESULTAT; } else { resultat = createStringFromDouble(pteController.getForskydningkraft()); } return FT + " = " + vinkel + " * " + fdim + " = " + resultat + " [N]"; } private String normalkraftTilPdf() { String vinkel = createStringFromDouble(pteController.getVinkel()); if (pteController.getProfil() == Profil.VANDRET) { vinkel = "sin(" + vinkel + ")"; } if (pteController.getProfil() == Profil.LODRET) { vinkel = "cos(" + vinkel + ")"; } String fdim = createStringFromDouble(pteController.getDimensionerendeKraft()); if (Double.isNaN(pteController.getDimensionerendeKraft())) { fdim = FDIM; } if (Double.isNaN(pteController.getNormalkraft())) { resultat = INGEN_RESULTAT; } else { resultat = createStringFromDouble(pteController.getNormalkraft()); } return FN + " = " + vinkel + " * " + fdim + " = " + resultat + " [N]" ; } private String foskydningsspaendingTilPdf() { String forskydningskraft; String areal; if(Double.isNaN(pteController.getForskydningkraft())) { forskydningskraft = FN; } else { forskydningskraft = createStringFromDouble(pteController.getForskydningkraft()); } if(Double.isNaN(pteController.getIndtastAreal())) { areal = AREAL; } else { areal = createStringFromDouble(pteController.getIndtastAreal()); } if(Double.isNaN(pteController.getForskydningkraft())) { resultat = INGEN_RESULTAT; } else { resultat = createStringFromDouble(pteController.getTau_ForskydningsSpaending()); } StringBuilder sb = new StringBuilder(); return sb.append(TAU).append(" = ").append(forskydningskraft) .append(" / ").append(areal).append(" = ").append(resultat).append(" N/mm2").toString(); } private String normalspaendingTilPdf() { String normalkraft; String areal; if(Double.isNaN(pteController.getNormalkraft())) { normalkraft = FN; } else { normalkraft = createStringFromDouble(pteController.getNormalkraft()); } if(Double.isNaN(pteController.getIndtastAreal())) { areal = AREAL; } else { areal = createStringFromDouble(pteController.getIndtastAreal()); } if(Double.isNaN(pteController.getSigmaN())) { resultat = INGEN_RESULTAT; } else { resultat = createStringFromDouble(pteController.getSigmaN()); } StringBuilder sb = new StringBuilder(); return sb.append(SIGMA_N).append(" = ").append(normalkraft) .append(" / ").append(areal).append(" = ").append(resultat).append(" N/mm2").toString(); } private String referencespaendingTilPdf() { String sigmaB; String sigmaN; String tau; if(Double.isNaN(pteController.getSigmaN())) { sigmaN = SIGMA_N; } else { sigmaN = createStringFromDouble(pteController.getSigmaN()); } if(Double.isNaN(pteController.getSigmaB())) { sigmaB = SIGMA_B; } else { sigmaB = createStringFromDouble(pteController.getSigmaB()); } if(Double.isNaN(pteController.getTau_ForskydningsSpaending())) { tau = TAU; } else { tau = createStringFromDouble(pteController.getTau_ForskydningsSpaending()); } if(Double.isNaN(pteController.getSigmaRef())) { resultat = INGEN_RESULTAT; } else { resultat = createStringFromDouble(pteController.getSigmaRef()); } return SIGMA_REF + " = " + "sqrt(pow(" + sigmaB + " + " + sigmaN + ") + 3 * " + "pow(" + tau + ")) = " + resultat + " N/mm2"; } private String sikkerhedsfaktorTilPdf() { String flydespaending; String sigmaRef; if(Double.isNaN(pteController.getFlydespaending())) { flydespaending = FLYDESPAENDING; } else { flydespaending = createStringFromDouble(pteController.getFlydespaending()); } if(Double.isNaN(pteController.getSigmaRef())) { sigmaRef = AREAL; } else { sigmaRef = createStringFromDouble(pteController.getSigmaRef()); } if(Double.isNaN(pteController.getSikkerhedsfaktor())) { resultat = INGEN_RESULTAT; } else { resultat = createStringFromDouble(pteController.getSikkerhedsfaktor()); } StringBuilder sb = new StringBuilder(); return sb.append(SF).append(" = ").append(flydespaending) .append(" / ").append(sigmaRef).append(" = ").append(resultat).toString(); } } <file_sep>/PTE/Implemenation/Logic/FormImpl.java package Logic; public class FormImpl extends PTEEntityImpl implements Form { private ProfilType profilType = ProfilType.UDEFINERET; @Override public void setProfilType(ProfilType profilType) { this.profilType = profilType; } @Override public ProfilType getProfilType() { return profilType; } @Override public void nulstil() { profilType = ProfilType.UDEFINERET; } @Override protected Tilstand getEgenAfhaengighed() { return Tilstand.PROFIL_TYPE; } } <file_sep>/README.md # PTE - Dette Git projekt er egnet til PTE projektet for Datamatiker 2. semester. - Gitmappen er til hele projektet, dvs. også til usecases, tests osv. Derfor skal alle slags dokumenter herind såsom: txt.filer, viseo filer, png osv. - Når du bruger pull funktionen, så vær sikker på, at der ikke er andre som har lavet ændringer i de filer, som du har ændret. - Sørg for at pull før I bruger commit/push. - I MÅ ALDRIG COMMIT .classpath & .project! - Tilføj en præcis beskrivelse af din commit. #Import GitHub (Sørg for at få trykket next til det hele!) - File -> Import -> Udvid Git mappen -> Projects from Git -> Clone URI(https://github.com/HEDMU-2015/PTE) -> Vælg samme lokation som workspace -> Import using the New Project wizard -> Java Project -> Finish - Prøv at tilføje nogle linjer i en af README filerne, commit/push og håb på at det virker. Når du har testet, at det virker så slet meget gerne de tilføjelser du har lavet, tak. #Rediger I skulle gerne have mulighed for at rediger og tilføje, hvis ikke i kan det, så kontakt Dennis eller Rasmus! #Tilføjelse af mapper og filer Når i tilføjer nye mapper, filer osv. så sørg selvfølglig for at det ikke kollapser med andre! #Diverse filer og bilag Alle jeres diverse filer og bilag må I meget godt smide i de tilsvarende mapper, så vi har det hele samlet på Github. I uploader ved at gå i den mappe som filen skal være i og trykker på 'upload files'. Husk at tilføje en beskrivende commit. #Lav en release version Der ligger en readme til hvordan man laver en release i root af PTE. <file_sep>/PTE/Implemenation/Logic/Areal.java package Logic; public interface Areal extends PTEEntity { public double getAreal(); public void setAreal(double areal); public void nulstil(); } <file_sep>/PTE/Implemenation/Exceptions/DimensionerendeKraftException.java package Exceptions; public class DimensionerendeKraftException extends RuntimeException { } <file_sep>/PTE/Test/Logic/Tau_ForskydningsSpaendingTest.java package Logic; import static org.junit.Assert.*; import org.junit.Before; import org.junit.Test; import org.junit.internal.runners.statements.Fail; import Exceptions.ArealException; import Exceptions.TyngdekraftException; import Exceptions.VaegtException; public class Tau_ForskydningsSpaendingTest { VaegtImpl vaegt; TyngdekraftImpl tyngdekraft; DimensionerendeKraftImpl dimensioneredeKraft; VinkelImpl vinkel; ForskydningskraftImpl forskydningskraft; ArealImpl areal; ForskydningsspaendingImpl forskydningsSpaending; @Before public void setUp() throws Exception { vaegt = new VaegtImpl(); tyngdekraft = new TyngdekraftImpl(); vinkel = new VinkelImpl(); dimensioneredeKraft = new DimensionerendeKraftImpl(vaegt, tyngdekraft); forskydningskraft = new ForskydningskraftImpl(vinkel, dimensioneredeKraft); areal = new ArealImpl(); forskydningsSpaending = new ForskydningsspaendingImpl(areal, forskydningskraft); } @Test public void getTauNulstilTest() { vinkel.setProfil(Profil.VANDRET); forskydningsSpaending.setTau_ForskydningsSpaending(5); forskydningsSpaending.nulstil(); assertEquals(Double.NaN, forskydningsSpaending.getTau_ForskydningsSpaending(), 0.001); } @Test public void GetTauNormalTest() { vinkel.setProfil(Profil.VANDRET); vaegt.setVaegt(10); tyngdekraft.setTyngdekraft(10); vinkel.setVinkel(10); areal.setAreal(10); assertEquals(9.848, forskydningsSpaending.getTau_ForskydningsSpaending(), 0.001); } @Test public void GetTauNegativVaegtTest() { vinkel.setProfil(Profil.VANDRET); vaegt.setVaegt(-10); tyngdekraft.setTyngdekraft(10); vinkel.setVinkel(10); areal.setAreal(40); try { forskydningsSpaending.getTau_ForskydningsSpaending(); fail("Exception blev ikke kastet"); } catch (VaegtException e) { //success } } @Test public void GetTauNegativTyngdekraftTest() { vinkel.setProfil(Profil.VANDRET); vaegt.setVaegt(10); tyngdekraft.setTyngdekraft(-10); vinkel.setVinkel(10); areal.setAreal(40); try { forskydningsSpaending.getTau_ForskydningsSpaending(); fail("Exception blev ikke kastet"); } catch (TyngdekraftException e) { //success } } @Test public void GetTauNegativArealTest() { vinkel.setProfil(Profil.VANDRET); vaegt.setVaegt(10); tyngdekraft.setTyngdekraft(10); vinkel.setVinkel(10); areal.setAreal(-40); try { forskydningsSpaending.getTau_ForskydningsSpaending(); fail("Exception blev ikke kastet"); } catch (ArealException e) { //success } } } <file_sep>/PTE/Test/Logic/BoejningsMomentTest.java package Logic; import static org.junit.Assert.assertEquals; import static org.junit.Assert.fail; import java.util.List; import org.junit.Before; import org.junit.Test; import Exceptions.BoejningsMomentException; public class BoejningsMomentTest { BoejningsMomentImpl boejningsMoment; LaengdeRetning laengdeRetning; @Test public void getBoejningsMomentNormalFdimTest() { laengdeRetning = LaengdeRetning.VINKELRET_TIL_FDIM; double laengde = 50; double dimensionerendeKraft = 2; double forskydningkraft = 3; assertEquals(100, boejningsMoment.getBoejningsMoment(laengdeRetning, laengde, dimensionerendeKraft, forskydningkraft), 0.001); } @Test public void getBoejningsMomentNormalFtTest() { laengdeRetning = LaengdeRetning.VINKELRET_TIL_FT; double laengde = 50; double dimensionerendeKraft = 2; double forskydningkraft = 3; assertEquals(150, boejningsMoment.getBoejningsMoment(laengdeRetning, laengde, dimensionerendeKraft, forskydningkraft), 0.001); } @Test public void getBoejningsMomentKommatalFdimTest() { laengdeRetning = LaengdeRetning.VINKELRET_TIL_FDIM; double laengde = 50.555555; double dimensionerendeKraft = 10; double forskydningkraft = 100; assertEquals(505.556, boejningsMoment.getBoejningsMoment(laengdeRetning, laengde, dimensionerendeKraft, forskydningkraft), 0.001); } @Test public void getBoejningsMomentNegativFdimTest() { try { boejningsMoment.setBoejningsMoment(-5); fail("bøjningsmoment fejl blev ikke grappet"); } catch (BoejningsMomentException e) { // succes } } @Test public void getBoejningsMomentNulFdimTest() { try { boejningsMoment.setBoejningsMoment(0); fail("bøjningsmoment fejl blev ikke grappet"); } catch (BoejningsMomentException e) { // succes } } @Before public void setUp() throws Exception { boejningsMoment = new BoejningsMomentImpl(new Vinkel() { @Override public void tilfoejAfhaengigEntitet(PTEEntity entity) { // TODO Auto-generated method stub } @Override public List<Tilstand> getAfhaengigheder() { // TODO Auto-generated method stub return null; } @Override public void setVinkel(double vinkel) { // TODO Auto-generated method stub } @Override public void setProfil(Profil profil) { // TODO Auto-generated method stub } @Override public void setLaengdeRetning(LaengdeRetning laengdeRetning) { // TODO Auto-generated method stub } @Override public void nulstil() { // TODO Auto-generated method stub } @Override public double getVinkel() { // TODO Auto-generated method stub return 0; } @Override public Profil getProfil() { // TODO Auto-generated method stub return null; } @Override public LaengdeRetning getLaengdeRetning() { // TODO Auto-generated method stub return null; } }, new Laengde() { @Override public void tilfoejAfhaengigEntitet(PTEEntity entity) { // TODO Auto-generated method stub } @Override public List<Tilstand> getAfhaengigheder() { // TODO Auto-generated method stub return null; } @Override public void setLaengde(double Laengde) { // TODO Auto-generated method stub } @Override public void nulstil() { // TODO Auto-generated method stub } @Override public double getLaengde() { // TODO Auto-generated method stub return 0; } @Override public double Laengde() { // TODO Auto-generated method stub return 0; } }, new DimensionerendeKraft() { @Override public void tilfoejAfhaengigEntitet(PTEEntity entity) { // TODO Auto-generated method stub } @Override public List<Tilstand> getAfhaengigheder() { // TODO Auto-generated method stub return null; } @Override public void setDimensionerendeKraft(double dimensionerendeKraft) { // TODO Auto-generated method stub } @Override public void nulstil() { // TODO Auto-generated method stub } @Override public double getDimensionerendeKraft() { // TODO Auto-generated method stub return 0; } @Override public double dimensionerendeKraftTilVaegt() { // TODO Auto-generated method stub return 0; } }, new Forskydningskraft() { @Override public void tilfoejAfhaengigEntitet(PTEEntity entity) { // TODO Auto-generated method stub } @Override public List<Tilstand> getAfhaengigheder() { // TODO Auto-generated method stub return null; } @Override public void setForskydningskraft(double forskydningskraft) { // TODO Auto-generated method stub } @Override public void nulstil() { // TODO Auto-generated method stub } @Override public double getForskydningskraft() { // TODO Auto-generated method stub return 0; } }); } } <file_sep>/PTE/Implemenation/gui/PaneUC10Controller.java package gui; import java.net.URL; import java.util.List; import java.util.ResourceBundle; import Logic.ProfilType; import Logic.Tilstand; import javafx.beans.value.ChangeListener; import javafx.beans.value.ObservableValue; import javafx.fxml.FXML; import javafx.fxml.Initializable; import javafx.scene.control.Label; import javafx.scene.control.RadioButton; import javafx.scene.control.TextField; import javafx.scene.control.ToggleGroup; public class PaneUC10Controller extends PTEPane implements Initializable { private TekstFormattering tekstfeltFormat = new TekstFormatteringImpl(); private boolean diameterAErndret = false; private boolean hoejdeErAEndret = false; private boolean breddeErAEndret = false; private boolean godstykkelseErAEndret = false; private boolean arealErAEndret = false; private boolean profiltypeErAEndret = false; private boolean cirkelErAEndret = false; private boolean hultRoerErAEndret = false; private boolean kvadratRoerErAEndret = false; private boolean kvadratErAEndret = false; @FXML private TextField tekstDiameter; @FXML private TextField tekstFeltHoejde; @FXML private ToggleGroup profiltype; @FXML private TextField tekstFeltBredde; @FXML private TextField tekstFeltAreal; @FXML private TextField tekstFeltGodstykkelse; @FXML private RadioButton btnCirkel; @FXML private RadioButton btnHultRoer; @FXML private RadioButton btnKvadratRoer; @FXML private RadioButton btnKvadrat; @FXML public void haandterUdregnKnap() { pteController.setDiameter(tekstfeltFormat.formaterStringTilDouble(tekstDiameter.getText())); pteController.setHoejde(tekstfeltFormat.formaterStringTilDouble(tekstFeltHoejde.getText())); pteController.setBredde(tekstfeltFormat.formaterStringTilDouble(tekstFeltBredde.getText())); pteController.setDiameter(tekstfeltFormat.formaterStringTilDouble(tekstDiameter.getText())); pteController.setGodstykkelse(tekstfeltFormat.formaterStringTilDouble(tekstFeltGodstykkelse.getText())); if(btnCirkel.isSelected()){ pteController.setProfilType(ProfilType.CIRKEL); } else if(btnHultRoer.isSelected()){ pteController.setProfilType(ProfilType.HULT_ROER); } else if(btnKvadrat.isSelected()){ pteController.setProfilType(ProfilType.KVADRAT); } else if(btnKvadratRoer.isSelected()){ pteController.setProfilType(ProfilType.KVADRET_ROER); } else{ pteController.setProfilType(ProfilType.UDEFINERET);; } tekstFeltAreal.setText(tekstfeltFormat.formaterDoubleTilString(pteController.getAreal())); } @FXML public void haandterResetKnap() { pteController.nulstil(); } @Override public void update(List<Tilstand> tilstande) { } private void formaterTekstfelt(TextField input) { tekstfeltFormat.formaterTekstfeltInput(input); } @Override public void initialize(URL arg0, ResourceBundle arg1) { formaterTekstfelt(tekstDiameter); formaterTekstfelt(tekstFeltHoejde); formaterTekstfelt(tekstFeltBredde); formaterTekstfelt(tekstFeltAreal); formaterTekstfelt(tekstFeltGodstykkelse); tekstDiameter.focusedProperty().addListener(new ChangeListener<Boolean>() { @Override public void changed(ObservableValue<? extends Boolean> observable, Boolean oldValue, Boolean newValue) { diameterAErndret = true; } }); tekstFeltHoejde.focusedProperty().addListener(new ChangeListener<Boolean>() { @Override public void changed(ObservableValue<? extends Boolean> observable, Boolean oldValue, Boolean newValue) { hoejdeErAEndret = true; } }); tekstFeltBredde.focusedProperty().addListener(new ChangeListener<Boolean>() { @Override public void changed(ObservableValue<? extends Boolean> observable, Boolean oldValue, Boolean newValue) { breddeErAEndret = true; } }); tekstFeltAreal.focusedProperty().addListener(new ChangeListener<Boolean>() { @Override public void changed(ObservableValue<? extends Boolean> observable, Boolean oldValue, Boolean newValue) { arealErAEndret = true; } }); tekstFeltGodstykkelse.focusedProperty().addListener(new ChangeListener<Boolean>() { @Override public void changed(ObservableValue<? extends Boolean> observable, Boolean oldValue, Boolean newValue) { godstykkelseErAEndret = true; } }); btnCirkel.focusedProperty().addListener(new ChangeListener<Boolean>() { @Override public void changed(ObservableValue<? extends Boolean> observable, Boolean oldValue, Boolean newValue) { cirkelErAEndret = true; } }); btnHultRoer.focusedProperty().addListener(new ChangeListener<Boolean>() { @Override public void changed(ObservableValue<? extends Boolean> observable, Boolean oldValue, Boolean newValue) { hultRoerErAEndret = true; } }); btnKvadrat.focusedProperty().addListener(new ChangeListener<Boolean>() { @Override public void changed(ObservableValue<? extends Boolean> observable, Boolean oldValue, Boolean newValue) { kvadratErAEndret = true; } }); btnKvadratRoer.focusedProperty().addListener(new ChangeListener<Boolean>() { @Override public void changed(ObservableValue<? extends Boolean> observable, Boolean oldValue, Boolean newValue) { kvadratRoerErAEndret = true; } }); } } <file_sep>/PTE/Implemenation/Logic/ProfilType.java package Logic; public enum ProfilType { HULT_ROER, CIRKEL, KVADRAT, KVADRET_ROER, UDEFINERET; } <file_sep>/PTE/Implemenation/gui/MainWindowController.java package gui; import java.net.URL; import java.util.ResourceBundle; import javafx.fxml.FXML; import javafx.fxml.Initializable; import javafx.scene.control.Label; import javafx.scene.layout.BorderPane; public class MainWindowController implements Initializable{ @FXML private Label label; @Override public void initialize(URL arg0, ResourceBundle arg1) { } } <file_sep>/PTE/Implemenation/utils/SimplePdfWriter.java package utils; import com.itextpdf.text.Font; import com.itextpdf.text.Font.FontFamily; import com.itextpdf.text.Font.FontStyle; import com.itextpdf.text.Image; /** * @author <NAME> <<EMAIL>> */ public interface SimplePdfWriter { /** * Adds a paragraph as title to PDF document. Must be called first, to set the first paragraph as title * @param title - The "title" of the PDF document. */ public void setPageTitle(String title); /** * Adds a paragraph as title to PDF document. Must be called first, to set the first paragraph as title * @param title - The "title" of the PDF document. * @param fontSize - Font size of the "title". */ public void setPageTitle(String title, int fontSize); /** * Adds a paragraph as title to PDF document. Must be called first, to set the first paragraph as title * @param title - The "title" of the PDF document. * @param fontStyle - Font style of the "title". */ public void setPageTitle(String title, FontStyle fontStyle); /** * Adds a paragraph as title to PDF document. Must be called first, to set the first paragraph as title * @param title - The "title" of the PDF document. * @param font - Font of the "title". */ public void setPageTitle(String title, Font font); /** * Adds a paragraph as title to PDF document. * @param text - Paragraph content. */ public void addParagraph(String text); /** * Adds a paragraph as title to PDF document. * @param text - Paragraph content. * @param fontSize - Paragraph font size. */ public void addParagraph(String text, int fontSize); /** * Adds a paragraph as title to PDF document. * @param text - Paragraph content. * @param fontFamily - Paragraph font family. */ public void addParagraph(String text, FontFamily fontFamily); /** * Adds a paragraph as title to PDF document. * @param text - Paragraph content. * @param fontStyle - Paragraph font style. */ public void addParagraph(String text, FontStyle fontStyle); /** * Adds a paragraph as title to PDF document. * @param text - Paragraph content. * @param font - Paragraph font. */ public void addParagraph(String text, Font font); /** * Sets document's font family * @param fontFamily */ public void setFontFamily(FontFamily fontFamily); /** * Sets document's font size * @param fontSize */ public void setFontSize(int fontSize); /** * Creates new page in PDF document. */ public void createNewPage(); /** * Closes the document. After the document is closed it is no longer possible to add content to document's body. */ public void close(); public void addImage(String imagePath, float height, float width); public void addImageWithText(String imagePath, String text); } <file_sep>/PTE/Implemenation/Logic/InertimomentImpl.java package Logic; public class InertimomentImpl extends PTEEntityImpl implements Inertimoment { private double inertimoment = Double.NaN; @Override public double getInertimoment() { return inertimoment; } @Override public void setInertimoment(double inertimoment) { this.inertimoment = inertimoment; } @Override public void nulstil() { setInertimoment(Double.NaN); } @Override protected Tilstand getEgenAfhaengighed() { return Tilstand.INERTIMOMENT; } } <file_sep>/PTE/Implemenation/Logic/NormalkraftImpl.java package Logic; class NormalkraftImpl extends PTEEntityImpl implements Normalkraft { private double normalkraft = Double.NaN; private DimensionerendeKraft dimensionerendeKraft; private Vinkel vinkel; public NormalkraftImpl(DimensionerendeKraft dimensionerendeKraft, Vinkel vinkel) { if (dimensionerendeKraft == null || vinkel == null) { throw new IllegalArgumentException(); } this.dimensionerendeKraft = dimensionerendeKraft; this.vinkel = vinkel; this.dimensionerendeKraft.tilfoejAfhaengigEntitet(this); this.vinkel.tilfoejAfhaengigEntitet(this); } @Override public double getNormalkraft() { return getNormalkraft(vinkel.getVinkel(), dimensionerendeKraft.getDimensionerendeKraft()); } double getNormalkraft(double vinkel, double dimensionerendeKraft) { if (!Double.isNaN(normalkraft)) { return normalkraft; } if (dimensionerendeKraft == Double.NaN || vinkel == Double.NaN) { return Double.NaN; } if (this.vinkel.getProfil() == Profil.VANDRET) { return (Math.sin(Math.toRadians(vinkel)) * this.dimensionerendeKraft.getDimensionerendeKraft()); } else { // this.vinkel.getProfil() == Profil.LODRET return (Math.cos((Math.toRadians(vinkel))) * this.dimensionerendeKraft.getDimensionerendeKraft()); } } @Override public void setNormalkraft(double normalkraft) { this.normalkraft = normalkraft; nulstilBoern(); } @Override public void nulstil() { normalkraft = Double.NaN; nulstilBoern(); } private void nulstilBoern() { dimensionerendeKraft.nulstil(); vinkel.nulstil(); } @Override protected Tilstand getEgenAfhaengighed() { return Tilstand.NORMALKRAFT; } } <file_sep>/PTE/Test/Logic/DimensionerendeKraftTest.java package Logic; import static org.junit.Assert.assertEquals; import static org.junit.Assert.fail; import java.util.List; import org.junit.Before; import org.junit.Test; import Exceptions.DimensionerendeKraftException; public class DimensionerendeKraftTest { DimensionerendeKraftImpl dimensionerendeKraft; @Test public void GetDimensionerendeKraftNegativVaegtTest() { double vaegt = -10; double tyngdekraft = 10; try { dimensionerendeKraft.getDimensionerendeKraft(vaegt, tyngdekraft); fail("Exception bliver ikke kastet."); } catch (DimensionerendeKraftException e) { // success } } @Test public void GetDimensionerendeKraftNegativTyngdekraftTest() { double vaegt = 10; double tyngdekraft = -10; try { dimensionerendeKraft.getDimensionerendeKraft(vaegt, tyngdekraft); fail("Exception bliver ikke kastet."); } catch (DimensionerendeKraftException e) { // success } } @Test public void GetDimensionerendeKraftNulVaegtTest() { double vaegt = 0; double tyngdekraft = 10; try { dimensionerendeKraft.getDimensionerendeKraft(vaegt, tyngdekraft); fail("Exception bliver ikke kastet."); } catch (DimensionerendeKraftException e) { // success } } @Test public void getDimernsionerendeKraftNulstilTest() { dimensionerendeKraft.setDimensionerendeKraft(5); dimensionerendeKraft.nulstil(); assertEquals(Double.NaN, dimensionerendeKraft.getDimensionerendeKraft(), 0.001); } @Test public void GetDimensionerendeKraftNulTyngdekraftTest() { double vaegt = 10; double tyngdekraft = 0; try { dimensionerendeKraft.getDimensionerendeKraft(vaegt, tyngdekraft); fail("Exception bliver ikke kastet."); } catch (DimensionerendeKraftException e) { // success } } @Test public void GetDimensionerendeKraftEnsVaegtOgTyngdeKraftTest() { double vaegt = 10; double tyngdekraft = 10; assertEquals(100, dimensionerendeKraft.getDimensionerendeKraft(vaegt, tyngdekraft), 0.001); } @Test public void GetDimensionerendeKraftAfrundTest() { double vaegt = 10.55555; double tyngdekraft = 10; assertEquals(105.556, dimensionerendeKraft.getDimensionerendeKraft(vaegt, tyngdekraft), 0.001); } @Test public void GetDimensionerendeKraftTyngdekraftNaNTest() { double vaegt = 10; double tyngdekraft = Double.NaN; assertEquals(Double.NaN, dimensionerendeKraft.getDimensionerendeKraft(vaegt, tyngdekraft), 0.001); } @Test public void GetDimensionerendeKraftVaegtNaNTest() { double vaegt = Double.NaN; double tyngdekraft = 10; assertEquals(Double.NaN, dimensionerendeKraft.getDimensionerendeKraft(vaegt, tyngdekraft), 0.001); } @Test public void GetDimensionerendeKraftNegativTest() { try { dimensionerendeKraft.setDimensionerendeKraft(-5); fail("Exception bliver ikke kastet."); } catch (DimensionerendeKraftException e) { // success } } @Test public void GetDimensionerendeKraftNulTest() { try { dimensionerendeKraft.setDimensionerendeKraft(0); fail("Exception bliver ikke kastet."); } catch (DimensionerendeKraftException e) { // success } } @Before public void setUp() throws Exception { dimensionerendeKraft = new DimensionerendeKraftImpl(new Vaegt() { @Override public void tilfoejAfhaengigEntitet(PTEEntity entity) { // TODO Auto-generated method stub } @Override public List<Tilstand> getAfhaengigheder() { // TODO Auto-generated method stub return null; } @Override public void setVaegt(double vaegt) { // TODO Auto-generated method stub } @Override public void nulstil() { // TODO Auto-generated method stub } @Override public double getVaegt() { // TODO Auto-generated method stub return 0; } }, new Tyngdekraft() { @Override public void tilfoejAfhaengigEntitet(PTEEntity entity) { // TODO Auto-generated method stub } @Override public List<Tilstand> getAfhaengigheder() { // TODO Auto-generated method stub return null; } @Override public void setTyngdekraft(double tyngdekraft) { // TODO Auto-generated method stub } @Override public void nulstil() { // TODO Auto-generated method stub } @Override public double getTyngdekraft() { // TODO Auto-generated method stub return 0; } }); } } <file_sep>/PTE/Implemenation/Logic/Form.java package Logic; public interface Form extends PTEEntity { public void setProfilType(ProfilType profilType); public ProfilType getProfilType(); public void nulstil(); } <file_sep>/PTE/Implemenation/Logic/PTEControllerImpl.java package Logic; import java.util.ArrayList; import java.util.List; /** * @author <NAME> - <<EMAIL>> * */ public class PTEControllerImpl implements PTEController { private Vinkel vinkel; private Vaegt vaegt; private DimensionerendeKraft dimensionerendeKraft; private Normalkraft normalkraft; private Tyngdekraft tyngdekraft; private Forskydningskraft forskydningskraft; private Areal areal; private Forskydningsspaending forskydningsspaending; private Laengde laengde; private List<Observer> observers; private BoejningsMoment boejningsmoment; private Normalspaending normalspaending; private Forskydningspunkt forskydningspunkt; private Inertimoment inertimoment; private Boejningsspaending boejningsspaending; private Referencespaending referencespaending; private Bredde bredde; private Diameter diameter; private Hoejde hoejde; private Godstykkelse godstykkelse; private Form form; private IndtastAreal indtastAreal; private Flydespaending flydeSpaending; private Sikkerhedsfaktor sikkerhedsfaktor; public PTEControllerImpl(LogicFactory logicFactory) { vinkel = logicFactory.createVinkel(); vinkel.setProfil(Profil.UDEFINERET); vinkel.setLaengdeRetning(LaengdeRetning.VINKELRET_TIL_FT); form = logicFactory.createForm(); form.setProfilType(ProfilType.CIRKEL); flydeSpaending = logicFactory.createFlydespaendning(); vaegt = logicFactory.createVaegt(); tyngdekraft = logicFactory.craeteTyngdeKraft(); dimensionerendeKraft = logicFactory.craeteDimensionerendeKraft(vaegt, tyngdekraft); normalkraft = logicFactory.createNormalKraft(dimensionerendeKraft, vinkel); forskydningskraft = logicFactory.createForskydningskraft(vinkel, dimensionerendeKraft); bredde = logicFactory.createBredde(); diameter = logicFactory.createDiameter(); godstykkelse = logicFactory.createGodstykkelse(); hoejde = logicFactory.createHoejde(); areal = logicFactory.createAreal(bredde, diameter, godstykkelse, hoejde, form); indtastAreal = logicFactory.createIndtastAreal(); forskydningsspaending = logicFactory.createTau_ForskydningsSpaending(indtastAreal, forskydningskraft); laengde = logicFactory.createLaengde(); boejningsmoment = logicFactory.createBoejningsMoment(vinkel, laengde, dimensionerendeKraft, forskydningskraft); normalspaending = logicFactory.createSigmaN(indtastAreal, normalkraft); forskydningspunkt = logicFactory.createForskydningspunkt(); inertimoment = logicFactory.createInertimoment(); boejningsspaending = logicFactory.createSigmaB(boejningsmoment, forskydningspunkt, inertimoment); referencespaending = logicFactory.createSigmaRef(boejningsspaending, normalspaending, forskydningsspaending); sikkerhedsfaktor = logicFactory.createSikkerhedsfaktor(flydeSpaending, referencespaending); observers = new ArrayList<Logic.Observer>(); } @Override public void vaelgProfil(Profil profil) { this.vinkel.setProfil(profil); notifyObservers(vinkel.getAfhaengigheder()); } @Override public void tilmeldObserver(Observer observer) { this.observers.add(observer); } @Override public void notifyObservers(List<Tilstand> tilstande) { for (Logic.Observer o : observers) { o.update(tilstande); } } @Override public void nulstil() { List<Tilstand> tilstande = new ArrayList<Tilstand>(); this.vaegt.nulstil(); tilstande.addAll(vaegt.getAfhaengigheder()); this.vinkel.nulstil(); tilstande.addAll(vinkel.getAfhaengigheder()); this.tyngdekraft.nulstil(); tilstande.addAll(tyngdekraft.getAfhaengigheder()); this.dimensionerendeKraft.nulstil(); tilstande.addAll(dimensionerendeKraft.getAfhaengigheder()); this.normalkraft.nulstil(); tilstande.addAll(normalkraft.getAfhaengigheder()); this.forskydningskraft.nulstil(); tilstande.addAll(forskydningskraft.getAfhaengigheder()); this.indtastAreal.nulstil(); tilstande.addAll(indtastAreal.getAfhaengigheder()); this.forskydningsspaending.nulstil(); tilstande.addAll(forskydningsspaending.getAfhaengigheder()); this.normalspaending.nulstil(); tilstande.addAll(normalspaending.getAfhaengigheder()); this.forskydningspunkt.nulstil(); tilstande.addAll(forskydningspunkt.getAfhaengigheder()); this.inertimoment.nulstil(); tilstande.addAll(inertimoment.getAfhaengigheder()); this.boejningsspaending.nulstil(); tilstande.addAll(boejningsspaending.getAfhaengigheder()); this.laengde.nulstil(); tilstande.addAll(laengde.getAfhaengigheder()); this.bredde.nulstil(); tilstande.addAll(bredde.getAfhaengigheder()); this.hoejde.nulstil(); tilstande.addAll(hoejde.getAfhaengigheder()); this.diameter.nulstil(); tilstande.addAll(diameter.getAfhaengigheder()); this.godstykkelse.nulstil(); tilstande.addAll(godstykkelse.getAfhaengigheder()); this.normalspaending.nulstil(); tilstande.addAll(normalspaending.getAfhaengigheder()); this.forskydningspunkt.nulstil(); tilstande.addAll(forskydningspunkt.getAfhaengigheder()); this.inertimoment.nulstil(); tilstande.addAll(inertimoment.getAfhaengigheder()); this.referencespaending.nulstil(); tilstande.addAll(referencespaending.getAfhaengigheder()); this.flydeSpaending.nulstil(); tilstande.addAll(flydeSpaending.getAfhaengigheder()); this.sikkerhedsfaktor.nulstil(); tilstande.addAll(sikkerhedsfaktor.getAfhaengigheder()); notifyObservers(tilstande); } @Override public double getForskydningkraft() { return this.forskydningskraft.getForskydningskraft(); } @Override public void setForskydningskraft(double forskydningskraft) { this.forskydningskraft.setForskydningskraft(forskydningskraft); notifyObservers(this.forskydningskraft.getAfhaengigheder()); } @Override public double getTyngdekraft() { return this.tyngdekraft.getTyngdekraft(); } @Override public void setTyngdekraft(double tyngdekraft) { this.setTyngdekraft(tyngdekraft); notifyObservers(this.tyngdekraft.getAfhaengigheder()); } @Override public void setVinkel(double vinkel) { this.vinkel.setVinkel(vinkel); notifyObservers(this.vinkel.getAfhaengigheder()); } @Override public double getVinkel() { return this.vinkel.getVinkel(); } @Override public void setProfil(Profil profil) { this.vinkel.setProfil(profil); notifyObservers(vinkel.getAfhaengigheder()); } @Override public Profil getProfil() { return this.vinkel.getProfil(); } @Override public double getVaegt() { return this.vaegt.getVaegt(); } @Override public void setVaegt(double vaegt) { this.vaegt.setVaegt(vaegt); notifyObservers(this.vaegt.getAfhaengigheder()); } @Override public double getNormalkraft() { return this.normalkraft.getNormalkraft(); } @Override public void setNormalkraft(double normalkraft) { this.normalkraft.setNormalkraft(normalkraft); notifyObservers(this.normalkraft.getAfhaengigheder()); } @Override public double getDimensionerendeKraft() { return this.dimensionerendeKraft.getDimensionerendeKraft(); } @Override public void setDimensioneredndeKraft(double dimensionerendeKraft) { this.dimensionerendeKraft.setDimensionerendeKraft(dimensionerendeKraft); vaegt.setVaegt(this.dimensionerendeKraft.dimensionerendeKraftTilVaegt()); notifyObservers(this.vaegt.getAfhaengigheder()); } @Override public double getTau_ForskydningsSpaending() { return this.forskydningsspaending.getTau_ForskydningsSpaending(); } @Override public void setTau_ForskydningsSpaending(double tau_ForskydningsSpaending) { this.forskydningsspaending.setTau_ForskydningsSpaending(tau_ForskydningsSpaending); notifyObservers(this.forskydningsspaending.getAfhaengigheder()); } @Override public LaengdeRetning getLaengdeRetning() { return this.vinkel.getLaengdeRetning(); } @Override public void setLaengdeRetning(LaengdeRetning laengdeRetning) { this.vinkel.setLaengdeRetning(laengdeRetning); notifyObservers(this.vinkel.getAfhaengigheder()); } @Override public double getLaengde() { return this.laengde.getLaengde(); } @Override public void setLaengde(double laengde) { this.laengde.setLaengde(laengde); notifyObservers(this.laengde.getAfhaengigheder()); } @Override public double getBoejningsMoment() { double boejningsMoment = Double.NaN; boejningsMoment = this.boejningsmoment.getBoejningsMoment(); return boejningsMoment; } @Override public void setBoejningsMoment(double boejningsMoment) { this.boejningsmoment.setBoejningsMoment(boejningsMoment); notifyObservers(this.boejningsmoment.getAfhaengigheder()); } @Override public double getSigmaN() { double sigmaN = Double.NaN; sigmaN = this.normalspaending.getSigmaN(); return sigmaN; } @Override public void setSigmaN(double sigmaN) { this.normalspaending.setSigmaN(sigmaN); notifyObservers(this.normalspaending.getAfhaengigheder()); } @Override public double getForskydningspunkt() { double forskydningspunkt = Double.NaN; forskydningspunkt = this.forskydningspunkt.getForskydningspunkt(); return forskydningspunkt; } @Override public void setForskydningspunkt(double forskydningspunkt) { this.forskydningspunkt.setForskydningspunkt(forskydningspunkt); notifyObservers(this.forskydningspunkt.getAfhaengigheder()); } @Override public double getInertimoment() { double inertimoment = Double.NaN; inertimoment = this.inertimoment.getInertimoment(); return inertimoment; } @Override public void setInertimoment(double inertimoment) { this.inertimoment.setInertimoment(inertimoment); notifyObservers(this.inertimoment.getAfhaengigheder()); } @Override public double getSigmaB() { double sigmaB = Double.NaN; sigmaB = this.boejningsspaending.getSigmaB(); return sigmaB; } @Override public void setSigmaB(double sigmaB) { this.boejningsspaending.setSigmaB(sigmaB); notifyObservers(this.boejningsspaending.getAfhaengigheder()); } @Override public double getSigmaRef() { double sigmaRef = Double.NaN; sigmaRef = this.referencespaending.getSigmaRef(); return sigmaRef; } @Override public void setSigmaRef(double sigmaRef) { this.referencespaending.setSigmaRef(sigmaRef); notifyObservers(this.referencespaending.getAfhaengigheder()); } @Override public double getBredde() { double bredde = Double.NaN; bredde = this.bredde.getBredde(); return bredde; } @Override public void setBredde(double bredde) { this.bredde.setBredde(bredde); notifyObservers(this.bredde.getAfhaengigheder()); } @Override public double getDiameter() { double diameter = Double.NaN; diameter = this.diameter.getDiameter(); return diameter; } @Override public void setDiameter(double diameter) { this.diameter.setDiameter(diameter); notifyObservers(this.diameter.getAfhaengigheder()); } @Override public double getHoejde() { double hoejde = Double.NaN; hoejde = this.diameter.getDiameter(); return hoejde; } @Override public void setHoejde(double hoejde) { this.hoejde.setHoejde(hoejde); notifyObservers(this.hoejde.getAfhaengigheder()); } @Override public double getGodstykkelse() { double godstykkelse = Double.NaN; godstykkelse = this.godstykkelse.getGodstykkelse(); return godstykkelse; } @Override public void setGodstykkelse(double godstykkelse) { this.godstykkelse.setGodstykkelse(godstykkelse); notifyObservers(this.godstykkelse.getAfhaengigheder()); } @Override public ProfilType getProfilType() { return this.form.getProfilType(); } @Override public void setProfilType(ProfilType profilType) { this.form.setProfilType(profilType); notifyObservers(form.getAfhaengigheder()); } @Override public double getAreal() { return this.areal.getAreal(); } @Override public void setAreal(double areal) { this.areal.setAreal(areal); notifyObservers(this.areal.getAfhaengigheder()); } @Override public double getIndtastAreal() { return this.indtastAreal.getIndtastAreal(); } @Override public void setIndtastAreal(double indtastAreal) { this.indtastAreal.setIndtastAreal(indtastAreal); notifyObservers(this.indtastAreal.getAfhaengigheder()); } @Override public double getFlydespaending() { return this.flydeSpaending.getFlydespaending(); } @Override public void setFlydespaending(double flydespaending) { this.flydeSpaending.setFlydespaending(flydespaending); notifyObservers(this.flydeSpaending.getAfhaengigheder()); } @Override public void setSikkerhedsfaktor(double sikkerhedsfaktor) { this.sikkerhedsfaktor.setSikkerhedsfaktor(sikkerhedsfaktor); notifyObservers(this.sikkerhedsfaktor.getAfhaengigheder()); } @Override public double getSikkerhedsfaktor() { return sikkerhedsfaktor.getSikkerhedsfaktor(); } @Override public boolean erSikkerhedsfaktorForLavt() { return sikkerhedsfaktor.erSikkerhedsfaktorForLavt(); } } <file_sep>/PTE/Implemenation/Logic/PTEEntity.java package Logic; import java.util.List; interface PTEEntity { List<Tilstand> getAfhaengigheder(); void tilfoejAfhaengigEntitet(PTEEntity entity); } <file_sep>/PTE/Implemenation/Logic/ForskydningsspaendingImpl.java package Logic; public class ForskydningsspaendingImpl extends PTEEntityImpl implements Forskydningsspaending { private double tau_ForskydningsSpaending = Double.NaN; private Forskydningskraft forskydningskraft; private IndtastAreal areal; public ForskydningsspaendingImpl(IndtastAreal areal, Forskydningskraft forskydningskraft) { if (areal == null || forskydningskraft == null) { throw new IllegalArgumentException(); } this.areal = areal; this.forskydningskraft = forskydningskraft; this.areal.tilfoejAfhaengigEntitet(this); this.forskydningskraft.tilfoejAfhaengigEntitet(this); } @Override public void setTau_ForskydningsSpaending(double tau_ForskydningsSpaending) { this.tau_ForskydningsSpaending = tau_ForskydningsSpaending; nulstilBoern(); } private void nulstilBoern() { forskydningskraft.nulstil(); areal.nulstil(); } @Override public double getTau_ForskydningsSpaending() { if (!Double.isNaN(tau_ForskydningsSpaending)) { return tau_ForskydningsSpaending; } return getTau_ForskydningsSpaending(forskydningskraft.getForskydningskraft(), areal.getIndtastAreal()); } double getTau_ForskydningsSpaending(double forskydningskraft, double areal) { try { return forskydningskraft / areal; } catch (Exception e) { return Double.NaN; } } @Override public void nulstil() { setTau_ForskydningsSpaending(Double.NaN); nulstilBoern(); } @Override protected Tilstand getEgenAfhaengighed() { return Tilstand.TAU_FORSKYDNINGSSPAENDING; } } <file_sep>/PTE/Implemenation/Logic/Inertimoment.java package Logic; public interface Inertimoment extends PTEEntity { public double getInertimoment(); public void setInertimoment(double inertimoment); public void nulstil(); }<file_sep>/PTE/Implemenation/Logic/SikkerhedsfaktorImpl.java package Logic; class SikkerhedsfaktorImpl extends PTEEntityImpl implements Sikkerhedsfaktor { private double sikkerhedsfaktor = Double.NaN; private Flydespaending flydespaending; private Referencespaending sigmaRef; public SikkerhedsfaktorImpl(Flydespaending flydespaending, Referencespaending sigmaRef) { this.flydespaending = flydespaending; this.sigmaRef = sigmaRef; this.flydespaending.tilfoejAfhaengigEntitet(this); this.sigmaRef.tilfoejAfhaengigEntitet(this); } @Override public void setSikkerhedsfaktor(double sikkerhedsfaktor) { this.sikkerhedsfaktor = sikkerhedsfaktor; nulstilBoern(); } @Override public double getSikkerhedsfaktor() { return getSikkerhedsfaktor(flydespaending.getFlydespaending(), sigmaRef.getSigmaRef()); } double getSikkerhedsfaktor(double flydespaending, double referencespaending) { return flydespaending / referencespaending; } @Override protected Tilstand getEgenAfhaengighed() { return Tilstand.SIKKERHEDSFAKTOR; } @Override public boolean erSikkerhedsfaktorForLavt() { return getSikkerhedsfaktor() <= 1; } @Override public void nulstil() { sikkerhedsfaktor = Double.NaN; nulstilBoern(); } public void nulstilBoern() { flydespaending.nulstil(); sigmaRef.nulstil(); } } <file_sep>/PTE/Test/Logic/VaegtTest.java package Logic; import static org.junit.Assert.*; import org.junit.Before; import org.junit.Test; import Exceptions.VaegtException; public class VaegtTest { VaegtImpl vaegt; @Before public void setUp() throws Exception { vaegt = new VaegtImpl(); } @Test public void setVaegtNulstil() { vaegt.setVaegt(5); vaegt.nulstil(); assertEquals(Double.NaN, vaegt.getVaegt(), 0.001); } @Test public void setVaegtNegativ() { try { vaegt.setVaegt(-5); fail("Exception bliver ikke kastet."); } catch (VaegtException e) { // success } } @Test public void setVaegtNul() { try { vaegt.setVaegt(0); fail("Exception bliver ikke kastet."); } catch (VaegtException e) { // success } } @Test public void setVaegtAfrunding() { vaegt.setVaegt(3.03456); assertEquals(3.035, vaegt.getVaegt(), 0.001); } @Test public void setVaegtDecimaltal() { vaegt.setVaegt(0.001); assertEquals(0.001, vaegt.getVaegt(), 0.001); } } <file_sep>/PTE/Test/Logic/DiameterTest.java package Logic; import static org.junit.Assert.assertEquals; import org.junit.Before; import org.junit.Test; import Exceptions.DiameterException; public class DiameterTest { DiameterImpl diameter; @Before public void setUp() throws Exception { diameter = new DiameterImpl(); } @Test public void diameterNulstilTest() { diameter.setDiameter(5); diameter.nulstil(); assertEquals(Double.NaN, diameter.getDiameter(), 0.001); } @Test public void diameterNulTest() { diameter.setDiameter(0); assertEquals(0, diameter.getDiameter(), 0.001); } @Test public void diameterNormalTest() { diameter.setDiameter(4); assertEquals(4, diameter.getDiameter(), 0.001); } @Test public void diameterNegativTest() { try { diameter.setDiameter(-4); } catch (DiameterException e) { // Success } } @Test public void diameterKommaTest() { diameter.setDiameter(5.5555); assertEquals(5.556, diameter.getDiameter(), 0.001); } } <file_sep>/PTE/Implemenation/Logic/Boejningsspaending.java package Logic; public interface Boejningsspaending extends PTEEntity { public void setSigmaB(double sigmaB); public double getSigmaB(); public void nulstil(); } <file_sep>/PTE/Implemenation/Logic/Tyngdekraft.java package Logic; interface Tyngdekraft extends PTEEntity { public double getTyngdekraft(); public void setTyngdekraft(double tyngdekraft); public void nulstil(); } <file_sep>/PTE/Test/Logic/ForskydningskraftTest.java package Logic; import static org.junit.Assert.assertEquals; import static org.junit.Assert.fail; import java.util.List; import org.junit.Before; import org.junit.Test; import Exceptions.DimensionerendeKraftException; import Exceptions.ForskydningskraftException; import Exceptions.NormalkraftException; import Exceptions.TyngdekraftException; import Exceptions.UdefineretProfilException; import Exceptions.VaegtException; import Exceptions.VinkelException; public class ForskydningskraftTest { ForskydningskraftImpl forskydningskraft; Profil profil; @Test public void getForskydningskraftNulstilTest() throws UdefineretProfilException { profil = Profil.VANDRET; double vinkel = 10; double dimensionerendeKraft = 10; assertEquals(9.848, forskydningskraft.getForskydningskraft(profil, vinkel, dimensionerendeKraft), 0.001); } @Test public void getForskydningskraftNulVinkelTest() throws UdefineretProfilException { profil = Profil.VANDRET; double vinkel = 0; double dimensionerendeKraft = 10; assertEquals(10, forskydningskraft.getForskydningskraft(profil, vinkel, dimensionerendeKraft), 0.001); } @Test public void getForskydningskraftNulTest() throws UdefineretProfilException { try { forskydningskraft.setForskydningskraft(0); fail("Exception bliver ikke kastet."); } catch (ForskydningskraftException e) { // success } } @Test public void getForskydningskraftNormalTest() throws UdefineretProfilException { assertEquals(9.962, forskydningskraft.getForskydningskraft(), 0.001); } @Test public void getForskydningskraftAfrundTest() throws UdefineretProfilException { assertEquals(0.529, forskydningskraft.getForskydningskraft(), 0.001); } @Test public void getForskydningskraftVinkelDoubleNanTest() throws UdefineretProfilException { assertEquals(Double.NaN, forskydningskraft.getForskydningskraft(), 0.001); } @Before public void setUp() { forskydningskraft = new ForskydningskraftImpl(new Vinkel() { @Override public void tilfoejAfhaengigEntitet(PTEEntity entity) { // TODO Auto-generated method stub } @Override public List<Tilstand> getAfhaengigheder() { // TODO Auto-generated method stub return null; } @Override public void setVinkel(double vinkel) { // TODO Auto-generated method stub } @Override public void setProfil(Profil profil) { // TODO Auto-generated method stub } @Override public void setLaengdeRetning(LaengdeRetning laengdeRetning) { // TODO Auto-generated method stub } @Override public void nulstil() { // TODO Auto-generated method stub } @Override public double getVinkel() { // TODO Auto-generated method stub return 0; } @Override public Profil getProfil() { // TODO Auto-generated method stub return null; } @Override public LaengdeRetning getLaengdeRetning() { // TODO Auto-generated method stub return null; } }, new DimensionerendeKraft() { @Override public void tilfoejAfhaengigEntitet(PTEEntity entity) { // TODO Auto-generated method stub } @Override public List<Tilstand> getAfhaengigheder() { // TODO Auto-generated method stub return null; } @Override public void setDimensionerendeKraft(double dimensionerendeKraft) { // TODO Auto-generated method stub } @Override public void nulstil() { // TODO Auto-generated method stub } @Override public double getDimensionerendeKraft() { // TODO Auto-generated method stub return 0; } @Override public double dimensionerendeKraftTilVaegt() { // TODO Auto-generated method stub return 0; } }) { @Override public void tilfoejAfhaengigEntitet(PTEEntity entity) { // TODO Auto-generated method stub } @Override public List<Tilstand> getAfhaengigheder() { // TODO Auto-generated method stub return null; } @Override public void setForskydningskraft(double forskydningskraft) { // TODO Auto-generated method stub } @Override public void nulstil() { // TODO Auto-generated method stub } @Override public double getForskydningskraft() { // TODO Auto-generated method stub return 0; } }; } } <file_sep>/PTE/Implemenation/utils/FileUtils.java package utils; import java.io.File; public interface FileUtils { public File createFile(String filePath); } <file_sep>/PTE/Implemenation/Exceptions/LaengdeException.java package Exceptions; public class LaengdeException extends RuntimeException { } <file_sep>/PTE/Implemenation/gui/PaneUC7Controller.java package gui; import java.net.URL; import java.util.List; import java.util.ResourceBundle; import Exceptions.SigmaBException; import Logic.Tilstand; import javafx.beans.value.ChangeListener; import javafx.beans.value.ObservableValue; import javafx.fxml.FXML; import javafx.fxml.Initializable; import javafx.scene.control.TextField; public class PaneUC7Controller extends PTEPane implements Initializable { private TekstFormattering tekstfeltFormat = new TekstFormatteringImpl(); private boolean forskydningspunktErAEndret = false; private boolean intertimomentErAEndret= false; private boolean sigmaBErAEndret = false; private static final String ERROR = "-fx-background-color: red;"; private static final String CSS = "@util/gui.css"; @FXML private TextField tekstFeltForskydningspunkt; @FXML private TextField tekstFeltIntertimoment; @FXML private TextField tekstFeltSigmaB; @FXML public void haandterUdregnKnap() { tekstFeltSigmaB.setStyle(CSS); if(forskydningspunktErAEndret) { forskydningspunktErAEndret = false; pteController.setForskydningspunkt(tekstfeltFormat.formaterStringTilDouble(tekstFeltForskydningspunkt.getText())); } if (intertimomentErAEndret) { intertimomentErAEndret = false; pteController.setInertimoment(tekstfeltFormat.formaterStringTilDouble(tekstFeltIntertimoment.getText())); } if (sigmaBErAEndret) { try{ sigmaBErAEndret = false; pteController.setSigmaB(tekstfeltFormat.formaterStringTilDouble(tekstFeltSigmaB.getText())); } catch(SigmaBException e){ tekstFeltSigmaB.setStyle(ERROR); } } } @FXML public void haandterResetKnap() { tekstFeltSigmaB.setStyle(CSS); pteController.nulstil(); } @Override public void update(List<Tilstand> tilstande) { if (tilstande.contains(Tilstand.FORSKYDNINGSPUNKT)) { tekstFeltForskydningspunkt.setText(tekstfeltFormat.formaterDoubleTilString(pteController.getForskydningspunkt())); } if (tilstande.contains(Tilstand.INERTIMOMENT)) { tekstFeltIntertimoment.setText(tekstfeltFormat.formaterDoubleTilString(pteController.getInertimoment())); } if (tilstande.contains(Tilstand.SIGMAB)) { tekstFeltSigmaB.setText(tekstfeltFormat.formaterDoubleTilString(pteController.getSigmaB())); } } private void formaterTekstfelt(TextField input) { tekstfeltFormat.formaterTekstfeltInput(input); } @Override public void initialize(URL arg0, ResourceBundle arg1) { formaterTekstfelt(tekstFeltForskydningspunkt); formaterTekstfelt(tekstFeltIntertimoment); formaterTekstfelt(tekstFeltSigmaB); tekstFeltForskydningspunkt.focusedProperty().addListener(new ChangeListener<Boolean>() { @Override public void changed(ObservableValue<? extends Boolean> observable, Boolean oldValue, Boolean newValue) { forskydningspunktErAEndret = true; } }); tekstFeltIntertimoment.focusedProperty().addListener(new ChangeListener<Boolean>() { @Override public void changed(ObservableValue<? extends Boolean> observable, Boolean oldValue, Boolean newValue) { intertimomentErAEndret = true; } }); tekstFeltSigmaB.focusedProperty().addListener(new ChangeListener<Boolean>() { @Override public void changed(ObservableValue<? extends Boolean> observable, Boolean oldValue, Boolean newValue) { sigmaBErAEndret = true; } }); } } <file_sep>/PTE/Test/Logic/ArealTest.java package Logic; import static org.junit.Assert.assertEquals; import static org.junit.Assert.fail; import java.util.List; import org.junit.Before; import org.junit.Test; import Exceptions.ArealException; public class ArealTest { ArealImpl areal; FormImpl form; @Test public void getArealNulstilTest() { form.setProfilType(ProfilType.UDEFINERET); areal.setAreal(5); areal.nulstil(); assertEquals(Double.NaN, areal.getAreal(), 0.001); } @Test public void getArealNegativTest() { try { areal.setAreal(-60); fail("Negativ areal"); } catch (ArealException e) { // Success } } @Test public void getArealNormalTest() { areal.setAreal(205); assertEquals(205, areal.getAreal(), 0.001); } @Test public void setLaengdeKommaTest() { areal.setAreal(55.3779); assertEquals(55.378, areal.getAreal(), 0.001); } @Test public void getArealNulTest() { try { areal.setAreal(0); fail("Nul Areal"); } catch (ArealException e) { // Success } } @Before public void setUp() throws Exception { form = new FormImpl(); areal = new ArealImpl(new Bredde() { @Override public void tilfoejAfhaengigEntitet(PTEEntity entity) { // TODO Auto-generated method stub } @Override public List<Tilstand> getAfhaengigheder() { // TODO Auto-generated method stub return null; } @Override public void setBredde(double bredde) { // TODO Auto-generated method stub } @Override public void nulstil() { // TODO Auto-generated method stub } @Override public double getBredde() { // TODO Auto-generated method stub return 0; } }, new Diameter() { @Override public void tilfoejAfhaengigEntitet(PTEEntity entity) { // TODO Auto-generated method stub } @Override public List<Tilstand> getAfhaengigheder() { // TODO Auto-generated method stub return null; } @Override public void setDiameter(double diameter) { // TODO Auto-generated method stub } @Override public void nulstil() { // TODO Auto-generated method stub } @Override public double getDiameter() { // TODO Auto-generated method stub return 0; } }, new Godstykkelse() { @Override public void tilfoejAfhaengigEntitet(PTEEntity entity) { // TODO Auto-generated method stub } @Override public List<Tilstand> getAfhaengigheder() { // TODO Auto-generated method stub return null; } @Override public void setGodstykkelse(double godstykkelse) { // TODO Auto-generated method stub } @Override public void nulstil() { // TODO Auto-generated method stub } @Override public double getGodstykkelse() { // TODO Auto-generated method stub return 0; } }, new Hoejde() { @Override public void tilfoejAfhaengigEntitet(PTEEntity entity) { // TODO Auto-generated method stub } @Override public List<Tilstand> getAfhaengigheder() { // TODO Auto-generated method stub return null; } @Override public void setHoejde(double godstykkelse) { // TODO Auto-generated method stub } @Override public void nulstil() { // TODO Auto-generated method stub } @Override public double getHoejde() { // TODO Auto-generated method stub return 0; } }, new Form() { @Override public void tilfoejAfhaengigEntitet(PTEEntity entity) { // TODO Auto-generated method stub } @Override public List<Tilstand> getAfhaengigheder() { // TODO Auto-generated method stub return null; } @Override public void setProfilType(ProfilType profilType) { // TODO Auto-generated method stub } @Override public void nulstil() { // TODO Auto-generated method stub } @Override public ProfilType getProfilType() { // TODO Auto-generated method stub return null; } }); } } <file_sep>/PTE/Implemenation/Logic/GodstykkelseImpl.java package Logic; import Exceptions.GodstykkelseException; public class GodstykkelseImpl extends PTEEntityImpl implements Godstykkelse { private double godstykkelse = Double.NaN; public void setGodstykkelse(double godstykkelse) { this.godstykkelse = godstykkelse; } public double getGodstykkelse() { if (godstykkelse < 0) { throw new GodstykkelseException(); } return godstykkelse; } public void nulstil() { godstykkelse = Double.NaN; } @Override protected Tilstand getEgenAfhaengighed() { return Tilstand.GODSTYKKELSE; } } <file_sep>/PTE/Implemenation/gui/KranTegner.java package gui; import java.util.List; import Logic.Profil; import Logic.Tilstand; import javafx.scene.Node; import javafx.scene.control.Button; import javafx.scene.control.TextField; import javafx.scene.layout.AnchorPane; import javafx.scene.layout.HBox; import javafx.scene.paint.Color; import javafx.scene.shape.Arc; import javafx.scene.shape.CubicCurveTo; import javafx.scene.shape.Line; import javafx.scene.shape.MoveTo; import javafx.scene.shape.Path; import javafx.scene.shape.StrokeLineCap; import javafx.scene.text.Text; import javafx.scene.transform.Rotate; public class KranTegner extends PTEPane { private static AnchorPane ap; private Line kranArm, xAxis, yAxis; private double x, y, height, width, nuvaerendeVinkel, rotateVinkel, katetA, vinkelSidePadding, vinkelHoejdePadding; boolean erKranTegnet = false; Profil profil; Path snit; Text vinkelVaerdi; Arc arc; public KranTegner(double width, double height) { ap = new AnchorPane(); this.width = width; this.height = height; this.x = width/4; this.y = this.height - this.height/3; vinkelSidePadding = 10; vinkelHoejdePadding = 17; kranArm = new Line(x, y, width - width/4, y); arc = new Arc(); snit = new Path(); vinkelVaerdi = new Text(); katetA = 30; tegnXYAxis(); } private void tegnKran() { setUpArc(); setUpKranArm(); setUpBoelgeStreg(); ap.getChildren().addAll(arc, kranArm, vinkelVaerdi, snit); } private void setUpKranArm() { kranArm.setStrokeWidth(10); kranArm.setStroke(Color.web("#55A9FC")); kranArm.setStrokeLineCap(StrokeLineCap.ROUND); kranArm.toFront(); } private void setUpArc() { arc.setStrokeWidth(2); arc.setStroke(Color.web("#000000")); arc.setFill(Color.CORNSILK.deriveColor(0, 0, 0, 0.0)); } private double udrengKatet_b() { return katetA / Math.tan(Math.toRadians(nuvaerendeVinkel)); } private void tegnXYAxis() { // X axis xAxis = new Line(x - 50, y, width - width/4 + 50, y); xAxis.setStrokeWidth(2); xAxis.setStroke(Color.BLACK); double xAxisHeadsStart = width - width/4 + 45; double xAxisHeadsEnd = width - width/4 + 52; Line xAxisHead1 = new Line(xAxisHeadsStart, y - 5, xAxisHeadsEnd, y); Line xAxisHead2 = new Line(xAxisHeadsStart, y + 5, xAxisHeadsEnd, y); yAxis = new Line(x, y + 50, x, y -(width - width/4 - 50)); yAxis.setStrokeWidth(2); yAxis.setStroke(Color.BLACK); double yAxisHeadsStart = y -(width - width/4 - 55); double yAxisHeadsEnd = y -(width - width/4 - 48); Line yAxisHead1 = new Line(x - 5, yAxisHeadsStart , x, yAxisHeadsEnd); Line yAxisHead2 = new Line(x + 5, yAxisHeadsStart, x, yAxisHeadsEnd); ap.getChildren().add(xAxis); ap.getChildren().add(yAxis); ap.getChildren().add(xAxisHead1); ap.getChildren().add(xAxisHead2); ap.getChildren().add(yAxisHead1); ap.getChildren().add(yAxisHead2); } private void setUpBoelgeStreg() { snit.setStroke(Color.web("#F27D7D")); snit.setStrokeWidth(3); snit.setStrokeLineCap(StrokeLineCap.ROUND); snit.setFill(Color.CORNSILK.deriveColor(0, 0, 0, 0.0)); // double[] snitPunkter = getSnitStartOgSlutPunkter(); MoveTo moveToCurve = new MoveTo(); moveToCurve.setX(x - 30); moveToCurve.setY(y); CubicCurveTo curve = new CubicCurveTo(); curve.setControlX1(x - 20); curve.setControlY1(y - 10); curve.setControlX2(x - 10); curve.setControlY2(y + 10); curve.setX(x); curve.setY(y); snit.getElements().add(moveToCurve); snit.getElements().add(curve); MoveTo moveToCurve2 = new MoveTo(); moveToCurve2.setX(x); moveToCurve2.setY(y); CubicCurveTo curve2 = new CubicCurveTo(); curve2.setControlX1(x + 10); curve2.setControlY1(y - 10); curve2.setControlX2(x + 20); curve2.setControlY2(y + 10); curve2.setX(x + 30); curve2.setY(y); snit.getTransforms().add(new Rotate(-90, x, y)); snit.getElements().add(moveToCurve2); snit.getElements().add(curve2); } private void flytArcOgVinkelVandret() { double katetB; if(nuvaerendeVinkel >= 45) { katetB = katetA; } else { katetB = udrengKatet_b(); } arc.setCenterX(x); arc.setCenterY(y); arc.setRadiusX(katetB); arc.setRadiusY(katetB); arc.setStartAngle(0); arc.setLength(nuvaerendeVinkel); if(nuvaerendeVinkel <= 10) { vinkelVaerdi.setX(x*3 + vinkelSidePadding); vinkelVaerdi.setY(y - vinkelHoejdePadding); arc.setRadiusX(x*2 - x/3); arc.setRadiusY(x*2 - x/3); } else { vinkelVaerdi.setX(x + katetB + vinkelSidePadding); vinkelVaerdi.setY(y - vinkelHoejdePadding); } } private void flytArcOgVinkelLodret() { double katetB; if(nuvaerendeVinkel >= 45) { katetB = katetA; } else { katetB = udrengKatet_b(); } arc.setCenterX(x); arc.setCenterY(y); arc.setStartAngle(90 - nuvaerendeVinkel); arc.setLength(nuvaerendeVinkel); arc.setRadiusX(katetB); arc.setRadiusY(katetB); if(nuvaerendeVinkel > 10 && nuvaerendeVinkel <= 22) { vinkelVaerdi.setX(x + vinkelSidePadding); vinkelVaerdi.setY(y - katetB - vinkelHoejdePadding - vinkelSidePadding); } else if(nuvaerendeVinkel <= 10) { vinkelVaerdi.setX(x + vinkelSidePadding); vinkelVaerdi.setY(y - y/2 - vinkelHoejdePadding*2); arc.setRadiusX(y - y/2); arc.setRadiusY(y - y/2); } else { vinkelVaerdi.setX(x + vinkelSidePadding); vinkelVaerdi.setY(y - katetB - vinkelHoejdePadding); } } private void rotateKranArmOgSnit(double vinkel) { if(vinkel <= 90 && vinkel >= 0) { nuvaerendeVinkel = vinkel; kranArm.getTransforms().clear(); snit.getTransforms().clear(); snit.getTransforms().add(new Rotate(-90, x, y)); if(profil == Profil.VANDRET) { kranArm.getTransforms().add(new Rotate(-vinkel, x, y)); snit.getTransforms().add(new Rotate(-vinkel, x, y)); vinkelVaerdi.setText(String.valueOf(vinkel) + "°"); flytArcOgVinkelVandret(); } else if(profil == Profil.LODRET) { kranArm.getTransforms().add(new Rotate(-(90 - vinkel), x, y)); snit.getTransforms().add(new Rotate(-(90 - vinkel), x, y)); vinkelVaerdi.setText(String.valueOf(vinkel) + "°"); flytArcOgVinkelLodret(); } } } // private void rotateLodretKranArmOgSnit(double vinkel) { // if(vinkel <= 90 && vinkel >= 0) { // Rotate kranRotate = null; // Rotate snitRotate = null; // if(vinkel > nuvaerendeVinkel) { // rotateVinkel = vinkel - nuvaerendeVinkel; // nuvaerendeVinkel = vinkel; // kranRotate = new Rotate(rotateVinkel, x, y); // snitRotate = new Rotate(rotateVinkel, x, y); // } else { // rotateVinkel = nuvaerendeVinkel - vinkel; // nuvaerendeVinkel = vinkel; // kranRotate = new Rotate(-rotateVinkel, x, y); // snitRotate = new Rotate(-rotateVinkel, x, y); // } // kranArm.getTransforms().add(kranRotate); // snit.getTransforms().add(snitRotate); // vinkelVaerdi.setText(String.valueOf(nuvaerendeVinkel) + "°"); // flytArcOgVinkelLodret(); // kranArm.getTransforms().clear(); // } // } public static Node getNode() { return ap; } // private void rotateKranArmOgSnit(double vinkel) { // if(profil == Profil.VANDRET) { // rotateVandretKranArmOgSnit(vinkel); // } else if(profil == Profil.LODRET) { // rotateLodretKranArmOgSnit(vinkel); // } // } @Override public void update(List<Tilstand> tilstande) { if(tilstande.contains(Tilstand.VINKEL)) { profil = pteController.getProfil(); if(!erKranTegnet) { tegnKran(); erKranTegnet = true; } rotateKranArmOgSnit(pteController.getVinkel()); } } } <file_sep>/PTE/Test/Logic/TyngdekraftTest.java package Logic; import static org.junit.Assert.*; import org.junit.Before; import org.junit.Test; import Exceptions.TyngdekraftException; import Exceptions.VaegtException; public class TyngdekraftTest { TyngdekraftImpl tyngdekraft; @Before public void setUp() throws Exception { tyngdekraft = new TyngdekraftImpl(); } @Test public void setTyngdekraftNulstill() { tyngdekraft.setTyngdekraft(9.816); assertEquals(9.816, tyngdekraft.getTyngdekraft(), 0.001); } @Test public void setTyngdekraftNegativ() { tyngdekraft.setTyngdekraft(-5); try { tyngdekraft.getTyngdekraft(); fail("Exception bliver ikke kastet."); } catch (TyngdekraftException e) { // success } } @Test public void setTyngdekraftNul() { tyngdekraft.setTyngdekraft(0); try { tyngdekraft.getTyngdekraft(); fail("Exception bliver ikke kastet."); } catch (TyngdekraftException e) { // success } } @Test public void setTyngdekraftAfrunding() { tyngdekraft.setTyngdekraft(3.03456); assertEquals(3.035, tyngdekraft.getTyngdekraft(), 0.001); } @Test public void setTyngdekraftDecimaltal() { tyngdekraft.setTyngdekraft(0.001); assertEquals(0.001, tyngdekraft.getTyngdekraft(), 0.001); } } <file_sep>/PTE/Implemenation/Logic/ForskydningspunktImpl.java package Logic; public class ForskydningspunktImpl extends PTEEntityImpl implements Forskydningspunkt { private double forskydningspunkt=Double.NaN; @Override public double getForskydningspunkt() { return forskydningspunkt; } @Override public void setForskydningspunkt(double forskydningspunkt) { this.forskydningspunkt = forskydningspunkt; } @Override public void nulstil() { setForskydningspunkt(Double.NaN); } @Override protected Tilstand getEgenAfhaengighed() { return Tilstand.FORSKYDNINGSPUNKT; } } <file_sep>/PTE/Test/Logic/laengdeTest.java package Logic; import static org.junit.Assert.*; import org.junit.Before; import org.junit.Test; import Exceptions.LaengdeException; import Exceptions.VinkelException; public class laengdeTest { Laengde laengde; @Before public void setUp() throws Exception { laengde = new LaengdeImpl(); } @Test public void laengdetest() { laengde.setLaengde(5); laengde.nulstil(); assertEquals(Double.NaN, laengde.getLaengde(), 0.001); } @Test public void setLaengdeNegativTest() { try { laengde.setLaengde(-60); fail("Negativ Længde"); } catch (LaengdeException e) { // Success } } @Test public void setLaengde2NormalTest() { laengde.setLaengde(60); assertEquals(60, laengde.getLaengde(), 0.001); } @Test public void setLaengdeNormalTest() { laengde.setLaengde(205); assertEquals(205, laengde.getLaengde(), 0.001); } @Test public void setLaengdeKommaTest() { laengde.setLaengde(55.3779); assertEquals(55.378, laengde.getLaengde(), 0.001); } } <file_sep>/PTE/Implemenation/Exceptions/DiameterException.java package Exceptions; public class DiameterException extends RuntimeException { } <file_sep>/PTE/Implemenation/Exceptions/HoejdeException.java package Exceptions; public class HoejdeException extends RuntimeException { }<file_sep>/PTE/Implemenation/Readme.md ####BEMÆRK! #####SimplePdfWriterImpl er wrapper klasse for ITEXTPDF java bibliotek, det betyder, at man skal tilføje itextpdf-x.x.x.jar til sin java buidpath! ######Det her er en eksempel, der viser hvordan man bruger FileUtilsImpl og SimplePdfWriterImpl klasser. ```java FileUtils fileUtils = new FileUtilsImpl(); File file = null; try { file = fileUtils.createFile("path/to/file/which/should/be/created"); } catch (FileExistsException e) { // handle exception } SimplePdfWriter pdf = new SimplePdfWriterImpl(file); pdf.setPageTitle("Test title with custom font", FontFactory.getFont(FontFamily.COURIER.toString(), 24, BaseColor.BLUE)); pdf.setPageTitle("Test title with font style", FontStyle.UNDERLINE); pdf.setPageTitle("Test title with font size", 40); pdf.addParagraph("Test paragraph"); pdf.addParagraph("Test paragraph with custom font", FontFactory.getFont(FontFamily.COURIER.toString(), 24, BaseColor.BLUE)); pdf.addParagraph("Test paragraph with font style", FontStyle.UNDERLINE); pdf.addParagraph("Test paragraph with font size", 40); pdf.close(); ``` <file_sep>/PTE/Implemenation/gui/TekstFormattering.java package gui; import javafx.scene.control.TextField; public interface TekstFormattering { void formaterTekstfeltInput(TextField input); Double formaterStringTilDouble(String tekstinput); String formaterDoubleTilString(Double resultat); } <file_sep>/PTE/Implemenation/Logic/BoejningsMomentImpl.java package Logic; import Exceptions.BoejningsMomentException; import Exceptions.DimensionerendeKraftException; import Exceptions.UdefineretLaengdeRetningException; class BoejningsMomentImpl extends PTEEntityImpl implements BoejningsMoment { private double boejningsMoment = Double.NaN; private DimensionerendeKraft dimensionerendeKraft = null; private Forskydningskraft forskydningskraft = null; private Vinkel v; private Laengde l; public BoejningsMomentImpl(Vinkel v, Laengde l, DimensionerendeKraft dimensionerendeKraft, Forskydningskraft forskydningskraft) { if (v == null || l == null || dimensionerendeKraft == null || forskydningskraft == null) { throw new IllegalArgumentException(); } this.v = v; this.v.tilfoejAfhaengigEntitet(this); this.l = l; this.l.tilfoejAfhaengigEntitet(this); this.dimensionerendeKraft = dimensionerendeKraft; this.dimensionerendeKraft.tilfoejAfhaengigEntitet(this); this.forskydningskraft = forskydningskraft; this.forskydningskraft.tilfoejAfhaengigEntitet(this); } @Override public void setBoejningsMoment(double boejningsMoment) { if (boejningsMoment <= 0) { throw new BoejningsMomentException(); } this.boejningsMoment = boejningsMoment; nulstilBoern(); } @Override public double getBoejningsMoment() { return getBoejningsMoment(v.getLaengdeRetning(), l.getLaengde(), dimensionerendeKraft.getDimensionerendeKraft(), forskydningskraft.getForskydningskraft()); } double getBoejningsMoment(LaengdeRetning lr, double l, double dimensionerendeKraft, double forskydningskraft) { if (!Double.isNaN(boejningsMoment)) { return boejningsMoment; } if (lr == LaengdeRetning.VINKELRET_TIL_FDIM) { return (l * dimensionerendeKraft); } else if (lr == LaengdeRetning.VINKELRET_TIL_FT) { return (l * forskydningskraft); } else throw new UdefineretLaengdeRetningException("Udefineret laengde retning"); } @Override public void nulstil() { setBoejningsMoment(Double.NaN); nulstilBoern(); } private void nulstilBoern() { v.nulstil(); l.nulstil(); dimensionerendeKraft.nulstil(); forskydningskraft.nulstil(); } @Override protected Tilstand getEgenAfhaengighed() { return Tilstand.BOEJNINGSMOMENT; } }<file_sep>/PTE/Implemenation/Exceptions/UdefineretLaengdeRetningException.java package Exceptions; public class UdefineretLaengdeRetningException extends RuntimeException { public UdefineretLaengdeRetningException(String besked){ super(besked); } } <file_sep>/PTE/Implemenation/Logic/VinkelImpl.java package Logic; import Exceptions.VinkelException; class VinkelImpl extends PTEEntityImpl implements Vinkel { private double vinkel = Double.NaN; private Profil profil = Profil.UDEFINERET; private LaengdeRetning laengdeRetning; @Override public void setVinkel(double vinkel) { if (vinkel > 90) { throw new VinkelException(); } if (vinkel < 0) { throw new VinkelException(); } this.vinkel = vinkel; } @Override public double getVinkel() { return vinkel; } @Override public void setProfil(Profil profil) { this.profil = profil; } @Override public Profil getProfil() { return profil; } @Override public void nulstil() { vinkel = Double.NaN; profil = Profil.UDEFINERET; } @Override protected Tilstand getEgenAfhaengighed() { return Tilstand.VINKEL; } @Override public void setLaengdeRetning(LaengdeRetning laengdeRetning) { this.laengdeRetning = laengdeRetning; } @Override public LaengdeRetning getLaengdeRetning() { return laengdeRetning; } }
c88c656e860da4ebafb075ee83a63096b3704452
[ "Markdown", "Java" ]
50
Java
HEDMU-2015/PTE
e9e93eeb93b7f69e896fd2dfc4cc02ebc195a902
58d02f08ac6907d4d5ce865392acae0e6d85d1fc
refs/heads/master
<file_sep>export interface IUser { id: number, name: string, username: any, email: any, address: any, phone: any, website: any, company: any }<file_sep>export default class ApiError { public status: number public message: string constructor(status: number, message: string) { this.status = status this.message = message } static badRequest(message: any) { return new ApiError(400, message) } }<file_sep>import express from 'express' import ValidateDTO from '../../middleware/validate-dto' import { registerController } from '../../controllers' import RegisterDTO from '../../dto/register.dto' const router = express.Router() router.post('/register', ValidateDTO.validate(RegisterDTO), registerController.register) export default router<file_sep>import { NextFunction, Request, Response } from "express"; import ApiError from '../models/api-error.model' class ErrorHandler { handle (error: any, req: Request, res: Response, next: NextFunction) { if (error instanceof ApiError) { return res.status(error.status).json(error.message) } return res.status(500).json('Parece que algo salió mal!') } } export default new ErrorHandler()<file_sep>import { Document } from 'mongoose' import DBConfig from "../config/db.config" export default class RegisterRepository { constructor (private dbConfig: DBConfig) {} create = async (): Promise<Document[] | undefined | string> => { try { await this.dbConfig.connect() //ADD CREATE NEW REGISTER await this.dbConfig.disconnect() return new Promise( (resolve) => { resolve ('created!') }) } catch (error) { return new Promise( (reject) => { reject(error.message) }) } } }<file_sep># Typescript backend boilerplate NodeJS backend with Typescript ## Installation Make sure you have Yarn installed on your machine. Then clone repo and run ```bash yarn install ``` ## Run server To start the server run ```bash yarn start ```<file_sep>import { Document } from 'mongoose' import DBConfig from "../config/db.config" import Customer from '../models/customers' export default class CustomerRepository { constructor (private dbConfig: DBConfig) {} findAll = async (): Promise<Document[] | undefined | string> => { try { await this.dbConfig.connect() const payload = await Customer.find() await this.dbConfig.disconnect() return new Promise( (resolve) => { resolve (payload) }) } catch (error) { return new Promise( (reject) => { reject(error.message) }) } } }<file_sep>import DBConfig from '../config/db.config' import CustomerRepository from './customer.repository' import RegisterRepository from './register.repository' const dbConfig = new DBConfig() const customerRepository = new CustomerRepository(dbConfig) const registerRepository = new RegisterRepository(dbConfig) const repositories = [ customerRepository, registerRepository ] export default repositories export { customerRepository, registerRepository }<file_sep>import dotenv from 'dotenv' dotenv.config(); import mongoose from 'mongoose' export default class DBConfig { private URI: string = `mongodb+srv://${process.env.MONGO_USERNAME}:${process.env.MONGO_PASSWORD}@${process.env.MONGO_HOST}/${process.env.MONGO_DATABASE}?retryWrites=true&w=majority` async connect () { return await mongoose.connect(this.URI, { useNewUrlParser: true, useUnifiedTopology: true }) } async disconnect () { return await mongoose.disconnect() } }<file_sep>import { NextFunction, Request, Response } from "express"; import ApiError from "../models/api-error.model"; import RegisterService from "../services/register.service"; export default class RegisterController { constructor (private registerService: RegisterService) {} register = async (req: Request, res: Response, next: NextFunction) => { try { const data = req.body const result = await this.registerService.register(data) res.status(200).json(result) } catch (error) { next(ApiError.badRequest(error.message)) } } }<file_sep>import { NextFunction, Request, Response } from "express"; import ApiError from "../models/api-error.model"; import CustomerService from "../services/customer.service"; export default class CustomerController { constructor (private customerService: CustomerService) {} getCustomers = async (req: Request, res: Response, next: NextFunction) => { try { const result = await this.customerService.getAddCustomers() res.status(200).json(result) } catch (error) { next(ApiError.badRequest(error.message)) } } }<file_sep>import { Document } from 'mongoose' import RegisterRepository from "../repositories/register.repository" export default class RegisterService { constructor (private registerRepository: RegisterRepository) {} register = async (data: any): Promise<Document[] | string> => { try { // ADD REPOSITORY HERE const result = data return new Promise( (resolve) => { resolve(result) }) } catch (error) { return new Promise( (reject) => { reject(error.message) }) } } }<file_sep>import express from 'express' import { customerController } from '../../controllers' const router = express.Router() router.get('/customers', customerController.getCustomers) export default router<file_sep>import CustomerService from './customer.service' import RegisterService from './register.service' import { customerRepository, registerRepository } from '../repositories' const customerService = new CustomerService(customerRepository) const registerService = new RegisterService(registerRepository) const services = [ customerService, registerService ] export default services export { customerService, registerService }<file_sep>import express from 'express' import errorHandler from './src/handlers/error.handler' import routers from './src/routes' const app = express() const port = 3000 || process.env.PORT app.use(express.json()) app.use(routers) app.use(errorHandler.handle) app.listen(port, () => { console.log(`Listening on port ${port}`) })<file_sep>import CustomerController from './customer.controller' import RegisterController from './register.controller' import { customerService, registerService } from '../services' const customerController = new CustomerController(customerService) const registerController = new RegisterController(registerService) const controllers = [ customerController, registerController ] export default controllers export { customerController, registerController }<file_sep>import { Document } from 'mongoose' import CustomerRepository from '../repositories/customer.repository' export default class CustomerService { constructor (private customerRepository: CustomerRepository) {} getAddCustomers = async (): Promise<Document[] | string> => { try { const result = await this.customerRepository.findAll() return new Promise( (resolve) => { resolve(result) }) } catch (error) { return new Promise( (reject) => { reject(error.message) }) } } }<file_sep>import { NextFunction, Request, Response } from "express"; import ApiError from '../models/api-error.model' class ValidateDTO { validate(schema: any) { return async (req: Request, res: Response, next: NextFunction) => { try { const validateBody = await schema.validate(req.body) req.body = validateBody next() } catch (error) { next(ApiError.badRequest(error.message)) } } } } export default new ValidateDTO()<file_sep>import RegisterRoute from './v1/register.route' import customerRoute from './v1/customer.route' const routers = [ RegisterRoute, customerRoute ] export default routers export { RegisterRoute, customerRoute }<file_sep>export interface IRegister { username: any, email: any }<file_sep>import mongoose, { Schema, Document } from 'mongoose'; export interface ICustomer extends Document { username: string; name: string; address: string; birthdate: string; email: string; active: boolean; } const CustomerSchema: Schema = new Schema({ username: { type: String, required: true, unique: true }, name: { type: String, required: true }, address: { type: String, required: true }, birthdate: { type: String, required: true }, email: { type: String, required: true }, active: { type: Boolean, required: true } }); export default mongoose.model('Customer', CustomerSchema);
4ae37212fd526b040bd86d40d4fe101e58befc8a
[ "Markdown", "TypeScript" ]
21
TypeScript
CristianH21/typescript-backend-boilerplate
97911ae7db7afabff8d0ed6809d1772d114ef00c
12ba6a5267ab052d31c5c07fdd8d1d12db19ee4c
refs/heads/master
<repo_name>Gigaspaces-sbp/IECloud<file_sep>/postinstall/run.sh #!/bin/bash echo curl -i --data '@/opt/scripts/note.json' -X POST http://$1/api/notebook/import curl -i --data '@/opt/scripts/note.json' -X POST http://$1/api/notebook/import <file_sep>/postinstall/Dockerfile FROM debian COPY ./note.json /opt/scripts/note.json COPY ./run.sh /opt/scripts/run.sh RUN chmod 755 /opt/scripts/run.sh RUN apt-get update && apt-get install -y curl ENTRYPOINT ["/bin/bash"] <file_sep>/feeder_docker/Dockerfile FROM java:8 ADD data-feeder-1.0.jar data-feeder.jar ADD data.csv data.csv ENTRYPOINT ["java", "-jar", "data-feeder.jar", "--spring.profiles.active=prod"] <file_sep>/docker/Dockerfile FROM gigaspaces/insightedge-enterprise:15.0.0-m16 COPY flightdelays20172018.csv /opt/gigaspaces/ COPY weather2017_8.csv /opt/gigaspaces/ COPY zeppelin/notebook/INSIGHTEDGE-GETTING-STARTED /opt/gigaspaces/insightedge/zeppelin/notebook/INSIGHTEDGE-GETTING-STARTED COPY zeppelin/notebook/INSIGHTEDGE-GETTING-STARTED-2 /opt/gigaspaces/insightedge/zeppelin/notebook/INSIGHTEDGE-GETTING-STARTED-2 COPY zeppelin/conf/interpreter.json /opt/gigaspaces/insightedge/zeppelin/conf/
3937bcbf8da89e98b458a12232306fc37403b001
[ "Dockerfile", "Shell" ]
4
Shell
Gigaspaces-sbp/IECloud
1734f5efb18fdb8e0616df447a1881ecb5b286f7
46f16860d085099496ace08d93bc16cd707da56c
refs/heads/master
<repo_name>kozmic-labs/title-from-url<file_sep>/test.js var test = require("prova"); var title = require("./"); test('generate a title from url', function (t) { t.plan(9); t.equal(title('http://wikipedia.org'), 'Wikipedia'); t.equal(title('http://wikipedia.org/'), 'Wikipedia'); t.equal(title('encrypted.google.org.tr/search?q=foo&bar=qux'), 'Search on Encrypted, Google'); t.equal(title('http://en.wikipedia.org/wiki/Foo_%28app%29'), 'Foo (app) - Wiki on En, Wikipedia'); });
b7ba111a31fe7ecdf3a999596a5a811c54580e9c
[ "JavaScript" ]
1
JavaScript
kozmic-labs/title-from-url
49527e9e20621454e0f9ee5732b561561864b07e
92bb3755e29b314097162fff0ad4069d4ad99efb
refs/heads/master
<file_sep># IS211_Assignment13 IS Homework Assignment Please be sure to pip install all the modules listed in requirements.txt file <file_sep>#!d:\notes\drconnork\python csv\is211_assignment13\student\venv\scripts\python.exe # EASY-INSTALL-ENTRY-SCRIPT: 'alembic==1.3.1','console_scripts','alembic' __requires__ = 'alembic==1.3.1' import sys from pkg_resources import load_entry_point if __name__ == '__main__': sys.exit( load_entry_point('alembic==1.3.1', 'console_scripts', 'alembic')() ) <file_sep>#!d:\notes\drconnork\python csv\is211_assignment13\student\venv\scripts\python.exe # EASY-INSTALL-ENTRY-SCRIPT: 'Mako==1.1.0','console_scripts','mako-render' __requires__ = 'Mako==1.1.0' import sys from pkg_resources import load_entry_point if __name__ == '__main__': sys.exit( load_entry_point('Mako==1.1.0', 'console_scripts', 'mako-render')() )
2bf6f8b2ef9f39d5c44e9038bf8037cf1740a7d0
[ "Markdown", "Python" ]
3
Markdown
NRJoseph49/IS211_Assignment13
ca377db392644c31e0896ca5f875b909521ce08f
96ac6a8659aaec02304158790d8fe569786eca3e
refs/heads/master
<file_sep>// // MovieCellViewModel.swift // RappiTest // // Created by <NAME> on 1/30/19. // Copyright © 2019 <NAME>. All rights reserved. // import Foundation import UIKit.UIImage protocol MovieCellViewModelDelegate: class { func didReceivePosterImage(_ image: UIImage?) } final class MovieCellViewModel { let movie: Movie let movieService: MovieService weak var delegate: MovieCellViewModelDelegate? private var dataTask: URLSessionDataTask? init(movie: Movie, movieService: MovieService) { self.movie = movie self.movieService = movieService } func getPosterImage() { dataTask = movieService.posterImageForMovie(imagePath: movie.posterPath ?? "") { [weak self] result in self?.dataTask = nil var image = UIImage(named: "placeholder") switch result { case .failure: break case .success(let value): image = value } DispatchQueue.main.async { self?.delegate?.didReceivePosterImage(image) } } } func cancelPosterImageRequest() { if let task = dataTask { task.cancel() } } } <file_sep>// // UITableView.swift // RappiTest // // Created by <NAME> on 1/30/19. // Copyright © 2019 <NAME>. All rights reserved. // import UIKit.UITableView extension UITableView { func dequeueCell<T: UITableViewCell>(indexPath: IndexPath) -> T { guard let cell = dequeueReusableCell(withIdentifier: T.identifier, for: indexPath) as? T else { preconditionFailure("Couldn't dequeue cell") } return cell } func registerNib(cellType: AnyClass) { guard let T = cellType as? UITableViewCell.Type else { preconditionFailure("Could'n cast value") } register(T.nib, forCellReuseIdentifier: T.identifier) } } <file_sep># RMovieTest ## Capas de la app - La capa de **vistas** que esta confomada por los controladores(subclases de UIViewController) y las vistas customizadas como las celdas(subclases de UITableViewCell) asi como sus respectivos archivos .xib - La logica de **negocio** se encuentra en los ViewModel, en este caso algunos archivos serian: MovieDetailListViewModel MovieCellViewModel - La capa de **red** esta conformada por los archivos ApiClient, ApiClientRouter, Result, etc... esta capa se encarga de hacer los request al servidor, es una "interfaz" para la comunicacion con el server. - La capa de **modelo** contiene las entidades que seran utilizadas para representar la informacion en la app, algunas son: Movie, MovieRequest - La capa de **navegación** la defino con la clase Navigator, esta se encarga de coordinar el flujo de la app. ## Pregunta - Principio de responsabilidad unica: Es un pricipio que dicta que cada entidad del sistema(clase, structura, modulo, etc...) tiene que cumplir una sola tarea, sólo debe tener una única responsabilidad. - Buen Codigo: Considero un buen codigo aquel que sea facil de leer, que al agregar una nueva funcionalidad sea facil de hacerlo, que haga uso de los patrones de diseño, que se sigan "buenas practias" cuando se escribe, que el codigo se exprese por sí mismo (pocos comentarios), que tenga bien definidas las capas(vista, negocio, red, etc...) <file_sep>// // Navigator.swift // RappiTest // // Created by <NAME> on 1/30/19. // Copyright © 2019 <NAME>. All rights reserved. // import UIKit protocol Navegable where Self:UIViewController { var navigator: Navigator? { get set } } class Navigator { enum Destination { case movieList case movieDetail(Movie) } let apiClient = ApiClient() let window: UIWindow lazy var tabViewController = UITabBarController() init(window: UIWindow) { self.window = window window.rootViewController = tabViewController window.makeKeyAndVisible() } func navigateTo(destination: Destination) { switch destination { case .movieList: let movieService = MovieService(apiClient: apiClient) let topRatedViewModel = MoviesListViewModel(movieService: movieService, section: .topRated) let topRatedMoviesViewController = MoviesListViewController(viewModel: topRatedViewModel) topRatedMoviesViewController.navigator = self let popularMoviesViewModel = MoviesListViewModel(movieService: movieService, section: .popular) let popularMovieViewController = MoviesListViewController(viewModel: popularMoviesViewModel) popularMovieViewController.navigator = self let upcomingMoviesViewModel = MoviesListViewModel(movieService: movieService, section: .upcoming) let upcomingMoviesViewController = MoviesListViewController(viewModel: upcomingMoviesViewModel) upcomingMoviesViewController.navigator = self topRatedMoviesViewController.tabBarItem = UITabBarItem(tabBarSystemItem: .topRated, tag: 0) popularMovieViewController.tabBarItem = UITabBarItem(tabBarSystemItem: .favorites, tag: 1) upcomingMoviesViewController.tabBarItem = UITabBarItem(tabBarSystemItem: .mostRecent, tag: 2) tabViewController.viewControllers = [topRatedMoviesViewController, popularMovieViewController, upcomingMoviesViewController] case .movieDetail(let movie): let movieDetail = MovieDetailViewController(movie: movie) let navigationController = UINavigationController(rootViewController: movieDetail) tabViewController.present(navigationController, animated: true, completion: nil) } } } <file_sep>// // ApiClientRouter.swift // RappiTest // // Created by <NAME> on 1/29/19. // Copyright © 2019 <NAME>. All rights reserved. // import Foundation typealias Parameters = [String: Any] enum ApiConstant: String { case apiKey = "API-Key" case baseURL = "BaseURL" case apiVersion = "API-Version" case baseImageURL = "BaseImageURL" } extension ApiConstant { var value: String { let key = self.rawValue guard let value = Bundle.main.object(forInfoDictionaryKey: key) as? String else { preconditionFailure("Cannot get value for key \(key)") } return value } } enum ApiClientRouter { case popularMovies(parameters: Parameters) case topRatedMovies(parameters: Parameters) case upcomingMovies(parameters: Parameters) case posterImage(path: String) } extension ApiClientRouter { private var path: (path: String, parameters: [String: Any]) { switch self { case .popularMovies(let parameters): return ("/\(ApiConstant.apiVersion.value)/movie/popular", parameters) case .topRatedMovies(let parameters): return ("/\(ApiConstant.apiVersion.value)/movie/top_rated", parameters) case .upcomingMovies(let parameters): return ("/\(ApiConstant.apiVersion.value)/movie/upcoming", parameters) case .posterImage(let path): return (path, [:]) } } func asURLRequest() throws -> URLRequest { var url: URL? switch self { case .posterImage: let baseURL = URL(string: ApiConstant.baseImageURL.value) url = baseURL?.appendingPathComponent(path.path) default: let baseURL = URL(string: ApiConstant.baseURL.value) let urlAppendedPath = baseURL?.appendingPathComponent(path.path) let components = buildURLComponents(urlAppendedPath, withParameters: path.parameters) url = components.url } guard let URL = url else { preconditionFailure("Cannot get url from \(String(describing: url))") } let urlRequest = URLRequest(url: URL) return urlRequest } private func buildURLComponents(_ url: URL?, withParameters parameters: Parameters) -> URLComponents { var urlComponents = URLComponents(url: url!, resolvingAgainstBaseURL: true) urlComponents?.queryItems = parameters.map { URLQueryItem(name: $0, value: String(describing: $1))} urlComponents?.queryItems?.append(URLQueryItem(name: "api_key", value: ApiConstant.apiKey.value)) urlComponents?.queryItems?.append(URLQueryItem(name: "language", value: "en-US")) guard let components = urlComponents else { preconditionFailure("Cannot build components") } return components } } <file_sep>// // Movie.swift // RappiTest // // Created by <NAME> on 1/29/19. // Copyright © 2019 <NAME>. All rights reserved. // import Foundation import UIKit.UIImage struct Movie: Codable { let voteCount: Int? let id: Int? let voteAverage: Double? let title: String? let posterPath: String? let overview: String? let releaseDate: String? var date: Date { let dateFormatter = DateFormatter() dateFormatter.dateFormat = "yyyy-MM-dd" guard let date = dateFormatter.date(from: releaseDate ?? "") else { preconditionFailure("Wrong format") } return date } var posterImage: UIImage? enum CodingKeys: String, CodingKey { case voteCount = "vote_count" case id case voteAverage = "vote_average" case title case posterPath = "poster_path" case overview case releaseDate = "release_date" } } <file_sep>// // UITableViewCell.swift // RappiTest // // Created by <NAME> on 1/30/19. // Copyright © 2019 <NAME>. All rights reserved. // import UIKit.UITableViewCell extension UITableViewCell { static var identifier: String { return String(describing: self.self) } static var nib: UINib? { return UINib(nibName: identifier, bundle: nil) } } <file_sep>// // MoviesListViewController.swift // RappiTest // // Created by <NAME> on 1/29/19. // Copyright © 2019 <NAME>. All rights reserved. // import UIKit final class MoviesListViewController: UIViewController, Navegable { var movies: [Movie] = [] let viewModel: MoviesListViewModel var navigator: Navigator? var section: MovieService.Section = .popular @IBOutlet var moviesTableView: UITableView! init(viewModel: MoviesListViewModel) { self.viewModel = viewModel super.init(nibName: nil, bundle: nil) self.viewModel.delegate = self } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func viewDidLoad() { super.viewDidLoad() viewModel.getMoviesBy() setupTableView() } private func setupTableView() { moviesTableView.registerNib(cellType: MovieCell.self) moviesTableView.delegate = self moviesTableView.dataSource = self moviesTableView.rowHeight = 120 } private func loadNextPage() { viewModel.loadNextPage() } } // MARK: - UITableViewDataSource extension MoviesListViewController: UITableViewDataSource { func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return movies.count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell: MovieCell = tableView.dequeueCell(indexPath: indexPath) let movie = movies[indexPath.row] let cellViewModel = MovieCellViewModel(movie: movie, movieService: viewModel.movieService) cellViewModel.delegate = cell cell.cellViewModel = cellViewModel if movies.count % 10 == 0 && indexPath.item == movies.count - 1 { loadNextPage() } return cell } } // MARK: - UITableViewDelegate extension MoviesListViewController: UITableViewDelegate { func tableView(_ tableView: UITableView, didEndDisplaying cell: UITableViewCell, forRowAt indexPath: IndexPath) { let cell = tableView.cellForRow(at: indexPath) as? MovieCell cell?.cellViewModel?.cancelPosterImageRequest() } func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { let selectedCell = tableView.cellForRow(at: indexPath) as! MovieCell var movieSelected = movies[indexPath.row] movieSelected.posterImage = selectedCell.moviePosterImageView.image navigator?.navigateTo(destination: .movieDetail(movieSelected)) } } // MARK: - MoviesListDelegate extension MoviesListViewController: MoviesListDelegate { func didReceiveMovies(_ movies: [Movie]) { self.movies += movies moviesTableView.reloadData() } func didThrow(_ error: Error) { print("Present Alert") } } <file_sep>// // ApiClient.swift // RappiTest // // Created by <NAME> on 1/29/19. // Copyright © 2019 <NAME>. All rights reserved. // import Foundation import UIKit enum ApiClientError: LocalizedError { case unknown case network } protocol ApiClientProtocol { func requestMovies(for section: MovieService.Section, atPage page: Int, _ completion: @escaping (Result<MovieRequest>) -> Void) func requestPosterImageWithPath(_ path: String, _ completion: @escaping (Result<UIImage>) -> Void) -> URLSessionDataTask } extension ApiClientProtocol { @discardableResult fileprivate func defaultRequest(_ urlRequest: ApiClientRouter, _ completion: @escaping (Data?, URLResponse?, Error?) -> Void) -> URLSessionDataTask { guard let request = try? urlRequest.asURLRequest() else { preconditionFailure("Cannot get request") } let task = URLSession.shared.dataTask(with: request, completionHandler: completion) task.resume() return task } fileprivate func defaultJSONDecoder<T: Codable>(data: Data?, _ completion: @escaping (Result<T>) -> Void) { do { let json = try JSONDecoder().decode(T.self, from: data!) completion(Result { json }) } catch { completion(Result { throw error }) } } } final class ApiClient: ApiClientProtocol { func requestMovies(for section: MovieService.Section, atPage page: Int, _ completion: @escaping (Result<MovieRequest>) -> Void) { let parameters: [String: Any] = ["page": page] let router: ApiClientRouter switch section { case .popular: router = .popularMovies(parameters: parameters) case .topRated: router = .topRatedMovies(parameters: parameters) case .upcoming: router = .upcomingMovies(parameters: parameters) } defaultRequest(router) { (data, _, error) in guard error == nil, let data = data else { completion(Result { throw ApiClientError.network }) return } self.defaultJSONDecoder(data: data, completion) } } func requestPosterImageWithPath(_ path: String, _ completion: @escaping (Result<UIImage>) -> Void) -> URLSessionDataTask { return defaultRequest(ApiClientRouter.posterImage(path: path)) { (data, _, error) in guard error == nil, let data = data, let image = UIImage(data: data) else { completion(Result { UIImage(named: "placeholder")! }) return } completion(Result { image }) } } } <file_sep>// // Result.swift // RappiTest // // Created by <NAME> on 1/29/19. // Copyright © 2019 <NAME>. All rights reserved. // import Foundation enum Result<Value> { case success(Value) case failure(Error) } extension Result { init(_ capturing: () throws -> Value) { do { self = .success(try capturing()) } catch { self = .failure(error) } } } <file_sep>// // MoviesListViewModel.swift // RappiTest // // Created by <NAME> on 1/29/19. // Copyright © 2019 <NAME>. All rights reserved. // import Foundation protocol MoviesListDelegate: class { func didReceiveMovies(_ movies: [Movie]) func didThrow(_ error: Error) } final class MoviesListViewModel { let movieService: MovieService weak var delegate: MoviesListDelegate? private var currentPage = 1 private var totalPages = 0 private let section: MovieService.Section init(movieService: MovieService, section: MovieService.Section) { self.movieService = movieService self.section = section } func getMoviesBy(atPage page: Int = 1) { movieService.moviesBy(section, atPage: page) { result in switch result { case .failure(let error): self.delegate?.didThrow(error) case .success(let value): self.totalPages = value.totalPages DispatchQueue.main.async { self.delegate?.didReceiveMovies(value.results) } } } } func loadNextPage() { currentPage += 1 if currentPage <= totalPages { getMoviesBy(atPage: currentPage) } } } <file_sep>// // MovieService.swift // RappiTest // // Created by <NAME> on 1/29/19. // Copyright © 2019 <NAME>. All rights reserved. // import Foundation import UIKit.UIImage final class MovieService { enum Section { case popular case topRated case upcoming } let apiClient: ApiClientProtocol init(apiClient: ApiClientProtocol) { self.apiClient = apiClient } func moviesBy(_ clasification: Section, atPage page: Int, _ completion: @escaping (Result<MovieRequest>) -> Void) { apiClient.requestMovies(for: clasification, atPage: page, completion) } func posterImageForMovie(imagePath: String, _ completion: @escaping (Result<UIImage>) -> Void) -> URLSessionDataTask { return apiClient.requestPosterImageWithPath(imagePath, completion) } } <file_sep>// // MovieTableViewCell.swift // RappiTest // // Created by <NAME> on 1/29/19. // Copyright © 2019 <NAME>. All rights reserved. // import UIKit final class MovieCell: UITableViewCell { var cellViewModel: MovieCellViewModel? { didSet { guard let movie = cellViewModel?.movie else { return } resetCell() setupCell(movie) } } @IBOutlet var movieTitleLabel: UILabel! @IBOutlet var movieVoteAverageLabel: UILabel! @IBOutlet var movieReleaseDateLabel: UILabel! @IBOutlet var moviePosterImageView: UIImageView! override func awakeFromNib() { super.awakeFromNib() accessoryType = .disclosureIndicator } private func setupCell(_ movie: Movie) { movieTitleLabel.text = movie.title movieVoteAverageLabel.text = String(movie.voteAverage ?? 0.0) movieReleaseDateLabel.text = movie.releaseDate cellViewModel?.getPosterImage() } func resetCell() { moviePosterImageView.image = UIImage(named: "placeholder") } } extension MovieCell: MovieCellViewModelDelegate { func didReceivePosterImage(_ image: UIImage?) { moviePosterImageView.image = image } } <file_sep>// // MovieDetailViewController.swift // RappiTest // // Created by <NAME> on 1/30/19. // Copyright © 2019 <NAME>. All rights reserved. // import UIKit final class MovieDetailViewController: UIViewController { let movie: Movie @IBOutlet var posterImageView: UIImageView! @IBOutlet var overviewTextView: UITextView! init(movie: Movie) { self.movie = movie super.init(nibName: nil, bundle: nil) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func viewDidLoad() { super.viewDidLoad() title = movie.title navigationItem.leftBarButtonItem = UIBarButtonItem(barButtonSystemItem: .done, target: self, action: #selector(dismissViewController)) overviewTextView.text = movie.overview posterImageView.image = movie.posterImage } @objc func dismissViewController() { dismiss(animated: true, completion: nil) } } <file_sep>// // RappiTestTests.swift // RappiTestTests // // Created by <NAME> on 1/28/19. // Copyright © 2019 <NAME>. All rights reserved. // import XCTest @testable import RappiTest class RappiTestTests: XCTestCase { var apiClient: ApiClientProtocol! override func setUp() { apiClient = ApiClient() } func testRequestMoviesForPopularSection() { let exp = expectation(description: "Request movies expectation") apiClient.requestMovies(for: .popular, atPage: 1) { result in switch result { case .failure(let error): XCTFail(error.localizedDescription) case .success(let value): XCTAssertNotNil(value.results.first) XCTAssertNotNil(value.results.first?.overview) XCTAssertNotNil(value.results.first?.title) XCTAssertNotNil(value.results.first?.posterPath) XCTAssertNotNil(value.results.first?.releaseDate) } exp.fulfill() } wait(for: [exp], timeout: 5) } func testRequestMoviesForTopRatedSection() { let exp = expectation(description: "Request movies expectation") apiClient.requestMovies(for: .topRated, atPage: 1) { result in switch result { case .failure(let error): XCTFail(error.localizedDescription) case .success(let value): XCTAssertNotNil(value.results.first) XCTAssertNotNil(value.results.first?.overview) XCTAssertNotNil(value.results.first?.title) XCTAssertNotNil(value.results.first?.posterPath) XCTAssertNotNil(value.results.first?.releaseDate) } exp.fulfill() } wait(for: [exp], timeout: 5) } func testRequestMoviesForUpcomingSection() { let exp = expectation(description: "Request movies expectation") apiClient.requestMovies(for: .upcoming, atPage: 1) { result in switch result { case .failure(let error): XCTFail(error.localizedDescription) case .success(let value): XCTAssertNotNil(value.results.first) XCTAssertNotNil(value.results.first?.overview) XCTAssertNotNil(value.results.first?.title) XCTAssertNotNil(value.results.first?.posterPath) XCTAssertNotNil(value.results.first?.releaseDate) } exp.fulfill() } wait(for: [exp], timeout: 5) } func testRequestImageForGivenPath() { let path = "/d4KNaTrltq6bpkFS01pYtyXa09m.jpg" let exp = expectation(description: "Request image for given path") let _ = apiClient.requestPosterImageWithPath(path) { result in switch result { case .failure(let error): XCTFail(error.localizedDescription) case .success(let value): XCTAssertTrue(value != UIImage(named: "placeholder")!) } exp.fulfill() } wait(for: [exp], timeout: 5) } } <file_sep>// // MovieRequest.swift // RappiTest // // Created by <NAME> on 1/29/19. // Copyright © 2019 <NAME>. All rights reserved. // import Foundation struct MovieRequest: Codable { let page: Int let totalResults: Int let totalPages: Int let results: [Movie] enum CodingKeys: String, CodingKey { case page case totalResults = "total_results" case totalPages = "total_pages" case results } }
979d6b2c01a84e4207210dcae59fd7bb124419d2
[ "Swift", "Markdown" ]
16
Swift
lugearma/RMovieTest
854277070cccd83cf497550429532454fe072587
85ce7542345b07e8db6534a827e20f7b31912fea
refs/heads/master
<repo_name>KMattis/Chess<file_sep>/Chess/MoveGenerator.cs using System; using System.Collections.Generic; using System.Linq; using System.Numerics; using System.Text; using static Chess.MoveHelper; namespace Chess { public class MoveGenerator { private Board board; //Mark where the pinned pieces are private ulong pinBitmask; private ulong rayCheckBitmask; public ulong opponentKnightAttackMap; public ulong opponentPawnAttackMap; public ulong opponentRayAttackMap; public ulong opponentKingAttackMap; public ulong opponentAttackMap; private ulong freeSquares; private ulong enemyPieces; private ulong friendlyPieces; private int ourKingSquare; public bool InCheck; public bool InDoubleCheck; public bool PinsExist; public MoveGenerator(Board board) { this.board = board; } private void Reset() { opponentKnightAttackMap = 0; opponentPawnAttackMap = 0; opponentRayAttackMap = 0; opponentKingAttackMap = 0; opponentAttackMap = 0; pinBitmask = 0; rayCheckBitmask = 0; InCheck = false; InDoubleCheck = false; PinsExist = false; ourKingSquare = board.pieceList[Piece.KING | board.Us][0]; } public void Setup() { Reset(); GenerateBitmasks(); } //Returns a list of all possible moves, not accounting for checks public IList<Move> GetMoves(bool onlyCaptures) { var moves = new List<Move>(64); //Add King moves AddKingMoves(moves, onlyCaptures); //if in double check: only king moves (excluding casteling) are legal if (InDoubleCheck) return moves; if (!InCheck) AddCastelingMoves(moves, ourKingSquare); var rooks = board.pieceList[Piece.ROOK | board.Us]; for(int i = 0; i < rooks.Count; i++) { AddRayMoves(moves, rooks[i], 0, 4, onlyCaptures); } var bishops = board.pieceList[Piece.BISHOP | board.Us]; for (int i = 0; i < bishops.Count; i++) { AddRayMoves(moves, bishops[i], 4, 8, onlyCaptures); } var queens = board.pieceList[Piece.QUEEN | board.Us]; for (int i = 0; i < queens.Count; i++) { AddRayMoves(moves, queens[i], 0, 8, onlyCaptures); } var knights = board.pieceList[Piece.KNIGHT | board.Us]; for (int i = 0; i < knights.Count; i++) { AddKnightMoves(moves, knights[i], onlyCaptures); } AddPawnMoves(moves, onlyCaptures); return moves; } private void AddRayMoves(IList<Move> moves, int start, int directionIndexStart, int directionIndexEnd, bool onlyCaptures) { bool isPinned = IsPinned(start); for(int direction = directionIndexStart; direction < directionIndexEnd; direction++) { if (isPinned && !IsMovingAlongRay(Directions[direction], start, ourKingSquare)) continue; for (int n = 1; n <= NumSquaresToEdge[start][direction]; n++) { var target = start + n * Directions[direction]; if ((board.board[target] & Piece.COLOR_MASK) == board.Us) break; bool isCapture = (board.board[target] & Piece.COLOR_MASK) == board.Them; if (!onlyCaptures || isCapture) { if (!InCheck || IsRayCheckSquare(target)) { moves.Add(new Move(start, target, board)); } } if (isCapture) break; } } } private bool IsMovingAlongRay(int rayDir, int startSquare, int targetSquare) { int moveDir = DirectionLookup[targetSquare - startSquare + 63]; return (rayDir == moveDir || -rayDir == moveDir); } private void AddPawnMoves(IList<Move> moves, bool onlyCaptures) { var pawnDirection = board.Us == Piece.WHITE ? Directions[N] : Directions[S]; var promotionRank = board.Us == Piece.WHITE ? 7 : 0; //one square moves var ourPawnsBitboard = board.Us == Piece.WHITE ? board.WhitePawnBitboard : board.BlackPawnBitboard; var pinnedPawns = pinBitmask & ourPawnsBitboard; if (!onlyCaptures) { var pseudoLegalSinglePawnMoveTargets = board.Us == Piece.WHITE ? BitboardUtilities.ShiftUp(ourPawnsBitboard) : BitboardUtilities.ShiftDown(ourPawnsBitboard); pseudoLegalSinglePawnMoveTargets &= freeSquares; var legalSinglePawnMoveTarget = pseudoLegalSinglePawnMoveTargets & rayCheckBitmask; while (legalSinglePawnMoveTarget != 0) { var targetSquare = BitOperations.TrailingZeroCount(legalSinglePawnMoveTarget); var startSquare = targetSquare - pawnDirection; legalSinglePawnMoveTarget ^= 1ul << targetSquare; if ((pinnedPawns & (1ul << startSquare)) != 0 && !IsMovingAlongRay(pawnDirection, startSquare, ourKingSquare)) { continue; } if (targetSquare / 8 == promotionRank) { moves.Add(new Move(startSquare, targetSquare, board).PromoteTo(Piece.QUEEN)); moves.Add(new Move(startSquare, targetSquare, board).PromoteTo(Piece.ROOK)); moves.Add(new Move(startSquare, targetSquare, board).PromoteTo(Piece.BISHOP)); moves.Add(new Move(startSquare, targetSquare, board).PromoteTo(Piece.KNIGHT)); } else { moves.Add(new Move(startSquare, targetSquare, board)); } } var doublePawnMoveTarget = board.Us == Piece.WHITE ? BitboardUtilities.ShiftUp(pseudoLegalSinglePawnMoveTargets) : BitboardUtilities.ShiftDown(pseudoLegalSinglePawnMoveTargets); doublePawnMoveTarget &= RankBitboards[board.Us == Piece.WHITE ? 3 : 4] & freeSquares & rayCheckBitmask; while (doublePawnMoveTarget != 0) { var targetSquare = BitOperations.TrailingZeroCount(doublePawnMoveTarget); var startSquare = targetSquare - 2 * pawnDirection; doublePawnMoveTarget ^= 1ul << targetSquare; if ((pinnedPawns & (1ul << startSquare)) != 0) { if (!IsMovingAlongRay(pawnDirection, startSquare, ourKingSquare)) { continue; } } moves.Add(new Move(startSquare, targetSquare, board).DoublePawnMove()); } } //Captures var upWest = Directions[board.Us == Piece.WHITE ? NW : SW]; var upEast = Directions[board.Us == Piece.WHITE ? NE : SE]; var enemyPiecesAndEnPassent = board.EnPassentSquare >= 0 ? enemyPieces | (1ul << board.EnPassentSquare) : enemyPieces; var captureUpWestTargets = board.Us == Piece.WHITE ? BitboardUtilities.ShiftUpLeft(ourPawnsBitboard) : BitboardUtilities.ShiftDownLeft(ourPawnsBitboard); captureUpWestTargets &= enemyPiecesAndEnPassent & rayCheckBitmask; var captureUpEastTargets = board.Us == Piece.WHITE ? BitboardUtilities.ShiftUpRight(ourPawnsBitboard) : BitboardUtilities.ShiftDownRight(ourPawnsBitboard); captureUpEastTargets &= enemyPiecesAndEnPassent & rayCheckBitmask; while(captureUpWestTargets != 0) { var targetSquare = BitOperations.TrailingZeroCount(captureUpWestTargets); var startSquare = targetSquare - upWest; captureUpWestTargets ^= 1ul << targetSquare; if ((pinnedPawns & (1ul << startSquare)) != 0 && !IsMovingAlongRay(upWest, startSquare, ourKingSquare)) { continue; } if (targetSquare / 8 == promotionRank) { moves.Add(new Move(startSquare, targetSquare, board).PromoteTo(Piece.QUEEN)); moves.Add(new Move(startSquare, targetSquare, board).PromoteTo(Piece.ROOK)); moves.Add(new Move(startSquare, targetSquare, board).PromoteTo(Piece.BISHOP)); moves.Add(new Move(startSquare, targetSquare, board).PromoteTo(Piece.KNIGHT)); } else { var move = new Move(startSquare, targetSquare, board); if (targetSquare == board.EnPassentSquare) move.EnPassent(); moves.Add(move); } } while (captureUpEastTargets != 0) { var targetSquare = BitOperations.TrailingZeroCount(captureUpEastTargets); var startSquare = targetSquare - upEast; captureUpEastTargets ^= 1ul << targetSquare; if ((pinnedPawns & (1ul << startSquare)) != 0 && !IsMovingAlongRay(upEast, startSquare, ourKingSquare)) { continue; } if (targetSquare / 8 == promotionRank) { moves.Add(new Move(startSquare, targetSquare, board).PromoteTo(Piece.QUEEN)); moves.Add(new Move(startSquare, targetSquare, board).PromoteTo(Piece.ROOK)); moves.Add(new Move(startSquare, targetSquare, board).PromoteTo(Piece.BISHOP)); moves.Add(new Move(startSquare, targetSquare, board).PromoteTo(Piece.KNIGHT)); } else { var move = new Move(startSquare, targetSquare, board); if (targetSquare == board.EnPassentSquare) move.EnPassent(); moves.Add(move); } } } private void AddKnightMoves(IList<Move> moves, int start, bool onlyCaptures) { if (IsPinned(start)) return; //Pinned knights cannot move for(int i = 0; i < KnightMoves[start].Length; i++) { var target = KnightMoves[start][i]; if (!InCheck || IsRayCheckSquare(target)) { //If InCheck, we might only move to a ray check square var color = board.board[target] & Piece.COLOR_MASK; if (color != board.Us) if (!onlyCaptures || color == board.Them) moves.Add(new Move(start, target, board)); } } } private void AddKingMoves(IList<Move> moves, bool onlyCaptures) { //targets are king moves which are not under a attack and not a friendly piece var targets = KingAttackBitboards[ourKingSquare] & ~friendlyPieces & ~opponentAttackMap; while(targets != 0) { var target = BitOperations.TrailingZeroCount(targets); targets ^= 1ul << target; moves.Add(new Move(ourKingSquare, target, board)); } } private void AddCastelingMoves(IList<Move> moves, int start) { const int B1 = 1; const int C1 = 2; const int D1 = 3; const int E1 = 4; const int F1 = 5; const int G1 = 6; const int B8 = B1 + 7 * 8; const int C8 = C1 + 7 * 8; const int D8 = D1 + 7 * 8; const int E8 = E1 + 7 * 8; const int F8 = F1 + 7 * 8; const int G8 = G1 + 7 * 8; if (board.Us == Piece.WHITE) { if((board.CastelingRights & Board.WHITE_KINGSIDE_CASTLE) != 0) { //White Kingside casteling allowed, hence the King is on e1. //We need to check if f1 and g1 are free and not attacked if(board.board[F1] == Piece.NONE && board.board[G1] == Piece.NONE && (opponentAttackMap & 1ul<<F1) == 0 && (opponentAttackMap & 1ul<<G1) == 0) { moves.Add(new Move(E1, G1, board).Casteling()); } } if((board.CastelingRights & Board.WHITE_QUEENSIDE_CASTLE) != 0) { if (board.board[D1] == Piece.NONE && board.board[C1] == Piece.NONE && board.board[B1] == Piece.NONE && (opponentAttackMap & 1ul << D1) == 0 && (opponentAttackMap & 1ul << C1) == 0) { moves.Add(new Move(E1, C1, board).Casteling()); } } } else { if ((board.CastelingRights & Board.BLACK_KINGSIDE_CASTLE) != 0) { if (board.board[F8] == Piece.NONE && board.board[G8] == Piece.NONE && (opponentAttackMap & 1ul << F8) == 0 && (opponentAttackMap & 1ul << G8) == 0) { moves.Add(new Move(E8, G8, board).Casteling()); } } if ((board.CastelingRights & Board.BLACK_QUEENSIDE_CASTLE) != 0) { if (board.board[D8] == Piece.NONE && board.board[C8] == Piece.NONE && board.board[B8] == Piece.NONE && (opponentAttackMap & 1ul << D8) == 0 && (opponentAttackMap & 1ul << C8) == 0) { moves.Add(new Move(E8, C8, board).Casteling()); } } } } private void GenerateRayAttackMap() { var rooks = board.pieceList[board.Them | Piece.ROOK]; for(int i = 0; i < rooks.Count; i++) { GenRayAttackMapForPiece(rooks[i], 0, 4); } var queens = board.pieceList[board.Them | Piece.QUEEN]; for(int i = 0; i < queens.Count; i++) { GenRayAttackMapForPiece(queens[i], 0, 8); } var bishops = board.pieceList[board.Them | Piece.BISHOP]; for(int i = 0; i < bishops.Count; i++) { GenRayAttackMapForPiece(bishops[i], 4, 8); } } void GenRayAttackMapForPiece(int start, int startDirIndex, int endDirIndex) { //Ray attacks can see through kings to help with determining king moves for (int directionIndex = startDirIndex; directionIndex < endDirIndex; directionIndex++) { for (int n = 1; n <= NumSquaresToEdge[start][directionIndex]; n++) { int target = start + Directions[directionIndex] * n; opponentRayAttackMap |= 1ul << target; if (target != ourKingSquare) { if (board.board[target] != Piece.NONE) { break; } } } } } private void GenerateBitmasks() { enemyPieces = board.Us == Piece.WHITE ? board.BlackPawnBitboard | board.BlackPiecesBitboard : board.WhitePawnBitboard | board.WhitePiecesBitboard; friendlyPieces = board.Us == Piece.WHITE ? board.WhitePawnBitboard | board.WhitePiecesBitboard : board.BlackPawnBitboard | board.BlackPiecesBitboard; freeSquares = ~(enemyPieces | friendlyPieces); GenerateRayAttackMap(); int startDirIndex = 0, endDirIndex = 8; if(board.pieceList[Piece.QUEEN | board.Them].Count == 0) { startDirIndex = board.pieceList[Piece.ROOK | board.Them].Count > 0 ? 0 : 4; endDirIndex = board.pieceList[Piece.BISHOP | board.Them].Count > 0 ? 8 : 4; } for(int dirIndex = startDirIndex; dirIndex < endDirIndex; dirIndex++) { bool isDiagonal = dirIndex > 3; bool isFriendlyPieceAlongRay = false; ulong rayBitmask = 0; for (int n = 1; n <= NumSquaresToEdge[ourKingSquare][dirIndex]; n++) { var target = ourKingSquare + Directions[dirIndex] * n; rayBitmask |= 1ul << target; var piece = board.board[target]; if(piece != Piece.NONE) { if((piece & Piece.COLOR_MASK) == board.Us) { //Friendly piece if (!isFriendlyPieceAlongRay) isFriendlyPieceAlongRay = true; else //Second friendly piece, no pins break; } else { //enemy piece, lookup its attack direction var type = Piece.PIECE_MASK & piece; if((isDiagonal && (type == Piece.QUEEN || type == Piece.BISHOP)) || (!isDiagonal && (type == Piece.QUEEN || type == Piece.ROOK))) { //Can attack (excluding pawns for checks) if (isFriendlyPieceAlongRay) { //pin pinBitmask |= rayBitmask; PinsExist = true; } else { //Check rayCheckBitmask |= rayBitmask; InDoubleCheck = InCheck; InCheck = true; } } break; } } } if (InDoubleCheck) break; //No need to search for pins, as only the king can move in double Check } //knight moves var knights = board.pieceList[Piece.KNIGHT | board.Them]; for (int i = 0; i < knights.Count; i++) { var knightSquare = knights[i]; opponentKnightAttackMap |= KnightBitboards[knightSquare]; if (((1ul << ourKingSquare) & opponentKnightAttackMap) != 0) { //Knight check rayCheckBitmask |= 1ul << knightSquare; InDoubleCheck = InCheck; InCheck = true; } } var pawns = board.pieceList[Piece.PAWN | board.Them]; for(int i = 0; i < pawns.Count; i++) { var pawnSquare = pawns[i]; opponentPawnAttackMap |= PawnAttackBitboards[board.Them][pawnSquare]; if (((1ul << ourKingSquare) & opponentPawnAttackMap) != 0) { //Pawn check rayCheckBitmask |= 1ul << pawnSquare; InDoubleCheck = InCheck; InCheck = true; } } if (!InCheck) rayCheckBitmask = ~0ul; //Every square "blocks the checks" opponentKingAttackMap = KingAttackBitboards[board.pieceList[board.Them | Piece.KING][0]]; opponentAttackMap = opponentKingAttackMap | opponentKnightAttackMap | opponentRayAttackMap | opponentPawnAttackMap; } private bool IsPinned(int square) { return PinsExist && (pinBitmask & 1ul << square) != 0; } private bool IsRayCheckSquare(int square) { return (rayCheckBitmask & 1ul << square) != 0; } } } <file_sep>/ChessTests/BasicMoveTests.cs using NUnit.Framework; using System; using System.Collections.Generic; using System.IO; using System.Linq; namespace Chess.Tests { public class BasicMoveTests { public static IDictionary<string, int> positionToLegalMoves = new Dictionary<string, int> { { "7k/8/8/4K3/8/8/8/8 w -", 8 }, { "7k/8/8/K7/8/8/8/8 w -", 5 }, { "7k/8/8/8/8/8/8/K7 w -", 3 }, { "7k/8/8/4R3/8/8/8/7K w -", 17 }, { "7k/8/8/R7/8/8/8/7K w -", 17 }, { "7k/8/8/7K/8/8/8/R7 w -", 19 }, { "4k3/8/8/4B3/8/8/8/4K3 w -", 18 }, { "7k/8/8/B7/8/8/8/7K w -", 10 }, { "7K/8/7k/8/8/8/8/7B w -", 8 }, }; public static IDictionary<string, int[]> positions = new Dictionary<string, int[]> { { "7K/P7/8/8/8/8/8/7k w - 0 1", new int[]{ 7, 19, 219, 1073, 15841 } }, { "rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1", new int[]{20, 400, 8902, 197281, 4865609 } }, { "rnQq1k1r/pp2bppp/2p5/8/2B5/8/PPP1NnPP/RNBQK2R b KQ - 1 9", new int[]{31, 1459, 44226, 2106366 } }, { "rnbq1k1r/pp1Pbppp/2p5/8/2B5/8/PPP1NnPP/RNBQK2R w KQ - 1 8", new int[]{44, 1486, 62379, 2103487, 89941194 } }, }; public StreamWriter Debug; [SetUp] public void SetUp() { Debug = new StreamWriter(new FileStream("debug.log", FileMode.Create)); } [TearDown] public void TearDown() { Debug.Flush(); Debug.Close(); } [Test] public void TestBasicMoves() { foreach((string pos, int moves) in positionToLegalMoves) { Assert.AreEqual(moves, CountLegalMoves(pos, 1)); } } [Test] public void TestPerftPositions() { foreach((string pos, int[] movesPerDepth) in positions) { for(int depth = 0; depth < movesPerDepth.Length; depth++) { Assert.AreEqual(movesPerDepth[depth], CountLegalMoves(pos, depth + 1)); } } } public int CountLegalMoves(string startingPosition, int depth) { var board = new Board(startingPosition); Debug.WriteLine("Beginning Counting Moves to depth " + depth + " in position " + startingPosition); Debug.Flush(); return CountLegalMoves(board, depth); } public int CountLegalMoves(Board board, int depth) { if (depth == 0) return 1; var count = 0; var generator = new MoveGenerator(board); generator.Setup(); foreach(var move in generator.GetMoves(false)) { board.SubmitMove(move); count += CountLegalMoves(board, depth - 1); board.UndoMove(); } if (board.states.Count == 1) Debug.WriteLine($"depth: {board.states.Count}, count: {count}, after {board.states.Peek().lastMove.ToAlgebraicNotation()}"); return count; } } }<file_sep>/ChessTests/BitboardTests.cs using NUnit.Framework; using System; using System.Collections.Generic; using System.Linq; using System.Numerics; using System.Text; using System.Threading.Tasks; namespace Chess.Tests { [TestFixture] public class BitboardTests { [Test] public void TestBitboardShiftLeft() { var square1 = 5 * 8 + 7; var square2 = 3 * 8 + 4; var square3 = 4 * 8; ulong bitboard = (1ul << square1) | (1ul << square2) | (1ul << square3); ulong shiftedLeft = BitboardUtilities.ShiftLeft(bitboard); Assert.AreEqual(2, BitOperations.PopCount(shiftedLeft)); Assert.AreEqual(3 * 8 + 3, BitOperations.TrailingZeroCount(shiftedLeft)); shiftedLeft ^= 1ul << 3 * 8 + 3; Assert.AreEqual(5 * 8 + 6, BitOperations.TrailingZeroCount(shiftedLeft)); } [Test] public void TestBitboardShiftRight() { var square1 = 5 * 8 + 7; var square2 = 3 * 8 + 4; var square3 = 4 * 8; ulong bitboard = (1ul << square1) | (1ul << square2) | (1ul << square3); ulong shiftedRight = BitboardUtilities.ShiftRight(bitboard); Assert.AreEqual(2, BitOperations.PopCount(shiftedRight)); Assert.AreEqual(3 * 8 + 5, BitOperations.TrailingZeroCount(shiftedRight)); shiftedRight ^= 1ul << 3 * 8 + 5; Assert.AreEqual(4 * 8 + 1, BitOperations.TrailingZeroCount(shiftedRight)); } } } <file_sep>/Chess/Evaluation.cs using System; using System.Collections.Generic; using System.Numerics; using System.Text; namespace Chess { public static class Evaluation { public const int PawnValue = 100; public const int KnightValue = 325; public const int BishopValue = 325; public const int RookValue = 550; public const int QueenValue = 1000; public static int[] PawnPositionTable = { 0, 0, 0, 0, 0, 0, 0, 0, 10, 10,-10,-30,-30,-10, 10, 10, 0, 10, 10, 20, 20, 10, 10, 0, 0, 0, 20, 30, 30, 20, 0, 0, 5, 5, 5, 10, 10, 5, 5, 5, 10, 10, 10, 10, 10, 10, 10, 10, 30, 30, 30, 30, 30, 30, 30, 30, 0, 0, 0, 0, 0, 0, 0, 0, }; public static int[] RookPositionTable = { 0, 0, 0, 20, 20, 0, 0, 0, 0, 0, 0, 20, 20, 0, 0, 0, 0, 0, 0, 20, 20, 0, 0, 0, 0, 0, 0, 20, 20, 0, 0, 0, 0, 0, 0, 20, 20, 0, 0, 0, 0, 0, 0, 20, 20, 0, 0, 0, 25, 25, 25, 25, 25, 25, 25, 25, 0, 0, 0, 20, 20, 0, 0, 0, }; public static int[] KnightPositionTable = { -20, -20, -10, -10, -10, -10, -20, -20, -10, -5, 0, 0, 0, 0, -5, -10, -10, 0, 20, 10, 10, 20, 0, -10, -10, 0, 10, 10, 10, 10, 0, -10, -10, 0, 10, 10, 10, 10, 0, -10, -10, 0, 20, 10, 10, 20, 0, -10, -10, -5, 0, 0, 0, 0, -5, -10, -20, -10, -10, -10, -10, -10, -10, -20, }; public static int[] BishopPositionTable = { -20, -20, -20, 0, 0, -20, -20, -20, -10, 5, 0, 5, 5, 0, 5, -10, -5, 0, 5, 10, 10, 5, 0, -5, 0, 5, 10, 20, 20, 10, 5, 0, 0, 5, 10, 20, 20, 10, 5, 0, -5, 0, 5, 10, 10, 5, 0, -5, -10, -5, 0, 5, 5, 0, -5, -10, -20, -10, -5, 0, 0, -5, -10, -20, }; public static int[] KingPositionTable = //King Safety { 30, 20, -10, -30, -30, 0, 20, 30, 10, 10, -80, -80, -80, -80, 10, 10, -80, -80, -80, -80, -80, -80, -80, -80, -80, -80, -80, -80, -80, -80, -80, -80, -80, -80, -80, -80, -80, -80, -80, -80, -80, -80, -80, -80, -80, -80, -80, -80, -80, -80, -80, -80, -80, -80, -80, -80, -80, -80, -80, -80, -80, -80, -80, -80, }; public static int[] Mirror = { 56, 57, 58, 59, 60, 61, 62, 63, 48, 49, 50, 51, 52, 53, 54, 55, 40, 41, 42, 43, 44, 45, 46, 47, 32, 33, 34, 35, 36, 37, 38, 39, 24, 25, 26, 27, 28, 29, 30, 31, 16, 17, 18, 19, 20, 21, 22, 23, 8, 9, 10, 11, 12, 13, 14, 15, 0, 1, 2, 3, 4, 5, 6, 7, }; public static int[][] PositionTables = new int[32][]; public static int[] PieceValues = new int[32]; public static int[] PieceValues_ColorIndependent = new int[32]; public static int BishopPairScore = 35; //[isOpenSelf][isOpenOpponent] (0 = isOpen, 1 = isClosed) public static int[][] RookFileScores = { new int[]{ 25, 15 }, new int[]{ 5, -10 } }; public static int DoubledRookBonus = 30; public static int IsolatedPawnBonus = -20; public static int[] PassedPawnBonus = new int[] { 0, 22, 33, 44, 55, 77, 88, 0 }; //Per rank public static int BishopClosednessPenalty = -1; //-1 per pawn public static int PawnShieldBonus = 40; public static IDictionary<ulong, int> MaterialDatabase = new Dictionary<ulong, int>(); //TODO: Clear database regularily? static Evaluation() { //Setup piece Values PieceValues[Piece.WHITE | Piece.QUEEN ] = QueenValue; PieceValues[Piece.WHITE | Piece.ROOK ] = RookValue; PieceValues[Piece.WHITE | Piece.KNIGHT] = KnightValue; PieceValues[Piece.WHITE | Piece.BISHOP] = BishopValue; PieceValues[Piece.WHITE | Piece.PAWN ] = PawnValue; PieceValues[Piece.BLACK | Piece.QUEEN ] = - QueenValue; PieceValues[Piece.BLACK | Piece.ROOK ] = - RookValue; PieceValues[Piece.BLACK | Piece.KNIGHT] = -KnightValue; PieceValues[Piece.BLACK | Piece.BISHOP] = -BishopValue; PieceValues[Piece.BLACK | Piece.PAWN ] = - PawnValue; foreach (var pieceType in Piece.PIECE_TYPES) { PieceValues_ColorIndependent[pieceType] = Math.Abs(PieceValues[pieceType]); PieceValues_ColorIndependent[pieceType & Piece.PIECE_MASK] = PieceValues_ColorIndependent[pieceType]; } //Setup position tables foreach (var pieceType in Piece.PIECE_TYPES) { PositionTables[pieceType] = new int[64]; var color = Piece.COLOR_MASK & pieceType; for(int i = 0; i < 64; i++) { var square = color == Piece.WHITE ? i : Mirror[i]; switch (pieceType & Piece.PIECE_MASK) { case Piece.PAWN: PositionTables[pieceType][i] = PawnPositionTable[square]; break; case Piece.ROOK: PositionTables[pieceType][i] = RookPositionTable[square]; break; case Piece.KNIGHT: PositionTables[pieceType][i] = KnightPositionTable[square]; break; case Piece.BISHOP: PositionTables[pieceType][i] = BishopPositionTable[square]; break; case Piece.KING: PositionTables[pieceType][i] = KingPositionTable[square]; break; default: break; } } } } private static int ProbeMaterial(Board board) { if (MaterialDatabase.ContainsKey(board.materialKey)) return MaterialDatabase[board.materialKey]; //Basic material counting var score = CountMaterial(board); var whitePawnsCount = board.pieceList[Piece.WHITE | Piece.PAWN].Count; var blackPawnsCount = board.pieceList[Piece.BLACK | Piece.PAWN].Count; //Bishop pair bonus if (board.pieceList[Piece.WHITE | Piece.BISHOP].Count >= 2) score += BishopPairScore; if (board.pieceList[Piece.BLACK | Piece.BISHOP].Count >= 2) score -= BishopPairScore; //Bishop Closedness Penalty score += board.pieceList[Piece.WHITE | Piece.BISHOP].Count * (whitePawnsCount * 2 + blackPawnsCount) * BishopClosednessPenalty; score -= board.pieceList[Piece.BLACK | Piece.BISHOP].Count * (blackPawnsCount * 2 + whitePawnsCount) * BishopClosednessPenalty; MaterialDatabase.Add(board.materialKey, score); return score; } public static int Evaluate(Board board) { var preference = board.Us == Piece.WHITE ? 1 : -1; var whitePawns = board.pieceList[Piece.WHITE | Piece.PAWN]; var blackPawns = board.pieceList[Piece.BLACK | Piece.PAWN]; var score = ProbeMaterial(board); var positionValues = new int[] { 0, 0 }; for(int pieceTypeIndex = 0; pieceTypeIndex < Piece.PIECE_TYPES.Length; pieceTypeIndex++) { var pieceType = Piece.PIECE_TYPES[pieceTypeIndex]; var color = Piece.COLOR_MASK & pieceType; var colorBit = color == Piece.WHITE ? 0 : 1; for(int pieceIndex = 0; pieceIndex < board.pieceList[pieceType].Count; pieceIndex++) { positionValues[colorBit] += PositionTables[pieceType][board.pieceList[pieceType][pieceIndex]]; } } score += positionValues[0] - positionValues[1]; //Pawn Scores int whitePawnScore = 0; int blackPawnScore = 0; for (int i = 0; i < whitePawns.Count; i++) { var pawnSquare = whitePawns[i]; var pawnFile = pawnSquare % 8; if ((MoveHelper.IsolatedPawnBitboards[pawnFile] & board.WhitePawnBitboard) == 0) //Isolated pawn whitePawnScore += IsolatedPawnBonus; if ((MoveHelper.PassedPawnBitboards[pawnFile] & board.BlackPawnBitboard) == 0) //Passed pawn whitePawnScore += PassedPawnBonus[pawnSquare / 8]; } for (int i = 0; i < blackPawns.Count; i++) { var pawnSquare = blackPawns[i]; var pawnFile = pawnSquare % 8; if ((MoveHelper.IsolatedPawnBitboards[pawnFile] & board.BlackPawnBitboard) == 0) //Isolated pawn blackPawnScore += IsolatedPawnBonus; if ((MoveHelper.PassedPawnBitboards[pawnFile] & board.WhitePawnBitboard) == 0) //Passed pawn blackPawnScore += PassedPawnBonus[7 - pawnSquare / 8]; } score += whitePawnScore - blackPawnScore; //Rook-Pawn Scores int whiteRookPawnScore = 0; int blackRookPawnScore = 0; int f0 = -1; for(int i = 0; i < board.pieceList[Piece.WHITE | Piece.ROOK].Count; i++) { var rookSquare = board.pieceList[Piece.WHITE | Piece.ROOK][i]; var rookFile = rookSquare % 8; if (rookFile == f0) { whiteRookPawnScore += DoubledRookBonus; //Does not work if there are more than 2 rooks } f0 = rookFile; bool isOpenWhite = (MoveHelper.FileBitboards[rookFile] & board.WhitePawnBitboard) == 0; bool isOpenBlack = (MoveHelper.FileBitboards[rookFile] & board.BlackPawnBitboard) == 0; whiteRookPawnScore += RookFileScores[isOpenWhite ? 0 : 1][isOpenBlack ? 0 : 1]; } f0 = -1; for (int i = 0; i < board.pieceList[Piece.BLACK | Piece.ROOK].Count; i++) { var rookSquare = board.pieceList[Piece.BLACK | Piece.ROOK][i]; var rookFile = rookSquare % 8; if (rookFile == f0) { blackRookPawnScore += DoubledRookBonus; //Does not work if there are more than 2 rooks } f0 = rookFile; bool isOpenWhite = (MoveHelper.FileBitboards[rookFile] & board.WhitePawnBitboard) == 0; bool isOpenBlack = (MoveHelper.FileBitboards[rookFile] & board.BlackPawnBitboard) == 0; blackRookPawnScore += RookFileScores[isOpenBlack ? 0 : 1][isOpenWhite ? 0 : 1]; } score += whiteRookPawnScore - blackRookPawnScore; var whiteKingSquare = board.pieceList[Piece.WHITE | Piece.KING][0]; var blackKingSquare = board.pieceList[Piece.BLACK | Piece.KING][0]; var whiteKingOnFlank = whiteKingSquare % 8 <= 2 || whiteKingSquare % 8 >= 6; var blackKingOnFlank = blackKingSquare % 8 <= 2 || blackKingSquare % 8 >= 6; var whiteKingPawnShield = whiteKingOnFlank ? BitOperations.PopCount(board.WhitePawnBitboard & MoveHelper.KingAttackBitboards[whiteKingSquare]) : 0; var blackKingPawnShield = blackKingOnFlank ? BitOperations.PopCount(board.BlackPawnBitboard & MoveHelper.KingAttackBitboards[blackKingSquare]) : 0; score += (whiteKingPawnShield - blackKingPawnShield) * PawnShieldBonus; return preference * score; } public static int CountMaterial(Board board) { var count = 0; for(int pieceTypeIndex = 0; pieceTypeIndex < Piece.PIECE_TYPES.Length; pieceTypeIndex++) { var pieceType = Piece.PIECE_TYPES[pieceTypeIndex]; count += PieceValues[pieceType] * board.pieceList[pieceType].Count; } return count; } } } <file_sep>/Chess/AI.cs using System; using System.Collections.Generic; using System.Globalization; using System.Linq; using System.Text; namespace Chess { public class SearchInfo { public int Depth { get; set; } public int Score { get; set; } public Move[] PV { get; set; } public int Nodes { get; set; } public int NullMoves { get; set; } public int NullMovesSuccess { get; set; } public int BetaCutoffs { get; set; } public int QNodes { get; set; } public int FutilityPrunes { get; set; } public int ScoutRemovals { get; set; } public int Scouts { get; set; } public int Transpositions { get; set; } public int MCPrunes { get; set; } public IDictionary<Move, int> TopLevelMoveOrder { get; set; } = new Dictionary<Move, int>(); } public enum TranspositionEntryType { Exact, UpperBound, LowerBound } //TODO Safe pv in TT public class TranspositionEntry { public int Score; public TranspositionEntryType Type; } public class AI { public const int INFINITY = 1000000; public const int CHECKMATE = 100000; public const int CHECKMATE_TRESHOLD = CHECKMATE - 1000; public const int DRAW = 0; public const int LookupFailed = int.MinValue; public const int R = 2; public const int MC_M = 6; public const int MC_C = 3; public const int MC_R = 3; private Board board; private MoveGenerator generator; private IDictionary<ulong, TranspositionEntry> transpositions = new Dictionary<ulong, TranspositionEntry>(); private SearchInfo searchInfo; Move[] lastpv; private Move[][] KillerMoves; public AI(Board board) { this.board = board; generator = new MoveGenerator(board); KillerMoves = new Move[1024][]; for (int i = 0; i < 1024; i++) { KillerMoves[i] = new Move[3]; } } private int GetKillerMoveValue(Move move) { for(int i = 0; i < 3; i++) { var killer = KillerMoves[board.Ply][i]; if (killer == null) return 0; if (killer.Start == move.Start && killer.Target == move.Target) return (3-i) * 1000000; } return 0; } private int MoveImportance(Move move, int depth, IDictionary<Move, int> ordering) { //if (ordering != null) // return ordering[move]; var pvMove = lastpv == null ? null : searchInfo.Depth - depth >= lastpv.Length ? null : depth < 0 ? null : lastpv[searchInfo.Depth - depth]; var pvValue = pvMove == null ? 0 : (pvMove.Start == move.Start && pvMove.Target == move.Target) ? 10000000 : 0; var killerValue = GetKillerMoveValue(move); var captureValue = -Evaluation.PieceValues_ColorIndependent[move.MovedPiece] * 100 + 1000 * Evaluation.PieceValues_ColorIndependent[move.CapturedPiece]; var promotionValue = Evaluation.PieceValues_ColorIndependent[move.Promotion]; var pawnCapturePenalty = (generator.opponentPawnAttackMap & 1ul << move.Target) != 0 ? -10 : 0; return killerValue + pvValue + captureValue + promotionValue + pawnCapturePenalty; } public SearchInfo FindBestMove(int depth, Move[] lastpv, int startAlpha, int startBeta, IDictionary<Move, int> lastTopLevelMoveOrder, bool resetTranpositionTable) { if (resetTranpositionTable) { transpositions.Clear(); } var pv = new Move[depth]; this.lastpv = lastpv; this.searchInfo = new SearchInfo { Depth = depth }; var score = DeepEval(depth, startAlpha, startBeta, false, pv, lastTopLevelMoveOrder); searchInfo.Score = score; searchInfo.PV = pv; return searchInfo; } private int LookupEvaluation(int alpha, int beta) { //TODO account for depth var transposition = transpositions[board.positionKey]; if (transposition.Type == TranspositionEntryType.Exact) { return transposition.Score; } if (transposition.Type == TranspositionEntryType.UpperBound && transposition.Score <= alpha) { return transposition.Score; } if (transposition.Type == TranspositionEntryType.LowerBound && transposition.Score >= beta) { return transposition.Score; } return LookupFailed; } private void StoreEvaluation(int score, TranspositionEntryType type) { if (!transpositions.ContainsKey(board.positionKey)) transpositions.Add(board.positionKey, new TranspositionEntry { Score = score, Type = type }); else if(type == TranspositionEntryType.Exact) //We have a better evaluation { transpositions[board.positionKey] = new TranspositionEntry { Score = score, Type = type }; } } //ZW search with multicut private int ZWSerach(int depth, int beta, bool cut = true, bool nullMoveAllowed= true) { searchInfo.Nodes++; generator.Setup(); var moves = generator.GetMoves(false); if (transpositions.ContainsKey(board.positionKey)) { searchInfo.Transpositions++; var score = LookupEvaluation(beta-1, beta); if (score != LookupFailed) return score; } if (!moves.Any()) { //When in Check: Checkmate: if (generator.InCheck) { return beta - 1; } else //Stalemate { if (0 >= beta) return beta; else return beta - 1; } } else if (board.states.Any(s => s.positionKey == board.positionKey)) { //Repetition if (0 >= beta) return beta; else return beta - 1; } if (depth <= 0) { return QuiesceneSearch(beta-1, beta); } if (depth == 1) { //Futility pruning var currentEval = Evaluation.Evaluate(board); if (currentEval + Evaluation.BishopValue < beta-1) { searchInfo.FutilityPrunes++; //Prune this node, i.e. go directly to QuiesceneSearch return QuiesceneSearch(beta-1, beta); } } if (nullMoveAllowed && !generator.InCheck && depth >= 1 + R) { searchInfo.NullMoves++; //Null move pruning board.SubmitNullMove(); int eval = -ZWSerach(depth - 1 - R, 1-beta, cut, false); board.UndoNullMove(); if (eval >= beta) { searchInfo.NullMovesSuccess++; return beta; } } var orderedMoves = moves.OrderByDescending(m => MoveImportance(m, depth, null)).ToList(); var moveIndex = 0; if (depth >= MC_R && cut) { int c = 0; for(int m = 0; m < MC_M && moveIndex < orderedMoves.Count; m++) { board.SubmitMove(orderedMoves[moveIndex]); int eval = -ZWSerach(depth - 1 - MC_R, 1 - beta, !cut, true); board.UndoMove(); moveIndex++; if (eval >= beta) { c++; if (c == MC_C) { searchInfo.MCPrunes++; return beta; // mc-prune } } } } for (moveIndex = 0; moveIndex < orderedMoves.Count; moveIndex++) { board.SubmitMove(orderedMoves[moveIndex]); int eval = -ZWSerach(depth - 1, 1 - beta, !cut, true); board.UndoMove(); if (eval >= beta) { return beta; } } return beta - 1; } private int DeepEval(int depth, int alpha, int beta, bool nullMoveAllowed, Move[] pv, IDictionary<Move, int> orderedTopLevelMoves = null) { searchInfo.Nodes++; if (transpositions.ContainsKey(board.positionKey)) { searchInfo.Transpositions++; var score = LookupEvaluation(alpha, beta); if (score != LookupFailed) return score; } generator.Setup(); var moves = generator.GetMoves(false); if (!moves.Any()) { //When in Check: Checkmate: if (generator.InCheck) { //Compute checkmate score: var currentDepth = board.states.Count; //TODO add ply variable to board return -CHECKMATE + currentDepth; } else //Stalemate return DRAW; } else if(board.states.Any(s => s.positionKey == board.positionKey)) { //Repetition return DRAW; } //TODO Add 50 moves rule if (depth == 0) { return QuiesceneSearch(alpha, beta); } if(depth == 1) { //Futility pruning var currentEval = Evaluation.Evaluate(board); if(currentEval + Evaluation.BishopValue < alpha) { searchInfo.FutilityPrunes++; //Prune this node, i.e. go directly to QuiesceneSearch return QuiesceneSearch(alpha, beta); } } if(nullMoveAllowed && !generator.InCheck && depth >= 1 + R) { searchInfo.NullMoves++; //Null move pruning var npv = new Move[depth]; //irellevant here board.SubmitNullMove(); int eval = -DeepEval(depth - 1 - R, -beta, -beta+1, false, npv); board.UndoNullMove(); if (eval >= beta) { searchInfo.NullMovesSuccess++; return eval; } } TranspositionEntryType ttType = TranspositionEntryType.UpperBound; int movenumber = 1; bool searchPV = true; foreach (var move in moves.OrderByDescending(m => MoveImportance(m, depth, orderedTopLevelMoves))) { if (depth == searchInfo.Depth) //Upper level { Console.WriteLine($"info currmove {move.ToAlgebraicNotation()} currmovenumber {movenumber++} depth {depth}"); } var npv = new Move[depth-1]; board.SubmitMove(move); int eval; if (searchPV) { eval = -DeepEval(depth - 1, -beta, -alpha, true, npv); } else { searchInfo.Scouts++; //Scout zw search eval = -ZWSerach(depth - 1 , -alpha); if (eval > alpha) { eval = -DeepEval(depth - 1, -beta, -alpha, true, npv); // re-search } else { searchInfo.ScoutRemovals++; } } board.UndoMove(); if(depth == searchInfo.Depth) { searchInfo.TopLevelMoveOrder.Add(move, eval); } if (eval >= beta) { searchInfo.BetaCutoffs++; //transposition is an upper bound StoreEvaluation(eval, TranspositionEntryType.LowerBound); if (move.CapturedPiece == Piece.NONE) { KillerMoves[board.Ply][2] = KillerMoves[board.Ply][1]; KillerMoves[board.Ply][1] = KillerMoves[board.Ply][0]; KillerMoves[board.Ply][0] = move; } return beta; } else if (eval > alpha) { alpha = eval; searchPV = false; pv[0] = move; Array.Copy(npv, 0, pv, 1, npv.Length); ttType = TranspositionEntryType.Exact; } } StoreEvaluation(alpha, ttType); return alpha; } private int QuiesceneSearch(int alpha, int beta) { searchInfo.Nodes++; searchInfo.QNodes++; int currentEval = Evaluation.Evaluate(board); if(currentEval >= beta) { searchInfo.BetaCutoffs++; return beta; } if(currentEval > alpha) { alpha = currentEval; } generator.Setup(); var moves = generator.GetMoves(true); foreach (var move in moves.OrderByDescending(m => MoveImportance(m, -1, null))) { board.SubmitMove(move); var eval = -QuiesceneSearch(-beta, -alpha); board.UndoMove(); if (eval >= beta) { searchInfo.BetaCutoffs++; return beta; } if(eval > alpha) { alpha = eval; } } return alpha; } } } <file_sep>/Chess/ZobristKey.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Chess { public static class ZobristKey { private static ulong[][] pieceSquareData = new ulong[32][]; private static ulong colorData; private static Random randomGenerator = new Random(); static ZobristKey() { foreach(var pieceType in Piece.PIECE_TYPES) { pieceSquareData[pieceType] = new ulong[64]; for(int i = 0; i < 64; i++) { pieceSquareData[pieceType][i] = NextULong(); } } colorData = NextULong(); } private static ulong NextULong() { var data = new byte[8]; randomGenerator.NextBytes(data); return BitConverter.ToUInt64(data); } public static ulong GetKey(Board board) { ulong hash = 0; for(int i = 0; i < 64; i++) { if (board.board[i] != Piece.NONE) hash ^= pieceSquareData[board.board[i]][i]; } hash ^= board.Us; hash ^= (uint)board.EnPassentSquare; return hash; } /// <summary> /// </summary> /// <param name="piece"></param> /// <param name="start"></param> /// <param name="target">target=-1 if piece was captured</param> /// <param name="key"></param> public static void PieceMoved(uint piece, int start, int target, ref ulong key) { key ^= pieceSquareData[piece][start]; if (target >= 0) key ^= pieceSquareData[piece][target]; } public static void ColorChanged(ref ulong key) { key ^= colorData; } } } <file_sep>/Chess/MoveHelper.cs using System; using System.Collections.Generic; using System.Text; namespace Chess { public static class MoveHelper { public const int N = 0; public const int E = 1; public const int S = 2; public const int W = 3; public const int NE = 4; public const int SE = 5; public const int SW = 6; public const int NW = 7; /// <summary> /// N, E, S, W, NE, SE, SW, NW /// </summary> public static int[] Directions = { 8, 1, -8, -1, 9, -7, -9, 7 }; public static int[][] NumSquaresToEdge = new int[64][]; public static int[][] KnightMoves = new int[64][]; public static ulong[] KnightBitboards = new ulong[64]; public static ulong[][] PawnAttackBitboards = new ulong[3][]; public static int[][] KingMoves = new int[64][]; public static ulong[] KingAttackBitboards = new ulong[64]; public static int[] DirectionLookup = new int[127]; public static ulong[] FileBitboards = new ulong[8]; public static ulong[] RankBitboards = new ulong[8]; public static ulong[] IsolatedPawnBitboards = new ulong[8]; public static ulong[] PassedPawnBitboards = new ulong[8]; //TODO PassedPawnBitboards are wrong! (they check all ranks, but need only check ranks in front. In fact, we need different ones for each color) static MoveHelper() { for (int square = 0; square < 64; square++) { int x = square % 8; int y = square / 8; int N = 7 - y; int S = y; int E = 7 - x; int W = x; NumSquaresToEdge[square] = new int[] { N, E, S, W, Math.Min(N, E), Math.Min(S, E), Math.Min(S, W), Math.Min(N, W) }; } //init knightMoves and king moves for (int square = 0; square < 64; square++) { int x = square % 8; int y = square / 8; var possibleKnightMoves = new List<int>(); if (x > 0 && y > 1) possibleKnightMoves.Add(x - 1 + 8 * (y - 2)); if (x > 1 && y > 0) possibleKnightMoves.Add(x - 2 + 8 * (y - 1)); if (x > 0 && y < 6) possibleKnightMoves.Add(x - 1 + 8 * (y + 2)); if (x > 1 && y < 7) possibleKnightMoves.Add(x - 2 + 8 * (y + 1)); if (x < 7 && y > 1) possibleKnightMoves.Add(x + 1 + 8 * (y - 2)); if (x < 6 && y > 0) possibleKnightMoves.Add(x + 2 + 8 * (y - 1)); if (x < 7 && y < 6) possibleKnightMoves.Add(x + 1 + 8 * (y + 2)); if (x < 6 && y < 7) possibleKnightMoves.Add(x + 2 + 8 * (y + 1)); foreach (var target in possibleKnightMoves) KnightBitboards[square] |= 1ul << target; KnightMoves[square] = possibleKnightMoves.ToArray(); var possibleKingMoves = new List<int>(); for(int dirIndex = 0; dirIndex < 8; dirIndex++) { if(NumSquaresToEdge[square][dirIndex] > 0) { possibleKingMoves.Add(square + Directions[dirIndex]); } } foreach (var target in possibleKingMoves) KingAttackBitboards[square] |= 1ul << target; KingMoves[square] = possibleKingMoves.ToArray(); } //Pawn attacks PawnAttackBitboards[Piece.WHITE] = new ulong[64]; PawnAttackBitboards[Piece.BLACK] = new ulong[64]; for(int square = 8; square < 56; square++) //Pawns can only be on 2nd to 7th rank { //Eastward attack if(NumSquaresToEdge[square][E] > 0) { PawnAttackBitboards[Piece.WHITE][square] |= 1ul << (square + Directions[NE]); PawnAttackBitboards[Piece.BLACK][square] |= 1ul << (square + Directions[SE]); } //Westward attack if (NumSquaresToEdge[square][W] > 0) { PawnAttackBitboards[Piece.WHITE][square] |= 1ul << (square + Directions[NW]); PawnAttackBitboards[Piece.BLACK][square] |= 1ul << (square + Directions[SW]); } } //Direction Lookup for (int i = 0; i < 127; i++) { int offset = i - 63; int absOffset = Math.Abs(offset); int absDir = 1; if (absOffset % 9 == 0) { absDir = 9; } else if (absOffset % 8 == 0) { absDir = 8; } else if (absOffset % 7 == 0) { absDir = 7; } DirectionLookup[i] = absDir * Math.Sign(offset); } for(var file = 0; file < 8; file++) { for(var rank = 0; rank < 8; rank++) { FileBitboards[file] |= 1ul << (rank * 8 + file); RankBitboards[rank] |= 1ul << (rank * 8 + file); } } for (var file = 0; file < 8; file++) { if (file >= 1) { IsolatedPawnBitboards[file] |= FileBitboards[file - 1]; PassedPawnBitboards[file] |= FileBitboards[file - 1]; } PassedPawnBitboards[file] |= FileBitboards[file]; if (file <= 6) { IsolatedPawnBitboards[file] |= FileBitboards[file + 1]; PassedPawnBitboards[file] |= FileBitboards[file + 1]; } } } public static void PrintBitboard(ulong bitboard) { for(int rank = 7; rank >= 0; rank--) { for(int file = 0; file < 8; file++) { int square = rank * 8 + file; if((bitboard & 1ul << square) != 0) { Console.Write('#'); } else { Console.Write('.'); } } Console.WriteLine(); } } } } <file_sep>/Chess.Client/Program.cs using System; using System.Collections.Generic; using System.Linq; namespace Chess.Client { class Program { public static Board board = new Board(); public static AI ai = new AI(board); public static void SetPosition(string[] line) { if(line[1] == "startpos") { board = new Board(); ai = new AI(board); } else { throw new Exception("UNSUPPORTED"); } for(int i = 3; i < line.Length; i++) { var moveAlg = line[i]; Move theMove = null; var gen = new MoveGenerator(board); gen.Setup(); foreach (var move in gen.GetMoves(false)) { if (move.ToAlgebraicNotation().Equals(moveAlg)) { theMove = move; break; } } if (theMove == null) Console.WriteLine("Move "+ moveAlg + " was not found"); board.SubmitMove(theMove); } } static void Main(string[] args) { Console.WriteLine("id name ChessTest1"); Console.WriteLine("id author <NAME>"); Console.WriteLine("uciok"); while (true) { var line = Console.ReadLine().Split(" "); switch (line[0]) { case "isready": Console.WriteLine("readyok"); break; case "position": SetPosition(line); break; case "ucinewgame": SetPosition(new string[] { "position", "startpos" }); break; case "go": Move move = SearchBestMove(); if (move != null) { board.SubmitMove(move); MoveHelper.PrintBitboard(board.WhitePawnBitboard | board.BlackPawnBitboard); Console.WriteLine($"bestmove {move.ToAlgebraicNotation()}"); //Tell UCI the best move } break; case "drawboard": Console.WriteLine(board); Console.WriteLine(); Console.WriteLine(board.Us == Piece.WHITE ? "W" : "B"); break; case "quit": return; default: Console.WriteLine("Unknown command: " + string.Join(" ", line)); break; } } } public static Move SearchBestMove() { var startTime = DateTime.Now; int depth = 4; Move[] lastpv = null; int? lastScore = null; IDictionary<Move, int> topLevelMoveOrder = null; while (true) //iterate search depth { var currentSearchStartTime = DateTime.Now; var lastAspirationWindowRestart = DateTime.Now; int delta = 17; //TODO: goood value? int alpha = lastScore.HasValue ? lastScore.Value - delta : -AI.INFINITY; int beta = lastScore.HasValue ? lastScore.Value + delta : AI.INFINITY; SearchInfo info; int failLowCount = 0; int failHighCount = 0; while (true) //Search, if necessary widen aspiration window size { info = ai.FindBestMove(depth, lastpv, alpha, beta, topLevelMoveOrder, (failLowCount + failHighCount == 0)); if (info.Score <= alpha) //Fail low { beta = (alpha + beta) / 2; alpha = info.Score - delta; failLowCount++; } else if (info.Score >= beta) //Fail high { beta = info.Score + delta; failHighCount++; } else break; lastAspirationWindowRestart = DateTime.Now; delta += delta / 4 + 5; } var pvstring = ""; foreach (var move in info.PV) { if (move == null) break; pvstring += move.ToAlgebraicNotation() + " "; } var searchTime = DateTime.Now - currentSearchStartTime; var aspirationTime = lastAspirationWindowRestart - currentSearchStartTime; int percentage = (int)(100 * aspirationTime.TotalMilliseconds / searchTime.TotalMilliseconds); var nodesPerSecond = (int)(info.Nodes / searchTime.TotalSeconds); //TODO: Add mating score info Console.WriteLine($"info score cp {info.Score} pv {pvstring} depth {info.Depth} nodes {info.Nodes} nps {nodesPerSecond}"); Console.WriteLine($"info string AWPer {percentage}% FailL {failLowCount} FailH {failHighCount} NM {info.NullMoves} NMS {info.NullMovesSuccess} QNodes {info.QNodes} BCutoffs {info.BetaCutoffs} FP {info.FutilityPrunes} TTHits {info.Transpositions} SR {info.ScoutRemovals} Scouts {info.Scouts} MCPrunes {info.MCPrunes}"); if (DateTime.Now - startTime > TimeSpan.FromSeconds(5)) { return info.PV[0]; } lastpv = info.PV; lastScore = info.Score; topLevelMoveOrder = info.TopLevelMoveOrder; depth++; } } public static int CountMoves(Board board, MoveGenerator generator, uint us, int depth) { if (depth == 0) return 1; var count = 0; var them = Piece.OtherColor(us); generator.Setup(); foreach (var move in generator.GetMoves(false)) { board.SubmitMove(move); count += CountMoves(board, generator, them, depth-1); board.UndoMove(); } return count; } } } <file_sep>/Chess/BitboardUtilities.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Chess { public class BitboardUtilities { public static ulong ShiftUp(ulong bitboard) { return bitboard << 8; } public static ulong ShiftDown(ulong bitboard) { return bitboard >> 8; } public static ulong ShiftLeft(ulong bitboard) { return (bitboard >> 1) & ~MoveHelper.FileBitboards[7]; } public static ulong ShiftRight(ulong bitboard) { return (bitboard << 1) & ~MoveHelper.FileBitboards[0]; } public static ulong ShiftUpLeft(ulong bitboard) { return bitboard << 7 & ~MoveHelper.FileBitboards[7]; } public static ulong ShiftUpRight(ulong bitboard) { return bitboard << 9 & ~MoveHelper.FileBitboards[0]; } public static ulong ShiftDownLeft(ulong bitboard) { return bitboard >> 9 & ~MoveHelper.FileBitboards[7]; } public static ulong ShiftDownRight(ulong bitboard) { return bitboard >> 7 & ~MoveHelper.FileBitboards[0]; } } } <file_sep>/Chess/Board.cs using System; using System.Collections.Generic; using System.Text; namespace Chess { public class BoardState { public ulong positionKey; public ulong materialKey; public int enPassentSquare; public uint castelingRights; public Move lastMove; public ulong WhitePawnBitboard; public ulong BlackPawnBitboard; public ulong WhitePiecesBitboard; public ulong BlackPiecesBitboard; } public class Board { public const string STARTING_POSITION = "rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w QKqk - 0 1"; public uint[] board = new uint[64]; public uint CastelingRights; // WHITE Q K, then BLACK Q K public const uint WHITE_QUEENSIDE_CASTLE = 0b1000; public const uint WHITE_KINGSIDE_CASTLE = 0b0100; public const uint BLACK_QUEENSIDE_CASTLE = 0b0010; public const uint BLACK_KINGSIDE_CASTLE = 0b0001; public Stack<BoardState> states = new Stack<BoardState>(); public IList<int>[] pieceList = new List<int>[32]; public ulong positionKey; public ulong materialKey = 0ul; public uint Us; public uint Them; public int EnPassentSquare = -1; public int Ply = 0; public ulong WhitePawnBitboard; public ulong BlackPawnBitboard; public ulong WhitePiecesBitboard; public ulong BlackPiecesBitboard; public Board(string fen = STARTING_POSITION) { foreach(var pieceType in Piece.PIECE_TYPES) { pieceList[pieceType] = new List<int>(); } var fenData = fen.Split(' '); var rankDataArray = fenData[0].Split('/'); for (int rank = 0; rank < 8; rank++) //rank { var rankData = rankDataArray[7 - rank]; //Ranks are stored backwards in fen int file = 0; foreach (char datapoint in rankData) { if (char.IsNumber(datapoint)) { file += int.Parse(datapoint.ToString()); } else { var piece = Piece.FromFenString(datapoint); var pos = rank * 8 + file; board[pos] = piece; if (piece != Piece.NONE) { MaterialKey.AddPiece(piece, ref materialKey); pieceList[piece].Add(pos); if (piece == (Piece.PAWN | Piece.WHITE)) { WhitePawnBitboard |= 1ul << pos; } else if (piece == (Piece.PAWN | Piece.BLACK)) { BlackPawnBitboard |= 1ul << pos; } else if((piece & Piece.COLOR_MASK) == Piece.WHITE) //White and not a pawn { WhitePiecesBitboard |= 1ul << pos; } else //Black and not a pawn { BlackPiecesBitboard |= 1ul << pos; } } file++; } } } Us = fenData[1] == "w" ? Piece.WHITE : Piece.BLACK; Them = Piece.OtherColor(Us); var castelingRightsString = fenData[2]; if (castelingRightsString.Contains("Q")) CastelingRights |= WHITE_QUEENSIDE_CASTLE; if (castelingRightsString.Contains("K")) CastelingRights |= WHITE_KINGSIDE_CASTLE; if (castelingRightsString.Contains("q")) CastelingRights |= BLACK_QUEENSIDE_CASTLE; if (castelingRightsString.Contains("k")) CastelingRights |= BLACK_KINGSIDE_CASTLE; } public void SubmitNullMove() { states.Push(new BoardState { lastMove = null, positionKey = positionKey, enPassentSquare = EnPassentSquare, castelingRights = CastelingRights, materialKey = materialKey, WhitePawnBitboard = WhitePawnBitboard, BlackPawnBitboard = BlackPawnBitboard, WhitePiecesBitboard = WhitePiecesBitboard, BlackPiecesBitboard = BlackPiecesBitboard }); //No EnPassent in NullMovePruning EnPassentSquare = -1; Ply++; Us = Them; Them = Piece.OtherColor(Us); ZobristKey.ColorChanged(ref positionKey); } public void UndoNullMove() { var state = states.Pop(); positionKey = state.positionKey; Ply--; Us = Them; Them = Piece.OtherColor(Us); EnPassentSquare = state.enPassentSquare; CastelingRights = state.castelingRights; //No need to revert material key, white or black pawn bitboards, they have not changed } //We assume the submitted move is legal public void SubmitMove(Move move) { states.Push(new BoardState //Save the current state to the history { lastMove = move, positionKey = positionKey, materialKey = materialKey, enPassentSquare = EnPassentSquare, castelingRights = CastelingRights, WhitePawnBitboard = WhitePawnBitboard, BlackPawnBitboard = BlackPawnBitboard, WhitePiecesBitboard = WhitePiecesBitboard, BlackPiecesBitboard = BlackPiecesBitboard }); Ply++; board[move.Start] = Piece.NONE; pieceList[move.MovedPiece].Remove(move.Start); if(move.Promotion != Piece.NONE) { var promotedPiece = (Piece.COLOR_MASK & move.MovedPiece) | move.Promotion; board[move.Target] = promotedPiece; pieceList[promotedPiece].Add(move.Target); //Update material key MaterialKey.RemovePiece(move.MovedPiece, ref materialKey); MaterialKey.AddPiece(promotedPiece, ref materialKey); //Update Zobrist key ZobristKey.PieceMoved(move.MovedPiece, move.Start, -1, ref positionKey); ZobristKey.PieceMoved(promotedPiece, move.Target, -1, ref positionKey); //Update piece and pawn Bitboards if(Us == Piece.WHITE) { WhitePawnBitboard &= ~(1ul << move.Start); WhitePiecesBitboard |= 1ul << move.Target; } else // Us == Piece.BLACK { BlackPawnBitboard &= ~(1ul << move.Start); BlackPiecesBitboard |= 1ul << move.Target; } } else { board[move.Target] = move.MovedPiece; pieceList[move.MovedPiece].Add(move.Target); //material key need not be updated, piece just moved //Update Zobrist key ZobristKey.PieceMoved(move.MovedPiece, move.Start, move.Target, ref positionKey); //Update Pawn and pieces Bitboards if (move.MovedPiece == (Piece.WHITE | Piece.PAWN)) { WhitePawnBitboard &= ~(1ul << move.Start); WhitePawnBitboard |= 1ul << move.Target; } else if (move.MovedPiece == (Piece.BLACK | Piece.PAWN)) { BlackPawnBitboard &= ~(1ul << move.Start); BlackPawnBitboard |= 1ul << move.Target; } else if(Us == Piece.WHITE) { WhitePiecesBitboard &= ~(1ul << move.Start); WhitePiecesBitboard |= 1ul << move.Target; } else { BlackPiecesBitboard &= ~(1ul << move.Start); BlackPiecesBitboard |= 1ul << move.Target; } } if (move.CapturedPiece != Piece.NONE) { pieceList[move.CapturedPiece].Remove(move.Target); //Update material key MaterialKey.RemovePiece(move.CapturedPiece, ref materialKey); //Update Zobrist Key ZobristKey.PieceMoved(move.CapturedPiece, move.Target, -1, ref positionKey); //Update pawn bitboards if (move.CapturedPiece == (Piece.BLACK | Piece.PAWN)) { BlackPawnBitboard &= ~(1ul << move.Target); } else if (move.CapturedPiece == (Piece.WHITE | Piece.PAWN)) { WhitePawnBitboard &= ~(1ul << move.Target); } else if(Us == Piece.WHITE) { BlackPiecesBitboard &= ~(1ul << move.Target); } else { WhitePiecesBitboard &= ~(1ul << move.Target); } } //EnPassent related stuff if (move.IsDoublePawnMove) { //set the enPassent square to the square behind the target EnPassentSquare = Us == Piece.WHITE ? move.Target - 8 : move.Target + 8; } else { //reset the enPassent square EnPassentSquare = -1; } if (move.IsEnPassent) { //Remove the pawn on the advanced square var captureSquare = Us == Piece.WHITE ? move.Target - 8 : move.Target + 8; //rank of start + file of target pieceList[Piece.PAWN | Them].Remove(captureSquare); board[captureSquare] = Piece.NONE; //Update material key MaterialKey.RemovePiece(Piece.PAWN | Them, ref materialKey); //Update Zobrist key ZobristKey.PieceMoved(Piece.PAWN | Them, captureSquare, -1, ref positionKey); //Update pawn bitboards if (Us == Piece.WHITE) { BlackPawnBitboard &= ~(1ul << captureSquare); } else //Us == BLACK { WhitePawnBitboard &= ~(1ul << captureSquare); } } //Casteling related stuff if (move.MovedPiece == (Piece.WHITE | Piece.KING)) { //Revoke whites casteling rights after a king move CastelingRights &= BLACK_KINGSIDE_CASTLE | BLACK_QUEENSIDE_CASTLE; } else if (move.MovedPiece == (Piece.BLACK | Piece.KING)) { //Revoke blacks casteling rights after a king move CastelingRights &= WHITE_KINGSIDE_CASTLE | WHITE_QUEENSIDE_CASTLE; } else { //Revoke whites casteling rights if the correpsonding rook moved or was captured if (move.Start == 0 || move.Target == 0) //A1 CastelingRights &= ~WHITE_QUEENSIDE_CASTLE; if (move.Start == 7 || move.Target == 7) //H1 CastelingRights &= ~WHITE_KINGSIDE_CASTLE; //Revoke blacks casteling rights if the correpsonding rook moved or was captured if (move.Start == 7 * 8 || move.Target == 7 * 8) //A8 CastelingRights &= ~BLACK_QUEENSIDE_CASTLE; if (move.Start == 7 * 8 + 7 || move.Target == 7 * 8 + 7) //H8 CastelingRights &= ~BLACK_KINGSIDE_CASTLE; } if (move.IsCasteling) { //We need not revoke casteling rights after castle, this has already happend //We only need to move the rook int rookStart, rookEnd; switch (move.Target) { case 2: //C1 rookStart = 0; //A1 rookEnd = 3; //D1 break; case 6: //G1 rookStart = 7; //H1 rookEnd = 5; //F1 break; case 7 * 8 + 2: //C8 rookStart = 7 * 8; //A8 rookEnd = 7 * 8 + 3; //D8 break; case 7 * 8 + 6: //G8 rookStart = 7 * 8 + 7; //H8 rookEnd = 7 * 8 + 5; //F8 break; default: throw new Exception("Illegal casteling move: " + move.ToAlgebraicNotation()); } var pieceType = Piece.ROOK | Us; board[rookStart] = Piece.NONE; board[rookEnd] = pieceType; pieceList[pieceType].Remove(rookStart); pieceList[pieceType].Add(rookEnd); ZobristKey.PieceMoved(pieceType, rookStart, rookEnd, ref positionKey); if (Us == Piece.WHITE) { WhitePiecesBitboard &= ~(1ul << rookStart); WhitePiecesBitboard |= 1ul << rookEnd; } else { BlackPiecesBitboard &= ~(1ul << rookStart); BlackPiecesBitboard |= 1ul << rookEnd; } } Us = Them; Them = Piece.OtherColor(Us); ZobristKey.ColorChanged(ref positionKey); } public void UndoMove() { var state = states.Pop(); var move = state.lastMove; positionKey = state.positionKey; materialKey = state.materialKey; WhitePawnBitboard = state.WhitePawnBitboard; BlackPawnBitboard = state.BlackPawnBitboard; WhitePiecesBitboard = state.WhitePiecesBitboard; BlackPiecesBitboard = state.BlackPiecesBitboard; Ply--; Us = Them; Them = Piece.OtherColor(Us); EnPassentSquare = state.enPassentSquare; CastelingRights = state.castelingRights; board[move.Start] = move.MovedPiece; board[move.Target] = move.CapturedPiece; if(move.Promotion != Piece.NONE) { var promotedPiece = (Piece.COLOR_MASK & move.MovedPiece) | move.Promotion; pieceList[promotedPiece].Remove(move.Target); } else { pieceList[move.MovedPiece].Remove(move.Target); } pieceList[move.MovedPiece].Add(move.Start); if (move.CapturedPiece != Piece.NONE) { pieceList[move.CapturedPiece].Add(move.Target); } //EnPassent related stuff if (move.IsEnPassent) { var captureSquare = Us == Piece.WHITE ? move.Target - 8 : move.Target + 8; //rank of start + file of target board[captureSquare] = Piece.PAWN | Them; pieceList[Piece.PAWN | Them].Add(captureSquare); } //Casteling related stuff if (move.IsCasteling) { //We need not revoke casteling rights after castle, this has already happend //We need to move the rook switch (move.Target) { case 2: //C1 board[0] = Piece.WHITE | Piece.ROOK; board[3] = Piece.NONE; pieceList[Piece.WHITE | Piece.ROOK].Remove(3); pieceList[Piece.WHITE | Piece.ROOK].Add(0); break; case 6: //G1 board[7] = Piece.WHITE | Piece.ROOK; board[5] = Piece.NONE; pieceList[Piece.WHITE | Piece.ROOK].Remove(5); pieceList[Piece.WHITE | Piece.ROOK].Add(7); break; case 7 * 8 + 2: //C8 board[7 * 8] = Piece.BLACK | Piece.ROOK; board[7 * 8 + 3] = Piece.NONE; pieceList[Piece.BLACK | Piece.ROOK].Remove(7 * 8 + 3); pieceList[Piece.BLACK | Piece.ROOK].Add(7 * 8); break; case 7 * 8 + 6: //G8 board[7 * 8 + 7] = Piece.BLACK | Piece.ROOK; board[7 * 8 + 5] = Piece.NONE; pieceList[Piece.BLACK | Piece.ROOK].Remove(7 * 8 + 5); pieceList[Piece.BLACK | Piece.ROOK].Add(7 * 8 + 7); break; default: throw new Exception("Illegal casteling move: " + move.ToAlgebraicNotation()); } } foreach(var pieceType in Piece.PIECE_TYPES) { if(pieceList[pieceType].Count > 10) { throw new Exception("Too much of type " + Piece.ToFenString(pieceType)); } } } public override string ToString() { var result = ""; for(int rank = 7; rank >= 0; rank--) { for(int file = 0; file < 8; file++) { result += Piece.ToFenString(board[rank * 8 + file]); } result += "\n"; } return result; } } } <file_sep>/Chess/Piece.cs using System; using System.Collections.Generic; using System.Text; namespace Chess { /// <summary> /// 5 Bits: /// /// 3 bits the piece type /// 2 bits the piece colour /// </summary> public static class Piece { public const uint NONE = 0b00000; public const uint PAWN = 0b00100; public const uint BISHOP = 0b01000; public const uint ROOK = 0b10000; public const uint QUEEN = 0b11000; public const uint KNIGHT = 0b01100; public const uint KING = 0b10100; public const uint WHITE = 0b01; public const uint BLACK = 0b10; public const uint PIECE_MASK = 0b11100; public const uint COLOR_MASK = 0b00011; public static readonly uint[] PIECE_TYPES = { WHITE | KING, WHITE | QUEEN, WHITE | ROOK, WHITE | BISHOP, WHITE | KNIGHT, WHITE | PAWN, BLACK | KING, BLACK | QUEEN, BLACK | ROOK, BLACK | BISHOP, BLACK | KNIGHT, BLACK | PAWN }; public static char ToFenString(uint piece) { char res; switch (piece & PIECE_MASK) { case NONE: res = '.'; break; case PAWN: res = 'p'; break; case BISHOP: res = 'b'; break; case KNIGHT: res = 'n'; break; case ROOK: res = 'r'; break; case QUEEN: res = 'q'; break; case KING: res = 'k'; break; default: throw new Exception("CANNOT HAPPEN"); } if ((piece & COLOR_MASK) == WHITE) return char.ToUpper(res); return res; } public static uint OtherColor(uint color) { return COLOR_MASK ^ color; } public static uint FromFenString(char fen) { uint piece; switch (char.ToLower(fen)) { case 'p': piece = PAWN; break; case 'b': piece = BISHOP; break; case 'n': piece = KNIGHT; break; case 'r': piece = ROOK; break; case 'q': piece = QUEEN; break; case 'k': piece = KING; break; default: throw new InvalidOperationException($"{fen} is not a valid fen piece type"); } if (char.IsUpper(fen)) return piece | WHITE; else return piece | BLACK; } } } <file_sep>/Chess/Move.cs using System; using System.Collections.Generic; using System.Text; namespace Chess { //TODO: maybe make move a integer (6 bit start, 6 bit target, 5 bits moved piece, 5 bits captured piece, 5 bits promoted, 1 bit casteling, 1 bit enPassent etc.) public class Move { public int Start { get; private set; } public int Target { get; private set; } public uint MovedPiece { get; private set; } public uint CapturedPiece { get; private set; } public uint Promotion { get; private set; } = Piece.NONE; public bool IsCasteling { get; private set; } = false; public bool IsEnPassent { get; private set; } = false; public bool IsDoublePawnMove { get; private set; } = false; public Move(int start, int target, Board b) { Start = start; Target = target; MovedPiece = b.board[start]; CapturedPiece = b.board[target]; } public Move PromoteTo(uint promotion) { Promotion = promotion; return this; } public Move EnPassent() { IsEnPassent = true; return this; } public Move DoublePawnMove() { IsDoublePawnMove = true; return this; } public Move Casteling() { IsCasteling = true; return this; } public override bool Equals(object obj) { if (obj == this) return true; if (obj == null) return false; if (obj.GetType() != GetType()) return false; var move = (Move)obj; return move.Start == Start && move.Target == Target; } public override int GetHashCode() { return Start * 64 + Target; } public string ToAlgebraicNotation() { var promotion = Promotion == Piece.NONE ? "" : Piece.ToFenString(Promotion).ToString().ToLower(); return $"{SquareToAlgebraicNotation(Start)}{SquareToAlgebraicNotation(Target)}{promotion}"; } public override string ToString() { return ToAlgebraicNotation(); } public static string SquareToAlgebraicNotation(int square) { const string files = "abcdefgh"; const string ranks = "12345678"; int rank = square / 8; int file = square % 8; return $"{files[file]}{ranks[rank]}"; } } } <file_sep>/Chess/MaterialKey.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Chess { /// <summary> /// Used to compute material keys /// </summary> public class MaterialKey { public static int[] OFFSETS = new int[32]; public static ulong[] MASKS = new ulong[32]; static MaterialKey() { int offset = 0; foreach(var pieceType in Piece.PIECE_TYPES) { //4 Bits for each piece, so we can distinguish up to 15 pieces (max: 10 rooks, 10 bishops, 10 knights, 9 Queens, 8 pawns) //This sumes to 2*(5*4) = 2*20 = 40 Bit, need a ulong! OFFSETS[pieceType] = offset; MASKS[pieceType] = 0xFul << offset; offset += 4; } } public static void AddPiece(uint pieceType, ref ulong key) { //Increase amount by one var amount = ((key & MASKS[pieceType]) >> OFFSETS[pieceType]) + 1; key &= ~MASKS[pieceType]; key |= amount << OFFSETS[pieceType]; } public static void RemovePiece(uint pieceType, ref ulong key) { //Decrease amount by one var amount = ((key & MASKS[pieceType]) >> OFFSETS[pieceType]) - 1; key &= ~MASKS[pieceType]; key |= amount << OFFSETS[pieceType]; } } }
3c5f3beec1720e1658f5b28bdb0105f3e474ec73
[ "C#" ]
13
C#
KMattis/Chess
9cdf6d61a23d07ad71b7117aede1a8e3e6f3a8e1
4404e5063ab2a455a087efc86d6f322c648b1b4a
refs/heads/master
<repo_name>wennycooper/IR_receiver_rosserial<file_sep>/IR_receiver_rosserial.ino #include <ros.h> #include <std_msgs/UInt16.h> #include <geometry_msgs/Vector3.h> #define LOOPTIME1 10 unsigned long lastMilli1 = 0; #define LOOPTIME2 1000 unsigned long lastMilli2 = 0; ros::NodeHandle nh; //std_msgs::UInt16 irValue; geometry_msgs::Vector3 irValue; ros::Publisher pub("irValue", &irValue); void setup() { nh.initNode(); nh.advertise(pub); Serial.begin(57600); } unsigned int i=0; unsigned lastTime = 0; void loop() { //lastTime = millis(); for (i=0; i<100; i++) { irValue.x += analogRead(A0); irValue.y += analogRead(A1); } // Serial.println(millis() - lastTime); irValue.x = irValue.x/100; irValue.y = irValue.y/100; // publish and clean up // pub.publish(&irValue); irValue.x = 0; irValue.y = 0; /* if ((millis()-lastMilli1) >= LOOPTIME1) { // time to read ADC lastMilli1 = millis(); // accumulate those readings irValue.x += analogRead(A0); irValue.y += analogRead(A1); //pub.publish(&irValue); } if ((millis()-lastMilli2) >= LOOPTIME2) { // time to pub lastMilli2 = millis(); //irValue.x = analogRead(A0); //irValue.y = analogRead(A1); pub.publish(&irValue); irValue.x = 0; irValue.y = 0; } */ nh.spinOnce(); }
802c4a37fcc9b1fcd95be6b45698633b3da5b9dd
[ "C++" ]
1
C++
wennycooper/IR_receiver_rosserial
f6431df48c18a396b9d6aa3c891ef871247f77bf
55a3c21f2d31f1291f001f4d018019a8f03512bd
refs/heads/master
<file_sep>//create firebase reference var dbRef = new Firebase("https://el2017-30cf0.firebaseio.com/"); var contactsRef = dbRef.child('contacts') var longitude = []; var latitude = []; var cars = []; var j = 0; //load older conatcts as well as any newly added one... contactsRef.on("child_added", function(snap) { console.log("added", snap.key(), snap.val()); cars[j] = snap.val(); j++; document.querySelector('#contacts').innerHTML += (contactHtmlFromObject(snap.val())); }); //save contact document.querySelector('.addValue').addEventListener("click", function( event ) { event.preventDefault(); if( document.querySelector('#name').value != '' ){ contactsRef .push({ name: document.querySelector('#name').value, speed: document.querySelector('#speed').value, load: (document.querySelector('#load').value)*100/255, mil: 256*(document.querySelector('#mil').value), maf: 256*(document.querySelector('#maf').value), temperature: ((256+document.querySelector('#temperature').value)/10)-40, rpm: document.querySelector('#rpm').value, os: document.querySelector('#os').value/200, aap: document.querySelector('#aap').value, lat: document.querySelector('#lat').value, lon: document.querySelector('#lon').value }) location.replace("map.html") } }, false); //prepare conatct object's HTML function contactHtmlFromObject(contact){ var html = ''; html += '<li class="list-group-item contact" style="background-color: inherit;border-radius: 25px;' + 'border: 2px solid #73AD21;border-color: black;margin: 5px 0px;">'; html += '<div>'; html += '<p class="lead"><b>Car Name:</b> '+contact.name+'</p>'; html += '<p><b>Vehicle Speed: </b>'+contact.speed+'</p>'; html += '<p><b>Engine Load: </b>'+contact.load+'</p>'; html += '<p><b>Distance with MIL on: </b>'+contact.mil+'</p>'; html += '<p><b>MAF: </b>'+contact.maf+'</p>'; html += '<p><b>Catalyst Temperature: </b>'+contact.temperature+'</p>'; html += '<p><b>RPM: </b>'+contact.rpm+'</p>'; html += '<p><b>Oxygen Sensor: </b>'+contact.os+'</p>'; html += '<p><b>Ambient Air Pressure: </b>'+contact.aap+'</p>'; html += '<p><b>Latitude: </b>'+contact.lat+'</p>'; html += '<p><b>Longitude: </b>'+contact.lon+'</p>'; html += '</div>'; html += '</li>'; return html; } function init() { console.log(cars); var mapDiv = document.getElementById("mymap"); var mapOptions = { center: new google.maps.LatLng (37.09024, -119.4179324), zoom: 5, mapTypeId: google.maps.MapTypeId.ROADMAP }; var map = new google.maps.Map(mapDiv, mapOptions); var locations = []; for(var i = 0 ; i < j ; i++) { locations.push({name: "Car name: "+cars[i].name+"\nVehicle Speed: "+cars[i].speed+"\nEngine Load: "+cars[i].load+"\nDistance with MIL on: "+cars[i].mil+"\nMAF: "+cars[i].maf+"\nCatalyst Temperature: "+cars[i].temperature+"\nRPM: "+cars[i].rpm+"\nOxygen Sensor: "+cars[i].os+"\nAmbient Air Pressure: "+cars[i].aap+"\nLatitude: "+cars[i].lat+"\nLongitude: "+cars[i].lon, latlng: new google.maps.LatLng(cars[i].lat, cars[i].lon)}); console.log(cars[i].latitude); } var bounds = new google.maps.LatLngBounds (); for(var i = 0; i < locations.length;i++) { var marker = new google.maps.Marker({position: locations[i].latlng, map:map, title:locations[i].name}); bounds.extend(locations[i].latlng); } map.fitBounds (bounds); } <file_sep># EL-Firebase-Project Created Using: HTML5, CSS3, BOOTSTRAP, JavaScript and PHP using Firebase Realtime Database. This project was for my College's Analog Circuits(Electronics) Course. It took realtime data from the vehicles and sent it to Firebase Database and dynamically linked all the information about the vehicles on the map using Rasberry Pi and Geological Tracking System.
01046a736c0c17a84dabd3dae73b3c273890c087
[ "JavaScript", "Markdown" ]
2
JavaScript
luvpatel801/EL-Firebase-Project
09f34cce6191fc6367d82293d9d351b8e0cdd976
abad3f40d962146fd80c113fb67383dd1d7865b3
refs/heads/master
<repo_name>kodluyoruz-react-bootcamp/odev-1-ozanorkun<file_sep>/src/app.js import getData from "./lib/service"; let data = getData(1); data.then((result) => console.log(result));
4f4a0ad677f101c42a0a1ece0ed19ca6fc644028
[ "JavaScript" ]
1
JavaScript
kodluyoruz-react-bootcamp/odev-1-ozanorkun
f8174a0564dc2ec5073da31f58338f3d02d53494
03a49416fb5d81b5b0fc914415a8297394a6b8c0
refs/heads/master
<file_sep>using ImageOrganizer.Web.CustomLogic; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Web; using System.Web.Mvc; namespace ImageOrganizer.Web.Controllers { public class ImageController : Controller { public ActionResult Get() { var imagePathFromRequestBase64 = RouteData.Values["pathInfo"] as string; var bytesFromImagePath = Convert.FromBase64String(imagePathFromRequestBase64); var imagePath = Encoding.UTF8.GetString(bytesFromImagePath); var imgData = ImageHelper.GetImageData(FileHelper.GetRootPath() + imagePath, Request["mode"]); return File(imgData.ImageBytes, imgData.MimeType); } } }<file_sep>using ImageOrganizer.Web.CustomLogic.Definitions; using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; using System.Web.Routing; namespace ImageOrganizer.Web { public class RouteConfig { public static void RegisterRoutes(RouteCollection routes) { routes.IgnoreRoute("{resource}.axd/{*pathInfo}"); routes.MapRoute( name: "LocalImage", url: PathDefinition.LOCAL_PATH_PREFIX_IMAGE + "/{*pathInfo}", defaults: new { controller = "Image", action = "Get", id = UrlParameter.Optional } ); routes.MapRoute( name: "LocalPath", url: PathDefinition.LOCAL_PATH_PREFIX + "/{*pathInfo}", defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional } ); routes.MapRoute( name: "Default", url: "{controller}/{action}/{id}", defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional } ); } } } <file_sep>using ImageOrganizer.Web.CustomLogic.Definitions; using ImageOrganizer.Web.Models; using System; using System.Collections.Generic; using System.Configuration; using System.IO; using System.Linq; using System.Web; using Humanizer; using Humanizer.Bytes; using System.Text; namespace ImageOrganizer.Web.CustomLogic { public class FileHelper { public static List<string> AutoGeneratedFolders = new List<string>(new[] { AutoGenerateFolder.LIST_PREVIEW }); public static string GetRootPath() { return ConfigurationManager.AppSettings["ImageOrganizer.RootPath"]; } public static string GetAbsolutePathFromLocal(string localPath) { var rootPath = GetRootPath(); return String.Concat(rootPath, @"\", localPath); } public static FolderInformation GetFolderInformation(string localPath = null) { var folderInformation = new FolderInformation(); var rootPath = GetRootPath(); folderInformation.Path = GetAbsolutePathFromLocal(localPath); folderInformation.BreadCrumb = PathHelper.GetBreadCrumb(folderInformation.Path); if (Directory.Exists(folderInformation.Path)) { // Gathering information about local folders. // [MB] folderInformation.Directories = GetDirectoriesFromFolder(folderInformation.Path); // Gathering information about local files. // [MB] var fileList = new DirectoryInfo(folderInformation.Path).GetFiles(); folderInformation.Files = new List<CustomFileInformation>(); foreach (var file in fileList) { var imageInfo = ImageHelper.GetImageInformation(file.FullName); var imagePathBytes = Encoding.UTF8.GetBytes(file.FullName.Replace(rootPath, String.Empty)); var imagePathBase64 = Convert.ToBase64String(imagePathBytes); folderInformation.Files.Add(new CustomFileInformation(imageInfo) { ImageHandlerPath = String.Format("/{0}/{1}", PathDefinition.LOCAL_PATH_PREFIX_IMAGE, imagePathBase64) }); } } return folderInformation; } public static List<CustomFolderInformation> GetDirectoriesFromFolder(string absolutePath) { var result = new List<CustomFolderInformation>(); var rootPath = GetRootPath(); var directoryList = new DirectoryInfo(absolutePath).GetDirectories(); foreach (var directory in directoryList) { // Hide auto-gen folders. // [MB] if (AutoGeneratedFolders.Contains(directory.Name)) { continue; } result.Add(new CustomFolderInformation() { FullName = directory.FullName, Name = directory.Name, LocalPath = String.Format("/{0}/{1}", PathDefinition.LOCAL_PATH_PREFIX, directory.FullName.Replace(rootPath, String.Empty)) }); } return result; } } }<file_sep>using Humanizer; using Humanizer.Bytes; using ImageMagick; using ImageOrganizer.Web.CustomLogic.Definitions; using ImageOrganizer.Web.Models; using System; using System.Collections.Generic; using System.Globalization; using System.IO; using System.Linq; using System.Security.Cryptography; using System.Web; namespace ImageOrganizer.Web.CustomLogic { public class ImageHelper { public static ImageInformation GetImageInformation(string path, ImageData imageData = null) { var imageInfo = new ImageInformation(); if (imageData == null) { imageData = GetImageData(path); } var fileInfo = new FileInfo(path); imageInfo.FileHash = GetFileHash(imageData.ImageBytes); imageInfo.Size = fileInfo.Length; imageInfo.HRSize = ByteSize.FromBytes(fileInfo.Length).Humanize("MB"); imageInfo.LastChange = fileInfo.LastWriteTime; imageInfo.FullName = fileInfo.FullName; imageInfo.Name = fileInfo.Name; imageInfo.Extension = fileInfo.Extension; using (MagickImage image = new MagickImage(imageInfo.FullName)) { // Searching for correct exif tag. // [MB] var exifProfile = image.GetExifProfile(); var originalDateTime = exifProfile.Values.FirstOrDefault(exifInfo => { if (exifInfo.Tag != null) { var tagName = exifInfo.Tag.ToString().ToLowerInvariant(); return (tagName == "datetimeoriginal"); } return false; }); // Trying to get the date from the exif-tag. // [MB] if (originalDateTime != null) { DateTime parsedDate; if (DateTime.TryParseExact(originalDateTime.Value as string, "yyyy:MM:dd hh:mm:ss", CultureInfo.InvariantCulture, DateTimeStyles.None, out parsedDate)) { imageInfo.OriginalDate = parsedDate; } } } return imageInfo; } public static ImageData GetImageData(string path, string mode = null) { var absolutePath = path; if (!String.IsNullOrWhiteSpace(mode)) { absolutePath = GetImageInMode(absolutePath, mode); } return new ImageData() { ImageBytes = File.ReadAllBytes(absolutePath), MimeType = "image/jpeg" }; } private static string GetImageInMode(string absolutePath, string mode) { if (!String.IsNullOrWhiteSpace(absolutePath)) { var splittedPath = absolutePath.Split(new[] { '\\' }).ToList(); if (splittedPath.Count > 0) { splittedPath.Insert(splittedPath.Count - 1, mode); var absolutePathExtended = String.Join("\\", splittedPath); var fileInformation = new FileInfo(absolutePathExtended); if (!Directory.Exists(fileInformation.Directory.FullName)) Directory.CreateDirectory(fileInformation.Directory.FullName); if (!File.Exists(fileInformation.FullName)) { using (MagickImage image = new MagickImage(absolutePath)) { image.BackgroundColor = new MagickColor(255, 255, 255); image.Resize(new MagickGeometry(200, 200) { FillArea = false }); image.Quality = 50; image.Write(absolutePathExtended); } } absolutePath = absolutePathExtended; } } return absolutePath; } public static string GetFileHash(string filePath) { return GetFileHash(File.ReadAllBytes(filePath)); } public static string GetFileHash(byte[] fileBytes) { using (var sha = SHA256.Create()) { var computedHash = sha.ComputeHash(fileBytes); return Convert.ToBase64String(computedHash); } } } }<file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Web; namespace ImageOrganizer.Web.Models { public class ImageData { public string MimeType { get; set; } public byte[] ImageBytes { get; set; } } public class ImageInformation { public ImageInformation() { Id = Guid.NewGuid(); } public Guid Id { get; set; } public string FileHash { get; set; } public long Size { get; set; } public string HRSize { get; set; } public string FullName { get; set; } public string Name { get; set; } public string Extension { get; set; } public DateTime LastChange { get; set; } public DateTime OriginalDate { get; set; } } }<file_sep>var imageHelper = function ($j) { var handleMouseDown = function (e) { if (e.which === 3) { // TODO: Handle right click. e.preventDefault(); e.stopPropagation(); } } var handleHeaderBarClicked = function (e) { var clickedHeader = $j(this); var cbUseThis = clickedHeader.find('[name=cbUseThis]'); if (cbUseThis.prop('checked')) { cbUseThis.prop('checked', false); clickedHeader.removeClass('selected'); } else { cbUseThis.prop('checked', true); clickedHeader.addClass('selected'); } e.preventDefault(); e.stopPropagation(); } return { init: function () { $j('.preview-image').on('mousedown', handleMouseDown); $j('.handle-header-bar').on('click', handleHeaderBarClicked); } }; }(jQuery); jQuery(function () { imageHelper.init(); });<file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Web; namespace ImageOrganizer.Web.CustomLogic.Definitions { public class PathDefinition { public const string LOCAL_PATH_PREFIX = "LocalPath"; public const string LOCAL_PATH_PREFIX_IMAGE = "LocalImage"; } }<file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Web; namespace ImageOrganizer.Web.Models { public class HomeIndexModel { public FolderInformation FolderInformation { get; set; } } }<file_sep>using ImageOrganizer.Web.CustomLogic; using ImageOrganizer.Web.Models; using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; namespace ImageOrganizer.Web.Controllers { public class HomeController : Controller { public ActionResult Index() { var viewModel = new HomeIndexModel(); viewModel.FolderInformation = FileHelper.GetFolderInformation(RouteData.Values["pathInfo"] as string); return View("~/Views/Home/Index.cshtml", viewModel); } } }<file_sep>using ImageOrganizer.Web.CustomLogic; using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; namespace ImageOrganizer.Web.Controllers { public class SuggestController : Controller { public ActionResult GetItems(CommandConfig request) { var suggestList = new List<SuggestItemConfig>(); if (request != null) { switch (request.CommandName) { case "move-file": case "move-folder": var directoryList = FileHelper.GetDirectoriesFromFolder(FileHelper.GetAbsolutePathFromLocal(request.Parameter)); if (!String.IsNullOrWhiteSpace(request.Parameter)) { suggestList.Add(new SuggestItemConfig() { Label = "Execute command", Value = "Execute", ListItemType = "execute" }); } foreach (var directory in directoryList) { suggestList.Add(new SuggestItemConfig() { Label = directory.Name, Value = directory.LocalPath, ListItemType = "folder" }); } break; default: break; } } return Json(suggestList, JsonRequestBehavior.AllowGet); } } public class SuggestItemConfig { public string Label { get; set; } public string Value { get; set; } public string ListItemType { get; set; } } public class CommandConfig { public string CommandName { get; set; } public string Parameter { get; set; } public string CurrentPath { get; set; } public string[] Ids { get; set; } } }<file_sep>using ImageOrganizer.Web.CustomLogic.Definitions; using ImageOrganizer.Web.Models; using System; using System.Collections.Generic; using System.Linq; using System.Web; namespace ImageOrganizer.Web.CustomLogic { public class PathHelper { internal static List<BreadCrumbPart> GetBreadCrumb(string path) { var result = new List<BreadCrumbPart>(); result.Add(new BreadCrumbPart() { Label = "Root", Path = "/" }); if (!String.IsNullOrWhiteSpace(path)) { path = path.Replace(FileHelper.GetRootPath(), String.Empty); var splittedPath = path.Split(new[] { '\\', '/' }, StringSplitOptions.RemoveEmptyEntries); if (splittedPath.Any()) { string previousPath = String.Empty; foreach (var pathPart in splittedPath) { previousPath += pathPart + "/"; result.Add(new BreadCrumbPart() { Label = pathPart, Path = String.Format("/{0}/{1}", PathDefinition.LOCAL_PATH_PREFIX, previousPath) }); } } } return result; } } }<file_sep>using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Web; namespace ImageOrganizer.Web.Models { public class FolderInformation { public List<CustomFolderInformation> Directories { get; set; } public List<CustomFileInformation> Files { get; set; } public string Path { get; set; } public List<BreadCrumbPart> BreadCrumb { get; set; } } public class BreadCrumbPart { public string Label { get; set; } public string Path { get; set; } } public class CustomFolderInformation { public string FullName { get; set; } public string Name { get; set; } public string LocalPath { get; set; } } public class CustomFileInformation : ImageInformation { public CustomFileInformation(ImageInformation imageInfo) { Extension = imageInfo.Extension; FileHash = imageInfo.FileHash; FullName = imageInfo.FullName; HRSize = imageInfo.HRSize; Id = imageInfo.Id; Name = imageInfo.Name; Size = imageInfo.Size; LastChange = imageInfo.LastChange; OriginalDate = imageInfo.OriginalDate; } public string ImageHandlerPath { get; set; } } }<file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Web; namespace ImageOrganizer.Web.CustomLogic.Definitions { public class AutoGenerateFolder { public const string LIST_PREVIEW = "listPreview"; } }<file_sep>ImageOrganizer ============== The intention of the project is to organize my image library.
fed482622fa4f041b8f573dfa673d41a187f577e
[ "JavaScript", "C#", "Markdown" ]
14
C#
matthiasbruch/ImageOrganizer
6eb295223014be4fdf4baa0867faa1e6087b17ce
bcde6a9f3ec3ea978e0e8c7de7481c96d3fa301e
refs/heads/master
<file_sep># Cookbook Name:: ssm # Recipe:: default # Copyright 2017, REANCLOUD case node['platform'] when 'ubuntu' execute 'update' do command 'apt-get update -y' end execute 'install' do command 'wget "https://s3.amazonaws.com/ec2-downloads-windows/SSMAgent/latest/debian_amd64/amazon-ssm-agent.deb"' end end <file_sep># Cookbook Name:: ssm # Recipe:: default # Copyright 2017, REANCLOUD case node['platform'] when 'amazon' include_recipe 'ssm::linux_ssm' when 'ubuntu' include_recipe 'ssm::ubuntu_ssm' end <file_sep># Cookbook Name:: ssm # Recipe:: default # Copyright 2017, REANCLOUD execute 'update' do command 'yum update -y' end execute 'installation' do command 'sudo yum install -yhttps://s3.amazonaws.com/ec2-downloads-windows/SSMAgent/latest/linux_amd64/amazon-ssm-agent.rpm' end
9c22c0b4fdc738e142e4589a2f298bb149fbadf8
[ "Ruby" ]
3
Ruby
priyanka561/ssm
4697cdd41d6d0067159e47c7f232e3b312aee2da
4c45f87313d3c671d4e1f348aaf1033ac49d3fba
refs/heads/master
<file_sep>import uniqueRandomArray from 'unique-random-array' import starWarsNames from './starwars-names.json' export { starWarsNames as all} const getRandomItem = uniqueRandomArray(starWarsNames) export let random = number => !number ? getRandomItem() : Array(number) .fill() .map(getRandomItem) <file_sep># starwars-names [![Travis](https://img.shields.io/travis/avilapedro/starwars-names.svg)](https://travis-ci.org/avilapedro/starwars-names) [![Codecov](https://img.shields.io/codecov/c/github/avilapedro/starwars-names.svg)](https://codecov.io/gh/avilapedro/starwars-names) ![npm (scoped)](https://img.shields.io/npm/v/@avilapedro/starwars-names.svg)
6a210d98e78a1c50ae2ba96e8550800aff5a110b
[ "JavaScript", "Markdown" ]
2
JavaScript
avilapedro/starwars-names
d10abd3a546d9d0d0fe9cc393e166935dce8ac18
07063ad4c41aada0341d38729aa0d36a473c2620
refs/heads/main
<repo_name>dobo90/ghidra-minidump-loader<file_sep>/MinidumpLoader/src/main/java/net/jubjubnest/minidump/loader/parser/MinidumpModule.java package net.jubjubnest.minidump.loader.parser; import java.io.File; import java.io.IOException; import java.nio.ByteBuffer; import ghidra.app.util.bin.ByteProvider; public class MinidumpModule { public static final int RECORD_SIZE = 8 + 4 + 4 + 4 + 4 + VsFixedFileInfo.RECORD_SIZE + MinidumpLocationDescriptor.RECORD_SIZE + MinidumpLocationDescriptor.RECORD_SIZE + 8 + 8; public static MinidumpModule parse(ByteBuffer byteBuffer, ByteProvider provider) throws IOException { var module = new MinidumpModule(); module.imageBase = byteBuffer.getLong(); module.imageSize = byteBuffer.getInt(); module.checksum = byteBuffer.getInt(); module.timestamp = byteBuffer.getInt(); module.moduleNameRva = byteBuffer.getInt(); module.versionInfo = VsFixedFileInfo.parse(byteBuffer); module.cvRecord = MinidumpLocationDescriptor.parse(byteBuffer); module.miscRecord = MinidumpLocationDescriptor.parse(byteBuffer); module.reserved0 = byteBuffer.getLong(); module.reserved1 = byteBuffer.getLong(); module.name = StringReader.readString(module.moduleNameRva, provider); return module; } public String getBaseName() { return getFilename(new File(this.name).getPath()); } private String getFilename(String fullPath) { // Remove any trailing slashes String editedPath = fullPath; editedPath = editedPath.replaceAll("[\\/]$", ""); int lastIndexForwardSlash = editedPath.lastIndexOf('/'); int lastIndexBackSlash = editedPath.lastIndexOf('\\'); if (lastIndexForwardSlash == -1 && lastIndexBackSlash == -1) { return editedPath; } int indexToUse = (lastIndexForwardSlash > lastIndexBackSlash) ? lastIndexForwardSlash : lastIndexBackSlash; return editedPath.substring(indexToUse + 1); } public long imageBase; public int imageSize; public int checksum; public int timestamp; public int moduleNameRva; public VsFixedFileInfo versionInfo; public MinidumpLocationDescriptor cvRecord; public MinidumpLocationDescriptor miscRecord; public long reserved0; public long reserved1; public String name; } <file_sep>/MinidumpLoader/src/main/java/net/jubjubnest/minidump/plugin/parser/UnwindCode.java package net.jubjubnest.minidump.plugin.parser; import java.io.IOException; import ghidra.app.util.bin.BinaryReader; import ghidra.util.exception.NotYetImplementedException; public class UnwindCode { public static UnwindCode parse(BinaryReader reader, byte fpreg) throws IOException { var code = new UnwindCode(); code.prologOffset = reader.readNextByte(); var op = reader.readNextByte(); byte opcode = (byte)(op & 0x0f); byte opinfo = (byte)((op & 0xf0) >> 4); switch (opcode) { case 0: // UWOP_PUSH_NONVOL code.spEffect = 8; code.opcodeSize = 1; break; case 1: // UWPO_ALLOC_LARGE if (opinfo == 0) { // Single scaled uint16le code.spEffect = (reader.readNextByte() & 0xff) + ((reader.readNextByte() & 0xff) << 8); code.spEffect *= 8; code.opcodeSize = 2; } else { // Single unscaled uint32le code.spEffect = reader.readNextByte() + (reader.readNextByte() << 8) + (reader.readNextByte() << 16) + (reader.readNextByte() << 24); code.opcodeSize = 3; } break; case 2: // UWPO_ALLOC_SMALL code.spEffect = opinfo * 8 + 8; code.opcodeSize = 1; break; case 3: code.spEffect = fpreg * 16; code.opcodeSize = 1; break; case 4: // Save register into previously allocated stack space. reader.readNextShort(); code.spEffect = 0; code.opcodeSize = 2; break; case 5: // Save register into previously allocated stack space. reader.readNextShort(); reader.readNextShort(); code.spEffect = 0; code.opcodeSize = 3; break; case 6: // Save register into previously allocated stack space. reader.readNextShort(); code.spEffect = 0; code.opcodeSize = 2; break; case 7: // Save register into previously allocated stack space. reader.readNextShort(); code.spEffect = 0; code.opcodeSize = 3; break; case 8: // Save register into previously allocated stack space. reader.readNextShort(); code.spEffect = 0; code.opcodeSize = 2; break; case 9: // Save register into previously allocated stack space. reader.readNextShort(); reader.readNextShort(); code.spEffect = 0; code.opcodeSize = 3; break; case 10: if (opcode == 0) { code.spEffect = 5 * 8; } else if (opinfo == 1) { code.spEffect = 6 * 8; } else { throw new NotYetImplementedException("Machine frame " + opinfo); } code.opcodeSize = 1; break; default: return null; } return code; } public byte prologOffset; public int spEffect; public byte opcodeSize; } <file_sep>/MinidumpLoader/src/main/java/net/jubjubnest/minidump/analyzer/SymbolLocationDialog.java package net.jubjubnest.minidump.analyzer; import java.awt.BorderLayout; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.List; import javax.swing.BorderFactory; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.JScrollPane; import docking.DialogComponentProvider; import docking.DockingWindowManager; import docking.widgets.table.AbstractGTableModel; import docking.widgets.table.GTable; import ghidra.app.util.bin.format.pdb2.pdbreader.PdbException; import ghidra.util.exception.CancelledException; import ghidra.util.exception.NotYetImplementedException; import ghidra.util.task.Task; import ghidra.util.task.TaskMonitor; import ghidra.util.worker.Job; import ghidra.util.worker.Worker; class SymbolLocationDialog extends DialogComponentProvider { GTable table; List<SymbolInfo> allRows; List<SymbolInfo> incompleteRows = new ArrayList<>(); boolean useModulePdbPath; boolean wasCancelled; Worker worker = Worker.createGuiWorker(); static final String[] COLUMN_NAMES = new String[] { "Module", "Symbols" }; public SymbolLocationDialog(List<SymbolInfo> symbols, boolean useModulePdbPath) { super("Confirm Symbols", true, false, true, true); setPreferredSize(600, 300); this.useModulePdbPath = useModulePdbPath; allRows = symbols; for (SymbolInfo info : symbols) { if (info.result == null) { incompleteRows.add(info); } } table = new GTable(new AbstractGTableModel<SymbolInfo>() { @Override public String getName() { return "Symbols"; } @Override public String getColumnName(int column) { return COLUMN_NAMES[column]; } @Override public List<SymbolInfo> getModelData() { return incompleteRows; } @Override public Object getColumnValueForRow(SymbolInfo row, int columnIndex) { switch (columnIndex) { case 0: return row.module.name; case 1: if (row.result != null) { return row.result.file.getAbsolutePath(); } if (row.message != null) { return row.message; } return "Double-click to specify symbols"; default: throw new NotYetImplementedException(); } } @Override public int getColumnCount() { return 2; } }); table.getColumnModel().getColumn(0).setPreferredWidth(75); table.getColumnModel().getColumn(1).setPreferredWidth(175); table.addMouseListener(new MouseAdapter() { @Override public void mouseClicked(MouseEvent e) { if (e.getClickCount() == 2) { changeSymbols(table.getSelectedRow()); } } }); JLabel label = new JLabel("No symbols were found for the following modules:"); label.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5)); JPanel panel = new JPanel(new BorderLayout(10, 10)); panel.add(label, BorderLayout.NORTH); panel.add(new JScrollPane(table)); this.addWorkPanel(panel); this.addOKButton(); this.addCancelButton(); } public void changeSymbols(int idx) { SymbolInfo row = this.incompleteRows.get(idx); FindSymbolsFileChooser pdbChooser = new FindSymbolsFileChooser(null, row.attributes, useModulePdbPath); if (useModulePdbPath && row.attributes != null) { pdbChooser.setCurrentDirectory(new File(row.attributes.getPdbFile())); } File pdbFile = pdbChooser.getSelectedFile(); if (pdbChooser.getValidatedResult() != null) { row.result = pdbChooser.getValidatedResult(); worker.schedule(new TryFindMissingSymbols(pdbChooser.getValidatedRoot())); return; } if (pdbFile == null) { return; } executeProgressTask(new Task("Processing PDB") { @Override public void run(TaskMonitor monitor) throws CancelledException { try { row.result = PdbResolver.validatePdbCandidate(pdbFile, true, row.attributes, monitor); } catch (IOException | PdbException e) { row.message = "Error: " + e.getMessage() + " (" + pdbFile.getPath() + ")"; } table.repaint(); } }, 0); } class TryFindMissingSymbols extends Job { private File root; public TryFindMissingSymbols(File root) { this.root = root; } @Override public void run(TaskMonitor monitor) throws CancelledException { for (SymbolInfo row : incompleteRows) { if (row.result != null) { continue; } row.result = PdbResolver.tryFindSymbols(root, row.attributes, monitor); table.repaint(); } } } @Override protected void cancelCallback() { wasCancelled = true; super.cancelCallback(); } @Override protected void okCallback() { super.okCallback(); close(); } public boolean confirm() { DockingWindowManager.showDialog(null, this); return !wasCancelled; } } <file_sep>/README.md # Windows Minidump loader for Ghidra ### Work in progress ![Ghidra UI](images/readme.png) # Feature status ## Loader - [x] Find the modules in the Minidump and load each module separately with the PE loader. - [x] Position the modules to their correct runtime addresses. - [x] Replace the use of `ImageBaseOffset..` data types with `ModuleBaseOffset..`. - [x] Store the module boundaries in the `UserData`. - [x] Load the private memory as its own fragment. - [x] Parse the thread information and separate the thread stacks as their own fragments. - [x] Find the thread information from the dump and store that into `UserData`. ## Thread view - [x] Display threads and their RSP/RIP registers. - [x] Implement stack walking based on exception handling `UNWIND_INFO` - [x] `UNWIND_CODE` based walking. - [x] Chained `RUNTIME_FUNCTION` support. - [ ] Frame register support. - [ ] 32-bit support. ## Other See open issues on GitHub. # Changes to Ghidra packages The implementation depends heavily on the built-in `PeLoader` and `PortableExecutable` but required some changes to them: - Support loading modules to other base addresses than `Program.imageBase`. - Support loading modules separately from processing them. - Support linking import symbols directly into memory locations if target memory is present. - Support for `ModuleBaseOffsetXY` data types. The goal would be to have these changes upstreamed to Ghidra in the future to avoid the need to duplicate the implementation of the whole `..format.pe.*` package in the repository. However this work might need some clean up to bring the current changes up to Ghidra standard. The current changes to the Ghidra files are made with the goal to keep actual code changes to minimum with no concern for single-responsibility principle, etc. ## License The majority of the source code under this repository is covered by the Apache 2.0 License as described in the LICENSE file. The `contrib` package (excluding the `contrib.new_` contents) is copied over from Ghidra and is covered under [Ghidra's Apache 2.0 License][apache-ghidra]. [apache-ghidra]: https://github.com/NationalSecurityAgency/ghidra/blob/8f8c3cfa1406cc4a78b55dac4bb284ab01333bae/LICENSE <file_sep>/MinidumpLoader/src/main/java/net/jubjubnest/minidump/loader/parser/VsFixedFileInfo.java package net.jubjubnest.minidump.loader.parser; import java.io.IOException; import java.nio.ByteBuffer; import java.nio.ByteOrder; import ghidra.app.util.bin.ByteProvider; /** * VS_FIXEDFILEINFO * * https://docs.microsoft.com/en-us/windows/win32/api/verrsrc/ns-verrsrc-vs_fixedfileinfo */ public class VsFixedFileInfo { public static final int RECORD_SIZE = 4 + 4 + 8 + 8 + 4 + 4 + 4 + 4 + 4 + 8; public static VsFixedFileInfo parse(long offset, ByteProvider provider) throws IOException { var bytes = provider.readBytes(offset, RECORD_SIZE); var byteBuffer = ByteBuffer.wrap(bytes); byteBuffer.order(ByteOrder.LITTLE_ENDIAN); return parse(byteBuffer); } public static VsFixedFileInfo parse(ByteBuffer byteBuffer) { var info = new VsFixedFileInfo(); info.signature = byteBuffer.getInt(); info.structVersion = byteBuffer.getInt(); info.fileVersion = byteBuffer.getLong(); info.productVersion = byteBuffer.getLong(); info.flagsMask = byteBuffer.getInt(); info.flags = byteBuffer.getInt(); info.fileOs = byteBuffer.getInt(); info.fileType = byteBuffer.getInt(); info.fileSubtype = byteBuffer.getInt(); info.fileDate = byteBuffer.getLong(); return info; } public int signature; public int structVersion; public long fileVersion; public long productVersion; public int flagsMask; public int flags; public int fileOs; public int fileType; public int fileSubtype; public long fileDate; } <file_sep>/MinidumpLoader/src/main/java/net/jubjubnest/minidump/data/ModuleData.java package net.jubjubnest.minidump.data; import java.util.ArrayList; import java.util.List; import ghidra.program.model.address.Address; import ghidra.program.model.address.AddressIterator; import ghidra.program.model.listing.Program; import ghidra.program.model.util.ObjectPropertyMap; import ghidra.util.ObjectStorage; import ghidra.util.Saveable; public class ModuleData { public static final String PROPERTY_NAME = "MODULE_DATA"; public String name; public String loadedSymbols; public Address baseAddress; public Address rtiStartAddress; public Address rtiEndAddress; public ModuleData(String name, Address baseAddress, Address rtiStart, Address rtiEnd) { this.name = name; this.loadedSymbols = null; this.baseAddress = baseAddress; this.rtiStartAddress = rtiStart; this.rtiEndAddress = rtiEnd; } private ModuleData(Program program, Record record) { this.name = record.name; this.loadedSymbols = record.loadedSymbols; this.baseAddress = program.getImageBase().getNewAddress(record.baseAddress); this.rtiStartAddress = baseAddress.getNewAddress(record.rtiStartAddress); this.rtiEndAddress = baseAddress.getNewAddress(record.rtiEndAddress); } public static ModuleData getContainingModuleData(Program program, Address address) { ObjectPropertyMap objectMap = getModuleDataMap(program, false); if (objectMap == null) return null; // The modules shouldn't be interleaved and the data is set at the start of the module so we'll first try the specific // address but when that eventually fails we'll find the previous address that has data and trust that's the data for this module. Record record = (Record)objectMap.getObject(address); if (record == null) { Address previousAddress = objectMap.getPreviousPropertyAddress(address); if (previousAddress == null) { return null; } record = (Record)objectMap.getObject(previousAddress); } return new ModuleData(program, record); } public static List<ModuleData> getAllModules(Program program) { ObjectPropertyMap objectMap = getModuleDataMap(program, false); if (objectMap == null) return null; List<ModuleData> modules = new ArrayList<>(); AddressIterator iterator = objectMap.getPropertyIterator(); for (Address addr = iterator.next(); addr != null; addr = iterator.next()) { ModuleData moduleData = new ModuleData(program, (Record)objectMap.getObject(addr)); modules.add(moduleData); } return modules; } public static ModuleData getModuleData(Program program, Address address) { ObjectPropertyMap objectMap = getModuleDataMap(program, false); Record record = (Record)objectMap.getObject(address); return record == null ? null : new ModuleData(program, record); } public static void setModuleData(Program program, ModuleData data) { ObjectPropertyMap objectMap = getModuleDataMap(program, true); objectMap.add(data.baseAddress, new Record(data)); } private static ObjectPropertyMap getModuleDataMap(Program program, boolean create) { return ObjectMapResolver.getModuleDataMap(program, PROPERTY_NAME, Record.class, create); } public static class Record implements Saveable { private String name; private String loadedSymbols; private long baseAddress; private long rtiStartAddress; private long rtiEndAddress; public Record(ModuleData data) { this.name = data.name; this.loadedSymbols = data.loadedSymbols; this.baseAddress = data.baseAddress.getOffset(); this.rtiStartAddress = data.rtiStartAddress.getOffset(); this.rtiEndAddress = data.rtiEndAddress.getOffset(); } public Record() {} @Override public Class<?>[] getObjectStorageFields() { return new Class[] { String.class, String.class, long.class, long.class, long.class, }; } @Override public void save(ObjectStorage objStorage) { objStorage.putString(name); objStorage.putString(loadedSymbols); objStorage.putLong(baseAddress); objStorage.putLong(rtiStartAddress); objStorage.putLong(rtiEndAddress); } @Override public void restore(ObjectStorage objStorage) { name = objStorage.getString(); loadedSymbols = objStorage.getString(); baseAddress = objStorage.getLong(); rtiStartAddress = objStorage.getLong(); rtiEndAddress = objStorage.getLong(); } @Override public int getSchemaVersion() { return 0; } @Override public boolean isUpgradeable(int oldSchemaVersion) { return false; } @Override public boolean upgrade(ObjectStorage oldObjStorage, int oldSchemaVersion, ObjectStorage currentObjStorage) { return false; } @Override public boolean isPrivate() { return false; } } } <file_sep>/MinidumpLoader/src/main/java/net/jubjubnest/minidump/contrib/new_/ImageLoadInfo.java package net.jubjubnest.minidump.contrib.new_; import ghidra.framework.options.Options; import ghidra.program.model.listing.Program; import net.jubjubnest.minidump.contrib.pe.PortableExecutable.SectionLayout; public class ImageLoadInfo { public String imageName; public long imageBase; public boolean sharedProgram; public SectionLayout sectionLayout; public ImageLoadInfo() { imageName = null; imageBase = 0; sharedProgram = false; sectionLayout = SectionLayout.FILE; } public ImageLoadInfo(String moduleName, long moduleOffset) { imageName = moduleName; imageBase = moduleOffset; sharedProgram = true; sectionLayout = SectionLayout.MEMORY; } public String prefixName(String name) { return name; /* if (sharedProgram == false) return name; return imageName.toUpperCase() + "::" + name; */ } public Options getModuleOptions(Program program) { Options programOptions = program.getOptions(Program.PROGRAM_INFO); if (sharedProgram == false) { return programOptions; } Options moduleOptions = programOptions.getOptions("Module Information"); return moduleOptions.getOptions(imageName.replace('.', '_')); } } <file_sep>/MinidumpLoader/src/main/java/net/jubjubnest/minidump/plugin/parser/RuntimeFunction.java package net.jubjubnest.minidump.plugin.parser; import java.io.IOException; import ghidra.app.util.bin.BinaryReader; import ghidra.app.util.bin.ByteProvider; import ghidra.program.model.address.Address; public class RuntimeFunction { public Address imageBase; public Address startOfFunction; public Address endOfFunction; public Address runtimeInfo; public static RuntimeFunction parse(Address imageBase, BinaryReader reader) throws IOException { return new RuntimeFunction( imageBase, imageBase.add(reader.readNextInt()), imageBase.add(reader.readNextInt()), imageBase.add(reader.readNextInt())); } public RuntimeFunction(Address base, Address startFn, Address endFn, Address rtInfo) { imageBase = base; startOfFunction = startFn; endOfFunction = endFn; runtimeInfo = rtInfo; } public RuntimeInfo readRuntimeInfo(ByteProvider bytes) throws IOException { BinaryReader reader = new BinaryReader(bytes, true); reader.setPointerIndex(runtimeInfo.getOffset()); return RuntimeInfo.parse(imageBase, reader); } } <file_sep>/MinidumpLoader/src/main/java/net/jubjubnest/minidump/plugin/MinidumpPluginPackage.java package net.jubjubnest.minidump.plugin; import javax.swing.Icon; import ghidra.framework.plugintool.util.PluginPackage; import resources.ResourceManager; public class MinidumpPluginPackage extends PluginPackage { public static final String NAME = "Minidump"; protected MinidumpPluginPackage(String name, Icon icon, String description) { super(NAME, ResourceManager.loadImage("images/vcard.png"), "Plugins for working with Windows Minidump files."); } } <file_sep>/MinidumpLoader/src/main/java/net/jubjubnest/minidump/plugin/ModuleViewPlugin.java package net.jubjubnest.minidump.plugin; import ghidra.app.events.ProgramActivatedPluginEvent; import ghidra.app.plugin.PluginCategoryNames; import ghidra.app.plugin.ProgramPlugin; import ghidra.app.services.GoToService; import ghidra.framework.plugintool.PluginEvent; import ghidra.framework.plugintool.PluginInfo; import ghidra.framework.plugintool.PluginTool; import ghidra.framework.plugintool.util.PluginStatus; import ghidra.program.model.listing.Program; //@formatter:off @PluginInfo( status = PluginStatus.STABLE, packageName = MinidumpPluginPackage.NAME, category = PluginCategoryNames.NAVIGATION, shortDescription = "Display Minidump loaded module information.", description = "Display Minidump loaded module information." ) //@formatter:on public class ModuleViewPlugin extends ProgramPlugin { ModuleViewProvider modulesProvider; GoToService goToService; Program program; public ModuleViewPlugin(PluginTool tool) { super(tool, false, false); modulesProvider = new ModuleViewProvider(this, getName()); } @Override public void init() { super.init(); goToService = tool.getService(GoToService.class); } @Override public void processEvent(PluginEvent event) { if (event instanceof ProgramActivatedPluginEvent) { var ev = (ProgramActivatedPluginEvent)event; program = ev.getActiveProgram(); modulesProvider.programActivated(program); } } } <file_sep>/MinidumpLoader/src/main/java/net/jubjubnest/minidump/contrib/new_/ModuleBaseMap.java package net.jubjubnest.minidump.contrib.new_; import ghidra.program.model.address.Address; import ghidra.program.model.address.AddressIterator; import ghidra.program.model.listing.Program; import ghidra.program.model.util.IntPropertyMap; import ghidra.program.model.util.PropertyMapManager; import ghidra.util.exception.DuplicateNameException; import ghidra.util.exception.NoValueException; public class ModuleBaseMap { static final String MODULE_LIMITS_MAP_NAME = "MODULEBASEOFFSET_MODULE_LIMITS"; static final int MODULE_START = 1; static final int MODULE_END = 0; public static void markModule(Program program, Address start, Address end) { PropertyMapManager manager = program.getUsrPropertyManager(); IntPropertyMap map = manager.getIntPropertyMap(MODULE_LIMITS_MAP_NAME); if (map == null) { try { map = manager.createIntPropertyMap(MODULE_LIMITS_MAP_NAME); } catch (DuplicateNameException e) { map = manager.getIntPropertyMap(MODULE_LIMITS_MAP_NAME); } } map.add(start, MODULE_START); map.add(end, MODULE_END); } public static Address getModuleBase(Program program, Address addr) { PropertyMapManager manager = program.getUsrPropertyManager(); IntPropertyMap map = manager.getIntPropertyMap(MODULE_LIMITS_MAP_NAME); if (map == null) { return null; } AddressIterator iter = map.getPropertyIterator(addr, false); Address closest = iter.next(); int flag; try { flag = map.getInt(closest); } catch (NoValueException e) { // The address used in lookup should have value according to the map. throw new RuntimeException(e); } // If the previous record is start of module we'll return that. if (flag == MODULE_START) { return closest; } // No start of module record found. // There's a chance the user queried the exact end-of-module address, which is still // inclusive to the current module. If this happened, we'll continue iterating backwards // to acquire the start-of-module address. if (closest.equals(addr)) { return iter.next(); } return null; } } <file_sep>/MinidumpLoader/src/main/java/net/jubjubnest/minidump/plugin/ModuleListItem.java package net.jubjubnest.minidump.plugin; import ghidra.program.model.address.Address; import ghidra.program.model.listing.Program; import net.jubjubnest.minidump.data.ModuleData; class ModuleListItem { public String name; public Address baseAddress; public String symbolPath; public boolean symbolsLoaded; public ModuleListItem(Program program, ModuleData data) { this.name = data.name; this.symbolPath = data.loadedSymbols; this.symbolsLoaded = data.loadedSymbols != null; this.baseAddress = data.baseAddress; } } <file_sep>/MinidumpLoader/src/main/java/net/jubjubnest/minidump/contrib/new_/AbstractModuleBaseOffsetDataType.java package net.jubjubnest.minidump.contrib.new_; import ghidra.docking.settings.Settings; import ghidra.program.model.address.Address; import ghidra.program.model.address.AddressOutOfBoundsException; import ghidra.program.model.data.BuiltIn; import ghidra.program.model.data.CategoryPath; import ghidra.program.model.data.DataType; import ghidra.program.model.data.DataTypeManager; import ghidra.program.model.mem.MemBuffer; import ghidra.program.model.scalar.Scalar; abstract class AbstractModuleBaseOffsetDataType extends BuiltIn { public AbstractModuleBaseOffsetDataType(CategoryPath path, String name, DataTypeManager dtm) { super(path, name, dtm); } abstract DataType getScalarDataType(); static String generateName(DataType dt) { return "ModuleBaseOffset" + dt.getLength() * 8; } static String generateMnemonic(DataType dt) { return "mbo" + dt.getLength() * 8; } static String generateDescription(DataType dt) { return (dt.getLength() * 8) + "-bit Module Base Offset"; } @Override public String getDescription() { DataType dt = getScalarDataType(); return generateDescription(dt); } @Override public String getMnemonic(Settings settings) { DataType dt = getScalarDataType(); return generateMnemonic(dt); } @Override public int getLength() { return getScalarDataType().getLength(); } @Override public boolean isDynamicallySized() { return false; } @Override public String getRepresentation(MemBuffer buf, Settings settings, int length) { Address addr = (Address) getValue(buf, settings, length); if (addr == null) return "NaP"; return addr.toString(); } @Override public Object getValue(MemBuffer buf, Settings settings, int length) { Address moduleBase = ModuleBaseMap.getModuleBase(buf.getMemory().getProgram(), buf.getAddress()); if (moduleBase == null) { return null; } Scalar value = (Scalar) getScalarDataType().getValue(buf, settings, length); if (value == null || value.getUnsignedValue() == 0) { return null; } try { return moduleBase.add(value.getUnsignedValue()); } catch (AddressOutOfBoundsException e) { return null; } } } <file_sep>/MinidumpLoader/src/main/java/net/jubjubnest/minidump/plugin/ThreadViewProvider.java package net.jubjubnest.minidump.plugin; import java.awt.BorderLayout; import java.io.IOException; import java.nio.ByteBuffer; import java.nio.ByteOrder; import java.util.ArrayList; import java.util.List; import javax.swing.JComponent; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.ListSelectionModel; import javax.swing.SwingConstants; import javax.swing.event.ListSelectionEvent; import javax.swing.event.ListSelectionListener; import javax.swing.table.DefaultTableModel; import javax.swing.JScrollPane; import javax.swing.JSplitPane; import docking.ComponentProvider; import docking.widgets.table.GTable; import ghidra.app.util.bin.BinaryReader; import ghidra.app.util.bin.ByteProvider; import ghidra.app.util.bin.MemoryByteProvider; import ghidra.framework.model.DomainObjectChangedEvent; import ghidra.framework.model.DomainObjectListener; import ghidra.program.model.address.Address; import ghidra.program.model.listing.Program; import ghidra.util.Msg; import net.jubjubnest.minidump.data.ModuleData; import net.jubjubnest.minidump.data.ThreadData; import net.jubjubnest.minidump.plugin.parser.RuntimeFunction; import net.jubjubnest.minidump.plugin.parser.RuntimeInfo; // TODO: If provider is desired, it is recommended to move it to its own file class ThreadViewProvider extends ComponentProvider implements DomainObjectListener { public static final String NAME = "Memory Dump Threads"; private JPanel panel; private GTable threadTable; private StackList stackList; private Program program; private List<ThreadData> threadList; private ThreadViewPlugin plugin; private ThreadData activeThread; private JSplitPane activePanel; public ThreadViewProvider(ThreadViewPlugin plugin, String owner) { super(plugin.getTool(), NAME, owner); this.plugin = plugin; buildPanel(); } // Customize GUI private void buildPanel() { threadTable = new GTable() { @Override public boolean isCellEditable(int row, int column) { return false; } }; threadTable.setColumnSelectionAllowed(false); threadTable.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); threadTable.getSelectionModel().addListSelectionListener(new ListSelectionListener() { public void valueChanged(ListSelectionEvent event) { if( event.getValueIsAdjusting()) return; threadActivated(threadTable.getSelectionModel().getAnchorSelectionIndex()); } }); stackList = new StackList(this.plugin); activePanel = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT, new JScrollPane(threadTable), new JScrollPane(stackList)); panel = new JPanel(new BorderLayout()); addToTool(); programActivated(null); } public void programActivated(Program newProgram) { if (program != null) { program.removeListener(this); program = null; } if( newProgram == null ) { setInactive("No program loaded"); return; } program = newProgram; program.addListener(this); threadList = ThreadData.getAllThreadData(program); if (threadList == null || threadList.size() == 0) { setInactive("No thread information present in the loaded program"); return; } setActive(); String[] headers = { "Thread ID", "StackP.", "InstP." }; String[][] data = new String[threadList.size()][headers.length]; for (int i = 0; i < threadList.size(); i++) { var thread = threadList.get(i); data[i][0] = Integer.toString(thread.id); data[i][1] = thread.sp.toString(); data[i][2] = thread.ip.toString(); } var model = new DefaultTableModel(data, headers); threadTable.setModel(model); threadTable.setRowSelectionInterval(0, 0); } public void threadActivated(int threadIdx) { if (threadIdx == -1) { activeThread = null; } else { activeThread = threadList.get(threadIdx); } refreshStack(); } private void refreshStack() { var frames = new ArrayList<StackListItem>(); if (activeThread == null) { stackList.setFrames(frames, program); return; } // Set up a pointer-sized byte buffer for re-using when reading addresses. var pointerSize = program.getLanguage().getLanguageDescription().getSize(); byte[] ptr = new byte[pointerSize / 8]; var buffer = ByteBuffer.wrap(ptr); buffer.order(ByteOrder.LITTLE_ENDIAN); // Thread info will give us the top-of-the-stack register values so we'll start with those and then // attempt to walk the stack back from there. try { var firstFrame = getCaller(activeThread.sp, activeThread.ip, buffer); while (firstFrame != null) { frames.add(firstFrame); var rip = firstFrame.getReturnAddress(program); if (rip == null) break; firstFrame = getCaller(firstFrame.returnPointer.add(ptr.length), rip, buffer); } } catch (IOException e1) { // In case of an IO error we'll log it but don't do anything else. // Show as much of the stack as we managed to gather. Msg.warn(this, "Memory violation when resolving the call stack"); } stackList.setFrames(frames, program); } private void setInactive(String message) { panel.removeAll(); panel.add(new JLabel(message, SwingConstants.CENTER)); threadTable.setModel(new DefaultTableModel()); threadTable.clearSelection(); return; } private void setActive() { panel.removeAll(); panel.add(activePanel); } StackListItem getCaller(Address stackPtr, Address instructionPtr, ByteBuffer buffer) throws IOException { var memoryProvider = new MemoryByteProvider(program.getMemory(), instructionPtr.getAddressSpace()); var data = new byte[4*3]; var rtBuffer = ByteBuffer.wrap(data); rtBuffer.order(ByteOrder.LITTLE_ENDIAN); ModuleData moduleData = ModuleData.getContainingModuleData(program, instructionPtr); if (moduleData == null) { return null; } RuntimeFunction runtimeFunction = getRuntimeFunction(instructionPtr, moduleData, memoryProvider); if (runtimeFunction == null) return null; UnwindResult unwind = unwindStackPtr(stackPtr, instructionPtr, runtimeFunction, memoryProvider); long functionOffset = instructionPtr.subtract(unwind.finalFunction.startOfFunction); return new StackListItem(stackPtr, instructionPtr, unwind.finalStack, functionOffset, moduleData.name); } static class UnwindResult { Address finalStack; RuntimeFunction finalFunction; } UnwindResult unwindStackPtr(Address current, Address instructionPtr, RuntimeFunction rtFunction, ByteProvider memory) throws IOException { RuntimeInfo runtimeInfo = rtFunction.readRuntimeInfo(memory); RuntimeFunction finalFunction = rtFunction; while (runtimeInfo != null) { var functionOffset = instructionPtr.subtract(finalFunction.startOfFunction); for (var unwindCode : runtimeInfo.unwindCodes ) { if (unwindCode.prologOffset <= functionOffset) { current = current.add(unwindCode.spEffect); } } if (runtimeInfo.parentFunction == null) break; finalFunction = runtimeInfo.parentFunction; runtimeInfo = finalFunction.readRuntimeInfo(memory); } UnwindResult result = new UnwindResult(); result.finalStack = current; result.finalFunction = finalFunction; return result; } RuntimeFunction getRuntimeFunction(Address instructionPtr, ModuleData moduleData, ByteProvider memoryProvider) throws IOException { Address moduleBaseAddress = moduleData.baseAddress; BinaryReader reader = new BinaryReader(memoryProvider, true); reader.setPointerIndex(moduleData.rtiStartAddress.getOffset()); for (;reader.getPointerIndex() < moduleData.rtiEndAddress.getOffset();) { RuntimeFunction rf = RuntimeFunction.parse(moduleBaseAddress, reader); if (rf.startOfFunction.compareTo(instructionPtr) > 0) continue; if (rf.endOfFunction.compareTo(instructionPtr) < 0) continue; return rf; } return null; } @Override public JComponent getComponent() { return panel; } @Override public void domainObjectChanged(DomainObjectChangedEvent ev) { this.stackList.updateAnalysis(program); } }<file_sep>/MinidumpLoader/extension.properties name=@extname@ description=Tools for analyzing Windows Minidump files. author=<NAME> createdOn= version=@extversion@ <file_sep>/MinidumpLoader/src/main/java/net/jubjubnest/minidump/plugin/StackList.java package net.jubjubnest.minidump.plugin; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import java.util.List; import javax.swing.table.TableColumnModel; import docking.widgets.table.GTable; import ghidra.program.model.listing.Program; class StackList extends GTable { private ThreadViewPlugin plugin; private List<StackListItem> frames; private StackListModel model; public StackList(ThreadViewPlugin plugin) { this.plugin = plugin; this.addMouseListener(new MouseAdapter() { @Override public void mouseClicked(MouseEvent e) { if (e.getClickCount() == 2) { boolean goToStack = StackList.this.getSelectedColumn() == 0; navigateStack(StackList.this.getSelectedRow(), goToStack); } } }); } public void setFrames(List<StackListItem> frames, Program program) { this.frames = frames; model = new StackListModel(frames, program); this.setModel(model); TableColumnModel columns = getColumnModel(); columns.getColumn(0).setPreferredWidth(100); columns.getColumn(1).setPreferredWidth(1000); columns.getColumn(2).setPreferredWidth(100); columns.getColumn(3).setPreferredWidth(100); } public void updateAnalysis(Program program) { if (model != null) { model.updateAnalysis(program); } } private void navigateStack(int item, boolean goToStack) { var frame = frames.get(item); if (frame == null) return; if (goToStack) { plugin.goToService.goTo(frame.stackPointer); } else { plugin.goToService.goTo(frame.instructionPointer); } } @Override public boolean isCellEditable(int row, int column) { return false; } @Override public boolean getColumnSelectionAllowed() { return false; } } <file_sep>/MinidumpLoader/src/main/java/net/jubjubnest/minidump/data/ThreadData.java package net.jubjubnest.minidump.data; import java.util.ArrayList; import java.util.List; import ghidra.program.model.address.Address; import ghidra.program.model.listing.Program; import ghidra.program.model.util.ObjectPropertyMap; import ghidra.util.ObjectStorage; import ghidra.util.Saveable; public class ThreadData { public int id; public Address stackBase; public Address stackLimit; public Address stackPointer; public Address sp; public Address ip; public ThreadContext context; private static final String OBJECT_MAP_KEY = ThreadData.class.getCanonicalName(); // Address with which the thread data is associated. // stackLimit should be at "top" which makes more sense if this is ever visible in the UI. // The program is given as a parameter in the case this ever needs to take stack direction into account. private Address key(Program program) { return this.stackLimit; } public ThreadData(int id, Address stackBase, Address stackLimit, Address stackPointer, Address sp, Address ip, ThreadContext context) { this.id = id; this.stackBase = stackBase; this.stackLimit = stackLimit; this.stackPointer = stackPointer; this.sp = sp; this.ip = ip; this.context = context; } private ThreadData(Program program, Record record) { id = record.id; stackBase = program.getImageBase().getNewAddress(record.stackBase); stackLimit = stackBase.getNewAddress(record.stackLimit); stackPointer = stackBase.getNewAddress(record.stackPointer); sp = stackBase.getNewAddress(record.sp); ip = stackBase.getNewAddress(record.ip); switch (record.contextType) { case Context64.CONTEXT_TYPE: context = Context64.fromBytes(record.context); break; } } public static List<ThreadData> getAllThreadData(Program program) { List<ThreadData> list = new ArrayList<>(); ObjectPropertyMap map = getObjectMap(program, false); if (map != null) { for (Address addr : map.getPropertyIterator()) { list.add(new ThreadData(program, (Record)map.getObject(addr))); } } return list; } public static void storeThreadData(Program program, ThreadData data) { ObjectPropertyMap map = getObjectMap(program, true); map.add(data.key(program), new Record(data)); } private static ObjectPropertyMap getObjectMap(Program program, boolean create) { return ObjectMapResolver.getModuleDataMap(program, OBJECT_MAP_KEY, Record.class, create); } public static class Record implements Saveable { // Version 0 public int id; public long stackBase; public long stackLimit; public long stackPointer; public long sp; public long ip; // Version 1 public int contextType; public byte[] context; public Record(ThreadData data) { id = data.id; stackBase = data.stackBase.getOffset(); stackLimit = data.stackLimit.getOffset(); stackPointer = data.stackPointer.getOffset(); sp = data.sp.getOffset(); ip = data.ip.getOffset(); if (data.context == null) { contextType = 0; context = new byte[0]; } else { contextType = data.context.getType(); context = data.context.toBytes(); } } public Record() {} @Override public Class<?>[] getObjectStorageFields() { return new Class[] { int.class, long.class, long.class, long.class, long.class, long.class, int.class, String.class, }; } @Override public void save(ObjectStorage objStorage) { objStorage.putInt(id); objStorage.putLong(stackBase); objStorage.putLong(stackLimit); objStorage.putLong(stackPointer); objStorage.putLong(sp); objStorage.putLong(ip); objStorage.putInt(contextType); objStorage.putBytes(context); } @Override public void restore(ObjectStorage objStorage) { id = objStorage.getInt(); stackBase = objStorage.getLong(); stackLimit = objStorage.getLong(); stackPointer = objStorage.getLong(); sp = objStorage.getLong(); ip = objStorage.getLong(); contextType = objStorage.getInt(); context = objStorage.getBytes(); } @Override public int getSchemaVersion() { return 1; } @Override public boolean isUpgradeable(int oldSchemaVersion) { return true; } @Override public boolean upgrade(ObjectStorage oldObjStorage, int oldSchemaVersion, ObjectStorage currentObjStorage) { currentObjStorage.putInt(oldObjStorage.getInt()); currentObjStorage.putLong(oldObjStorage.getLong()); currentObjStorage.putLong(oldObjStorage.getLong()); currentObjStorage.putLong(oldObjStorage.getLong()); currentObjStorage.putLong(oldObjStorage.getLong()); currentObjStorage.putLong(oldObjStorage.getLong()); if (oldSchemaVersion < 1) { currentObjStorage.putInt(0); currentObjStorage.putBytes(new byte[0]); } else { currentObjStorage.putInt(oldObjStorage.getInt()); currentObjStorage.putBytes(oldObjStorage.getBytes()); } return true; } @Override public boolean isPrivate() { return false; } } }
3dae6353a3aab4892c490a5d5928144fb5b487fa
[ "Markdown", "Java", "INI" ]
17
Java
dobo90/ghidra-minidump-loader
025da0a34eaeda71fca437c3dd555db5f4522fcc
a3698958ac0d3062bf3f0641fd32c59ab3f9eed8
refs/heads/master
<file_sep>import csv,sys,os,re import numpy as np MONTH ={} MONTH["Jan"] = 1 MONTH["Feb"] = 2 MONTH["Mar"] = 3 MONTH["Apr"] = 4 MONTH["May"] = 5 MONTH["Jun"] = 6 MONTH["Jul"] = 7 MONTH["Aug"] = 8 MONTH["Sep"] = 9 MONTH["Oct"] = 10 MONTH["Nov"] = 11 MONTH["Dec"] = 12 def get_bloomberg_time(row_string): time_search = re.search(r"\s([\w,]+)\s+([\w]+),\s([\w]+)",row_string) if (time_search): month = MONTH[time_search.group(1)] day = time_search.group(2) year = time_search.group(3) time = str(month)+"/"+str(day)+"/"+str(year) return time def get_guardian_time(row_string): time_search = re.search(r'"([\w]+)\s([\w]+),([\w]+)"',row_string) if (time_search): month = MONTH[time_search.group(1).title()] day = time_search.group(2) year = time_search.group(3) time = str(month)+"/"+str(day)+"/"+str(year) return time if __name__ == "__main__": csv_file = sys.argv[1] out_csv = sys.argv[2] clean_rows=[] with open(csv_file, 'rb') as csvfile: spamreader = csv.reader(csvfile, delimiter=";", quotechar='|') for row in spamreader: row_string= ', '.join(row) time = get_bloomberg_time(row_string) if time: clean_row=[] clean_row.append(time) title_string_search = re.search(r'"(,[\w,]+)$',row_string) if(title_string_search): words = re.findall(r",([\w]+)",title_string_search.group(1)) print title_string_search.group(1) print words clean_row += words clean_rows.append(clean_row) with open(out_csv,'w') as ccf: writer = csv.writer(ccf) for clean_row in clean_rows: writer.writerow(clean_row) <file_sep>import scrapy from fintech_times.items import FintechTimesItem from scrapy.contrib.spiders import CrawlSpider, Rule from scrapy.contrib.linkextractors.sgml import SgmlLinkExtractor class FinNewsSpider(CrawlSpider): name = "times" allowed_domains = ["www.thetimes.co.uk"] url = "" start_urls = [] for i in range(1, 10): url = "http://www.thetimes.co.uk/search?p={}&q=iphone".format(i) start_urls.append(url) def parse(self, response): item = FintechTimesItem() itemlist = [] try: for ele in response.xpath('//h2[@class="Item-headline Headline--s Headline--regular"]'): title = ele.xpath('a').extract() date = ele.xpath('../div/span[@class="Dateline Item-dateline"]/text()').extract() print("{}:{}".format(date, title)) item["news"] = itemlist except Exception, e: pass <file_sep>import re def transform(link): result = "" for w in link: result += w return result def remove_special_characters(link_string): letters = list(link_string) for i in range(len(letters)): l = letters[i] if not (l.isalnum() or l == ">" or l == "<" or l == " "): letters[i] = " " return "".join(letters) def get_guardian_time(link_string): time_search = re.search(r"/([\d]+)/([\w]+)/+([\d]+)/", link_string) if (time_search): year = time_search.group(1) month = time_search.group(2) date = time_search.group(3) time = month + " " + date + "," + year return time def get_guardian_words(link_string): total_words = [] titles = re.findall(r">([\w\s]+)<", link_string) for title in titles: words = re.findall(r"[\w]+", title) total_words += words return total_words def get_guardian_time_words(link): link_string = transform(link) time = get_guardian_time(link_string) link_string = remove_special_characters(link_string) words = get_guardian_words(link_string) return time, words if __name__ == "__main__": test = "" get_guardian_time_words(test)<file_sep>The project is developed under the bitwisehacks hakathron program. With the use of web crawler, words frequency counting , machine learning, we aims to predict the stock price of Apple Inc by analyzing the last weeks' financial news. The project can be divided into followings: 1. grabbing the financial news titles about Apple Inc from mainstream financial news archive (e.g. Bloomberg, The Guardian) 2. grabbing the stock price record about Apple Inc in 2015 3. cleaning the data set, implementing word frequency counting and principle component analyze (PCA) 4. performing linear regression learning algorithms on the data <file_sep>import scrapy from fintech_guardian.items import FintechNytimesItem from scrapy.contrib.spiders import CrawlSpider, Rule from fintech_guardian.get_guardian import get_guardian_time_words from fintech_guardian.csv_write import write_csv from scrapy.contrib.linkextractors.sgml import SgmlLinkExtractor class FinNewsSpider(CrawlSpider): name = "guardian" allowed_domains = ["theguardian"] url = "" start_urls = [] for i in range(1, 13): url = 'https://www.theguardian.com/technology/ipod?page={}'.format(i) start_urls.append(url) def parse(self, response): item = FintechNytimesItem() try: for subitem in response.xpath('//div[@class="fc-item__container"]/a'): news = {} time, words = get_guardian_time_words(subitem.extract()) news[str(time)] = words write_csv(news) except Exception, e: pass <file_sep>import re def transform(link): result = "" for w in link: result += w return result def get_time(link): time_search = re.search(r"/([0-9-]+)/", link) time = "" if time_search: search = re.findall(r"[0-9]+", time_search.group(1)) time = search[1] + "/" + search[-1] + "/" + search[0] return time def get_words(link): total_words = [] titles = re.findall(r">([\w'?!&%;.\s]+)<", link) for title in titles: words = re.findall(r"[\w]+", title) total_words += words return total_words def get_time_words(time_title_dist): if not bool(time_title_dist): return None else: time_words = {} for key in time_title_dist.keys(): title = transform(time_title_dist[key]) letters = list(title) for i in range(len(letters)): l = letters[i] if not (l.isalnum() or l == ">" or l == "<" or l == " "): letters[i] = " " title = "".join(letters) words = get_words(title) time_words[key] = words return time_words<file_sep>import scrapy from fintech_bloomberg.items import FintechItem from scrapy.contrib.spiders import CrawlSpider, Rule from csv_write import write_csv from fintech_bloomberg.tools import get_time_words class FinNewsSpider(CrawlSpider): name = "finnews" allowed_domains = ["bloomberg"] url = "" start_urls = [] for i in range(1, 3001): url = 'http://www.bloomberg.com/search?query=apple&page={}'.format(i) start_urls.append(url) def parse(self, response): item = FintechItem() for subitem in response.xpath('//article[contains(@class, "search-result-story")]/div'): title = subitem.xpath('h1[@class="search-result-story__headline"]/a').extract() time = subitem.xpath('div/span/time[@class="published-at"]/text()').extract() # print('{} : {}'.format(title, time)) news = {} news[str(time)] = title # print(get_time_words(news)) write_csv(get_time_words(news)) # item["title"] = get_time_words(response.xpath('//article[@class="search-result-story type-article"]/' # 'div/h1[@class="search-result-story__headline"]/a').extract()) # item["date"] = response.xpath('//article[@class="search-result-story type-article"]/' # 'div/div/span/time[@class="published-at"]/text()').extract() # return item <file_sep>import csv def write_csv(time_words_dict): if not bool(time_words_dict) and len(time_words_dict.keys()) == 0: return False with open('bloomberg_apple_record.csv', 'a') as csv_file: writer = csv.writer(csv_file) for time, words in time_words_dict.items(): row = [] row.append(time) for word in words: row.append(word) writer.writerow(row) return True if __name__ == "__main__": dista = {} dista["time"] = ["2016", "2017", "2018"] write_csv(dista)
31ebebc6cb9fb6ee0763b1e8a828a829522a2ad6
[ "Markdown", "Python" ]
8
Python
wuchichung/apple-stock-price-trend-prediction
0c48a55d605f82ca311d85a07c38d9fa50013521
d14e25da461fd8e1bbeab72e9bb280e45ba51826
refs/heads/master
<file_sep>import React, { Component } from 'react'; class ArticleDetail extends Component { constructor(props) { super(props); this.state = {}; } render() { const { summary, showSummary, subHeadline, byLine } = this.props; const displaySummary = showSummary ? <div className='home-article-summary'>{summary}</div> : <div className='home-article-subheadline'>{`${subHeadline} `}<span>{byLine}</span></div>; return ( <React.Fragment> {displaySummary} </React.Fragment> ); } } ArticleDetail.defaultProps = {}; export default ArticleDetail;<file_sep>import React, { Component } from 'react'; import { Link } from 'react-router-dom'; //import any other components here import HelloWorld from '../src/helloworld'; import Article from '../src/article'; //import CSS here, so webpack knows to include in bundle import style from '../client/style/main.css'; //this is the component that generates the body of the page class App extends Component { constructor(props) { super(props); this.updateCategory = this.updateCategory.bind(this); //default state //this keeps track of "live" data on the browser this.state = { articles: null, error: null, loaded: false, selectedCategory: '' }; } componentDidMount() { //fetching data clientside fetch('/api/articles').then((data) => { return data.json(); }).then((data) => { console.log(data); //send data to our state //which will trigger render() this.setState({ articles: data.items, loaded: true }); }).catch((error) => { console.log(error); this.setState({ error: error, loaded: true }); }); } // UPDATE updateCategory(evt) { this.setState({selectedCategory: evt.target.innerText}) let category = document.getElementById('active') if (category) { category.removeAttribute('id'); } evt.target.setAttribute('id', 'active'); } render() { const {loaded, error, articles, selectedCategory} = this.state; // code above is equal to this: // const loaded = this.state.loaded; // const error = this.state.error; // const articles = this.state.articles; let categoriesSet = new Set(); articles && articles.map(article => { categoriesSet.add(article.category) }) let key = 1; if (error) { //render this when there's error getting data return <div>Sorry! Something went wrong</div> } else if (!loaded) { //render while content is loading return <div>Loading...</div> } else { //render articles let articleJSX = []; let filteredArticleJSX = []; articles.map((article, idx) => { articleJSX.push( <Article key={idx} headline={article.headline} summary={article.summary} image={article.image} category={article.category} subHeadline={article.subheadline} byLine={article.byline} publishedDate={article.date_published} selectedCategory={selectedCategory} link={article.share_link} /> ); }); // code above is equal to this: // for (let i = 0; i < articles.length; i++) { // articleJSX.push( // <Article key={i} headline={articles[i].headline}></Article> // ); // } if (this.state.selectedCategory) { filteredArticleJSX = articleJSX.filter(article => { return article.props.category === this.state.selectedCategory }) } return ( <React.Fragment> <HelloWorld /> <nav className='home-dropdown-category'> <ul> { [...categoriesSet].sort().map(category => {return <li className='home-dropdown-content' key={category} onClick={this.updateCategory} > <Link to='/'> {category} </Link> </li> }) } </ul> </nav> <div className='app-container'> {this.state.selectedCategory ? filteredArticleJSX : articleJSX} </div> </React.Fragment> ); } } } export default App;
680dd1940eee81b40ed4577a435a673903d0eaf9
[ "JavaScript" ]
2
JavaScript
mbetances805/dwReact
2e5f021c12a5339a79e1f6eeef29151e0eca3d30
a6131e09d7c95c3171039c192d583413e6832c25
refs/heads/master
<file_sep>hello! world Today is a windy day. Today is December 7th. <file_sep>package homework.twice; interface Computable<E>{ E add(E other); E minus(E other); } class Vector implements Computable<Vector>{ private int x,y; Vector(int x, int y){this.x=x;this.y=y;} public Vector add(Vector other){ return new Vector(this.x+other.x,+this.y+other.y); } public Vector minus(Vector other){ return new Vector(this.x-other.x,+this.y-other.y); } public String toString(){ return "("+x+","+y+")"; } } public class VectorTest { public static void main(String[] args){ Vector apple = new Vector(5,2); Vector banana = new Vector(3,-1); System.out.println(apple.add(banana)); System.out.println(apple.minus(banana)); } } <file_sep>package homework.twice; abstract class Vehicle { String number; double weight, height; abstract void display(); } class Bicycle extends Vehicle { Bicycle() { number = "T12345"; weight = 10; height = 20; } void display() { System.out.println("The Bicycle's number is " + number + ". It is " + weight + "kg heavy and " + height + " high."); } } class Car extends Vehicle { Car() { number = "B123456"; weight = 30.5; height = 10.5; } void display() { System.out.println("The Car's number is " + number + ". It is " + weight + "kg heavy and " + height + " high."); } } class Train extends Vehicle { Train() { number = "G8633"; weight = 100.6; height = 50.4; } void display() { System.out.println("The Train's number is " + number + ". It is " + weight + "kg heavy and " + height + " high."); } } public class Translation { public static void main(String[] args) { Bicycle x = new Bicycle(); Car y = new Car(); Train z = new Train(); x.display(); y.display(); z.display(); } } <file_sep>package homework.twice; class People{ private double weight,height; People(){ weight=50.2; height=172; } public String toString(){ return "Weight: " + weight + " kg\nHeight: " + height +" cm"; } } public class PeopleTest { public static void main(String[] agrs){ People wang=new People(); System.out.println(wang); } } <file_sep>interface InterfaceA{ String s="good "; void f(); } abstract class ClassA{ abstract void g(); } class ClassB extends ClassA implements InterfaceA{ void g(){ System.out.print(this.s); } public void f(){ System.out.print(" "+s); } } class E { public static void main(String[] args) { System.out.println(InterfaceA.s); } }
daf4e3cdb975fa8a6a02b62aa338ea66f4769da3
[ "Java", "Text" ]
5
Text
HeWeiChun/Homework5
dab8c13a6bcdb48688877d136f22e23b305860fc
959a48f65b5aca1f2655685b478245c71e10a8b2
refs/heads/main
<repo_name>Mihakgma/concat_all_excel_tables_into_only_one<file_sep>/Concat_all_Excel_tables_into_ONLY_ONE.py #!/usr/bin/env python # coding: utf-8 # In[15]: import os import pandas as pd from datetime import datetime as dt # In[2]: print(f'Текущая рабочая директория {(os.getcwd())}') # In[3]: #os.chdir('C:/Users/tabakaev_mv/Desktop/Сведение таблиц в одну') # In[4]: #print(f'Текущая рабочая директория {(os.getcwd())}') # In[57]: def excel_to_data_frame_parser(file): """ Парсит эксель-файл. Возвращает датафрейм (далее - ДФ). """ data = pd.ExcelFile(file) my_sheet_names = data.sheet_names list_number = 0 df = data.parse(my_sheet_names[list_number]) print(f'В ДФ с названием {file} {df.shape[0]} строк') print(f'В ДФ с названием {file} {df.shape[1]} столбцов') #print('OK!') return df # In[69]: def excel_concatenator(file_list, num_columns_to_remove: int = 8, num_to_drop_na: int = 12): for current_file in file_list: try: df = pd.DataFrame(columns=list(excel_to_data_frame_parser(current_file))) break except BaseException: print(f'Ошибка чтения таблицы из файла {current_file}') continue for file_name in file_list: if 'свод' in file_name.lower(): continue try: current_df = excel_to_data_frame_parser(file_name) except BaseException: print(f'Ошибка чтения таблицы из файла {file_name}') continue names_identical = list(df) == list(current_df) if not(names_identical): print(f'В данном файле {file_name} названия столбцов не соответствуют таковым в первом файле') df = df.append(current_df) print(df.shape) print(f'Размерность ДФ ДО удаления строк {df.shape}') df = df.iloc[:,:-num_columns_to_remove] df = df.dropna(thresh=num_to_drop_na) print(f'Размерность ДФ ПОСЛЕ удаления строк {df.shape}') today_date = dt.today().strftime('%d.%m.%Y') print(f"Сегодняшняя дата: {today_date}") df.to_excel('СВОД_'+str(today_date)+'.xlsx', startrow=0, index=True) print(f'Файл эксель с названием "СВОД_{today_date}.xlsx" сохранен в текущей директории!') print('ВСЕГО ХОРОШЕГО!') input() return df # In[63]: file_list = os.listdir() print(f'Список файлов для сведения: {file_list}') # In[71]: answer_go_forth = input('y/n') num_col_del = input('Количество колонок справа к удалению (по умолчанию задано 8): ') num_remove_in_row = input('Количество столбцов с пропущенными значениями для удаления всей строки (по умолчанию задано 12): ') if 'n' not in answer_go_forth.lower() and (len(num_col_del)>0 and len(num_remove_in_row)>0): df = excel_concatenator(file_list, int(num_col_del), int(num_remove_in_row)) elif 'n' not in answer_go_forth.lower(): df = excel_concatenator(file_list) else: print('ВСЕГО ХОРОШЕГО!') input() # In[ ]: # In[ ]:
9e18ca75fb8c9eac2fb8b7e0629ded0ee4085797
[ "Python" ]
1
Python
Mihakgma/concat_all_excel_tables_into_only_one
231b836950682849848a7cc2f72e94b40d02c678
052ba0fae5e359c8c80f6afed09cce04f0676d87
refs/heads/master
<repo_name>uS-aito/QueensLanceWebApp<file_sep>/QueensLanceHQ-WEBAPP/QueensLanceHQ-WEBAPP/MainForm.aspx.cs using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; namespace QueensLanceHQ_WEBAPP { public partial class MainForm : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { } protected void LogonButton_Click(object sender, EventArgs e) { if(UserNameTextBox.Text == "User1" && UserPasswordTextBox.Text == "<PASSWORD>") { ResultMessageLabel.Text = "ユーザ認証されました"; ResultMessageLabel.ForeColor = System.Drawing.Color.Blue; } else { ResultMessageLabel.Text = "ユーザ認証に失敗しました"; ResultMessageLabel.ForeColor = System.Drawing.Color.Red; } } } }
c5ab6cd712d9365ffc668a66eaa658c350538b6e
[ "C#" ]
1
C#
uS-aito/QueensLanceWebApp
54fe74072a56f73f0624abf6d6037cb48ee9e6aa
ec798b3242c73ec5fc48c6861f2ec0d1bb8f91ce
refs/heads/master
<repo_name>afrodeb/SuperGroupAssessment<file_sep>/front/web/src/app/login/login.component.ts import { Component, OnInit } from '@angular/core'; import {Router} from "@angular/router" import { UserService } from '../user.service'; import { User } from '../user'; @Component({ selector: 'app-login', templateUrl: './login.component.html', styleUrls: ['./login.component.css'] }) export class LoginComponent implements OnInit { user: User=new User; response: string=''; email = ''; password = ''; constructor(private router: Router,private userService: UserService) { } ngOnInit() { } tryLogin(){ this.userService.login(this.user) .subscribe(data => //console.log(data[0].text); data.forEach(c => { console.log(c); if(c.text === "true"){ localStorage.setItem('isLoggedIn', "true"); this.router.navigate(['/']); }else{ alert("Login failed"); } }); //response: string=this.data[0]; // console.log(this.response); this.user = new User(); /**/, error => console.log(error)); } } <file_sep>/src/main/java/supergroup/demo/repos/MovieRepository.java /* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package supergroup.demo.repos; import org.springframework.data.repository.CrudRepository; import supergroup.demo.models.Movie; import java.util.List; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.PathVariable; /** * * @author afrodeb */ public interface MovieRepository extends CrudRepository<Movie, Integer> { List<Movie> findById(int id); // void deleteById(int id); public Movie findByName(String name); } <file_sep>/sg.sql -- phpMyAdmin SQL Dump -- version 4.7.7 -- https://www.phpmyadmin.net/ -- -- Host: 127.0.0.1 -- Generation Time: Feb 27, 2019 at 11:16 PM -- Server version: 10.1.30-MariaDB -- PHP Version: 7.2.2 SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO"; SET AUTOCOMMIT = 0; START TRANSACTION; SET time_zone = "+00:00"; /*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */; /*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */; /*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */; /*!40101 SET NAMES utf8mb4 */; -- -- Database: `sg` -- -- -------------------------------------------------------- -- -- Table structure for table `movie` -- CREATE TABLE `movie` ( `id` int(11) NOT NULL, `name` varchar(255) NOT NULL, `type` varchar(255) NOT NULL, `rating` int(11) NOT NULL, `created` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ) ENGINE=InnoDB DEFAULT CHARSET=latin1; -- -- Dumping data for table `movie` -- INSERT INTO `movie` (`id`, `name`, `type`, `rating`, `created`) VALUES (5, 'Men In Black', 'Action', 5, '2019-02-27 09:35:57'), (6, 'Castle', 'Series', 4, '2019-02-27 09:50:15'), (7, 'Castle', 'Series', 4, '2019-02-27 09:52:07'), (8, 'Castle', 'Series', 4, '2019-02-27 09:52:31'), (9, 'Test2', 'Comedy', 3, '2019-02-27 10:40:45'), (10, 'Men In Black', 'Action', 5, '2019-02-27 11:25:18'), (11, 'Men In Black', 'Action', 5, '2019-02-27 11:41:48'), (12, 'Men In Black', 'Action', 5, '2019-02-27 11:44:00'), (13, 'Delon ', 'Comedy', 2, '2019-02-27 14:41:17'); -- -- Indexes for dumped tables -- -- -- Indexes for table `movie` -- ALTER TABLE `movie` ADD PRIMARY KEY (`id`); -- -- AUTO_INCREMENT for dumped tables -- -- -- AUTO_INCREMENT for table `movie` -- ALTER TABLE `movie` MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=14; COMMIT; /*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */; /*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */; /*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */; <file_sep>/src/test/java/supergroup/demo/AssessmentApplicationTests.java package supergroup.demo; import org.junit.Test; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.boot.test.context.SpringBootTest.WebEnvironment; @SpringBootTest(webEnvironment=WebEnvironment.RANDOM_PORT) public class AssessmentApplicationTests { @Test public void contextLoads() { } } <file_sep>/src/main/java/supergroup/demo/controllers/MovieRestController.java /* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package supergroup.demo.controllers; import supergroup.demo.models.Movie; import supergroup.demo.repos.MovieRepository; import java.util.ArrayList; import java.util.List; import java.util.Optional; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpHeaders; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.http.converter.HttpMessageNotReadableException; import org.springframework.web.bind.annotation.ControllerAdvice; import org.springframework.web.bind.annotation.CrossOrigin; import org.springframework.web.bind.annotation.DeleteMapping; import org.springframework.web.bind.annotation.ExceptionHandler; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.PutMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.ResponseStatus; import org.springframework.web.bind.annotation.RestController; import org.springframework.web.context.request.WebRequest; import org.springframework.web.servlet.mvc.method.annotation.ResponseEntityExceptionHandler; /** * * @author afrodeb */ @CrossOrigin(origins = "http://localhost:4200") @RestController @RequestMapping("/api") public class MovieRestController { @Autowired MovieRepository repository; @GetMapping("/movies") public List<Movie> fetchAll() { List<Movie> movies = new ArrayList<>(); repository.findAll().forEach(movies::add); return movies; } @PostMapping(value = "/movies/create") public Movie postMovie(@RequestBody Movie movie) { try { Movie _movie = repository.save(new Movie(movie.getName(), movie.getType(), movie.getRating())); return _movie; } catch (Exception ex) { ex.printStackTrace(); return null; } } @DeleteMapping("/movies/{id}") public ResponseEntity<String> deleteMovie(@PathVariable("id") Integer id) { try { repository.deleteById(id); return new ResponseEntity<>("Movie has been deleted!", HttpStatus.OK); } catch (Exception ex) { ex.printStackTrace(); return new ResponseEntity<>("Error occured while deleting!", HttpStatus.OK); } } @DeleteMapping("/movies/delete") public ResponseEntity<String> deleteAllMovies() { repository.deleteAll(); return new ResponseEntity<>("All movies have been deleted!", HttpStatus.OK); } @GetMapping(value = "/movies/id/{id}") public List<Movie> findById(@PathVariable int id) { List<Movie> movie = repository.findById(id); return movie; } @PutMapping("/movies/{id}") public ResponseEntity<Movie> updateMovie(@PathVariable("id") Integer id, @RequestBody Movie movie) { Optional<Movie> movieData = repository.findById(id); if (movieData.isPresent()) { Movie _movie = movieData.get(); _movie.setName(movie.getName()); return new ResponseEntity<>(repository.save(_movie), HttpStatus.OK); } else { return new ResponseEntity<>(HttpStatus.NOT_FOUND); } } @ExceptionHandler(Exception.class) @ResponseStatus(value = HttpStatus.INTERNAL_SERVER_ERROR, reason = "Error message") public void handleError() { } @ExceptionHandler(Exception.class) protected ResponseEntity<Object> handleHttpMessageNotReadable(HttpMessageNotReadableException ex, HttpHeaders headers, HttpStatus status, WebRequest request) { return new ResponseEntity<>(HttpStatus.BAD_REQUEST); } } <file_sep>/src/main/resources/application.properties spring.jpa.hibernate.ddl-auto=none spring.datasource.url=jdbc:mysql://localhost:3306/sg spring.datasource.username=root spring.datasource.password= spring.thymeleaf.cache=false spring.thymeleaf.enabled=true spring.thymeleaf.prefix=classpath:/templates/ spring.thymeleaf.suffix=.html logging.path=C:/musvo/ spring.application.name=Bootstrap Spring Boot server.port=9000 logging.level.org.hibernate.SQL=debug <file_sep>/front/web/src/app/app.routing.ts import { RouterModule, Routes } from '@angular/router'; import { CreateMovieComponent } from './create-movie/create-movie.component'; import { MovieListComponent } from './movie-list/movie-list.component'; import { MovieDetailsComponent } from './movie-details/movie-details.component'; import { EditMovieComponent } from './edit-movie/edit-movie.component'; import { LoginComponent } from './login/login.component'; const routes: Routes = [ { path: '', component: MovieListComponent }, { path: 'movies', component: MovieListComponent }, { path: 'view/:id', component: MovieDetailsComponent }, { path: 'edit/:id', component: EditMovieComponent }, { path: 'movie-create', component: CreateMovieComponent }, { path: 'login', component: LoginComponent }, ]; export const routing = RouterModule.forRoot(routes);<file_sep>/front/web/src/app/movie-details/movie-details.component.ts import { Component, OnInit } from '@angular/core'; import { Observable } from 'rxjs'; import {Router} from "@angular/router" import { ActivatedRoute } from '@angular/router'; import { MoviesService } from '../movies.service'; import { Movie } from '../movie'; @Component({ selector: 'app-movie-details', templateUrl: './movie-details.component.html', styleUrls: ['./movie-details.component.css'] }) export class MovieDetailsComponent implements OnInit { movie: Movie=new Movie; movies: Array<object> = []; submitted = false; constructor(private moviesService: MoviesService,private route: ActivatedRoute,private router: Router) { } ngOnInit() { this.route.queryParams.subscribe(params => { this.moviesService.getMovie(this.route.snapshot.params.id).subscribe((data: Array<object>) => { //this.movie = data; this.movies=data; console.log(data); }); }); //this.reloadData(); } deleteMovie(id, name) { if(confirm("Are you sure to delete "+name)) { this.moviesService.deleteMovie(id) .subscribe( data => { console.log(data); this.router.navigate(['/']); //this.reloadData(); }, error => console.log('ERROR: ' + error)); console.log(id); } } } <file_sep>/front/web/src/app/user.service.ts import { Injectable } from '@angular/core'; import { HttpClient } from '@angular/common/http'; import { Observable } from 'rxjs'; import { Movie } from './movie'; @Injectable({ providedIn: 'root' }) export class UserService { private baseUrl = 'http://localhost:9000/api/user'; constructor(private http: HttpClient) { } login(user: Object): Observable<any> { return this.http.post(`${this.baseUrl}` + `/login`, user); } } <file_sep>/front/web/src/app/edit-movie/edit-movie.component.ts import { Component, OnInit } from '@angular/core'; import { Observable } from 'rxjs'; import {Router} from "@angular/router" import { ActivatedRoute } from '@angular/router'; import { MoviesService } from '../movies.service'; import { Movie } from '../movie'; @Component({ selector: 'app-edit-movie', templateUrl: './edit-movie.component.html', styleUrls: ['./edit-movie.component.css'] }) export class EditMovieComponent implements OnInit { movie: Movie=new Movie(); movies: Array<Movie> = []; submitted = false; constructor(private moviesService: MoviesService,private route: ActivatedRoute,private router: Router) { } ngOnInit() { this.route.queryParams.subscribe(params => { this.moviesService.getMovie(this.route.snapshot.params.id).subscribe((data: Array<Movie>) => { this.movies=data; //console.log(this.movie); }); }); //this.reloadData(); } newMovie(): void { this.submitted = false; this.movie = new Movie(); this.router.navigate(['/']); } update() { // console.log(this.movies[0].id); this.moviesService.updateMovie(this.movies[0].id,this.movies[0]) .subscribe(data => console.log(data), error => console.log(error)); this.submitted = true; } }<file_sep>/src/main/java/supergroup/demo/controllers/UserRestController.java /* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package supergroup.demo.controllers; import java.util.ArrayList; import java.util.List; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.CrossOrigin; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RestController; import org.springframework.web.bind.annotation.RequestMapping; import supergroup.demo.models.LoginResponse; import supergroup.demo.models.User; /** * * @author afrodeb */ @CrossOrigin(origins = "http://localhost:4200") @RestController @RequestMapping("/api") public class UserRestController { @PostMapping(value = "/user/login") public List<LoginResponse> login(@RequestBody User user) { List result=new ArrayList<String>(); try { User _user=new User(user.getEmail(),user.getPassword()); result.add(new LoginResponse(_user.login())); //return _user.login(); } catch (Exception ex) { ex.printStackTrace(); //return "Error Occured"; } return result; } } <file_sep>/README.md <center><h1>SuperGroupAssessment</h1></center> <pre>The proect files are structed as follows</pre> #Step 1 Create a database 'sg' and import sg.sql into it. #Step 2 Open IDE and import the maven project #Step 3 Run the Spring Boot application, it will listen on port 9000. #Step 4 Open Terminal and navigate to /front/web, Type in <b>ng build</b>, then <b>ng serve</b> #Step 5 Access the frontend on http://localhost:4200<file_sep>/front/web/src/app/movie-list/movie-list.component.ts import { Component, OnInit } from '@angular/core'; import { Observable } from 'rxjs'; import {Router} from "@angular/router" import { MoviesService } from '../movies.service'; import { Movie } from '../movie'; @Component({ selector: 'app-movie-list', templateUrl: './movie-list.component.html', styleUrls: ['./movie-list.component.css'] }) export class MovieListComponent implements OnInit { movie: Movie=new Movie; movies: Array<object> = []; submitted = false; constructor(private moviesService: MoviesService,private router: Router) { } ngOnInit() { if(localStorage.getItem('isLoggedIn') != "true"){ this.router.navigate(['/login']); } this.reloadData(); } deleteUsers() { this.moviesService.deleteAll() .subscribe( data => { console.log(data); this.reloadData(); }, error => console.log('ERROR: ' + error)); } reloadData() { this.moviesService.getMovieList().subscribe((data: Array<object>) => { this.movies = data; console.log(data); }); } } <file_sep>/front/web/src/app/app.module.ts import { BrowserModule } from '@angular/platform-browser'; import { NgModule } from '@angular/core'; import { FormsModule } from '@angular/forms'; import { AppComponent } from './app.component'; import { MovieListComponent } from './movie-list/movie-list.component'; import { MovieDetailsComponent } from './movie-details/movie-details.component'; import { CreateMovieComponent } from './create-movie/create-movie.component'; import { HttpClient } from '@angular/common/http'; import { Observable } from 'rxjs'; import {routing} from "./app.routing"; import {ReactiveFormsModule} from "@angular/forms"; import {HttpClientModule} from "@angular/common/http"; import {MoviesService} from "./movies.service"; import { LoginComponent } from './login/login.component'; import { EditMovieComponent } from './edit-movie/edit-movie.component'; @NgModule({ declarations: [ AppComponent, MovieListComponent, MovieDetailsComponent, CreateMovieComponent, LoginComponent, EditMovieComponent ], imports: [ BrowserModule, routing, FormsModule, ReactiveFormsModule, HttpClientModule ], providers: [MoviesService], bootstrap: [AppComponent] }) export class AppModule { }<file_sep>/front/web/src/app/movie-details/movie-details.component.html <h1> Movie Details </h1> <div> <table *ngFor="let movie of movies" style="widtd:100%" class="table"> <tr> <td>Name</td> <td> {{ movie.name }} </td> </tr> <tr> <td>Genre</td> <td> {{ movie.type }} </td> </tr> <tr> <td>Rating</td> <td> {{ movie.rating }}/5</td> </tr> <tr> <td>Added</td> <td> {{ movie.created | date }} </td> </tr> <tr> <td>Action</td> <td> <button class='btn btn-warning' class="btn btn-warning" (click)="deleteMovie(movie.id,movie.name)">Delete</button> </td> </tr> </table> <file_sep>/front/web/src/app/movie-list/movie-list.component.html <h1> Movie List </h1> <div> <a class="btn btn-primary" routerLink="/movie-create" routerLinkActive="active">Add New Movie</a> <table style="width:100%" class="table"> <tr> <th>Name</th> <th>Genre</th> <th>Rating</th> <th>Added</th> <th>Action</th> </tr> <tr *ngFor="let movie of movies"> <td> {{ movie.name }} </td> <td> {{ movie.type }} </td> <td> {{ movie.rating }}/5</td> <td> {{ movie.created | date }} </td> <td> <a class='btn btn-primary' routerLink='/view/{{movie.id}}' routerLinkActive="active">View</a> <a class='btn btn-warning' routerLink='/edit/{{movie.id}}' routerLinkActive="active">Edit</a> </td> </tr> </table>
fb6f745eb2f53c1e1e3bb4908ac95c1a92c3b31f
[ "SQL", "HTML", "Markdown", "INI", "Java", "TypeScript" ]
16
TypeScript
afrodeb/SuperGroupAssessment
7aff81f22c3714bb3a28650c2ed232bd6e227b21
234ae4d296526dae9e0e9b1af051fc79e696b5c7
refs/heads/master
<repo_name>keiiti975/Insect_Phenology_Detector<file_sep>/model/resnet/unused/data_augmentation.py # -*- coding: utf-8 -*- from os.path import join as pj import random import torchvision from model.resnet.unused import aa_transforms from model.resnet.unused import faa_transforms class AutoAugment(object): def __init__(self, policy_dir=None): """ 初期化関数 引数: - policy_dir: str, FastAutoAugmentで得られたpolicy.txtが格納されているフォルダへのパス """ self.policy_dir = policy_dir if policy_dir is not None: self.policies = read_transform_txt(policy_dir) # FastAutoAugmentで得られたデータ拡張 else: # AutoAugmentで指摘されたデータ拡張 self.policies = [ ['Invert', 0.1, 7, 'Contrast', 0.2, 6], ['Rotate', 0.7, 2, 'TranslateX', 0.3, 9], ['Sharpness', 0.8, 1, 'Sharpness', 0.9, 3], ['ShearY', 0.5, 8, 'TranslateY', 0.7, 9], ['AutoContrast', 0.5, 8, 'Equalize', 0.9, 2], ['ShearY', 0.2, 7, 'Posterize', 0.3, 7], ['Color', 0.4, 3, 'Brightness', 0.6, 7], ['Sharpness', 0.3, 9, 'Brightness', 0.7, 9], ['Equalize', 0.6, 5, 'Equalize', 0.5, 1], ['Contrast', 0.6, 7, 'Sharpness', 0.6, 5], ['Color', 0.7, 7, 'TranslateX', 0.5, 8], ['Equalize', 0.3, 7, 'AutoContrast', 0.4, 8], ['TranslateY', 0.4, 3, 'Sharpness', 0.2, 6], ['Brightness', 0.9, 6, 'Color', 0.2, 8], ['Solarize', 0.5, 2, 'Invert', 0, 0.3], ['Equalize', 0.2, 0, 'AutoContrast', 0.6, 0], ['Equalize', 0.2, 8, 'Equalize', 0.6, 4], ['Color', 0.9, 9, 'Equalize', 0.6, 6], ['AutoContrast', 0.8, 4, 'Solarize', 0.2, 8], ['Brightness', 0.1, 3, 'Color', 0.7, 0], ['Solarize', 0.4, 5, 'AutoContrast', 0.9, 3], ['TranslateY', 0.9, 9, 'TranslateY', 0.7, 9], ['AutoContrast', 0.9, 2, 'Solarize', 0.8, 3], ['Equalize', 0.8, 8, 'Invert', 0.1, 3], ['TranslateY', 0.7, 9, 'AutoContrast', 0.9, 1], ] def __call__(self, img): if self.policy_dir is not None: # 昆虫の分類を用いてFastAutoAugmentを動かし、得られた最長データ拡張を適用 # 得られたデータ拡張はpolicy.txtに記載 img = self.policies[random.randrange(len(self.policies))](img) else: # AutoAugmentで指摘された最良データ拡張を適用 img = apply_policy(img, self.policies[random.randrange(len(self.policies))]) return img operations = { 'ShearX': lambda img, magnitude: aa_transforms.shear_x(img, magnitude), 'ShearY': lambda img, magnitude: aa_transforms.shear_y(img, magnitude), 'TranslateX': lambda img, magnitude: aa_transforms.translate_x(img, magnitude), 'TranslateY': lambda img, magnitude: aa_transforms.translate_y(img, magnitude), 'Rotate': lambda img, magnitude: aa_transforms.rotate(img, magnitude), 'AutoContrast': lambda img, magnitude: aa_transforms.auto_contrast(img, magnitude), 'Invert': lambda img, magnitude: aa_transforms.invert(img, magnitude), 'Equalize': lambda img, magnitude: aa_transforms.equalize(img, magnitude), 'Solarize': lambda img, magnitude: aa_transforms.solarize(img, magnitude), 'Posterize': lambda img, magnitude: aa_transforms.posterize(img, magnitude), 'Contrast': lambda img, magnitude: aa_transforms.contrast(img, magnitude), 'Color': lambda img, magnitude: aa_transforms.color(img, magnitude), 'Brightness': lambda img, magnitude: aa_transforms.brightness(img, magnitude), 'Sharpness': lambda img, magnitude: aa_transforms.sharpness(img, magnitude), 'Cutout': lambda img, magnitude: aa_transforms.cutout(img, magnitude), } def apply_policy(img, policy): """ AutoAugmentを適用 引数: img: PIL画像だったはず policy: self.policiesに記載しているデータ拡張 """ if random.random() < policy[1]: img = operations[policy[0]](img, policy[2]) if random.random() < policy[4]: img = operations[policy[3]](img, policy[5]) return img def read_transform_txt(policy_dir, policy_filename="policy.txt"): """ FastAutoAugmentで得られたデータ拡張を読み込み、torchvisionのデータ拡張に変換 引数: - policy_dir: str, FastAutoAugmentで得られたpolicy.txtが格納されているフォルダへのパス - policy_filename: str, データ拡張が格納されたファイルのファイル名 """ with open(pj(policy_dir, policy_filename), mode='r') as f: lines = f.readlines() transform = [] for line in lines: elem_array = line.split(' ') policy_array = [] for i, elem in enumerate(elem_array): if i % 3 == 0: if elem == "ShearXY": policy_array.append(faa_transforms.ShearXY(prob=float(elem_array[i+1]), mag=float(elem_array[i+2]))) if elem == "TranslateXY": policy_array.append(faa_transforms.TranslateXY(prob=float(elem_array[i+1]), mag=float(elem_array[i+2]))) if elem == "Rotate": policy_array.append(faa_transforms.Rotate(prob=float(elem_array[i+1]), mag=float(elem_array[i+2]))) if elem == "AutoContrast": policy_array.append(faa_transforms.AutoContrast(prob=float(elem_array[i+1]), mag=float(elem_array[i+2]))) if elem == "Invert": policy_array.append(faa_transforms.Invert(prob=float(elem_array[i+1]), mag=float(elem_array[i+2]))) if elem == "Equalize": policy_array.append(faa_transforms.Equalize(prob=float(elem_array[i+1]), mag=float(elem_array[i+2]))) if elem == "Solarize": policy_array.append(faa_transforms.Solarize(prob=float(elem_array[i+1]), mag=float(elem_array[i+2]))) if elem == "Posterize": policy_array.append(faa_transforms.Posterize(prob=float(elem_array[i+1]), mag=float(elem_array[i+2]))) if elem == "Contrast": policy_array.append(faa_transforms.Contrast(prob=float(elem_array[i+1]), mag=float(elem_array[i+2]))) if elem == "Color": policy_array.append(faa_transforms.Color(prob=float(elem_array[i+1]), mag=float(elem_array[i+2]))) if elem == "Brightness": policy_array.append(faa_transforms.Brightness(prob=float(elem_array[i+1]), mag=float(elem_array[i+2]))) if elem == "Sharpness": policy_array.append(faa_transforms.Sharpness(prob=float(elem_array[i+1]), mag=float(elem_array[i+2]))) if elem == "Cutout": policy_array.append(faa_transforms.Cutout(prob=float(elem_array[i+1]), mag=float(elem_array[i+2]))) else: continue policy_array = torchvision.transforms.Compose(policy_array) transform.append(policy_array) return transform<file_sep>/model/refinedet/vgg_base.py import torch import torch.nn as nn from model.conv_layer import WS_Conv2d from torch.utils.model_zoo import load_url as load_state_dict_from_url __all__ = [ 'VGG', 'vgg16' ] model_urls = { 'vgg16': 'https://download.pytorch.org/models/vgg16-397923af.pth' } cfg = [64, 64, 'M', 128, 128, 'M', 256, 256, 256, 'M', 512, 512, 512, 'M', 512, 512, 512, 'M'] class VGG(nn.Module): def __init__(self, features, num_classes=1000, init_weights=True): super(VGG, self).__init__() self.features = features self.avgpool = nn.AdaptiveAvgPool2d((7, 7)) self.classifier = nn.Sequential( nn.Linear(512 * 7 * 7, 4096), nn.ReLU(True), nn.Dropout(), nn.Linear(4096, 4096), nn.ReLU(True), nn.Dropout(), nn.Linear(4096, num_classes), ) self._initialize_weights() def forward(self, x): x = self.features(x) x = self.avgpool(x) x = torch.flatten(x, 1) x = self.classifier(x) return x def _initialize_weights(self): for m in self.modules(): if isinstance(m, nn.Conv2d): nn.init.xavier_uniform_(m.weight) if m.bias is not None: nn.init.constant_(m.bias, 0) elif isinstance(m, nn.BatchNorm2d): nn.init.constant_(m.weight, 1) nn.init.constant_(m.bias, 0) elif isinstance(m, nn.Linear): nn.init.normal_(m.weight, 0, 0.01) nn.init.constant_(m.bias, 0) def make_layers(cfg, activation_function, use_GN_WS): if use_GN_WS is True: Conv2d = WS_Conv2d else: Conv2d = nn.Conv2d layers = [] in_channels = 3 for v in cfg: if v == 'M': layers += [nn.MaxPool2d(kernel_size=2, stride=2)] else: conv2d = Conv2d(in_channels, v, kernel_size=3, padding=1) layers += [conv2d] if activation_function == "ReLU": layers += [nn.ReLU(inplace=True)] elif activation_function == "LeakyReLU": layers += [nn.LeakyReLU(inplace=True)] elif activation_function == "ELU": layers += [nn.ELU(inplace=True)] elif activation_function == "LogSigmoid": layers += [nn.LogSigmoid()] elif activation_function == "RReLU": layers += [nn.RReLU(inplace=True)] elif activation_function == "SELU": layers += [nn.SELU(inplace=True)] elif activation_function == "CELU": layers += [nn.CELU(inplace=True)] elif activation_function == "Sigmoid": layers += [nn.Sigmoid()] in_channels = v return nn.Sequential(*layers) def _vgg(arch, pretrained, progress, activation_function, use_GN_WS, **kwargs): if pretrained: kwargs['init_weights'] = False model = VGG(make_layers(cfg, activation_function, use_GN_WS), **kwargs) if pretrained: state_dict = load_state_dict_from_url(model_urls[arch], progress=progress) model.load_state_dict(state_dict) return model <file_sep>/model/refinedet/utils/predict.py import numpy as np from tqdm import tqdm import torch def test_prediction(model, data_loader, crop_num, num_classes, nms_thresh=0.3): """ get refinedet prediction with classification (dataset = insects_dataset_from_voc_style_txt) - model: pytorch model - data_loader: insects_dataset_from_voc_style_txt - crop_num: (int, int) - num_classes: (int), front_class + background_class - nms_thresh: (float) """ # set refinedet to eval mode model.eval() result = {} # image_id is needed because order of all_boxes is different from order of recs image_id = [] for images, default_height, default_width, data_ids in tqdm(data_loader): images = images[0] default_height = default_height[0] default_width = default_width[0] data_ids = data_ids[0] image_id.append(data_ids[0][0]) print("detecting ... : " + str(data_ids[0][0])) # define cropped image height,width img_after_crop_h = int(default_height / crop_num[0]) img_after_crop_w = int(default_width / crop_num[1]) # class detection for all image cls_dets_per_class = [[] for i in range(num_classes-1)] # estimate for cropped image for i in range(images.shape[0]): image = images[i:i + 1] image = torch.from_numpy(image).cuda() # estimate detections = model(image) for j in range(num_classes-1): detection = detections[0][j+1].detach().cpu().numpy() boxes = detection[:, 1:] scores = detection[:, 0] if data_ids[i][1][0] == crop_num[0] - 1 and data_ids[i][1][1] == crop_num[1] - 1: boxes[:, 0] = (boxes[:, 0] * img_after_crop_w) + \ data_ids[i][1][1] / crop_num[1] * default_width boxes[:, 1] = (boxes[:, 1] * img_after_crop_h) + \ data_ids[i][1][0] / crop_num[0] * default_height boxes[:, 2] = (boxes[:, 2] * img_after_crop_w) + \ data_ids[i][1][1] / crop_num[1] * default_width boxes[:, 3] = (boxes[:, 3] * img_after_crop_h) + \ data_ids[i][1][0] / crop_num[0] * default_height elif data_ids[i][1][0] == crop_num[0] - 1: boxes[:, 0] = (boxes[:, 0] * (img_after_crop_w + 100)) + \ data_ids[i][1][1] / crop_num[1] * default_width boxes[:, 1] = (boxes[:, 1] * img_after_crop_h) + \ data_ids[i][1][0] / crop_num[0] * default_height boxes[:, 2] = (boxes[:, 2] * (img_after_crop_w + 100)) + \ data_ids[i][1][1] / crop_num[1] * default_width boxes[:, 3] = (boxes[:, 3] * img_after_crop_h) + \ data_ids[i][1][0] / crop_num[0] * default_height elif data_ids[i][1][1] == crop_num[1] - 1: boxes[:, 0] = (boxes[:, 0] * img_after_crop_w) + \ data_ids[i][1][1] / crop_num[1] * default_width boxes[:, 1] = (boxes[:, 1] * (img_after_crop_h + 100)) + \ data_ids[i][1][0] / crop_num[0] * default_height boxes[:, 2] = (boxes[:, 2] * img_after_crop_w) + \ data_ids[i][1][1] / crop_num[1] * default_width boxes[:, 3] = (boxes[:, 3] * (img_after_crop_h + 100)) + \ data_ids[i][1][0] / crop_num[0] * default_height else: boxes[:, 0] = (boxes[:, 0] * (img_after_crop_w + 100)) + \ data_ids[i][1][1] / crop_num[1] * default_width boxes[:, 1] = (boxes[:, 1] * (img_after_crop_h + 100)) + \ data_ids[i][1][0] / crop_num[0] * default_height boxes[:, 2] = (boxes[:, 2] * (img_after_crop_w + 100)) + \ data_ids[i][1][1] / crop_num[1] * default_width boxes[:, 3] = (boxes[:, 3] * (img_after_crop_h + 100)) + \ data_ids[i][1][0] / crop_num[0] * default_height # class detection for cropped image cropped_cls_dets = np.hstack( (boxes, scores[:, np.newaxis])).astype(np.float32, copy=False) # collect detection result cls_dets_per_class[j].extend(cropped_cls_dets) dic_cls_dets_per_class = {} for i in range(num_classes-1): cls_dets_per_class[i] = np.asarray(cls_dets_per_class[i]) keep = nms(cls_dets_per_class[i], nms_thresh) cls_dets_per_class[i] = cls_dets_per_class[i][keep] dic_cls_dets_per_class.update({i: cls_dets_per_class[i]}) result.update({data_ids[0][0]: dic_cls_dets_per_class}) return result # Malisiewicz et al. def nms(boxes, overlapThresh=0.3): # if there are no boxes, return an empty list if len(boxes) == 0: return [] # if the bounding boxes integers, convert them to floats -- # this is important since we'll be doing a bunch of divisions if boxes.dtype.kind == "i": boxes = boxes.astype("float") # initialize the list of picked indexes pick = [] # grab the coordinates of the bounding boxes x1 = boxes[:, 0] y1 = boxes[:, 1] x2 = boxes[:, 2] y2 = boxes[:, 3] scores = boxes[:, 4] # compute the area of the bounding boxes and sort the bounding # boxes by the bottom-right y-coordinate of the bounding box area = (x2 - x1 + 1) * (y2 - y1 + 1) idxs = np.argsort(scores) # keep looping while some indexes still remain in the indexes # list while len(idxs) > 0: # grab the last index in the indexes list and add the # index value to the list of picked indexes last = len(idxs) - 1 i = idxs[last] pick.append(i) # find the largest (x, y) coordinates for the start of # the bounding box and the smallest (x, y) coordinates # for the end of the bounding box xx1 = np.maximum(x1[i], x1[idxs[:last]]) yy1 = np.maximum(y1[i], y1[idxs[:last]]) xx2 = np.minimum(x2[i], x2[idxs[:last]]) yy2 = np.minimum(y2[i], y2[idxs[:last]]) # compute the width and height of the bounding box w = np.maximum(0, xx2 - xx1 + 1) h = np.maximum(0, yy2 - yy1 + 1) # compute the ratio of overlap overlap = (w * h) / area[idxs[:last]] # delete all indexes from the index list that have idxs = np.delete(idxs, np.concatenate(([last], np.where(overlap > overlapThresh)[0]))) # return only the bounding boxes that were picked using the # integer data type return pick <file_sep>/evaluation/classification/evaluate.py # -*- coding: utf-8 -*- import numpy as np import torch from model.resnet.predict import test_classification def accuracy(test_dataloader, model, return_correct=False): """ 正解率の計算 引数: - test_dataloader: データローダ - model: モデル - return_correct: bool, 実験結果(correct)を返す """ result_a = test_classification(test_dataloader, model) y = test_dataloader.dataset.labels correct = result_a == y if return_correct is True: return correct.mean(), correct else: return correct.mean() def confusion_matrix(test_dataloader, model, labels): """ 混同行列の計算 引数: - test_dataloader: データローダ - model: モデル - labels: [str, ...], 昆虫ラベル, 順番注意! """ result_c = test_classification(model, test_dataloader) y = test_dataloader.dataset.labels confusion_matrix = [] for i in range(len(labels)): msk = np.isin(y, i) class_estimation = [] for j in range(len(labels)): estimation = result_c[msk] == j class_estimation.append(estimation.sum()) confusion_matrix.append(class_estimation) return np.asarray(confusion_matrix).astype("float")<file_sep>/dataset/classification/loader.py # -*- coding: utf-8 -*- import numpy as np def create_validation_split(Y, test_ratio=0.2): """ 学習/テストの交差検証用インデックスを作成 引数: - Y: np.array, size=[insect_num], 昆虫ラベル - test_ratio: float, テストに使用するインデックスの割合 test_ratioから交差検証の回数を計算している """ idx, counts = np.unique(Y, return_counts=True) ntests = counts * test_ratio ntests = np.round(ntests).astype("int") valid_num = int(1.0 / test_ratio) valid_idx = [np.where(Y == i)[0] for i in range(len(ntests))] default_idx = [np.where(Y == i)[0] for i in range(len(ntests))] test = [] train = [] for i in range(valid_num): if i == valid_num - 1: ntests = counts - ntests * (valid_num - 1) valid_test = [] valid_train = [] for i, n in enumerate(ntests): test_id = np.asarray(valid_idx[i][:n]) # クラス別のテストインデックスを取得 train_id = list(set(default_idx[i]) - set(test_id)) # クラス別の学習インデックスを取得 valid_test.extend(test_id.tolist()) # テストインデックスを交差検証用インデックスの配列に格納 valid_train.extend(train_id) # 学習インデックスを交差検証用インデックスの配列に格納 valid_idx[i] = list(set(valid_idx[i]) - set(test_id)) # 次の交差検証インデックス作成のために、テストインデックスを除去 test.append(valid_test) train.append(valid_train) return train, test def load_validation_data(X, Y, valid_train_idx, valid_test_idx): """ 学習/テストデータをインデックスから読み込む Args: - X: np.array, 昆虫画像全体 - Y: np.array, ラベル全体 - valid_train_idx: np.array, 交差検証用学習インデックス - valid_test_idx: np.array, 交差検証用テストインデックス """ xtr = X[valid_train_idx] ytr = Y[valid_train_idx] xte = X[valid_test_idx] yte = Y[valid_test_idx] return xtr, ytr, xte, yte<file_sep>/model/resnet/predict.py # -*- coding: utf-8 -*- import numpy as np import torch from tqdm import tqdm def test_classification(test_dataloader, model): """ 分類する 引数: - test_dataloader: データローダ - model: モデル """ model.eval() result_lbl = [] for x in test_dataloader: x = x.cuda() out = model(x) if len(out.shape) == 1: # bsが1だとエラーとなるので, 空の次元を挿入 out = out[None, :] result = torch.max(out, 1)[1] result = result.cpu().numpy() result_lbl.extend(result) return np.asarray(result_lbl)<file_sep>/result/hikitsugi.md ### 引き継ぎ資料 #### 各結果の場所について 修士論文で用いたデータはmaster_paperに保存している classification: 分類モデルの結果 detection: 検出モデルの結果 resource_estimation: 資源量予測モデルの結果 size_estimation: 体サイズ予測モデルの結果 それまでに得られた結果はresult直下のフォルダに分けて保存している 色々な結果があるけど、修士論文に書いたモデルが最も良くなったので参考にはならないと思う #### その他の重要なファイル 以下に示すファイルは研究を行う上で重要です ・result/classification/visualize_annotation annotation_0 ~ 4の解析結果 ・result/classification/visualize_annotation annotation_0 ~ 4 + annotation_20200806の解析結果 ・result/classification/dataset_distributions annotation_0 ~ 4 + annotation_20200806のデータを、クラス分布として可視化したもの ・result/detection/visualize_bounding_box annotation_0 ~ 4 + annotation_20200806のデータを、クラス別のバウンディングボックスの大きさの観点から可視化したもの ・result/ilsvrc2012_analysis ILSVRC2012データセットを分析して、クラスカテゴリの分布の可視化と昆虫の占める割合を調べたもの #### その他注意 compare_* と書いてあるファイルはモデルを比較したものです visualize_* と書いてあるファイルは何かを可視化したものです <file_sep>/evaluation/classification/statistics.py # -*- coding: utf-8 -*- import numpy as np import pandas as pd def compute_anno_stats(anno): """ compute annotation stats - anno: {file id: [(insect name, [x1, y1, x2, y2]), ...]} """ C,H,W = [], [], [] center = [] idx = [] for k,v in anno.items(): for item in v: c = item[0] xmin, ymin, xmax, ymax = item[1] w = xmax - xmin h = ymax - ymin H.append(h) W.append(w) C.append(c) center.append(((xmin+xmax)//2, (ymin+ymax)//2)) idx.append(k) H = np.array(H) W = np.array(W) C = np.array(C) center = np.array(center) idx = np.array(idx) return H,W,C,center,idx def compute_average_size(H,W,C): """ compute H*W average per class - H: [int, ...] - W: [int, ...] - C: [str, ...] """ idx, count = np.unique(C, return_counts=True) map_idx = {k:i for i,k in enumerate(idx)} sum_S = np.zeros(idx.shape[0]) for i in range(len(H)): sum_S[map_idx[C[i]]] += H[i] * W[i] sum_S_mean = sum_S / count return sum_S_mean, idx def compute_size_correction(H,W,C): """ compute width (or height) size correction - H: [int, ...] - W: [int, ...] - C: [str, ...] """ avg_size, labels = compute_average_size(H,W,C) size_correction = np.ones(avg_size.shape[0]) avg_size = avg_size[:-4] avg_size = avg_size/avg_size.max() avg_size = 1/avg_size size_correction[:-4] = avg_size ** 0.5 size_correction = {label:resize_size for resize_size, label in zip(size_correction, labels)} return size_correction def compute_each_size_df(result, xte, yte): """ 実験結果と昆虫サイズを並べたデータフレームを作成 引数: - result: np.array, 実験結果 - xte: np.array, テスト用昆虫画像 - yte: np.array, テスト用ラベル """ xte_size = np.asarray(get_size_list_from_xte(xte)) # 画像から昆虫サイズを逆算 mask = result == yte return pd.DataFrame({"Recall": mask, "Insect_size": xte_size}) def compute_all_size_df(df): """ サイズ帯(=log_2 Insect_size)ごとに実験結果を集計 引数: - df: pd.DataFrame({"Recall", "Insect_size"}) """ df["order"] = df["Insect_size"].apply(lambda x: np.floor(np.log2(x))) df2 = df.groupby("order").apply(np.mean) df2 = pd.DataFrame({"order": df2["order"].values, "Recall": df2["Recall"].values, "Insect_size": df2["Insect_size"].values}) return df2 def get_size_list_from_xte(xte): """ 昆虫画像から昆虫サイズを逆算 引数: - xte: np.array, テスト用昆虫画像 """ size_list = [] for img in xte: size = get_size_from_cropped_img(img) size_list.append(size) return size_list def get_size_from_cropped_img(img): """ get insect size from test image Args: - img: np.array, shape == [height, width, channels] """ mask_y, mask_x = np.where(img[:, :, 0] > 0) crop_img = img[mask_y[0]:mask_y[-1], mask_x[0]:mask_x[-1], :] return crop_img.shape[0] * crop_img.shape[1] def get_precisions(df): """ compute precision from validation matrix Args: - df: pd.DataFrame, validation matrix """ precisions = [] for i in range(len(df)): val_count_per_label = df[i:i+1] index = val_count_per_label.columns[1:] val_count_per_label = [int(val_count_per_label[idx]) for idx in index] precision = val_count_per_label[i]/sum(val_count_per_label) precisions.append(precision) return np.asarray(precisions) def get_average_precision(df): """ compute average precision from validation matrix Args: - df: pd.DataFrame, validation matrix """ total_insects = 0 column_count = len(df.columns) - 1 for i in range(column_count): total_insects += sum(df.iloc[:, i + 1]) true_positive_count = 0 for i in range(column_count): true_positive_count += df.iloc[i, i + 1] return float(true_positive_count / total_insects)<file_sep>/evaluation/detection/statistics.py import numpy as np import pandas as pd def compute_each_size_df(eval_metrics): """ compute each insect size & accuracy dataframe - result: Voc_Evaluater output """ all_label_gt_size = [] all_label_gt_result = [] for eval_metric in eval_metrics: all_label_gt_size.extend(eval_metric["gt_size"]) all_label_gt_result.extend(eval_metric["gt_result"]) return pd.DataFrame({"Accuracy": np.asarray(all_label_gt_result), "Insect_size": np.asarray(all_label_gt_size)}) def compute_all_size_df(each_df): """ compute all insect size & accuracy dataframe - each_df: pd.DataFrame({"Accuracy", "Insect_size"}) """ each_df["order"] = each_df["Insect_size"].apply(lambda x: np.floor(np.log2(x))) df = each_df.groupby("order").apply(np.mean) df = pd.DataFrame({"order": df["order"].values, "Accuracy": df["Accuracy"].values, "Insect_size": df["Insect_size"].values}) return df<file_sep>/IO/loader.py import xml.etree.ElementTree as ET from os import listdir as ld from os.path import join as pj import numpy as np from PIL import Image from scipy import sparse import torch from tqdm import tqdm_notebook as tqdm def get_name(child): """ """ return child.getchildren()[0].text def get_coords(child): """ """ bndbox = child.getchildren()[-1] return [int(x.text) for x in bndbox.getchildren()] def get_objects(fp, return_body=False): """ """ tree = ET.parse(fp) x = filter(lambda x:x.tag=="object", tree.getroot()) if return_body is True: return x else: return filter(lambda x:get_name(x) != "body size", x) def parse_annotations(fp, return_body=False): """ XML annotation file kara annotation list shutsuryoku """ return [(get_name(objects), get_coords(objects)) for objects in get_objects(fp, return_body)] def file_id(file_path): """ get file id from file path ex. ~/20180614-1959.xml -> 20180614-1959 - file_path: str """ file_id = file_path.split("/")[-1] file_id = file_id.split(".")[0] return file_id def load_path(data_root, img_folder, anno_folders): """ load annotation and image path - data_root: str - img_folder: str - anno_folders: [str, ...] """ annos = [] for anno_folder in anno_folders: annos_name = ld(pj(data_root, anno_folder)) annos.extend([pj(data_root, anno_folder, x) for x in annos_name]) imgs = ld(pj(data_root, img_folder)) imgs = [pj(data_root, img_folder, x) for x in imgs] return annos, imgs def load_images(img_paths): """ load images and map to file id - img_paths: [str, ...] """ for img_path in img_paths: if ".ipynb_checkpoints" in img_path.split("/")[-1]: img_paths.remove(img_path) images = {file_id(img_path):np.array(Image.open(img_path)) for img_path in img_paths} return images def load_annotations_path(annos, images): """ load annotations path and map to filename - annos: [str, ...] - images: {file id: image data, np.array} """ annotations_path = {idx: list(filter(lambda x:idx in x, annos)) for idx in images} annotations_path = {k:v for k,v in annotations_path.items() if len(v)>0} return annotations_path def load_images_path(imgs, annotations_path): """ unused load images path and map to filename """ images_path = {idx: list(filter(lambda x:idx in x,imgs))[0] for idx in annotations_path} return images_path def load_annotations(annotations_path, return_body=False): """ load annotations - annotations_path: {file id: [str]} """ anno = {} for k,v in annotations_path.items(): anno[k]=[] for x in filter(lambda x:x.endswith(".xml"), v): anno[k].extend(parse_annotations(x, return_body)) return anno def get_label_dic(anno, each_flag=False, make_refinedet_data=False): """ get label_dic from annotations - anno: {file id: [(insect name, [x1, y1, x2, y2]), ...]} - each_flag: bool """ lbl = [] for k,v in anno.items(): for value in v: lbl.append(value[0]) lbl = np.asarray(lbl) lbls, counts = np.unique(lbl, return_counts=True) if each_flag is True: label_dic = {k:i for i,k in enumerate(lbls)} else: if make_refinedet_data is False: label_dic = {k:1 for k in lbls} else: label_dic = {k:0 for k in lbls} return label_dic def rank_roidb_ratio(roidb): """ rank roidb based on the ratio between width and height. """ ratio_large = 2 # largest ratio to preserve. ratio_small = 0.5 # smallest ratio to preserve. ratio_list = [] for i in range(len(roidb)): width = roidb[i]['width'] height = roidb[i]['height'] ratio = width / float(height) if ratio > ratio_large: roidb[i]['need_crop'] = 1 ratio = ratio_large elif ratio < ratio_small: roidb[i]['need_crop'] = 1 ratio = ratio_small else: roidb[i]['need_crop'] = 0 ratio_list.append(ratio) ratio_list = np.array(ratio_list) ratio_index = np.argsort(ratio_list) return ratio_list[ratio_index], ratio_index def make_roidb(anno, label_dic, images_path): """ make roidb """ count = 0 roidb = [] for k,v in anno.items(): boxes = {"boxes": np.array([value[1] for value in anno[k]], dtype="uint16")} names = [value[0] for value in anno[k]] gt_classes = {"gt_classes": np.array([label_dic[name] for name in names], dtype="int32")} overlap = [[1 if i==idx else 0 for i in range(10)] for idx in gt_classes["gt_classes"]] gt_overlap = {"gt_overlap": sparse.csr_matrix(np.array(overlap, dtype="float32"))} flipped = {"flipped": False} img_id = {"img_id": count} image = {"image": images_path[k]} img = np.array(Image.open(images_path[k])) width = {"width": img.shape[1]} height = {"height": img.shape[0]} need_crop = {"need_crop": 0} count += 1 db = {} db.update(boxes) db.update(gt_classes) db.update(gt_overlap) db.update(flipped) db.update(img_id) db.update(image) db.update(width) db.update(height) db.update(need_crop) roidb.append(db) return roidb def make_roi_dataset(anno, label_dic, images_path): """ make roi dataset """ roidb = make_roidb(anno, label_dic, images_path) ratio_list, ratio_index = rank_roidb_ratio(roidb) return roidb, ratio_list, ratio_index def get_anno_recs(anno, each_flag=False): """ get annotation recs """ imagenames = [] recs = {} for k,v in anno.items(): imagenames.append(k) rec_image = [] for i in range(len(v)): if each_flag is True: name = {"name": v[i][0]} else: name = {"name": "insects"} default_name = {"default_name": v[i][0]} difficult = {"difficult": 0} bbox = {"bbox": v[i][1]} rec = {} rec.update(name) rec.update(default_name) rec.update(difficult) rec.update(bbox) rec_image.append(rec) imagename = {k: rec_image} recs.update(imagename) return imagenames, recs def compute_padding(coord, delta=100): """ return padding size """ xmin, ymin, xmax, ymax = coord padleft = (2*delta - (xmax - xmin)) // 2 padright = 2*delta - padleft - (xmax - xmin) padtop = (2*delta - (ymax - ymin)) // 2 padbottom = 2*delta - padtop - (ymax - ymin) return ((padtop,padbottom),(padleft,padright),(0,0)) def check_coord(coord, size=200): """ check coordination """ xmin, ymin, xmax, ymax = coord if (xmax - xmin) > size: xc = (xmin+xmax)//2 xmin, xmax = xc-(size//2), xc+(size//2) if (ymax - ymin) > size: yc = (ymin+ymax)//2 ymin, ymax = yc-(size//2), yc+(size//2) return xmin, ymin, xmax, ymax def crop_adjusted_std(img, coord, delta=100): """ adjusting crop and padding constant and std """ coord = check_coord(coord) xmin, ymin, xmax, ymax = coord img = (img - np.mean(img))/np.std(img)*32+128 img = img[ymin:ymax, xmin:xmax].copy() padding = compute_padding(coord) img = np.pad(img, padding, "constant") return img[None,:] def load_semantic_vector(path): """ load semantic vector - path <str> """ with open(path, "r") as f: lines = f.readlines() semantic_vectors = [] for vec in lines: semantic_vectors.append(np.asarray(vec.split("\n")[0].split(" ")).astype("float32")) return torch.from_numpy(np.asarray(semantic_vectors))<file_sep>/model/refinedet/loss/multiboxloss.py import torch import torch.nn as nn import torch.nn.functional as F from model.refinedet.utils.functions import refine_match, log_sum_exp class RefineDetMultiBoxLoss(nn.Module): """SSD Weighted Loss Function Compute Targets: 1) Produce Confidence Target Indices by matching ground truth boxes with (default) 'priorboxes' that have jaccard index > threshold parameter (default threshold: 0.5). 2) Produce localization target by 'encoding' variance into offsets of ground truth boxes and their matched 'priorboxes'. 3) Hard negative mining to filter the excessive number of negative examples that comes with using a large number of default bounding boxes. (default negative:positive ratio 3:1) Objective Loss: L(x,c,l,g) = (Lconf(x, c) + αLloc(x,l,g)) / N Where, Lconf is the CrossEntropy Loss and Lloc is the SmoothL1 Loss weighted by α which is set to 1 by cross val. Args: c: class confidences, l: predicted boxes, g: ground truth boxes N: number of matched default boxes See: https://arxiv.org/pdf/1512.02325.pdf for more details. """ def __init__(self, num_classes, use_ARM=False, use_BCE=True): super(RefineDetMultiBoxLoss, self).__init__() self.num_classes = num_classes self.use_ARM = use_ARM self.use_BCE = use_BCE self.overlap_thresh = 0.5 self.background_label = 0 self.negpos_ratio = 3 self.use_gpu = True self.theta = 0.01 self.variance = [0.1, 0.2] if use_BCE is True: self.cross_entropy = binary_cross_entropy else: self.cross_entropy = F.cross_entropy def forward(self, predictions, targets): """Multibox Loss Args: predictions (tuple): (arm_loc_data, arm_conf_data, odm_loc_data, odm_conf_data, prior_data) arm_loc_data.shape == [batch_size, num_priors, 4] arm_conf_data.shape == [batch_size, num_priors, 2] odm_loc_data.shape == [batch_size, num_priors, 4] odm_conf_data.shape == [batch_size, num_priors, num_classes] prior_data.shape == [num_priors, 4] targets (tensor): [target_per_cropped_img, ...] target_per_cropped_img: tensor(array([[x1, y1, x2, y2, cls_lbl], ...], dtype=float32)) x1, y1, x2, y2 -> 0 <= value <= 1, value based on cropped_image len(targets) == batch_size target_per_cropped_img.shape == [num_objects, 5] """ arm_loc_data, arm_conf_data, odm_loc_data, odm_conf_data, prior_data = predictions if self.use_ARM is True: loc_data, conf_data = odm_loc_data, odm_conf_data else: loc_data, conf_data = arm_loc_data, arm_conf_data batch_size = loc_data.size(0) prior_data = prior_data[:loc_data.size(1), :] num_priors = (prior_data.size(0)) num_classes = self.num_classes # match priors (default boxes) and ground truth boxes loc_t = torch.Tensor(batch_size, num_priors, 4) conf_t = torch.LongTensor(batch_size, num_priors) for idx in range(batch_size): target_boxes = targets[idx][:, :-1].detach() target_labels = targets[idx][:, -1].detach() if self.use_ARM is False: target_labels = target_labels >= 0 prior_data = prior_data.detach() if self.use_ARM is True: refine_match(self.overlap_thresh, target_boxes, prior_data, self.variance, target_labels, loc_t, conf_t, idx, arm_loc_data=arm_loc_data[idx].detach()) else: refine_match(self.overlap_thresh, target_boxes, prior_data, self.variance, target_labels, loc_t, conf_t, idx) if self.use_gpu: loc_t = loc_t.cuda() conf_t = conf_t.cuda() loc_t.requires_grad = False conf_t.requires_grad = False if self.use_ARM is True: P = F.softmax(arm_conf_data, 2) arm_conf_tmp = P[:, :, 1] object_score_index = arm_conf_tmp <= self.theta pos = conf_t > 0 pos[object_score_index.detach()] = 0 else: pos = conf_t > 0 # Localization Loss (Smooth L1) # Shape: [batch,num_priors,4] pos_idx = pos.unsqueeze(pos.dim()).expand_as(loc_data) loc_p = loc_data[pos_idx].view(-1, 4) loc_t = loc_t[pos_idx].view(-1, 4) loss_l = F.smooth_l1_loss(loc_p, loc_t) # Compute max conf across batch for hard negative mining batch_conf = conf_data.view(-1, self.num_classes) loss_c = log_sum_exp(batch_conf) - batch_conf.gather(1, conf_t.view(-1, 1)) # Hard Negative Mining loss_c[pos.view(-1, 1)] = 0 # filter out pos boxes for now loss_c = loss_c.view(batch_size, -1) _, loss_idx = loss_c.sort(1, descending=True) _, idx_rank = loss_idx.sort(1) num_pos = pos.long().sum(1, keepdim=True) num_neg = torch.clamp(self.negpos_ratio * num_pos, max=pos.size(1) - 1) neg = idx_rank < num_neg.expand_as(idx_rank) N = num_pos.detach().sum().float() # Confidence Loss Including Positive and Negative Examples pos_idx = pos.unsqueeze(2).expand_as(conf_data) neg_idx = neg.unsqueeze(2).expand_as(conf_data) conf_p = conf_data[(pos_idx + neg_idx).gt(0) ].view(-1, self.num_classes) targets_weighted = conf_t[(pos + neg).gt(0)] if (conf_p.size())[0] == 0 or (targets_weighted.size())[0] == 0: # size error occured and set loss_c = 0 loss_c = 0 else: # check dimention size and calculate loss loss_c = self.cross_entropy(conf_p, targets_weighted) # Sum of losses: L(x,c,l,g) = (Lconf(x, c) + αLloc(x,l,g)) / N loss_l /= N loss_c /= N return loss_l, loss_c def binary_cross_entropy(conf_p, targets_weighted): """ create onehot target and calculate BCELoss Args: - conf_p: torch.FloatTensor, shape==[box_num, class_num] - targets_weighted: torch.FloatTensor, shape==[box_num] """ onehot = torch.FloatTensor(conf_p.shape).zero_().cuda() targets_weighted = targets_weighted.unsqueeze_(1) onehot = onehot.scatter_(1, targets_weighted, 1) loss_c = F.binary_cross_entropy_with_logits(conf_p, onehot) return loss_c<file_sep>/model/resnet/unused/readme.md ### AutoAugment/FastAutoAugmentデータ拡張の使い方 1. AutoAugmentクラスを作成 この時、policy_dirを与えれば昆虫の分類に適応したFastAutoAugmentの結果を使用できる。 与えなければ、AutoAugmentで指摘された最良データ拡張を使用できる。 2. AutoAugment(img)の形でデータ拡張を行える FastAutoAugmentのコードも残してあるので、tanidaのフォルダを探してもらえば使えるはずです。 だけど、今のResNetのコードでは動かないと思うのでその部分は修正をお願いします。 <file_sep>/model/resnet/unused/aa_transforms.py import random import numpy as np import scipy from scipy import ndimage from PIL import Image, ImageEnhance, ImageOps def transform_matrix_offset_center(matrix, x, y): o_x = float(x) / 2 + 0.5 o_y = float(y) / 2 + 0.5 offset_matrix = np.array([[1, 0, o_x], [0, 1, o_y], [0, 0, 1]]) reset_matrix = np.array([[1, 0, -o_x], [0, 1, -o_y], [0, 0, 1]]) transform_matrix = offset_matrix @ matrix @ reset_matrix return transform_matrix def shear_x(img, magnitude): img = np.array(img) magnitudes = np.linspace(-0.3, 0.3, 11) transform_matrix = np.array([[1, random.uniform(magnitudes[magnitude], magnitudes[magnitude+1]), 0], [0, 1, 0], [0, 0, 1]]) transform_matrix = transform_matrix_offset_center(transform_matrix, img.shape[0], img.shape[1]) affine_matrix = transform_matrix[:2, :2] offset = transform_matrix[:2, 2] img = np.stack([ndimage.interpolation.affine_transform( img[:, :, c], affine_matrix, offset) for c in range(img.shape[2])], axis=2) img = Image.fromarray(img) return img def shear_y(img, magnitude): img = np.array(img) magnitudes = np.linspace(-0.3, 0.3, 11) transform_matrix = np.array([[1, 0, 0], [random.uniform(magnitudes[magnitude], magnitudes[magnitude+1]), 1, 0], [0, 0, 1]]) transform_matrix = transform_matrix_offset_center(transform_matrix, img.shape[0], img.shape[1]) affine_matrix = transform_matrix[:2, :2] offset = transform_matrix[:2, 2] img = np.stack([ndimage.interpolation.affine_transform( img[:, :, c], affine_matrix, offset) for c in range(img.shape[2])], axis=2) img = Image.fromarray(img) return img def translate_x(img, magnitude): img = np.array(img) magnitudes = np.linspace(-150/331, 150/331, 11) transform_matrix = np.array([[1, 0, 0], [0, 1, img.shape[1]*random.uniform(magnitudes[magnitude], magnitudes[magnitude+1])], [0, 0, 1]]) transform_matrix = transform_matrix_offset_center(transform_matrix, img.shape[0], img.shape[1]) affine_matrix = transform_matrix[:2, :2] offset = transform_matrix[:2, 2] img = np.stack([ndimage.interpolation.affine_transform( img[:, :, c], affine_matrix, offset) for c in range(img.shape[2])], axis=2) img = Image.fromarray(img) return img def translate_y(img, magnitude): img = np.array(img) magnitudes = np.linspace(-150/331, 150/331, 11) transform_matrix = np.array([[1, 0, img.shape[0]*random.uniform(magnitudes[magnitude], magnitudes[magnitude+1])], [0, 1, 0], [0, 0, 1]]) transform_matrix = transform_matrix_offset_center(transform_matrix, img.shape[0], img.shape[1]) affine_matrix = transform_matrix[:2, :2] offset = transform_matrix[:2, 2] img = np.stack([ndimage.interpolation.affine_transform( img[:, :, c], affine_matrix, offset) for c in range(img.shape[2])], axis=2) img = Image.fromarray(img) return img def rotate(img, magnitude): img = np.array(img) magnitudes = np.linspace(-30, 30, 11) theta = np.deg2rad(random.uniform(magnitudes[magnitude], magnitudes[magnitude+1])) transform_matrix = np.array([[np.cos(theta), -np.sin(theta), 0], [np.sin(theta), np.cos(theta), 0], [0, 0, 1]]) transform_matrix = transform_matrix_offset_center(transform_matrix, img.shape[0], img.shape[1]) affine_matrix = transform_matrix[:2, :2] offset = transform_matrix[:2, 2] img = np.stack([ndimage.interpolation.affine_transform( img[:, :, c], affine_matrix, offset) for c in range(img.shape[2])], axis=2) img = Image.fromarray(img) return img def auto_contrast(img, magnitude): img = ImageOps.autocontrast(img) return img def invert(img, magnitude): img = ImageOps.invert(img) return img def equalize(img, magnitude): img = ImageOps.equalize(img) return img def solarize(img, magnitude): magnitudes = np.linspace(0, 256, 11) img = ImageOps.solarize(img, random.uniform(magnitudes[magnitude], magnitudes[magnitude+1])) return img def posterize(img, magnitude): magnitudes = np.linspace(4, 8, 11) img = ImageOps.posterize(img, int(round(random.uniform(magnitudes[magnitude], magnitudes[magnitude+1])))) return img def contrast(img, magnitude): magnitudes = np.linspace(0.1, 1.9, 11) img = ImageEnhance.Contrast(img).enhance(random.uniform(magnitudes[magnitude], magnitudes[magnitude+1])) return img def color(img, magnitude): magnitudes = np.linspace(0.1, 1.9, 11) img = ImageEnhance.Color(img).enhance(random.uniform(magnitudes[magnitude], magnitudes[magnitude+1])) return img def brightness(img, magnitude): magnitudes = np.linspace(0.1, 1.9, 11) img = ImageEnhance.Brightness(img).enhance(random.uniform(magnitudes[magnitude], magnitudes[magnitude+1])) return img def sharpness(img, magnitude): magnitudes = np.linspace(0.1, 1.9, 11) img = ImageEnhance.Sharpness(img).enhance(random.uniform(magnitudes[magnitude], magnitudes[magnitude+1])) return img def cutout(org_img, magnitude=None): img = np.array(img) magnitudes = np.linspace(0, 60/331, 11) img = np.copy(org_img) mask_val = img.mean() if magnitude is None: mask_size = 16 else: mask_size = int(round(img.shape[0]*random.uniform(magnitudes[magnitude], magnitudes[magnitude+1]))) top = np.random.randint(0 - mask_size//2, img.shape[0] - mask_size) left = np.random.randint(0 - mask_size//2, img.shape[1] - mask_size) bottom = top + mask_size right = left + mask_size if top < 0: top = 0 if left < 0: left = 0 img[top:bottom, left:right, :].fill(mask_val) img = Image.fromarray(img) return img class Cutout(object): def __init__(self, length=16): self.length = length def __call__(self, img): img = np.array(img) mask_val = img.mean() top = np.random.randint(0 - self.length//2, img.shape[0] - self.length) left = np.random.randint(0 - self.length//2, img.shape[1] - self.length) bottom = top + self.length right = left + self.length top = 0 if top < 0 else top left = 0 if left < 0 else top img[top:bottom, left:right, :] = mask_val img = Image.fromarray(img) return img<file_sep>/model/resnet/resnet.py # -*- coding: utf-8 -*- import numpy as np import torch import torch.nn as nn import torch.nn.functional as F from model.resnet.resnet_base import BasicBlock, Bottleneck, _resnet class ResNet(nn.Module): """ ResNet """ def __init__(self, model_name, n_class, pretrain=False, param_freeze=False, vis_feature=False, use_dropout=False, activation_function="ReLU", decoder=None): """ 初期化関数 引数: - model_name: str, ResNetの種類を指定, ["resnet18", "resnet34", "resnet50", "resnet101", "resnet152"]の中から一つ - n_class: int, 分類するクラス数 - pretrain: bool, ImageNetの転移学習を行うか否か - param_freeze: bool, 特徴抽出モデルの重みを固定するか否か - vis_feature: bool, 特徴量の可視化を行うか否か - use_dropout: bool, ヘッドの中にDropoutを組み込むか否か - activation_function: str, 発火関数を指定 ["ReLU", "LeakyReLU", "RReLU"]の中から (コメント: これ以外の発火関数はうまくいかなかったため取り除いている) - decoder: str or None: デコーダーの構造を指定 [None, "Concatenate", "FPN"]の中から Concatenateは畳み込みブロック特徴量1~4をconcatするもの FPNはFeature Pyramid Networkを実装したもの """ super(ResNet, self).__init__() if activation_function == "ReLU": print("activation_function == ReLU") self.relu = nn.ReLU(inplace=True) elif activation_function == "LeakyReLU": print("activation_function == LeakyReLU") self.relu = nn.LeakyReLU(inplace=True) elif activation_function == "RReLU": print("activation_function == RReLU") self.relu = nn.RReLU(inplace=True) if model_name == 'resnet18': resnet = _resnet('resnet18', BasicBlock, [2, 2, 2, 2], pretrained=pretrain, progress=True, activation_function=self.relu) elif model_name == 'resnet34': resnet = _resnet('resnet34', BasicBlock, [3, 4, 6, 3], pretrained=pretrain, progress=True, activation_function=self.relu) elif model_name == 'resnet50': resnet = _resnet('resnet50', Bottleneck, [3, 4, 6, 3], pretrained=pretrain, progress=True, activation_function=self.relu) elif model_name == 'resnet101': resnet = _resnet('resnet101', Bottleneck, [3, 4, 23, 3], pretrained=pretrain, progress=True, activation_function=self.relu) elif model_name == 'resnet152': resnet = _resnet('resnet152', Bottleneck, [3, 8, 36, 3], pretrained=pretrain, progress=True, activation_function=self.relu) else: print("error: model_name missmatch!") if param_freeze is True: for param in resnet.parameters(): param.requires_grad = False self.model_name = model_name self.n_class = n_class self.pretrain = pretrain self.param_freeze = param_freeze self.vis_feature = vis_feature self.use_dropout = use_dropout self.activation_function = activation_function self.decoder = decoder self.resnet = nn.Sequential(*list(resnet.children())[:-2]) # エンコーダ部 self.avgpool = nn.AvgPool2d(kernel_size=7, stride=1) # TrueでConcatenate中でconcatするブロックを指定できる # Falseは全ブロックを指定する self.use_conv_compression = True print("conv_compression == " + str(self.use_conv_compression)) # デコーダ部 if decoder == "Concatenate": self.adaptive_avgpool = nn.AdaptiveAvgPool2d(7) print("decoder == Concatenate") self.concat_layer = [True, True, True, True] # concatするブロックを指定 print("concat_layer == " + str(self.concat_layer)) if model_name == 'resnet18' or model_name == 'resnet34': layer_feature = np.array([64, 128, 256, 512]) elif model_name == 'resnet50' or model_name == 'resnet101' or model_name == 'resnet152': layer_feature = np.array([256, 512, 1024, 2048]) if self.use_conv_compression is True: # 出力する特徴量の大きさを揃えるための畳み込み層 self.conv_compression = nn.Conv2d(layer_feature[self.concat_layer].sum(), layer_feature[self.concat_layer].sum(), kernel_size=1) elif decoder == "FPN": self.adaptive_avgpool = nn.AdaptiveAvgPool2d(7) print("decoder == FPN") if model_name == 'resnet18' or model_name == 'resnet34': # Top Layer self.toplayer = nn.Conv2d(512, 64, kernel_size=1, stride=1, padding=0) # Reduce channels # Smooth Layers self.smooth1 = nn.Conv2d(64, 64, kernel_size=3, stride=1, padding=1) self.smooth2 = nn.Conv2d(64, 64, kernel_size=3, stride=1, padding=1) self.smooth3 = nn.Conv2d(64, 64, kernel_size=3, stride=1, padding=1) # Lateral Layers self.latlayer1 = nn.Conv2d(256, 64, kernel_size=1, stride=1, padding=0) self.latlayer2 = nn.Conv2d(128, 64, kernel_size=1, stride=1, padding=0) self.latlayer3 = nn.Conv2d(64, 64, kernel_size=1, stride=1, padding=0) elif model_name == 'resnet50' or model_name == 'resnet101' or model_name == 'resnet152': # Top Layer self.toplayer = nn.Conv2d(2048, 256, kernel_size=1, stride=1, padding=0) # Reduce channels # Smooth Layers self.smooth1 = nn.Conv2d(256, 256, kernel_size=3, stride=1, padding=1) self.smooth2 = nn.Conv2d(256, 256, kernel_size=3, stride=1, padding=1) self.smooth3 = nn.Conv2d(256, 256, kernel_size=3, stride=1, padding=1) # Lateral Layers self.latlayer1 = nn.Conv2d(1024, 256, kernel_size=1, stride=1, padding=0) self.latlayer2 = nn.Conv2d(512, 256, kernel_size=1, stride=1, padding=0) self.latlayer3 = nn.Conv2d(256, 256, kernel_size=1, stride=1, padding=0) # ヘッドに入力する特徴量の大きさを取得 if model_name == 'resnet18' or model_name == 'resnet34': if decoder == "Concatenate": linear_feature = layer_feature[self.concat_layer].sum() elif decoder == "FPN": linear_feature = 256 else: linear_feature = 512 elif model_name == 'resnet50' or model_name == 'resnet101' or model_name == 'resnet152': if decoder == "Concatenate": linear_feature = layer_feature[self.concat_layer].sum() elif decoder == "FPN": linear_feature = 1024 else: linear_feature = 2048 # ヘッド if use_dropout is True: print("use_dropout == True") self.linear = nn.Sequential( nn.Dropout(p=0.5, inplace=True), nn.Linear(linear_feature, n_class), ) else: print("use_dropout == False") self.linear = nn.Linear(linear_feature, n_class) def _upsample_add(self, x, y): """ 特徴量補完を行い、特徴量を足し合わせる FPNの中でのみ使用 """ _, _, H, W = y.size() return F.interpolate(x, size=(H,W), mode='bilinear', align_corners=False) + y def forward(self, x): """ 順伝播 引数: - x: torch.Tensor, size==[bs, channel, H, W], モデル入力 """ if self.vis_feature is True: # 特徴量可視化のために、特徴量を取得 # ブロック1~4の特徴量を辞書にして取得する model_features = {} for i in range(len(self.resnet)): if i in [4, 5, 6, 7]: model_features.update({"conv_block_"+str(i-3): self.resnet[:i+1](x)}) return model_features else: # 順伝播を行う if self.decoder == "Concatenate" or self.decoder == "FPN": output_conv1, output_conv2, output_conv3, output_conv4 = self.forward_encoder(x) x = self.forward_decoder(output_conv1, output_conv2, output_conv3, output_conv4) else: x = self.forward_encoder(x) x = self.avgpool(x).squeeze() x = self.linear(x) return x def forward_encoder(self, x): """ エンコーダ部の順伝播 引数: - x: torch.Tensor, size==[bs, channel, H, W], モデル入力 """ if self.decoder == "Concatenate" or self.decoder == "FPN": output_conv1 = self.resnet[:5](x) output_conv2 = self.resnet[5](output_conv1) output_conv3 = self.resnet[6](output_conv2) output_conv4 = self.resnet[7](output_conv3) return output_conv1, output_conv2, output_conv3, output_conv4 else: x = self.resnet(x) return x def forward_decoder(self, output_conv1, output_conv2, output_conv3, output_conv4): """ デコーダ部の順伝播 decoderが"Concatenate"もしくは"FPN"の時のみ使用 引数: - output_conv1: torch.Tensor, size==[bs, channel, H, W], ブロック1の特徴量 - output_conv2: torch.Tensor, size==[bs, channel, H, W], ブロック2の特徴量 - output_conv3: torch.Tensor, size==[bs, channel, H, W], ブロック3の特徴量 - output_conv4: torch.Tensor, size==[bs, channel, H, W], ブロック4の特徴量 """ if self.decoder == "Concatenate": concat_feature = [] if self.concat_layer[0] is True: output_conv1 = self.adaptive_avgpool(output_conv1) concat_feature.append(output_conv1) if self.concat_layer[1] is True: output_conv2 = self.adaptive_avgpool(output_conv2) concat_feature.append(output_conv2) if self.concat_layer[2] is True: output_conv3 = self.adaptive_avgpool(output_conv3) concat_feature.append(output_conv3) if self.concat_layer[3] is True: concat_feature.append(output_conv4) output_feature = torch.cat(concat_feature, 1) if self.use_conv_compression is True: # 出力する特徴量の大きさを揃える必要がある x = self.relu(self.conv_compression(output_feature)) else: x = output_feature return x else: # Top-down up_output_conv4 = self.relu(self.toplayer(output_conv4)) up_output_conv3 = self._upsample_add(up_output_conv4, self.relu(self.latlayer1(output_conv3))) up_output_conv3 = self.relu(self.smooth1(up_output_conv3)) up_output_conv2 = self._upsample_add(up_output_conv3, self.relu(self.latlayer2(output_conv2))) up_output_conv2 = self.relu(self.smooth2(up_output_conv2)) up_output_conv1 = self._upsample_add(up_output_conv2, self.relu(self.latlayer3(output_conv1))) up_output_conv1 = self.relu(self.smooth3(up_output_conv1)) # fit size up_output_conv3 = self.adaptive_avgpool(up_output_conv3) up_output_conv2 = self.adaptive_avgpool(up_output_conv2) up_output_conv1 = self.adaptive_avgpool(up_output_conv1) # classify x = torch.cat((up_output_conv4, up_output_conv3, up_output_conv2, up_output_conv1), 1) return x<file_sep>/IO/build_ds.py import numpy as np import os from os.path import join as pj import pandas as pd from sklearn.cluster import DBSCAN from tqdm import tqdm from IO.loader import load_path, load_images, load_annotations_path, load_annotations, get_label_dic from utils.crop import compute_padding, check_coord, crop_adjusted_std, crop_adjusted_std_resize """ for classification or size regression """ def build_classification_ds(anno, images, crop, size=200, return_sizes=False): """ build classification dataset - anno: {image_id: list(tuple(insect_name, coord))} - images: {image_id: image} - crop: choice from [crop_standard, crop_adjusted, crop_adjusted_std, crop_adjusted_std_resize] - size: image size after crop and padding - return_sizes: if true, return insect sizes this parameter need anno: {image_id: list(tuple(insect_name, coord, insect_size))} """ if return_sizes is True: imgs, lbls, sizes = [], [], [] for k, v in tqdm(anno.items()): img = images[k] for lbl, coord, size in v: xmin, ymin, xmax, ymax = coord if (xmin != xmax) and (ymin != ymax): x = crop(img, coord, size//2) imgs.append(x) lbls.append(lbl) sizes.append(size) else: continue imgs = np.concatenate(imgs) sizes = np.asarray(sizes) lbl_dic = {k:i for i,k in enumerate(np.unique(lbls))} print(lbl_dic) lbls = np.asarray(list(map(lambda x:lbl_dic[x], lbls))) return imgs.astype("int32"), lbls, sizes.astype("float") else: imgs, lbls = [], [] for k, v in tqdm(anno.items()): img = images[k] for lbl, coord in v: xmin, ymin, xmax, ymax = coord if (xmin != xmax) and (ymin != ymax): x = crop(img, coord, size//2) imgs.append(x) lbls.append(lbl) else: continue imgs = np.concatenate(imgs) lbl_dic = {k:i for i,k in enumerate(np.unique(lbls))} print(lbl_dic) lbls = np.asarray(list(map(lambda x:lbl_dic[x], lbls))) return imgs.astype("int32"), lbls """ for size segmentation """ def gaussian(x, mu=0., sigma=1.): """ gaussian function Args: - x: int, input - mu: float - sigma: float """ return np.exp(-(x - mu)**2 / (2*sigma**2)) def step(x, slope=0.25): """ step function Args: - x: int, input - slope: float, 0 < slope < 0.5 """ return 1.0 - slope * x def create_size_annotation(mode="gaussian"): """ return 5*5 size annotation """ annotation = np.array( [[2, 2, 2, 2, 2], [2, 1, 1, 1, 2], [2, 1, 0, 1, 2], [2, 1, 1, 1, 2], [2, 2, 2, 2, 2]] ) if mode == "step": anno_filter = step else: anno_filter = gaussian return anno_filter(annotation) def create_lbl_img(coord, size_feature_points): """ create lbl img for size segmentation Args: - coord: list(dtype=int), shape==[4] - size_feature_points: np.array(dtype=int), shape==[2, 4] """ coord = check_coord(coord) xmin, ymin, xmax, ymax = coord lbl_img = np.zeros((ymax-ymin, xmax-xmin), dtype="float32") for size_feature_point in size_feature_points: point_center = ((size_feature_point[2]+size_feature_point[0]) // 2 - xmin, (size_feature_point[3]+size_feature_point[1]) // 2 - ymin) if lbl_img[point_center[1]-2:point_center[1]+3, point_center[0]-2:point_center[0]+3].shape == (5,5): lbl_img[point_center[1]-2:point_center[1]+3, point_center[0]-2:point_center[0]+3] = create_size_annotation(mode="step") else: return None padding = compute_padding((0, 0, lbl_img.shape[1], lbl_img.shape[0]), use_segmentation_lbl=True) lbl_img = np.pad(lbl_img, padding, "constant") return lbl_img[None, :] def build_size_segmentation_ds(anno, images, crop, size=200): """ build segmentation dataset for estimating size Args: - anno: {image_id: list(tuple(insect_name, coord, size_feature_points))} - images: {image_id: image} - crop: choice from [crop_standard, crop_adjusted, crop_adjusted_std, crop_adjusted_std_resize] - size: int, image size after crop and padding """ imgs, lbls = [], [] for k, v in tqdm(anno.items()): img = images[k] for lbl, coord, size_feature_points in v: xmin, ymin, xmax, ymax = coord if (xmin != xmax) and (ymin != ymax): x = crop(img, coord, size//2) lbl_img = create_lbl_img(coord, size_feature_points) if lbl_img is not None: imgs.append(x) lbls.append(lbl_img) else: continue imgs = np.concatenate(imgs) lbls = np.concatenate(lbls) return imgs.astype("int32"), lbls.astype("float32") """ for detection """ def load_anno(data_root, img_folder, anno_folders, return_body=False): """ load anno Args: - data_root: str - img_folder: str - anno_folders: list(dtype=str) """ print("loading path ...") annos, imgs = load_path(data_root, img_folder, anno_folders) print("loading images ...") images = load_images(imgs) annotations_path = load_annotations_path(annos, images) print("loading annos ...") anno = load_annotations(annotations_path, return_body) return images, anno def load_label_dic(anno, each_flag=False, plus_other=False, target_with_other=False): """ load label_dic with experiment setting Args: - anno: {image_id: list(tuple(insect_name, coord))} - each_flag: bool - plus_other: bool, if divide into target_class + other_class - target_with_other: bool, if divide into target_class(split label) + other_class """ if plus_other is True: label_dic = {'Coleoptera': 1, 'Diptera': 0, 'Ephemeridae': 0, 'Ephemeroptera': 0, 'Hemiptera': 1, 'Hymenoptera': 1, 'Lepidoptera': 0, 'Megaloptera': 1, 'Plecoptera': 0, 'Trichoptera': 0, 'medium insect': 1, 'small insect': 1, 'snail': 1, 'spider': 1, 'Unknown': 1} elif target_with_other is True: label_dic = {'Coleoptera': 6, 'Diptera': 0, 'Ephemeridae': 1, 'Ephemeroptera': 2, 'Hemiptera': 6, 'Hymenoptera': 6, 'Lepidoptera': 3, 'Megaloptera': 6, 'Plecoptera': 4, 'Trichoptera': 5, 'medium insect': 6, 'small insect': 6, 'snail': 6, 'spider': 6, 'Unknown': 6} else: label_dic = get_label_dic(anno, each_flag=each_flag, make_refinedet_data=True) print(label_dic) return label_dic def get_coord(value, centering=False): """ translate value to (x_center, y_center, w, h) or (x1, y1, x2, y2) Args: - value: list(dtype=int), [x1, y1, x2, y2] - centering: bool """ if centering is True: width = (value[2] - value[0])/2 height = (value[3] - value[1])/2 x_center = value[0] + width y_center = value[1] + height return x_center, y_center, width, height else: upper_left_x = value[0] upper_left_y = value[1] under_right_x = value[2] under_right_y = value[3] return upper_left_x, upper_left_y, under_right_x, under_right_y def coord_in_percentage_notation(coord, image_size, centering=False): """ get value in percentage notation Args: - value: list(dtype=int), [x1, y1, x2, y2] - image_size: tuple(dtype=int), [height, width] - centering: bool """ if centering is True: coord[0] /= 2*image_size[1] coord[1] /= 2*image_size[0] coord[2] /= image_size[1] coord[3] /= image_size[0] else: coord[0] /= image_size[1] coord[1] /= image_size[0] coord[2] /= image_size[1] coord[3] /= image_size[0] return coord def create_annotation(images, anno, unused_labels, centering=False, percent=False): """ adopt coord to training condition Args: - images: {image_id: image} - anno: {image_id: list(tuple(insect_name, coord))} - unused_labels: list(dtype=str) - centering: bool - percent: bool """ new_anno = {} for k,v in tqdm(anno.items()): new_value = [] if k == ".ipynb_checkpoints": continue image_size = images[k].shape[0:2] for value in anno[k]: if value[0] in unused_labels: continue coord = get_coord(value[1], centering) if percent is True: coord = coord_in_percentage_notation(list(coord), image_size, centering) if value[0] in ["unknown", "medium insect", "small insect"]: label = "Unknown" else: label = value[0] new_annotation = (label, coord) new_value.append(new_annotation) new_anno.update({k:new_value}) return new_anno def init_data_dic(label_dic, new_anno, new_anno_not_percent=None): """ initialize data_dic Args: - label_dic: {insect_name, label} - new_anno: {image_id: list(tuple(insect_name, coord))} coord in percentage notation - new_anno_not_percent: {image_id: list(tuple(insect_name, coord))} coord in pixel notation, use if result coord in pixel notation """ data_dic = {} for k, v in label_dic.items(): data_dic.update({k: {"size": [], "file_id": [], "coord": []}}) for k, v in new_anno.items(): if k == ".ipynb_checkpoints": continue for i, value in enumerate(v): data_dic[value[0]]["size"].append([value[1][2] - value[1][0], value[1][3] - value[1][1]]) data_dic[value[0]]["file_id"].append(k) if new_anno_not_percent is not None: data_dic[value[0]]["coord"].append(new_anno_not_percent[k][i][1]) else: data_dic[value[0]]["coord"].append(value[1]) for k, v in data_dic.items(): data_dic[k]["size"] = np.array(data_dic[k]["size"]) data_dic[k]["file_id"] = np.array(data_dic[k]["file_id"]) data_dic[k]["coord"] = np.array(data_dic[k]["coord"]) return data_dic def get_dbscan_result(X_data, eps=0.005, min_samples=5): """ get DBSCAN clastering result Args: - X_data: pd.DataFrame - eps: float - min_samples: int """ leaf_size = 30 n_jobs = 1 db = DBSCAN(eps=eps, min_samples=min_samples, leaf_size=leaf_size, n_jobs=n_jobs) X_data_dbscanClustered = db.fit_predict(X_data.loc[:, :]) cluster_sum_X_data_dbscanClustered = [] for value in X_data_dbscanClustered: if value > 0: cluster_sum_X_data_dbscanClustered.append(0) else: cluster_sum_X_data_dbscanClustered.append(value) cluster_sum_X_data_dbscanClustered = pd.DataFrame(data=cluster_sum_X_data_dbscanClustered, index=X_data.index, columns=['cluster']) return cluster_sum_X_data_dbscanClustered def adopt_DBSCAN_to_data_dic(data_dic): """ adopt DBSCAN to data_dic Args: - data_dic: {insect_name: { "size": list(dtype=float), "file_id": list(dtype=float), "coord": list(dtype=float) }} """ for k, v in data_dic.items(): data_index = range(0, len(v["size"])) X_data = pd.DataFrame(data=v["size"], index=data_index) X_data_dbscanClustered = get_dbscan_result(X_data) abnormal_id = [] for i, val in enumerate(X_data_dbscanClustered.cluster): if val != 0: abnormal_id.append(i) abnormal_filter = np.ones(len(X_data), dtype="bool") abnormal_filter[abnormal_id] = False data_dic[k]["size"] = data_dic[k]["size"][abnormal_filter] data_dic[k]["file_id"] = data_dic[k]["file_id"][abnormal_filter] data_dic[k]["coord"] = data_dic[k]["coord"][abnormal_filter] return data_dic def create_DBSCAN_filtered_annotation(new_anno, data_dic): """ create DBSCAN filtered annotation from data_dic Args: - new_anno: {image_id: list(tuple(insect_name, coord))} - data_dic: {insect_name: { "size": list(dtype=float), "file_id": list(dtype=float), "coord": list(dtype=float) }} """ DBSCAN_filtered_new_anno = {} for k, v in new_anno.items(): DBSCAN_filtered_new_anno.update({k: []}) for anno_k, anno_v in new_anno.items(): for data_k, data_v in data_dic.items(): file_id_filter = data_v["file_id"] == anno_k file_id_filtered_coord = data_v["coord"][file_id_filter] new_annotation = [(data_k, coord.tolist()) for coord in file_id_filtered_coord] DBSCAN_filtered_new_anno[anno_k].extend(new_annotation) return DBSCAN_filtered_new_anno def adopt_DBSCAN(label_dic, new_anno, new_anno_not_percent=None): """ adopt DBSCAN to new_anno Args: - label_dic: {insect_name, label} - new_anno: {image_id: list(tuple(insect_name, coord))} coord is percentage notation - new_anno_not_percent: {image_id: list(tuple(insect_name, coord))} coord is pixel notation, use if result coord in pixel notation """ data_dic = init_data_dic(label_dic, new_anno, new_anno_not_percent) data_dic = adopt_DBSCAN_to_data_dic(data_dic) DBSCAN_filtered_new_anno = create_DBSCAN_filtered_annotation(new_anno, data_dic) return DBSCAN_filtered_new_anno def write_annotation(new_anno, label_dic, label_path, last_flag=False): """ output annotation file Args: - new_anno: {image_id: list(tuple(insect_name, coord))} - label_dic: {insect_name, label} - label_path: str - last_flag: bool """ labels = [] os.makedirs(label_path) for k,v in tqdm(new_anno.items()): path = pj(label_path, k+".txt") with open(path, "w") as f: for value in new_anno[k]: label = label_dic[value[0]] labels.append(label) coord = value[1] if last_flag is False: line = str(label)+" "+str(coord[0])+" "+str(coord[1])+" "+str(coord[2])+" "+str(coord[3])+"\n" else: line = str(coord[0])+" "+str(coord[1])+" "+str(coord[2])+" "+str(coord[3])+" "+str(label)+"\n" f.write(line) labels = np.array(labels) idx, count = np.unique(labels, return_counts=True) print("idx = {}".format(idx)) print("count = {}".format(count)) def build_detection_dataset_as_txt(data_root, img_folder, anno_folders, label_path, each_flag=False, plus_other=False, target_with_other=False, centering=False, percent=False, last_flag=False, use_DBSCAN=False): """ build detection dataset as txt Args: - data_root: str - img_folder: str - anno_folders: list(dtype=str) - label_path: str - each_flag: bool - plus_other: bool, if divide into target_class + other_class - target_with_other: bool, if divide into target_class(split label) + other_class - centering: bool - percent: bool - last_flag: bool - use_DBSCAN: bool """ unused_labels = ["]"] images, anno = load_anno(data_root, img_folder, anno_folders) new_anno = create_annotation(images, anno, unused_labels, centering, percent) label_dic = load_label_dic(new_anno, each_flag, plus_other, target_with_other) if use_DBSCAN is True: new_anno = adopt_DBSCAN(label_dic, new_anno) write_annotation(new_anno, label_dic, label_path, last_flag) def build_classification_ds_from_result(images, result, use_resize=False): """ make classification dataset using result coord - images: {file id: <np.array>} - result: {file id: {label id: <np.array>}} - use_resize: bool """ insect_dataset = {} for image_id, res in result.items(): print("creating images: {}".format(image_id)) res = res[0] default_imgs = images[image_id] cropped_imgs = [] for box in tqdm(res): coord = box[:4] if use_resize is True: cropped_img = crop_adjusted_std_resize(default_imgs, coord, 100, use_integer_coord=True) else: cropped_img = crop_adjusted_std(default_imgs, coord, 100, use_integer_coord=True) cropped_imgs.append(cropped_img) cropped_imgs = np.concatenate(cropped_imgs) insect_dataset.update({image_id: cropped_imgs.astype("float32")}) return insect_dataset<file_sep>/readme.md # Insect Phenology Detector ホワイトボードに映った昆虫の個体数を計測するためのシステム ### --- TODO --- ### 実験関連 ### コード修正 - [ ] train_RefineDet.ipynbをフルHDで学習可能にする - [ ] 昆虫の体サイズを予測できるようにモデルを修正 ### その他 - 30分、1時間ずっと同じ場所にいる昆虫をゴミかどうか判断して、ゴミなら背景差分を取って取り除く - 昆虫の体長を測れるモデルの構築 - 昆虫の分類形質を学習時に意味表現として与える --- ### 研究ログ - 2019/12 - [x] train_ResNet.ipynbのtrain()をcheckpointごとに保存可能にする - [x] compare_models.ipynbの完成 - [x] ResNet101/resnet18_b20_r45_lr1e-5_crossvalid_not_pretrainの実験を回す - [x] ResNet101/resnet18_b20_r45_lr1e-5_crossvalidの実験を回す - [x] ResNet101/resnet34_b20_r45_lr1e-5_crossvalid_not_pretrainの実験を回す - [x] ResNet101/resnet34_b20_r45_lr1e-5_crossvalidの実験を回す - [x] ResNet101/resnet50_b20_r45_lr1e-5_crossvalid_not_pretrainの実験を回す - [x] ResNet101/resnet50_b20_r45_lr1e-5_crossvalidの実験を回す - [x] ResNet101/resnet101_b20_r45_lr1e-5_crossvalid_not_pretrainの実験を回す - [x] ResNet101/resnet101_b20_r45_lr1e-5_crossvalidの実験を回す - [x] compare_insect_resize.ipynbの完成 - [x] ResNet101/resnet50_b20_r45_lr1e-5_crossvalid_resizeの実験を回す - [x] compare_DCL.ipynbの完成 - [x] ResNet101/resnet50_b20_r45_lr1e-5_crossvalid_resize_DCLの実験を回す - 検出結果から水生昆虫を分離するモデルの比較 結果の場所: det2cls/compare_div_model →水生昆虫判別器を使用しないほうが結果が良くなった(AP 0.654 vs 0.786) また分類モデルは全ての昆虫の分類を学習してから水生昆虫とその他の昆虫に分けた方が結果が良くなった(AP 0.786 vs 0.826) - 検出モデルのコスト考慮型学習の学習重みの考察 - RefineDetのコスト考慮型学習(CSL,Cost-Sensitive Learning) 学習誤差がクロスエントロピーで与えられるため、クラス別の重みしか定義できない - [1.2, 0.8]で学習してみる(param1) 結果の場所: detection/compare_crop →結果は良くならなかった - [0.8, 1.2]で学習してみる(param2) 結果の場所: detection/compare_crop →結果は良くならなかった - データセット:classify_insect_std_resize_aquatic_other_without_groupingの作成 {'Diptera': 0, 'Ephemeridae': 1, 'Ephemeroptera': 2, 'Lepidoptera': 3, 'Plecoptera': 4 , 'Trichoptera': 5, 'Coleoptera': 6, 'Hemiptera': 7, 'medium insect': 8, 'small insect': 9} - 4k画像をそもそも使う必要があるのか? 検出モデルをフルHDで学習してみる、tristanさん曰く精度は良くならない(ただ学習時間は短くなる) - 検出モデルで分類も学習してみる クラスは全部で13個(背景クラス+昆虫クラス)ある - 分類モデルで昆虫画像をresizeしたものとしてないものを比較 結果の場所: classification/compare_insect_size ほとんど同じ結果、実は昆虫の大きさも学習の重要な要因なのかも... - 分類モデルでDCLを使用したものとしてないものを比較 結果の場所: classification/compare_DCL 小さい昆虫の識別率が悪くなっただけ、今回のタスクでは大きいモデルの学習が難しいのかもしれない - 検出モデルで事前学習したときに小さい昆虫の識別率だけ悪くなる 事前学習のデータセットには小さい物体が含まれていない可能性がある →小さい物体を含めた事前学習の方法を提案できないか? →小さい物体の検出を学習しやすくする方法はないか? - 分類モデルの学習時に個体数の多い大きさで識別率が悪くなる 個体数が多いことで学習が難しくなっている、昆虫同士が似ているため判別できない →個体数を減らすのは良くないので、個体数の少ない大きさの昆虫をupsamplingする →昆虫の局所的な特徴を学習しやすくする方法を考える - 2020/1 - [x] compare_finetuning(cls).ipynbの完成 - [x] ResNet101/resnet50_b20_r45_lr1e-5_crossvalid_not_pretrainの実験を回す - [x] ResNet101/resnet50_b20_r45_lr1e-5_crossvalidの実験を回す - [x] ResNet101/resnet50_b20_r45_lr1e-5_crossvalid_freezeの実験を回す - imbalanced-learnを用いてUndersampling/OversamplingをするのにPCAが必須 - RandomSizeCropでは物体を小さく出来ないので、物体を小さくする方法を考える必要あり - テスト結果に応じて学習量を変えれば、少し結果が良くなった。 - 2020/2 - [x] compare_correction.ipynbの完成 - [x] ResNet101/resnet50_b20_r45_lr1e-5_crossvalidの実験を回す - [x] ResNet101/resnet50_b20_r45_lr1e-5_crossvalid_correctionの実験を回す - [x] ResNet101/resnet50_b20_r45_lr1e-5_crossvalid_correction_LowTrainableの実験を回す - [x] compare_resize.ipynbの完成 - [x] ResNet101/resnet50_b20_r45_lr1e-5_crossvalidの実験を回す - [x] ResNet101/resnet50_b20_r45_lr1e-5_crossvalid_resizeの実験を回す - [x] ResNet101/resnet50_b20_r45_lr1e-5_resize_crossvalidの実験を回す - [x] compare_sampling.ipynbの完成 - [x] ResNet101/resnet50_b20_r45_lr1e-5_crossvalidの実験を回す - [x] ResNet101/resnet50_b20_r45_lr1e-5_crossvalid_randomsamplingの実験を回す - [x] ResNet101/resnet50_b20_r45_lr1e-5_crossvalid_randomoversamplingの実験を回す - Zero-Paddingで学習した分類モデルの中間特徴量がおかしい →分類モデルの画像を大きさを揃える処理はZero-PaddingよりResizeの方が良い - 水生昆虫以外が入っているデータセットを削除 - 検出モデルでは昆虫の種類ごとにIoUの値を変えても良いのでは - 分類モデルでは過学習していることが分かった。学習する特徴を増やせるかも... - 分類モデルで入力サイズを揃える処理はZero-PaddingよりResizeの方が良さそう 結果は同程度だが、特徴量はResizeの方が正しく得られていた - 分類モデルでRegionConfusionMechanism単体のデータ拡張をすると結果が良くなった - 入力寄りの中間特徴量しか識別に関与していないかもしれない - 2020/3 - [x] compare_decoder.ipynbの完成 - [x] ResNet101/resnet50_b20_r45_lr1e-5_crossvalidの実験を回す - [x] ResNet101/resnet50_b20_r45_lr1e-5_crossvalid_concatenateの実験を回す - [x] ResNet101/resnet50_b20_r45_lr1e-5_crossvalid_FPNの実験を回す - [x] compare_concatenate_resize.ipynbの完成 - [x] ResNet101/resnet50_b20_r45_lr1e-5_crossvalid_concatenateの実験を回す - [x] ResNet101/resnet50_b20_r45_lr1e-5_crossvalid_resizeFAR_concatenateの実験を回す(FAR=Fix Aspect Ratio) - [x] ResNet101/resnet50_b20_r45_lr1e-5_crossvalid_resize_concatenateの実験を回す - oversamplingは結果良くなりそう - ResNet_concatenateは結果良くなる - 2020/6 - [x] train_RefineDet.ipynbのtrain()にコスト考慮型学習を適用する - [x] RefineDetで検出と分類を同時に学習出来るようにする - [ ] compare_divide_architecture.ipynbの完成 - refinedet_det2cls - [x] RefineDet/crop_b2_2_4_8_16_32_im512_det2clsの実験を回す - refinedet_resnet_plus_other - [x] RefineDet/crop_b2_2_4_8_16_32_im512の実験を回す - [x] ResNet101/resnet50_b20_r45_lr1e-5_crossvalid_otherの実験を回す - refinedet_plus_other_resnet - [x] RefineDet/crop_b2_2_4_8_16_32_im512_otherの実験を回す - [x] ResNet101/resnet50_b20_r45_lr1e-5_crossvalidの実験を回す - 検出モデルはGroup Normalization+Weight Standardizationで結果が少し改善 - クラス内サイズ分散とクラス別識別率・サイズ別識別率の関係を調べたが、有意差はなかった - クラス内サイズ分散について気になった点 - 個体数が多いとresizeFARが有利 - 昆虫サイズが大きいとconcat無しの方が良い - 2020/7 - [x] 検出評価コードのAPが違う原因を調べる - refinedetのtop_kを100から1000に変更すると同等の結果が出た - 100epochだと過学習しているので、20epochで評価を行う必要がある - [x] compare_autoaugment_oversample.ipynbの完成 - [x] ResNet101/resnet50_b20_lr1e-5_crossvalid_fastautoaugmentの実験を回す - [x] ResNet101/resnet50_b20_lr1e-5_crossvalid_fastautoaugment_randomoversampleの実験を回す - 以下のデータセットを作成 - classify_insect_std_plus_other(分類) - refinedet_plus_other(refinedet) - target_with_other(det2clsの評価用) - 分類モデルにautoaugmentを適用 昆虫認識とautoaugmentは相性が悪そう - クラス別の個体数を揃えるためにOverSampleが便利 - 画像データを偏りをFew-Shot学習の視点から解決していこう (Class-Imbalanceの解決を目指す論文(関連研究)がそもそも少ない) - 辞書のコピーは値渡しでないので、copyモジュールを使用する - ["annotations_4"]には"Hemiptera"が含まれていないので注意! - 検出で使用している評価コードによる結果が、以前の結果と異なる問題が発生 - 2020/8 - [x] 佐藤先生に新しくもらった画像データのモデル出力を送る - [x] visualize_annotation_20200806.ipynbの完成 - [x] 検出評価コードの検出結果を解析するコードの実装 - データ拡張について古典的なアプローチ(全数調査など)で調査する - 以下のデータセットを作成 - refinedet_all_20200806(refinedet) - refinedet_plus_other_20200806(refinedet) - refinedet_all_test_20200806(refinedet) - classify_insect_std_20200806(分類) - classify_insect_std_only_20200806(分類) - 検出にimgaugを用いたデータ拡張を実装 - テストにSPREAD_ALL_OVERの関数が使用できない(学習時とテスト時で処理される画像が異なる) - 検出でRandomの関数を使用すると、検出率が悪化した - 分類にimgaugを用いたデータ拡張を実装 - AutoAugmentと同様のデータ拡張を一つずつ実験 - 2020/9 - [x] 分類モデルで識別を間違えた昆虫のラベルを出力 - [x] compare_crop.ipynbの完成 - [x] RefineDet/b2_2_4_8_16_32_im512 - [x] RefineDet/crop_b2_2_4_8_16_32_im512 - [x] compare_finetuning(det).ipynbの完成 - [x] RefineDet/crop_b2_2_4_8_16_32_im512_not_pretrain - [x] RefineDet/crop_b2_2_4_8_16_32_im512 - [x] RefineDet/crop_b2_2_4_8_16_32_im512_freeze - [x] compare_add_data.ipynbの完成 - [x] RefineDet/crop_b2_2_4_8_16_32_im512_freeze - [x] RefineDet/crop_b2_2_4_8_16_32_im512_freeze_20200806 - [x] compare_use_extra.ipynbの完成 - [x] RefineDet/crop_b2_2_4_8_16_32_im512_freeze_20200806 - [x] RefineDet/crop_b2_2_4_8_16_32_im512_freeze_20200806_use_extra - [x] compare_augmentations.ipynbの完成 - [x] Shear: crop_b2_2_4_8_16_32_im512_freeze_20200806_use_extra_Shear - [x] Translate: crop_b2_2_4_8_16_32_im512_freeze_20200806_use_extra_Translate - [x] Rotate: crop_b2_2_4_8_16_32_im512_freeze_20200806_use_extra_Rotate - [x] AutoContrast: crop_b2_2_4_8_16_32_im512_freeze_20200806_use_extra_AutoContrast - [x] Invert: crop_b2_2_4_8_16_32_im512_freeze_20200806_use_extra_Invert - [x] Equalize: crop_b2_2_4_8_16_32_im512_freeze_20200806_use_extra_Equalize - [x] Solarize: crop_b2_2_4_8_16_32_im512_freeze_20200806_use_extra_Solarize - [x] Posterize: crop_b2_2_4_8_16_32_im512_freeze_20200806_use_extra_Posterize - [x] Contrast: crop_b2_2_4_8_16_32_im512_freeze_20200806_use_extra_Contrast - [x] Color: crop_b2_2_4_8_16_32_im512_freeze_20200806_use_extra_Color - [x] Brightness: crop_b2_2_4_8_16_32_im512_freeze_20200806_use_extra_Brightness - [x] Sharpness: crop_b2_2_4_8_16_32_im512_freeze_20200806_use_extra_Sharpness - [x] Cutout: crop_b2_2_4_8_16_32_im512_freeze_20200806_use_extra_Cutout - [x] compare_augmentation_combination.ipynbの完成 - [x] crop_b2_2_4_8_16_32_im512_freeze_20200806_use_extra - [x] crop_b2_2_4_8_16_32_im512_freeze_20200806_use_extra_Cutout - [x] crop_b2_2_4_8_16_32_im512_freeze_20200806_use_extra_All - [x] compare_add_data.ipynbの完成 - [x] ResNet101/resnet50_b20_r45_lr1e-5_crossvalid - [x] ResNet101/resnet50_b20_r45_lr1e-5_crossvalid_20200806_Rotate - [x] compare_augmentations.ipynbの完成 - [x] Shear: resnet50_b20_r45_lr1e-5_crossvalid_20200806_Shear - [x] Translate: resnet50_b20_r45_lr1e-5_crossvalid_20200806_Translate - [x] Rotate: resnet50_b20_r45_lr1e-5_crossvalid_20200806_Rotate - [x] AutoContrast: resnet50_b20_r45_lr1e-5_crossvalid_20200806_Autocontrast - [x] Invert: resnet50_b20_r45_lr1e-5_crossvalid_20200806_Invert - [x] Equalize: resnet50_b20_r45_lr1e-5_crossvalid_20200806_Equalize - [x] Solarize: resnet50_b20_r45_lr1e-5_crossvalid_20200806_Solarize - [x] Posterize: resnet50_b20_r45_lr1e-5_crossvalid_20200806_Posterize - [x] Contrast: resnet50_b20_r45_lr1e-5_crossvalid_20200806_Contrast - [x] Color: resnet50_b20_r45_lr1e-5_crossvalid_20200806_Color - [x] Brightness: resnet50_b20_r45_lr1e-5_crossvalid_20200806_Brightness - [x] Sharpness: resnet50_b20_r45_lr1e-5_crossvalid_20200806_Sharpness - [x] Cutout: resnet50_b20_r45_lr1e-5_crossvalid_20200806_Cutout - [x] compare_augmentation_combination.ipynbの完成 - [x] ResNet101/resnet50_b20_r45_lr1e-5_crossvalid_20200806 - [x] ResNet101/resnet50_b20_r45_lr1e-5_crossvalid_20200806_Rotate - [x] ResNet101/resnet50_b20_r45_lr1e-5_crossvalid_20200806_All - [x] compare_size_augmentation.ipynbの完成 - [x] ResNet101/resnet50_b20_r45_lr1e-5_crossvalid_20200806_Rotate - [x] ResNet101/resnet50_b20_r45_lr1e-5_crossvalid_20200806_Rotate_mu - [x] ResNet101/resnet50_b20_r45_lr1e-5_crossvalid_20200806_Rotate_sigma - [x] ResNet101/resnet50_b20_r45_lr1e-5_crossvalid_20200806_Rotate_uniform30 - [x] compare_labelsmoothing.ipynbの完成 - [x] ResNet101/resnet50_b20_r45_lr1e-5_crossvalid_20200806_Rotate - [x] ResNet101/resnet50_b20_r45_lr1e-5_crossvalid_20200806_Rotate_manual - [x] ResNet101/resnet50_b20_r45_lr1e-5_crossvalid_20200806_Rotate_KD - 研究室発表会での指摘 - 検出精度が下がったのはアンカーサイズの問題では? - Dipteraに識別が偏っているのは、データ量の問題 - 撮影環境の影響を軽減するために、色々な撮影環境でデータを作れば良い - フェノロジーの話を研究資料に足しておくように - データ拡張が良くなかったのはパラメータの問題があるかも - 追加データのアノテーションに余白が含まれていて、正しく学習・テストが行えない - body_sizeに昆虫ラベルがついているものがある - 佐藤先生にアノテーションの修正をお願い - 追加データのサイズを自力で修正 - 修正の結果、識別率が20%ほど改善 - 検出結果には足が識別できているものもあり、アノテーションに工夫が必要 - 佐藤先生とのMTG - 佐藤研究室でアノテーションを修正 - 足・手などははっきり見えるものは残す、それ以外は余白を除去 - 後輩たちに人工知能について軽く講義するようにお願いされた - アノテーションの主観による誤差を取り除ける手法を考える - 学習時の正解ボックスをランダムに拡張する →縮小拡張は良くない、精度は良くならなかった - 検出で大きいボックスを出力できていない気がする - refinedetの出力層数を増やす →出力層数を増やすと精度が良くなった - RIMG2338のアノテーションが修正できていなかった。データセット再構築 - LabelSmoothingLossを実装 - 学習は安定したが、結果は良くならなかった - Virtual Augmentationも実装してみる - 特徴量が多すぎて過学習してしまう可能性がある - モデルのサイズを変えて学習してみる →resnet50が一番良いことに変わりはなかった - 出力層手前で線形層を入れて、特徴圧縮ができるか確かめる →精度は良くならなかった - mobilenetを実装 - resnet18の方が学習が速くて精度も良かった - 初期学習率を1e-4に変えると大幅に性能が向上 - 現時点では比較のために学習率は揃えて実験を行う - pytorch+optunaでハイパーパラメータチューニングが出来る - 昆虫の体サイズの正規化として、ランダムリサイズ(平均固定、分散固定、完全正規化)を試す - 平均固定は個別の体サイズを与えずに実装できる - 分散固定、完全正規化の実装には個別の体サイズが必要 - 平均固定は個体数の大きい昆虫に学習が引っ張られて結果が悪くなる - 分散固定は平均が近い昆虫どうしで誤りが発生しやすくなる - ランダムリサイズで体サイズを変化させると、体サイズの分布に依存しない学習ができ結果が良くなる - 分類モデルの最良モデル =ランダムリサイズ、ファインチューニング、Concatenate、dropout、全データ拡張(複数適用)、oversample - 検出モデルの最良モデル =クロップ+リサイズ、特徴抽出モデルを凍結しファインチューニング、use_extra、全データ拡張、AugTarget - 分類モデルの間違いを可視化 - Diptera: 翅が見えているもの(少数)と見えていないもの(多数)がある 小さい個体と大きい個体でアノテーションの付け方が違う気がする - Ephemeridae: 目がはっきり見えない個体の識別が難しい 長いしっぽが見えない - Ephemeroptera: 翅が見えているもの(少数)と見えていないもの(多数)がある、大きい個体 - Lepidoptera: 翅が見えているもの(多数)と見えていないもの(少数)がある - trichoptera: 触角が見えていないと識別が難しい 頭が太い個体(多数)と細い個体(少数)がある - 画像がぼやけている→何らかのフィルターで鮮明化できないか? - 分類モデルで知識蒸留を試してみる - 単体なら結果が良くなる。他の手法と組み合わせると結果が悪くなる - RAdamを実装 - 過学習が緩和されたが、AdamWの方が結果は良かった - 2020/10 - [x] 学習モデルと実験結果を細かくフォルダ分けする - [x] visualize_bounding_box.ipynbの完成 - [ ] compare_best_model.ipynbの完成 - [x] resnet50/b20_lr1e-5/crossvalid_20200806_not_pretrain - [x] resnet50/b20_lr1e-5/crossvalid_20200806 - [x] resnet50/b20_lr1e-5/crossvalid_20200806_All - [x] resnet50/b20_lr1e-5/crossvalid_20200806_All_uniform30 - [x] resnet50/b20_lr1e-5/crossvalid_20200806_All_uniform30_dropout - [x] compare_lr.ipynbの完成 - [x] ResNet101/resnet50_b20_r45_lr1e-3_crossvalid_20200806_All_uniform30 - [x] ResNet101/resnet50_b20_r45_lr1e-4_crossvalid_20200806_All_uniform30 - [x] ResNet101/resnet50_b20_r45_lr1e-5_crossvalid_20200806_All_uniform30 - [x] compare_dropout.ipynbの完成 - [x] ResNet101/resnet50_b20_r45_lr1e-5_crossvalid_20200806_All_uniform30 - [x] ResNet101/resnet50_b20_r45_lr1e-5_crossvalid_20200806_All_uniform30_dropout - [x] compare_uniform_width.ipynbの完成 - [x] resnet50/b20_lr1e-5/crossvalid_20200806_All_uniform10 - [x] resnet50/b20_lr1e-5/crossvalid_20200806_All_uniform30 - [x] resnet50/b20_lr1e-5/crossvalid_20200806_All_uniform50 - [x] resnet50/b20_lr1e-5/crossvalid_20200806_All_uniform70 - [x] resnet50/b20_lr1e-5/crossvalid_20200806_All_uniform90 - [x] compare_DBSCAN.ipynbの完成 - [x] resnet50/b20_lr1e-5/crossvalid_20200806_All_uniform30_dropout - [x] resnet50/b20_lr1e-5/crossvalid_20200806_All_uniform30_dropout_DBSCAN - [ ] compare_size_augmentation.ipynbの完成 - [x] crop_b2/tcb5_im512_freeze_20200806_use_extra_All - [x] crop_b2/tcb5_im512_freeze_20200806_use_extra_All_uniform - [x] crop_b2/tcb5_im512_freeze_20200806_use_extra_All_AugTarget - [x] crop_b2/tcb5_im512_freeze_20200806_use_extra_All_uniform_AugTarget - ResNet50は100epochでは学習が足りない - ResNet18は200epochの学習で過学習を確認 - 分類モデルの学習が初期学習率に左右される - 学習率を変えて実験してみる - 忘却機構(Dropout)を足して、学習が学習率に依存しにくくならないか調べる →過学習がすごく軽減された - クラスタリングを用いた異常検知を用いて学習データを減らしてみる - DBSCANが良さそう(sklearnで実装可能) - データ作成時に特徴量を(width, height)にし、PCA →DBSCANでクラスタ数1にし、外れ値を取り除く - 結果は良くならなかった - バッチサイズの影響を調べる - 小さいと精度は良くならない - 大きいと個体数の違いの影響を受けやすくなるかも - 分類モデルの出力バッチサイズを1に固定し、GPUメモリの使用を軽減 - pythonは実行時にファイルを読み込むので、configの設定に注意 - 検出モデルは2値分類なのでbinary_cross_entropyの方が良いかもしれない - 検出モデルのPR_curveの軸の範囲を(0, 1)に固定 - 検出モデルの命名ミスが判明、結果を再構築 - 分類モデルの学習方法を工夫してみる - エポックごとに学習データをランダムに選択する - エポックごとにアンダーサンプルでデータセットを再構築 - 検出出力のconfidenceが低すぎて、学習時とテスト時の精度の差が大きい - モデルのbox出力数を減らしてみる →結果がすごく悪くなるので減らしてはならない - 2020/11 - [ ] 体サイズ測定のために追加したデータセットの詳細をまとめる - [ ] compare_number_of_augmentation.ipynbの完成 - [x] resnet50/b20_lr1e-5/crossvalid_20200806_All_uniform30_dropout_oversample - [x] resnet50/b20_lr1e-5/crossvalid_20200806_All1to2_uniform30_dropout_oversample - [x] resnet50/b20_lr1e-5/crossvalid_20200806_All2to3_uniform30_dropout_oversample - [x] resnet50/b20_lr1e-5/crossvalid_20200806_All3to4_uniform30_dropout_oversample - [x] resnet50/b20_lr1e-5/crossvalid_20200806_All4to5_uniform30_dropout_oversample - [x] resnet50/b20_lr1e-5/crossvalid_20200806_All5to6_uniform30_dropout_oversample - [x] resnet50/b20_lr1e-5/crossvalid_20200806_All6to7_uniform30_dropout_oversample - [x] resnet50/b20_lr1e-5/crossvalid_20200806_All7to8_uniform30_dropout_oversample - [x] resnet50/b20_lr1e-5/crossvalid_20200806_All8to9_uniform30_dropout_oversample - [ ] compare_decoder.ipynbの完成 - [x] resnet50/b20_lr1e-5/crossvalid_20200806_All6to7_uniform30_dropout_oversample - [x] resnet50/b20_lr1e-5/crossvalid_20200806_All6to7_uniform30_dropout_oversample_concat_not_compression - [x] resnet50/b20_lr1e-5/crossvalid_20200806_All6to7_uniform30_dropout_oversample_concat - [x] resnet50/b20_lr1e-5/crossvalid_20200806_All6to7_uniform30_dropout_oversample_FPN_not_compression - [x] resnet50/b20_lr1e-5/crossvalid_20200806_All6to7_uniform30_dropout_oversample_FPN - マハラノビス距離は学習・予測ともにうまく行かなかった - Few-Shot学習の手法はデータ数が多いと適用が難しい - 分類モデルは単に線形層が足りない可能性がある - 特徴量を結果に結びつけるのが難しいのでは - 結果は変わらなかった - 分類モデルの可視化の結果、oversampleは必須だと分かった - 出力ラベルが偏っていた - 分類モデルのデータ拡張の適用数を変えてみる - データ拡張の適用数0はまずい、過学習の原因になってる - 適用数を増やすと結果が良くなった - 検出モデルのアスペクト比を増やしてみる - バウンディングボックスから体サイズを予測するモデルを構築した - 1000epoch程度の学習が必要(学習にGPUが必要) - batch数が多いと学習が安定する - 誤差の大きさから、クラスごとの予測精度に差が生じていると思われる →クラス重みを付けて学習できるようにする、またクラスごとの誤差を表示する - 重み付けしても結果は劇的には良くならなかった →結果を可視化してみる - デコーダーのconcatenateにbottleneckブロックを追加 - 通常のconv2dよりメモリ・学習効率が良い - 学習の収束が遅いため、追加の学習が必要かも - 体サイズ推定のモデルで、特徴量が足りない - 昆虫の触角や足が含まれているかによってboxの大きさが大きく異なり、モデル化が困難 →昆虫画像から体サイズを推定するモデルの構築が必要 - AdamWのweight_decayにはL2正規化の効果があるので適用したほうが良い - 昆虫画像から体サイズを推定するモデルを構築 - 学習誤差は非常に小さくなったが、テスト誤差が小さくならない →モデルはこのままでも良いが、誤差関数を工夫して学習方針を示す必要がある - 転移学習が有効と思われる - バッチサイズが大きい方が学習が安定する - oversampleを適用すると少し誤差が減った - 分類モデルのデータ拡張について、座標変換系列のものだけを使用した方が性能が良くなる - FPNの挙動を正しい物に変更 - 体サイズ推定にセグメンテーションを使えばどうなるか - 画像から体サイズを直接推定した方が性能が良かった - 2020/12 - 修論用実験 - RefineDet - [x] 転移学習無し - [x] 転移学習(freeze) - [x] 転移学習 - [x] 転移学習(freeze) + 昆虫サイズ拡張 -->Recall最良 - [x] 転移学習(freeze) + データ拡張 -->AP最良 - [x] 転移学習(freeze) + データ拡張 + 昆虫サイズ拡張(All + Resize) - [x] 転移学習(freeze) + データ拡張 + 昆虫サイズ拡張(AllwithResize) - [x] (Aquatic + other) 転移学習(freeze) + データ拡張 - 以降時間があれば - [x] 転移学習 + データ拡張(0~2) -->適用数比較では最良 - [x] 転移学習 + データ拡張(1~3) - [x] 転移学習 + データ拡張(2~4) - [x] 転移学習 + データ拡張(3~5) - [x] 転移学習 + データ拡張(1) - [x] 転移学習 + データ拡張(2) - ResNet(分類) - [x] 転移学習無し - [x] 転移学習(freeze) - [x] 転移学習 - [x] 転移学習 + OS(OverSampling) - [x] 転移学習 + データ拡張 - [x] 転移学習 + OS + データ拡張 -->mAP最良 - [x] 転移学習 + OS + 昆虫サイズ拡張 - [x] 転移学習 + OS + データ拡張 + 昆虫サイズ拡張(All + Resize) - [x] 転移学習 + OS + データ拡張 + 昆虫サイズ拡張(AllwithResize) -->AP最良 - [x] 転移学習 + OS + データ拡張 + FC - 以降時間があれば - [x] 転移学習 + OS + データ拡張 + 昆虫サイズ拡張(AllwithResize, 0.5~2倍) - [x] 転移学習 + OS + データ拡張(0~1) - [x] 転移学習 + OS + データ拡張(1~2) - [x] 転移学習 + OS + データ拡張(2~3) - [x] 転移学習 + OS + データ拡張(3~4) - [x] 転移学習 + OS + データ拡張(4~5) - [x] 転移学習 + OS + データ拡張(5~6) -->適用数比較では最良 - [x] 転移学習 + OS + データ拡張(6~7) - [x] 転移学習 + OS + データ拡張(7~8) - [x] 転移学習 + OS + データ拡張(8~9) - ResNet(体長測定) - [x] 転移学習無し - [x] 転移学習(freeze) - [x] 転移学習 - [x] 転移学習 + OS - [x] 転移学習 + データ拡張 - [x] 転移学習 + OS + データ拡張 - [x] 転移学習 + OS + 昆虫サイズ拡張 - [x] 転移学習 + OS + データ拡張 + 昆虫サイズ拡張(All + Resize) - [x] 転移学習 + OS + データ拡張 + 昆虫サイズ拡張(AllwithResize) - [x] 転移学習 + OS + データ拡張 + FC - [x] 転移学習 + 昆虫サイズ拡張 - [x] 転移学習 + データ拡張 + 昆虫サイズ拡張(All + Resize) - [x] 転移学習 + データ拡張 + 昆虫サイズ拡張(AllwithResize) - 以降時間があれば - [x] 転移学習 + OS + データ拡張(0~2) - [x] 転移学習 + OS + データ拡張(1~3) - [x] 転移学習 + OS + データ拡張(2~4) - [x] 転移学習 + OS + データ拡張(3~5) -->適用数比較では最良 - [ ] 転移学習 + OS + データ拡張(4~6) - [ ] 転移学習 + OS + データ拡張(5~7) - [ ] 転移学習 + OS + データ拡張(6~8) - [ ] 転移学習 + OS + データ拡張(7~9) - モデル学習時にベストモデルを保存するようにした - サイズ拡張を元サイズの1~2倍に固定 --- ### 昆虫の分類形質 - Ephemeroptera(カゲロウ目) ###佐藤先生から聞いた特徴### 色はほぼ同じ、頭が大きい、尾が長い、羽が透明、止まるときは羽が垂直で、かつ頭が大きく見える。 ###日本産水生昆虫### 亜成虫と呼ばれる蛹に該当する発育段階があり、成虫と見分けがつかない。 目に複眼がある。中胸部、後胸部にそれぞれ前翅、後翅が発達するが、あったりなかったりする。 背中に線が入っている。 - Plecoptera(カワゲラ目) ###佐藤先生から聞いた特徴### 色はほぼ同じ、頭が小さい、羽をくっつけて畳む、羽の部分が広く見える。 ###日本産水生昆虫### 翅を背面に重ねて水平に畳む。頭に触角、複眼を持つ。尾は短い。 - Trichoptera(トビケラ目) ###佐藤先生から聞いた特徴### 色はほぼ同じ、羽を三角形に畳む、棒のように見える。 ###日本産水生昆虫### 全体的に蛾に似ているが、翅には鱗粉ではなく小毛がある場合が多い。 触角は棒状。翅は楕円もしくは逆三角形で地味な色が多い。 - Lepidoptera(チョウ、ガ) ###佐藤先生から聞いた特徴### 色は様々 ###日本産水生昆虫### 特になし - Diptera(ハエ目) ###佐藤先生から聞いた特徴### 足が6本しっかり見える。羽が横に垂直に開く ###日本産水生昆虫### 種類がすごく多い、2枚の翅を持っている。(前翅、後翅) 足がしっかりしていて、翅も丈夫そう。 <file_sep>/evaluation/detection/evaluate.py import cv2 from IPython.display import display from os import listdir as ld from os.path import join as pj import numpy as np import pandas as pd from PIL import Image from evaluation.Object_Detection_Metrics.lib.BoundingBox import BoundingBox from evaluation.Object_Detection_Metrics.lib.BoundingBoxes import BoundingBoxes from evaluation.Object_Detection_Metrics.lib.Evaluator import Evaluator from evaluation.Object_Detection_Metrics.lib.utils import * class Voc_Evaluater: def __init__(self, image_root, target_root, savePath): self.image_root = image_root self.target_root = target_root self.savePath = savePath self.default_img_size_dic = self.get_default_img_size_dic() self.gtBoundingBoxes = BoundingBoxes() self.myBoundingBoxes = BoundingBoxes() def get_default_img_size_dic(self): default_img_size_dic = {} anno_file_names = ld(self.target_root) anno_file_names = [filename.split('.')[0] for filename in anno_file_names if filename != ".ipynb_checkpoints"] for anno_file_name in anno_file_names: img = np.asarray(Image.open(pj(self.image_root, anno_file_name + ".png"))) img_height, img_width, _ = img.shape default_img_size_dic.update({anno_file_name: [img_height, img_width]}) return default_img_size_dic def initialize_ground_truth(self): gtBoundingBoxes = BoundingBoxes() print("initialize evaluater ...") anno_file_names = ld(self.target_root) anno_file_names = [filename.split('.')[0] for filename in anno_file_names if filename != ".ipynb_checkpoints"] for anno_file_name in anno_file_names: img_height, img_width = self.default_img_size_dic[anno_file_name] with open(pj(self.target_root, anno_file_name + ".txt"), mode='r') as f: lines = f.readlines() for line in lines: line = line.split("\n")[0] line = line.split(" ") x_min = np.round(float(line[0]) * float(img_width)) y_min = np.round(float(line[1]) * float(img_height)) x_max = np.round(float(line[2]) * float(img_width)) y_max = np.round(float(line[3]) * float(img_height)) label = str(line[4]) bb = BoundingBox(imageName = anno_file_name, classId = label, x = x_min, y = y_min, w = x_max, h = y_max, typeCoordinates=CoordinatesType.Absolute, bbType=BBType.GroundTruth, format=BBFormat.XYX2Y2) """ print("-----") print("anno_file_name = " + anno_file_name) print("label = " + label) print("x_min = " + str(x_min)) print("y_min = " + str(y_min)) print("x_max = " + str(x_max)) print("y_max = " + str(y_max)) print("typeCoordinates = " + str(CoordinatesType.Absolute)) print("bbType = " + str(BBType.GroundTruth)) print("format = " + str(BBFormat.XYX2Y2)) print("imgSize = x: " + str(img_width) + " y: " + str(img_height)) print("#####") """ gtBoundingBoxes.addBoundingBox(bb) self.gtBoundingBoxes = gtBoundingBoxes def set_result(self, result): self.initialize_ground_truth() myBoundingBoxes = self.gtBoundingBoxes print("setting result ...") for data_id, cls_dets_per_class in result.items(): img_height, img_width = self.default_img_size_dic[data_id] for cls_label, detections in cls_dets_per_class.items(): label = str(cls_label) for detection in detections: x_min = np.round(float(detection[0])) y_min = np.round(float(detection[1])) x_max = np.round(float(detection[2])) y_max = np.round(float(detection[3])) conf = float(detection[4]) bb = BoundingBox(imageName = data_id, classId = label, x = x_min, y = y_min, w = x_max, h = y_max, typeCoordinates=CoordinatesType.Absolute, bbType=BBType.Detected, format=BBFormat.XYX2Y2, classConfidence=conf) """ print("-----") print("anno_file_name = " + data_id) print("label = " + label) print("x_min = " + str(x_min)) print("y_min = " + str(y_min)) print("x_max = " + str(x_max)) print("y_max = " + str(y_max)) print("typeCoordinates = " + str(CoordinatesType.Absolute)) print("bbType = " + str(BBType.Detected)) print("format = " + str(BBFormat.XYX2Y2)) print("classConfidence = " + str(conf)) print("imgSize = x: " + str(img_width) + " y: " + str(img_height)) print("#####") """ myBoundingBoxes.addBoundingBox(bb) self.myBoundingBoxes = myBoundingBoxes def get_eval_metrics(self): evaluator = Evaluator() # Get metrics with PASCAL VOC metrics metricsPerClass = evaluator.PlotPrecisionRecallCurve( boundingBoxes=self.myBoundingBoxes, IOUThreshold=0.3, method=MethodAveragePrecision.voc_ap, showAP=True, showInterpolatedPrecision=False, savePath=self.savePath, showGraphic=False) return metricsPerClass def draw_boundingbox(self): anno_file_names = ld(self.target_root) anno_file_names = [filename.split('.')[0] for filename in anno_file_names if filename != ".ipynb_checkpoints"] for anno_file_name in anno_file_names: img = cv2.imread(pj(self.image_root, anno_file_name + ".png")) # Add bounding boxes img = self.gtBoundingBoxes.drawAllBoundingBoxes(img, anno_file_name) cv2.imwrite(pj(self.savePath, anno_file_name + ".png"), img) print("Image %s created successfully!" % anno_file_name) def visualize_mean_index(eval_metrics, refinedet_only=False, figure_root=None): """ calculate mean evaluation index and print - eval_metrics: metricsPerClass, output of Voc_Evaluater - refinedet_only: bool, whether training config == "det2cls" - figure_root: str, figure save root """ # --- calculate AP, precision, recall of Other insects --- if refinedet_only is False: eval_metric = eval_metrics[6] tp_fn = eval_metric['total positives'] tp = eval_metric['total TP'] fp = eval_metric['total FP'] other_AP = eval_metric['AP'] other_precision = tp/(tp + fp) other_recall = tp/tp_fn print("--- evaluation index for Other ---") print("AP = {}".format(other_AP)) print("precision = {}".format(other_precision)) print("recall = {}".format(other_recall)) # --- calculate mAP, mean_precision, mean_recall of Target insects --- AP_array = [] precision_array = [] recall_array = [] if refinedet_only is False: lbl_array = range(6) else: lbl_array = [1, 2, 3, 4, 5, 6] for class_lbl in lbl_array: eval_metric = eval_metrics[class_lbl] tp_fn = eval_metric['total positives'] tp = eval_metric['total TP'] fp = eval_metric['total FP'] AP_array.append(eval_metric['AP']) precision_array.append(tp/(tp + fp)) recall_array.append(tp/tp_fn) AP_array = np.asarray(AP_array) precision_array = np.asarray(precision_array) recall_array = np.asarray(recall_array) print("--- evaluation index for each Target ---") each_target_df = pd.DataFrame({"AP": AP_array, "Precision": precision_array, "Recall": recall_array}) display(each_target_df) print("--- evaluation index for Target ---") print("mAP = {}".format(AP_array.mean())) print("mean_precision = {}".format(precision_array.mean())) print("mean_recall = {}".format(recall_array.mean())) if figure_root is not None: target_df = pd.DataFrame({ "AP": [other_AP, AP_array.mean()], "Precision": [other_precision, precision_array.mean()], "Recall": [other_recall, recall_array.mean()]}) target_df.index = ["Other", "Aquatic Insect"] each_target_df.to_csv(pj(figure_root, "each_target_df.csv")) target_df.to_csv(pj(figure_root, "target_df.csv"))<file_sep>/model/resnet/utils.py import torch def define_weight(counts): """ get class weight from class count - counts: [int, ...] """ counts = counts / counts.sum() weights = torch.from_numpy(1 / counts).cuda().float() return weights def min_euclidean(out, sem): """ unused pytorch calculate euclidean """ nbr = sem.size(1) ab = torch.mm(out.view(-1, nbr), sem.t()) ab = ab.view(out.size(0), out.size(1), sem.size(0)) aa = (sem**2).sum(1) bb = (out**2).sum(-1) res = aa[None, None, :] + bb[:, :, None] - 2 * ab return res.min(-1)[1] def predict_label_from_semantic(predict_semantic, semantic_vectors): """ unused """ predict_labels = [] for p_semantic in predict_semantic: p_semantic = p_semantic[:, None, None].transpose(0, 1).transpose(1, 2) label = min_euclidean(p_semantic, semantic_vectors) predict_labels.append(int(label.cpu().numpy())) return predict_labels <file_sep>/utils/annotate.py import numpy as np def annotate_center(target, coord): """ unused """ xmin, ymin, xmax, ymax = coord xc, yc = (xmin+xmax)//2, (ymin+ymax)//2 target[yc,xc]=1 def annotate_full(target, coord): """ unused """ xmin, ymin, xmax, ymax = coord target[ymin:ymax,xmin:xmax]=1 def annotate_gaussian(target, coord): """ unused """ fill_values = None #create_gaussian target[ymin:ymax,xmin:xmax]=fill_values def make_detect_target(img, coords, anno_func=annotate_full): """ unused """ target = np.zeros((img.shape[0], img.shape[1]), dtype="uint8") for coord in coords: anno_func(target, coord) return target<file_sep>/model/readme.md ### 各モデルの使用方法 ### --- RefineDet --- - 必要ライブラリ pytorch >= 1.0 - 読み込みデータ形式 クラスラベルは0始まり(背景クラス:-1、識別クラス:0,1,...)で与える [x1:Float, y1:Float, x2:Float, y2:Float, label: Float]の形で読み込む (x1, y1)はボックスの左上の座標、(x2, y2)はボックスの右下の座標 - モデル入力時のデータ形式 画像: 512[pixel] * 512[pixel]のRGB画像(256 * 256, 1024 * 1024でも可) 教師データ: targets = torch.Tensor([[x1, y1, x2, y2, label], ...])を教師データとして与える 座標は0.0~1.0に正規化して渡す必要がある テスト時の識別は1始まり(学習時にラベルが+1されて、背景クラスが0になるように補正されている) <-- 注意!! refine_match()の中にラベル補正箇所あり ### --- ResNet, MobileNet --- - 必要ライブラリ pytorch >= 1.0 torchvision >= 0.2 - モデル入力時のデータ形式 配列はtorch.Tensor型 画像: 指定なし 教師データ: label, dtype=int ### --- SegNet, Unet --- 研究で使ってない(以前の研究のもの) - 必要ライブラリ 無し - モデル入力時のデータ形式 配列はtorch.Tensor型 画像: 指定なし 教師データ: segmentation_map, 入力画像と同サイズのグレースケール画像 <file_sep>/model/refinedet/utils/config.py def get_feature_sizes(input_size, tcb_layer_num, use_extra_layer): """ get feature sizes of vgg Args: - input_size: int, image size, choice [320, 512, 1024] - tcb_layer_num: int, number of TCB blocks, choice [4, 5, 6] - use_extra_layer: bool, add extra layer to vgg or not """ if tcb_layer_num == 4 and use_extra_layer == True: return [int(input_size / 8), int(input_size / 16), int(input_size / 32), int(input_size / 64)] elif tcb_layer_num == 4 and use_extra_layer == False: return [int(input_size / 4), int(input_size / 8), int(input_size / 16), int(input_size / 32)] elif tcb_layer_num == 5 and use_extra_layer == True: return [int(input_size / 4), int(input_size / 8), int(input_size / 16), int(input_size / 32), int(input_size / 64)] elif tcb_layer_num == 5 and use_extra_layer == False: return [int(input_size / 2), int(input_size / 4), int(input_size / 8), int(input_size / 16), int(input_size / 32)] elif tcb_layer_num == 6 and use_extra_layer == True: return [int(input_size / 2), int(input_size / 4), int(input_size / 8), int(input_size / 16), int(input_size / 32), int(input_size / 64)] else: print("ERROR: selected config can not get feature sizes") <file_sep>/dataset/classification/sampler.py import numpy as np def adopt_sampling(Y, idx, sampling): """ adopt sampling to idx Args: - Y: np.array, insect labels - idx: [[int, ...], ...], target of sampling - sampling: str, choice [RandomSample, OverSample] or None """ if sampling == "RandomSample": print("sampling == RandomSample") new_idx = get_randomsampled_idx(Y, idx) elif sampling == "OverSample": print("sampling == OverSample") new_idx = get_oversampled_idx(Y, idx) else: print("sampling == None") new_idx = idx return new_idx def get_randomsampled_idx(Y, idx): """ randomsample with smallest idx and get idxs Args: - Y: np.array, insect labels - idx: [[int, ...], ...], target of sampling """ idx = np.asarray(idx) idx_filtered_Y = Y[idx] insect_ids, count = np.unique(idx_filtered_Y, return_counts=True) min_count = count.min() new_idx = [] for insect_id in insect_ids: id_filter = idx_filtered_Y == insect_id filtered_idx = idx[id_filter] sampled_filtered_idx = np.random.choice(filtered_idx, min_count, replace=False) new_idx.extend(sampled_filtered_idx) return new_idx def get_oversampled_idx(Y, idx): """ oversample with largest idx and get idxs Args: - Y: np.array, insect labels - idx: [int, ...], target of sampling """ idx = np.asarray(idx) idx_filtered_Y = Y[idx] insect_ids, count = np.unique(idx_filtered_Y, return_counts=True) max_count = count.max() new_idx = [] for insect_id in insect_ids: id_filter = idx_filtered_Y == insect_id filtered_idx = idx[id_filter] oversampled_filtered_idx = oversample_idx_to_max_count(filtered_idx, max_count) new_idx.extend(oversampled_filtered_idx) return new_idx def oversample_idx_to_max_count(filtered_idx, max_count): """ oversample id up to max_count Args: - filtered_idx: [int, ...], insect_id filtered idx - max_count: int """ now_idx_count = 0 oversampled_idx = [] while now_idx_count < max_count: if (filtered_idx.shape[0] + now_idx_count) <= max_count: oversampled_idx.extend(filtered_idx) now_idx_count += filtered_idx.shape[0] elif max_count < (filtered_idx.shape[0] + now_idx_count) and now_idx_count < max_count: random_sampled_idx = np.random.choice(filtered_idx, max_count - now_idx_count, replace=False) oversampled_idx.extend(random_sampled_idx) now_idx_count += max_count - now_idx_count return oversampled_idx<file_sep>/evaluation/det2cls/visualize.py import cv2 import numpy as np def vis_detections(im, dets, class_name="insects", color_name="green", thresh=0.5): """Visual debugging of detections.""" color = {"white":[255,255,255], "red":[255,0,0], "lime":[0,255,0], "blue":[0,0,255], "yellow":[255,255,0], "fuchsia":[255,0,255], "aqua":[0,255,255], "gray":[128,128,128], "maroon":[128,0,0], "green":[0,128,0], "navy":[0,0,128], "olive":[128,128,0], "purple":[128,0,128], "teal":[0,128,128], "black":[0,0,0]}[color_name] for i in range(dets.shape[0]): bbox = tuple(int(np.round(x)) for x in dets[i, :4]) score = dets[i, -1] if score > 1.0: cv2.rectangle(im, bbox[0:2], bbox[2:4], color, 2) cv2.putText(im, '%s: ground truth' % (class_name), (bbox[0], bbox[1] + 15), cv2.FONT_HERSHEY_PLAIN, 1.0, (0, 0, 255), thickness=1) elif score > thresh: cv2.rectangle(im, bbox[0:2], bbox[2:4], color, 2) cv2.putText(im, '%s: %.3f' % (class_name, score), (bbox[0], bbox[1] + 15), cv2.FONT_HERSHEY_PLAIN, 1.0, (0, 0, 255), thickness=1) return im <file_sep>/utils/crop.py import cv2 import numpy as np def compute_padding(coord, delta=100, use_segmentation_lbl=False): """ compute padding size - coord: [x1, y1, x2, y2] - delta: int """ xmin, ymin, xmax, ymax = coord padleft = (2*delta - (xmax - xmin)) // 2 padright = 2*delta - padleft - (xmax - xmin) padtop = (2*delta - (ymax - ymin)) // 2 padbottom = 2*delta - padtop - (ymax - ymin) if use_segmentation_lbl is True: return ((padtop,padbottom), (padleft,padright)) else: return ((padtop,padbottom), (padleft,padright), (0,0)) def check_coord(coord, size=200): """ check coordination and correct (width, height) - coord: [x1, y1, x2, y2] - size: int """ xmin, ymin, xmax, ymax = coord if (xmax - xmin) > size: xc = (xmin+xmax)//2 xmin, xmax = xc-(size//2), xc+(size//2) if (ymax - ymin) > size: yc = (ymin+ymax)//2 ymin, ymax = yc-(size//2), yc+(size//2) return xmin, ymin, xmax, ymax def crop_standard(img, coord, delta=100): """ standard crop and padding constant - img: image_data, np.array - coord: [x1, y1, x2, y2] - delta: int """ xmin, ymin, xmax, ymax = coord xc, yc = (xmin+xmax)//2, (ymin+ymax)//2 img = img[max(0,yc-delta):yc+delta, max(0,xc-delta):xc+delta] xs, ys, _ = img.shape padleft = 2*delta - xs padtop = 2*delta - ys if padleft or padtop: padright = 2*delta - xs - padleft // 2 padbottom = 2*delta - ys - padtop // 2 pad = ((padleft//2,padright),(padtop//2,padbottom), (0,0)) img = np.pad(img, pad, "constant") return img[None,:] def crop_adjusted(img, coord, delta=100, use_integer_coord=False): """ adjusting crop and padding constant - img: image_data, np.array - coord: [x1, y1, x2, y2] - delta: int """ coord = check_coord(coord) xmin, ymin, xmax, ymax = coord if use_integer_coord is True: xmin = int(xmin) ymin = int(ymin) xmax = int(xmax) ymax = int(ymax) img = img[ymin:ymax, xmin:xmax].copy() padding = compute_padding((0, 0, img.shape[1], img.shape[0])) img = np.pad(img, padding, "constant") return img[None,:] def crop_adjusted_std(img, coord, delta=100, use_integer_coord=False): """ adjusting crop and padding constant and std - img: image_data, np.array - coord: [x1, y1, x2, y2] - delta: int """ coord = check_coord(coord) xmin, ymin, xmax, ymax = coord if use_integer_coord is True: xmin = int(xmin) ymin = int(ymin) xmax = int(xmax) ymax = int(ymax) img = (img - np.mean(img, keepdims=True))/np.std(img, keepdims=True)*32+128 img = img[ymin:ymax, xmin:xmax].copy() padding = compute_padding((0, 0, img.shape[1], img.shape[0])) img = np.pad(img, padding, "constant") return img[None,:] def crop_adjusted_std_resize(img, coord, delta=100, use_integer_coord=False): """ adjusting crop and padding constant and std and resize to (200*200) - img: image_data, np.array - coord: [x1, y1, x2, y2] - delta: int - use_integer_coord: bool """ coord = check_coord(coord) xmin, ymin, xmax, ymax = coord if use_integer_coord is True: xmin = int(xmin) ymin = int(ymin) xmax = int(xmax) ymax = int(ymax) if (xmax - xmin) > (ymax - ymin): max_length_axis = xmax - xmin else: max_length_axis = ymax - ymin img = (img - np.mean(img, keepdims=True))/np.std(img, keepdims=True)*32+128 img = img[ymin:ymax, xmin:xmax].copy() img = cv2.resize(img, dsize=(200, 200), interpolation=cv2.INTER_LINEAR) return img[None,:] def crop_adjusted_std_resizeFAR(img, coord, delta=100, use_integer_coord=False): """ adjusting crop and padding constant and std and resizeFAR FAR: Fix Aspect Ratio - img: image_data, np.array - coord: [x1, y1, x2, y2] - delta: int - use_integer_coord: bool """ coord = check_coord(coord) xmin, ymin, xmax, ymax = coord if use_integer_coord is True: xmin = int(xmin) ymin = int(ymin) xmax = int(xmax) ymax = int(ymax) if (xmax - xmin) > (ymax - ymin): max_length_axis = xmax - xmin else: max_length_axis = ymax - ymin img = (img - np.mean(img, keepdims=True))/np.std(img, keepdims=True)*32+128 img = img[ymin:ymax, xmin:xmax].copy() if (xmax - xmin) > (ymax - ymin): img = cv2.resize(img, dsize=(200, (int)(img.shape[0]*200/max_length_axis)), interpolation=cv2.INTER_LINEAR) else: img = cv2.resize(img, dsize=((int)(img.shape[1]*200/max_length_axis), 200), interpolation=cv2.INTER_LINEAR) padding = compute_padding((0, 0, img.shape[1], img.shape[0])) img = np.pad(img, padding, "constant") return img[None,:]<file_sep>/hikitsugi.md ### 引き継ぎ資料 #### 各フォルダとファイルの説明 - data - all_classification_data 分類モデルを学習するようのデータ。 make_classification_data.ipynbを使って作成できる。 詳しくはdataset.mdに記載している。 - annotations_0, annotations_2, annotations_3, annotations_4, annotations_20200806 データセットを作成するためのアノテーションデータ。 LabelImgを用いて作成してもらっている。 ファイル名は画像と連動している。 annotations_0〜annotations_4とannotations_20200806は撮影時期が異なり、 annotations_20200806の方が新しいデータである。 データ形式はPascalVocのアノテーションと同一のものを使用している。 (これらのデータはLabelImgで可視化できるのでぜひとも見て欲しい) - insect_knowledge 分類モデルの予測のクラス平均をとったもの。 知識蒸留の手法として、学習済みモデルの予測をターゲットラベルに使用する手法があり、 それを実装するために作った。 - ooe_pict 撮影されたが、アノテーションが付けられていない画像。 モデル予測を提供するためにあり、相手からモデル予測を出して欲しいと言われたら、 適当にフォルダを作ってモデル予測を提供して欲しい。 - refined_images 学習・テストに使用できる全画像(annotations 0, 2, 3, 4, 20200806)が含まれている。 jpeg形式で画像をもらっているが、モデルの学習・テストにはpng形式を用いている。 jpeg形式は圧縮方式なので、モデルの画素が安定しないため画像認識には向かないことを覚えておいて欲しい。 - train_detection_data, train_refined_images 検出モデルを学習するためのデータ。 detection_dataはモデルで読み込むためのアノテーションデータで、 refined_imagesは画像データである。 make_detection_data.ipynbを使って作成できる。 詳しくはdataset.mdに記載している。 - test_detection_data, test_refined_images 検出モデルをテストするためのデータ。 make_detection_data.ipynbを使って作成できる。 詳しくはdataset.mdに記載している。 - dataset - classification - dataset.py 分類モデルのデータセットクラス。 - loader.py 分類モデルのデータ読み込み用関数をまとめたもの。 - sampler.py データサンプリング用関数。 オーバーサンプリング、アンダーサンプリングは実装している。 - detection - dataset.py 検出モデルのデータセットクラス。 - evaluation - classification - evaluate.py 正答率と混同行列を計算する関数が入っている。 - statistics.py pandasのデータフレームを作成する関数が入っている。 - visualize.py 可視化用関数がまとめてある。 - det2cls - visualize.py 検出予測を可視化するための関数が入っている。 モデル予測と正解ラベルが同じ色で可視化されるようになっている。 - detection - evaluate.py 検出モデルのVOC-APを計算するためのクラスが入っている。 Object_Detection_Metricsというライブラリを改造して作った。 - statistics.py pandasのデータフレームを作成する関数が入っている。 - Object_Detection_Metrics VOC-APを計算するライブラリ。 ところどころいじっている。 - figure モデル予測や可視化した図などはここにいれている。 - finished 今は使わなくなったものを、ここに残してある。 vis_classification_dataやvis_detection_dataは少し直せば使える可視化関数。 他は説明しないが、研究の役に立つかもしれない。 - IO - build_ds.py 検出・分類データセットを構築する関数が入っている。 - create_bbox2size_ds.py 現在は使っていない。 昆虫の体サイズを計算する関数は入っており、 体サイズ関連の処理を書くときに役立つかもしれない。 - loader.py 様々なデータ読み込み用の関数が入っている。 - logger.py 学習・テスト時の引数を保存するロガーが入っている。 - utils.py xml出力のための関数などが入っている。 PascalVoc形式のアノテーションを出力できる。 - visdom.py visdomで可視化を行うための関数が入っている。 - model - mobilenet 作ってみたけど、性能は良くならなかったmobilenetを構築するクラス - refinedet 現在検出モデルとして使用しているモデル。 モデル構築用のクラスや関数がまとめてある。 詳しくはコードを見て欲しい。 - resnet 現在分類モデル・体サイズ予測モデルとして使用しているモデル。 モデル構築用のクラスや関数がまとめてある。 詳しくはコードを見て欲しい。 unusedの中にAutoAugment/FastAutoAugmentの結果を適用する関数を まとめてあるが、詳しくはreadme.mdを見て欲しい。 - segnet, unet 自分の以前の研究で使っていたコードを残してある。 セグメンテーションのモデルだが、役立つときがあるかもしれない。 - conv_layer.py Group_Normalization + Weight_Standardizationを実装するために、 Conv2dを改造したもの。 - optimizer.py AdamW, RAdamが入っている。 - output_model 学習したモデルはここに保存される。 - output_xml 出力した予測結果のxmlはここに保存される。 詳しくはhikitsugi.mdを見て欲しい。 - result 解析した結果はここにまとめられている。 詳しくはhikitsugi.mdを見て欲しい。 - utils クロップやアノテーションのための関数が入っているが、 ほとんど使っていない。 - dataset.md データセット関連の情報はここに記載している。 ここに載っていない情報は自分で調べて欲しい。 - test_Refinedet_ResNet.ipynb 自分の提案した資源量予測モデルを全体を通して動かすためのコード。 - test_RefineDet.ipynb 検出モデルを単体でテストするためのコード。 - train_classification.ipynb 分類モデルを学習するためのコード。 日本語でコメントをつけた。 - train_detection.ipynb 検出モデルを学習するためのコード。 日本語でコメントをつけた。 - train_image2size.ipynb 体サイズ予測モデルを学習するためのコード。 - visualize_resnet_feature.ipynb ResNetの特徴量を可視化するためのコード。 日本語でコメントをつけた。 #### 現在の進捗状況 自分の研究の流れはreadme.mdに記載しているが、特に記載しておきたいことだけまとめる。 ・分類モデルの最良 転移学習 + オーバーサンプリング + ランダムデータ拡張 モデルの場所: /home/tanida/workspace/Insect_Phenology_Detector/output_model/classification/master_paper/resnet50/b20_lr1e-5/crossvalid_20200806_OS_All5to6 ・検出モデルの最良 転移学習 + ランダムデータ拡張 モデルの場所: /home/tanida/workspace/Insect_Phenology_Detector/output_model/detection/RefineDet/master_paper/crop_b2/tcb5_im512_freeze_All0to2 ・体サイズ予測モデルの最良 転移学習 + オーバーサンプリング + ランダムデータ拡張 モデルの場所: /home/tanida/workspace/Insect_Phenology_Detector/output_model/image2size/ResNet34_b80_lr1e-4_OS_all02 いろいろな手法を試したが、不均衡データの影響が大きすぎて転移学習・データ拡張などの学習量を正規化する 手法しか良い効果を得られなかった。 そのため、データそのものを増やすためにアノテーション作成の補助ツールを作る研究などが必要だと考えている。 そして、モデルと人がうまく協力してアノテーションの精度・モデルの精度を高め合う仕組みが必要だと思う。 機械学習のアプローチからはあまり良い結果が得られなかったが、生物学の分野から研究を進めると より良い機械学習手法が生み出せると自分は考えている。 #### 研究の始め方 各モデルの学習コードを動かしてみて、現在の処理の流れを確認して欲しい。 また、テストコードを動かして現在のモデルの精度を確認して欲しい。 ここまで動かせば処理の流れがつかめると思う。 他にもデータセット作成用のコードなども用意してあるので、確認しながら研究を進めて欲しい。 <file_sep>/model/mobilenet/mobilenet.py import torch from torch import nn import torch.nn.functional as F import torchvision.models as tv_models class MobileNet(nn.Module): def __init__(self, n_class, pretrain=False, param_freeze=False): super(MobileNet, self).__init__() mobilenet = tv_models.mobilenet_v2(pretrained=pretrain, progress=True) if param_freeze is True: for param in mobilenet.parameters(): param.requires_grad = False self.n_class = n_class self.pretrain = pretrain self.param_freeze = param_freeze self.mobilenet = nn.Sequential(*list(mobilenet.children())[:-1]) self.dropout = nn.Dropout(p=0.2, inplace=False) self.linear = nn.Linear(in_features=1280, out_features=n_class, bias=True) def forward(self, x): x = self.mobilenet(x) x = F.adaptive_avg_pool2d(x, 1).reshape(x.shape[0], -1) x = self.dropout(x) x = self.linear(x) return x<file_sep>/model/refinedet/refinedet.py # -*- coding: utf-8 -*- import torch import torch.nn as nn import torch.nn.functional as F from model.refinedet.utils.config import get_feature_sizes from model.refinedet.layers.l2norm import L2Norm from model.refinedet.layers.detection import Detect from model.refinedet.layers.prior_box import get_prior_box from model.refinedet.refinedet_base import vgg, vgg_extra, anchor_refinement_module, object_detection_module, transfer_connection_blocks class RefineDet(nn.Module): def __init__(self, input_size, num_classes, tcb_layer_num, pretrain=False, freeze=False, activation_function="ReLU", init_function="xavier_uniform_", use_extra_layer=False, use_GN_WS=False): """ 初期化関数 引数: - input_size: int, refinedetの入力サイズを指定, [320, 512, 1024]の中から一つ - num_classes: int, 分類するクラス数(前景+背景) - tcb_layer_num: int, TCB(Transfer Connection Block)の数, [4, 5, 6]の中から一つ - pretrain: bool, ImageNetの転移学習を行うか否か - freeze: bool, 特徴抽出モデル(VGG)の重みを固定するか否か - activation_function: str, 発火関数を指定 - init_function: str, 初期化関数を指定 - use_extra_layer: bool, VGGに追加の層を入れるかどうか 追加の層を入れるとvgg_sourceが一つずつずれる 例)tcb_layer_num == 4, use_GN_WS == Falseのとき, use_extra_layer == False: vgg_source = [14, 21, 28, -2] -> True: vgg_source = [21, 28, -2] - use_GN_WS: bool, Group Normalization + Weight Standardizationを使用するか否か RefineDetにはバッチ正規化が入っていないので, その代わりとなるもの これらを採用したのは, 単に性能が良さそうだったから """ super(RefineDet, self).__init__() if input_size == 320 or input_size == 512 or input_size == 1024: pass else: print("ERROR: You specified size " + str(input_size) + ". However, currently only RefineDet320 and RefineDet512 and RefineDet1024 is supported!") if tcb_layer_num == 4: if use_GN_WS is True: if use_extra_layer is True: vgg_source = [30, 40, -3] tcb_source_channels = [512, 512, 1024, 512] else: vgg_source = [20, 30, 40, -3] tcb_source_channels = [256, 512, 512, 1024] else: if use_extra_layer is True: vgg_source = [21, 28, -2] tcb_source_channels = [512, 512, 1024, 512] else: vgg_source = [14, 21, 28, -2] tcb_source_channels = [256, 512, 512, 1024] elif tcb_layer_num == 5: if use_GN_WS is True: if use_extra_layer is True: vgg_source = [20, 30, 40, -3] tcb_source_channels = [256, 512, 512, 1024, 512] else: vgg_source = [10, 20, 30, 40, -3] tcb_source_channels = [128, 256, 512, 512, 1024] else: if use_extra_layer is True: vgg_source = [14, 21, 28, -2] tcb_source_channels = [256, 512, 512, 1024, 512] else: vgg_source = [7, 14, 21, 28, -2] tcb_source_channels = [128, 256, 512, 512, 1024] elif tcb_layer_num == 6: if use_GN_WS is True: if use_extra_layer is True: vgg_source = [10, 20, 30, 40, -3] tcb_source_channels = [128, 256, 512, 512, 1024, 512] else: print("ERROR: tcb_layer_num=6 and use_extra_layer=False is not defined") else: if use_extra_layer is True: vgg_source = [7, 14, 21, 28, -2] tcb_source_channels = [128, 256, 512, 512, 1024, 512] else: print("ERROR: tcb_layer_num=6 and use_extra_layer=False is not defined") else: print("ERROR: You specified tcb_layer_num " + str(tcb_layer_num) + ". 4,5,6 is allowed for this value") if activation_function == "ReLU": print("activation_function = ReLU") elif activation_function == "LeakyReLU": print("activation_function = LeakyReLU") elif activation_function == "ELU": print("activation_function = ELU") elif activation_function == "LogSigmoid": print("activation_function = LogSigmoid") elif activation_function == "RReLU": print("activation_function = RReLU") elif activation_function == "SELU": print("activation_function = SELU") elif activation_function == "CELU": print("activation_function = CELU") elif activation_function == "Sigmoid": print("activation_function = Sigmoid") if init_function == "xavier_uniform_": print("init_function = xavier_uniform_") elif init_function == "xavier_normal_": print("init_function = xavier_normal_") elif init_function == "kaiming_uniform_": print("init_function = kaiming_uniform_") elif init_function == "kaiming_normal_": print("init_function = kaiming_normal_") elif init_function == "orthogonal_": print("init_function = orthogonal_") # config self.input_size = input_size self.num_classes = num_classes self.tcb_layer_num = tcb_layer_num self.pretrain = pretrain self.freeze = freeze self.activation_function = activation_function self.init_function = init_function self.use_extra_layer = use_extra_layer self.use_GN_WS = use_GN_WS # compute prior anchor box feature_sizes = get_feature_sizes(input_size, tcb_layer_num, use_extra_layer) self.priors = get_prior_box(input_size, feature_sizes) # create models model_base = vgg(pretrain, activation_function, use_GN_WS) self.vgg = nn.ModuleList(model_base) if self.use_extra_layer is True: model_extra = vgg_extra(use_GN_WS) self.extras = nn.ModuleList(model_extra) else: model_extra = None ARM = anchor_refinement_module(model_base, model_extra, vgg_source, use_extra_layer, use_GN_WS) ODM = object_detection_module(model_base, model_extra, num_classes, vgg_source, use_extra_layer, use_GN_WS) TCB = transfer_connection_blocks(tcb_source_channels, activation_function, use_GN_WS) self.conv2_3_L2Norm = L2Norm(128) self.conv3_3_L2Norm = L2Norm(256) self.conv4_3_L2Norm = L2Norm(512) self.conv5_3_L2Norm = L2Norm(512) self.arm_loc = nn.ModuleList(ARM[0]) self.arm_conf = nn.ModuleList(ARM[1]) self.odm_loc = nn.ModuleList(ODM[0]) self.odm_conf = nn.ModuleList(ODM[1]) self.tcb0 = nn.ModuleList(TCB[0]) self.tcb1 = nn.ModuleList(TCB[1]) self.tcb2 = nn.ModuleList(TCB[2]) self.init_weights() self.softmax = nn.Softmax(dim=-1) self.detect = Detect def forward(self, x): """ 順伝播 引数: - x: torch.Tensor, size==[bs, 3, input_size, input_size], モデル入力 """ sources = list() tcb_source = list() arm_loc = list() arm_conf = list() odm_loc = list() odm_conf = list() if self.use_GN_WS is True: # apply vgg up to conv4_3 relu and conv5_3 relu for k in range(43): x = self.vgg[k](x) if 12 == k: if self.use_extra_layer is True and self.tcb_layer_num == 6: s = self.conv2_3_L2Norm(x) sources.append(s) if self.use_extra_layer is False and self.tcb_layer_num == 5: s = self.conv2_3_L2Norm(x) sources.append(s) if 22 == k: if self.use_extra_layer is True and (self.tcb_layer_num == 5 or self.tcb_layer_num == 6): s = self.conv3_3_L2Norm(x) sources.append(s) if self.use_extra_layer is False: s = self.conv3_3_L2Norm(x) sources.append(s) if 32 == k: s = self.conv4_3_L2Norm(x) sources.append(s) if 42 == k: s = self.conv5_3_L2Norm(x) sources.append(s) # apply vgg up to fc7 for k in range(43, len(self.vgg)): x = self.vgg[k](x) sources.append(x) else: # apply vgg up to conv4_3 relu and conv5_3 relu for k in range(30): x = self.vgg[k](x) if 8 == k: if self.use_extra_layer is True and self.tcb_layer_num == 6: s = self.conv2_3_L2Norm(x) sources.append(s) if self.use_extra_layer is False and self.tcb_layer_num == 5: s = self.conv2_3_L2Norm(x) sources.append(s) if 15 == k: if self.use_extra_layer is True and (self.tcb_layer_num == 5 or self.tcb_layer_num == 6): s = self.conv3_3_L2Norm(x) sources.append(s) if self.use_extra_layer is False: s = self.conv3_3_L2Norm(x) sources.append(s) if 22 == k: s = self.conv4_3_L2Norm(x) sources.append(s) if 29 == k: s = self.conv5_3_L2Norm(x) sources.append(s) # apply vgg up to fc7 for k in range(30, len(self.vgg)): x = self.vgg[k](x) sources.append(x) # apply extra layers and cache source layer outputs if self.use_extra_layer is True: for k, v in enumerate(self.extras): if self.activation_function == "ReLU": x = F.relu(v(x), inplace=True) elif self.activation_function == "LeakyReLU": x = F.leaky_relu(v(x), inplace=True) elif self.activation_function == "ELU": x = F.elu(v(x), inplace=True) elif self.activation_function == "LogSigmoid": x = F.logsigmoid(v(x)) elif self.activation_function == "RReLU": x = F.rrelu(v(x), inplace=True) elif self.activation_function == "SELU": x = F.selu(v(x), inplace=True) elif self.activation_function == "CELU": x = F.celu(v(x), inplace=True) elif self.activation_function == "Sigmoid": x = F.sigmoid(v(x)) if k % 2 == 1: sources.append(x) # apply ARM to source layers if self.use_GN_WS is True: for k, x in enumerate(sources): arm_loc.append(self.arm_loc[2*k+1](self.arm_loc[2*k](x)).permute(0, 2, 3, 1).contiguous()) arm_conf.append(self.arm_conf[2*k+1](self.arm_conf[2*k](x)).permute(0, 2, 3, 1).contiguous()) arm_loc = torch.cat([o.view(o.size(0), -1) for o in arm_loc], 1) arm_conf = torch.cat([o.view(o.size(0), -1) for o in arm_conf], 1) else: for (x, l, c) in zip(sources, self.arm_loc, self.arm_conf): arm_loc.append(l(x).permute(0, 2, 3, 1).contiguous()) arm_conf.append(c(x).permute(0, 2, 3, 1).contiguous()) arm_loc = torch.cat([o.view(o.size(0), -1) for o in arm_loc], 1) arm_conf = torch.cat([o.view(o.size(0), -1) for o in arm_conf], 1) # apply TCB to source layers p = None for k, v in enumerate(sources[::-1]): s = v # --- tcb0 --- for i in range(3): s = self.tcb0[(self.tcb_layer_num - 1 - k) * 3 + i](s) # --- tcb1 --- if k != 0: u = p u = self.tcb1[self.tcb_layer_num - 1 - k](u) s += u # --- tcb2 --- for i in range(3): s = self.tcb2[(self.tcb_layer_num - 1 - k) * 3 + i](s) p = s tcb_source.append(s) tcb_source.reverse() # apply ODM to source layers if self.use_GN_WS is True: for k, x in enumerate(tcb_source): odm_loc.append(self.odm_loc[2*k+1](self.odm_loc[2*k](x)).permute(0, 2, 3, 1).contiguous()) odm_conf.append(self.odm_conf[2*k+1](self.odm_conf[2*k](x)).permute(0, 2, 3, 1).contiguous()) odm_loc = torch.cat([o.view(o.size(0), -1) for o in odm_loc], 1) odm_conf = torch.cat([o.view(o.size(0), -1) for o in odm_conf], 1) else: for (x, l, c) in zip(tcb_source, self.odm_loc, self.odm_conf): odm_loc.append(l(x).permute(0, 2, 3, 1).contiguous()) odm_conf.append(c(x).permute(0, 2, 3, 1).contiguous()) odm_loc = torch.cat([o.view(o.size(0), -1) for o in odm_loc], 1) odm_conf = torch.cat([o.view(o.size(0), -1) for o in odm_conf], 1) if self.training is True: # if model is train mode output = ( arm_loc.view(arm_loc.size(0), -1, 4), arm_conf.view(arm_conf.size(0), -1, 2), odm_loc.view(odm_loc.size(0), -1, 4), odm_conf.view(odm_conf.size(0), -1, self.num_classes), self.priors ) else: # if model is test mode output = self.detect.apply( arm_loc.view(arm_loc.size(0), -1, 4), # arm loc preds self.softmax(arm_conf.view(arm_conf.size(0), -1, 2)), # arm conf preds odm_loc.view(odm_loc.size(0), -1, 4), # odm loc preds self.softmax(odm_conf.view(odm_conf.size(0), -1, self.num_classes)), # odm conf preds self.priors.type(type(x.detach())), # default boxes, match type with x self.num_classes, ) return output def init_weights(self): """ 重み初期化関数 """ print('Initializing weights ...') if self.freeze is True: for param in self.vgg.parameters(): param.requires_grad = False if self.init_function == "xavier_uniform_": layer_initializer = xavier_uniform_initializer elif self.init_function == "xavier_normal_": layer_initializer = xavier_normal_initializer elif self.init_function == "kaiming_uniform_": layer_initializer = kaiming_uniform_initializer elif self.init_function == "kaiming_normal_": layer_initializer = kaiming_normal_initializer elif self.init_function == "orthogonal_": layer_initializer = orthogonal_initializer self.arm_loc.apply(layer_initializer) self.arm_conf.apply(layer_initializer) self.odm_loc.apply(layer_initializer) self.odm_conf.apply(layer_initializer) self.tcb0.apply(layer_initializer) self.tcb1.apply(layer_initializer) self.tcb2.apply(layer_initializer) def xavier_uniform_initializer(layer): """ initialize layer weight Args: - layer: layer module """ if isinstance(layer, nn.Conv2d) or isinstance(layer, nn.ConvTranspose2d): nn.init.xavier_uniform_(layer.weight) nn.init.constant_(layer.bias, 0.) def xavier_normal_initializer(layer): """ initialize layer weight Args: - layer: layer module """ if isinstance(layer, nn.Conv2d) or isinstance(layer, nn.ConvTranspose2d): nn.init.xavier_normal_(layer.weight) nn.init.constant_(layer.bias, 0.) def kaiming_uniform_initializer(layer): """ initialize layer weight Args: - layer: layer module """ if isinstance(layer, nn.Conv2d) or isinstance(layer, nn.ConvTranspose2d): nn.init.kaiming_uniform_(layer.weight) nn.init.constant_(layer.bias, 0.) def kaiming_normal_initializer(layer): """ initialize layer weight Args: - layer: layer module """ if isinstance(layer, nn.Conv2d) or isinstance(layer, nn.ConvTranspose2d): nn.init.kaiming_normal_(layer.weight) nn.init.constant_(layer.bias, 0.) def orthogonal_initializer(layer): """ initialize layer weight Args: - layer: layer module """ if isinstance(layer, nn.Conv2d) or isinstance(layer, nn.ConvTranspose2d): nn.init.orthogonal_(layer.weight) nn.init.constant_(layer.bias, 0.)<file_sep>/model/refinedet/refinedet_base.py import torch.nn as nn from model.conv_layer import WS_Conv2d from model.refinedet.vgg_base import _vgg def get_vgg_with_GN(vgg_features): """ create VGG with GN Args: - vgg_features: module list, pytorch vgg model """ new_module_list = [] for module in vgg_features: if isinstance(module, nn.Conv2d): new_module_list += [module, nn.GroupNorm(int(module.out_channels / 4), module.out_channels)] else: new_module_list += [module] return list(nn.Sequential(*new_module_list)) # This function is derived from torchvision VGG make_layers() # https://github.com/pytorch/vision/blob/master/torchvision/models/vgg.py def vgg(pretrain, activation_function, use_GN_WS=False): """ create VGG model Args: - input_channels: int, input channels for vgg - activation_function: str - batch_norm: bool, flag for using batch_norm """ if use_GN_WS is True: Conv2d = WS_Conv2d else: Conv2d = nn.Conv2d vgg = _vgg('vgg16', pretrain, True, activation_function, use_GN_WS) vgg_features = list(nn.Sequential(*list(vgg.features.children())[:-1])) pool5 = nn.MaxPool2d(kernel_size=2, stride=2, padding=0) conv6 = Conv2d(512, 1024, kernel_size=3, padding=3, dilation=3) conv7 = Conv2d(1024, 1024, kernel_size=1) nn.init.xavier_uniform_(conv6.weight) nn.init.xavier_uniform_(conv7.weight) nn.init.constant_(conv6.bias, 0) nn.init.constant_(conv7.bias, 0) if activation_function == "ReLU": vgg_features += [pool5, conv6, nn.ReLU(inplace=True), conv7, nn.ReLU(inplace=True)] elif activation_function == "LeakyReLU": vgg_features += [pool5, conv6, nn.LeakyReLU(inplace=True), conv7, nn.LeakyReLU(inplace=True)] elif activation_function == "ELU": vgg_features += [pool5, conv6, nn.ELU(inplace=True), conv7, nn.ELU(inplace=True)] elif activation_function == "LogSigmoid": vgg_features += [pool5, conv6, nn.LogSigmoid(), conv7, nn.LogSigmoid()] elif activation_function == "RReLU": vgg_features += [pool5, conv6, nn.RReLU(inplace=True), conv7, nn.RReLU(inplace=True)] elif activation_function == "SELU": vgg_features += [pool5, conv6, nn.SELU(inplace=True), conv7, nn.SELU(inplace=True)] elif activation_function == "CELU": vgg_features += [pool5, conv6, nn.CELU(inplace=True), conv7, nn.CELU(inplace=True)] elif activation_function == "Sigmoid": vgg_features += [pool5, conv6, nn.Sigmoid(), conv7, nn.Sigmoid()] if use_GN_WS is True: vgg_features = get_vgg_with_GN(vgg_features) return vgg_features def vgg_extra(use_GN_WS=False): """ Extra layers added to VGG for feature scaling """ if use_GN_WS is True: Conv2d = WS_Conv2d else: Conv2d = nn.Conv2d model_parts = [256, 'S', 512] layers = [] input_channels = 1024 flag = False for k, v in enumerate(model_parts): if input_channels != 'S': if v == 'S': layers += [Conv2d(input_channels, model_parts[k + 1], kernel_size=(1, 3)[flag], stride=2, padding=1)] else: layers += [Conv2d(input_channels, v, kernel_size=(1, 3)[flag])] flag = not flag input_channels = v return layers def anchor_refinement_module(model_base, model_extra, vgg_source, use_extra_layer=False, use_GN_WS=False): """ create ARM model Args: - model_base: VGG model - model_extra: extra layers for VGG - vgg_source: [int, ...], source layers of TCB - use_extra_layer: bool, add extra layer to vgg or not """ if use_GN_WS is True: Conv2d = WS_Conv2d else: Conv2d = nn.Conv2d arm_loc_layers = [] arm_conf_layers = [] if use_GN_WS is True: for k, v in enumerate(vgg_source): arm_loc_layers += [Conv2d(model_base[v].out_channels, 3 * 4, kernel_size=3, padding=1), nn.GroupNorm(4, 3 * 4)] arm_conf_layers += [Conv2d(model_base[v].out_channels, 3 * 2, kernel_size=3, padding=1), nn.GroupNorm(2, 3 * 2)] if use_extra_layer is True: for k, v in enumerate(model_extra[1::2], 3): arm_loc_layers += [Conv2d(v.out_channels, 3 * 4, kernel_size=3, padding=1), nn.GroupNorm(4, 3 * 4)] arm_conf_layers += [Conv2d(v.out_channels, 3 * 2, kernel_size=3, padding=1), nn.GroupNorm(2, 3 * 2)] else: for k, v in enumerate(vgg_source): arm_loc_layers += [Conv2d(model_base[v].out_channels, 3 * 4, kernel_size=3, padding=1)] arm_conf_layers += [Conv2d(model_base[v].out_channels, 3 * 2, kernel_size=3, padding=1)] if use_extra_layer is True: for k, v in enumerate(model_extra[1::2], 3): arm_loc_layers += [Conv2d(v.out_channels, 3 * 4, kernel_size=3, padding=1)] arm_conf_layers += [Conv2d(v.out_channels, 3 * 2, kernel_size=3, padding=1)] return (arm_loc_layers, arm_conf_layers) def object_detection_module(model_base, model_extra, num_classes, vgg_source, use_extra_layer=False, use_GN_WS=False): """ create ODM model Args: - model_base: VGG model - model_extra: extra layers for VGG - num_classes: int, number of object class - vgg_source: [int, ...], source layers of TCB - use_extra_layer: bool, add extra layer to vgg or not """ if use_GN_WS is True: Conv2d = WS_Conv2d else: Conv2d = nn.Conv2d odm_loc_layers = [] odm_conf_layers = [] if use_GN_WS is True: for k, v in enumerate(vgg_source): odm_loc_layers += [Conv2d(256, 3 * 4, kernel_size=3, padding=1), nn.GroupNorm(4, 3 * 4)] odm_conf_layers += [Conv2d(256, 3 * num_classes, kernel_size=3, padding=1), nn.GroupNorm(num_classes, 3 * num_classes)] if use_extra_layer is True: for k, v in enumerate(model_extra[1::2], 3): odm_loc_layers += [Conv2d(256, 3 * 4, kernel_size=3, padding=1), nn.GroupNorm(4, 3 * 4)] odm_conf_layers += [Conv2d(256, 3 * num_classes, kernel_size=3, padding=1), nn.GroupNorm(num_classes, 3 * num_classes)] else: for k, v in enumerate(vgg_source): odm_loc_layers += [Conv2d(256, 3 * 4, kernel_size=3, padding=1)] odm_conf_layers += [Conv2d(256, 3 * num_classes, kernel_size=3, padding=1)] if use_extra_layer is True: for k, v in enumerate(model_extra[1::2], 3): odm_loc_layers += [Conv2d(256, 3 * 4, kernel_size=3, padding=1)] odm_conf_layers += [Conv2d(256, 3 * num_classes, kernel_size=3, padding=1)] return (odm_loc_layers, odm_conf_layers) def transfer_connection_blocks(tcb_source_channels, activation_function, use_GN_WS=False): """ create TCB Args: - tcb_source_channels: [int, ...], source channels of TCB - relu: nn.ReLU or nn.LeakyReLU or nn.RReLU """ if use_GN_WS is True: Conv2d = WS_Conv2d else: Conv2d = nn.Conv2d feature_scale_layers = [] feature_upsample_layers = [] feature_pred_layers = [] for k, v in enumerate(tcb_source_channels): if activation_function == "ReLU": feature_scale_layers += [Conv2d(tcb_source_channels[k], 256, 3, padding=1), nn.ReLU(inplace=True), Conv2d(256, 256, 3, padding=1) ] feature_pred_layers += [nn.ReLU(inplace=True), Conv2d(256, 256, 3, padding=1), nn.ReLU(inplace=True) ] elif activation_function == "LeakyReLU": feature_scale_layers += [Conv2d(tcb_source_channels[k], 256, 3, padding=1), nn.LeakyReLU(inplace=True), Conv2d(256, 256, 3, padding=1) ] feature_pred_layers += [nn.LeakyReLU(inplace=True), Conv2d(256, 256, 3, padding=1), nn.LeakyReLU(inplace=True) ] elif activation_function == "ELU": feature_scale_layers += [Conv2d(tcb_source_channels[k], 256, 3, padding=1), nn.ELU(inplace=True), Conv2d(256, 256, 3, padding=1) ] feature_pred_layers += [nn.ELU(inplace=True), Conv2d(256, 256, 3, padding=1), nn.ELU(inplace=True) ] elif activation_function == "LogSigmoid": feature_scale_layers += [Conv2d(tcb_source_channels[k], 256, 3, padding=1), nn.LogSigmoid(), Conv2d(256, 256, 3, padding=1) ] feature_pred_layers += [nn.LogSigmoid(), Conv2d(256, 256, 3, padding=1), nn.LogSigmoid() ] elif activation_function == "RReLU": feature_scale_layers += [Conv2d(tcb_source_channels[k], 256, 3, padding=1), nn.RReLU(inplace=True), Conv2d(256, 256, 3, padding=1) ] feature_pred_layers += [nn.RReLU(inplace=True), Conv2d(256, 256, 3, padding=1), nn.RReLU(inplace=True) ] elif activation_function == "SELU": feature_scale_layers += [Conv2d(tcb_source_channels[k], 256, 3, padding=1), nn.SELU(inplace=True), Conv2d(256, 256, 3, padding=1) ] feature_pred_layers += [nn.SELU(inplace=True), Conv2d(256, 256, 3, padding=1), nn.SELU(inplace=True) ] elif activation_function == "CELU": feature_scale_layers += [Conv2d(tcb_source_channels[k], 256, 3, padding=1), nn.CELU(inplace=True), Conv2d(256, 256, 3, padding=1) ] feature_pred_layers += [nn.CELU(inplace=True), Conv2d(256, 256, 3, padding=1), nn.CELU(inplace=True) ] elif activation_function == "Sigmoid": feature_scale_layers += [Conv2d(tcb_source_channels[k], 256, 3, padding=1), nn.Sigmoid(), Conv2d(256, 256, 3, padding=1) ] feature_pred_layers += [nn.Sigmoid(), Conv2d(256, 256, 3, padding=1), nn.Sigmoid() ] if k != len(tcb_source_channels) - 1: feature_upsample_layers += [nn.ConvTranspose2d(256, 256, 2, 2)] return (feature_scale_layers, feature_upsample_layers, feature_pred_layers) <file_sep>/evaluation/classification/visualize.py # -*- coding: utf-8 -*- import matplotlib.pyplot as plt import numpy as np from os.path import join as pj def plot_size_of_anno(W,H): """ plot size (scatter, H, W) of anno - H: [int, ...] - W: [int, ...] """ fig, axes = plt.subplots(1,3, figsize=(30,10)) axes[0].scatter(W,H, alpha=0.5) axes[1].hist(H) axes[2].hist(W) def plot_size_by_class_of_anno(H,W,C): """ plot size scatter of anno, by class - H: [int, ...] - W: [int, ...] - C: [str, ...] """ fig, axes = plt.subplots(1,1, figsize=(10,10)) for c in np.unique(C): msk = C==c h = H[msk] w = W[msk] axes.scatter(w,h, alpha=.5, label=c) fig.legend() def create_confusion_matrix(matrix, ntests, labels, figure_root, save=False): """ 混同行列の描画 引数: - matrix: np.array, 混同行列 - ntests: np.array, 各クラスの個体数 - labels: [str, ...], 昆虫ラベル - figure_root: str, 図の保存先フォルダのパス - save: bool, 図を保存するかどうか """ plt.rcParams["font.size"] = 20 plt.rcParams["axes.grid"] = False fig, axe = plt.subplots(1, 1, figsize=(10, 10)) for i in range(len(labels)): for j in range(len(labels)): matrix[i, j] = matrix[i, j] / ntests[i] axe.set_xticks(np.arange(len(labels))) axe.set_yticks(np.arange(len(labels))) axe.set_xticklabels(labels) axe.set_yticklabels(labels) axe.imshow(matrix) plt.setp(axe.get_xticklabels(), rotation=45, ha="right", rotation_mode="anchor") matrix2 = np.round(matrix, 2) for i in range(len(labels)): for j in range(len(labels)): axe.text(j, i, matrix2[i, j], size=20, ha="center", va="center", color="black") axe.set_title("Confusion_matrix") axe.set_xlabel("Output_class") axe.set_ylabel("Target_class") if save is True: plt.savefig(pj(figure_root, "confusion_matrix.png"), bbox_inches="tight") def plot_df_distrib_size(df, figure_root, save=False): """ サイズ帯(=log2 Insect_size)ごとのRecallを描画 この関数での描画は不十分なので, resultフォルダにある関数を使ってほしい 引数: - df: pd.DataFrame({"order", "Accuracy", "Insect_size"}) - figure_root: str, 図の保存先フォルダのパス - save: bool, 図を保存するかどうか """ df.plot(x="Insect_size", y="Recall", logx=True, legend=False) plt.title("Recall with size distribution") plt.ylabel("Recall") plt.ylim(0.7, 1.01) if save is True: plt.savefig(pj(output_dir, "recall_with_size_distribution.png"), bbox_inches="tight")<file_sep>/IO/logger.py import os from os.path import join as pj import re class Logger(object): """ 引数ロガー """ def __init__(self, args, filename="args.txt"): """ 初期化関数 引数: - args: 引数クラス model_rootが必須 - filename: str, 引数を保存するファイルのファイル名 """ self.args = args self.file_path = pj(args.model_root, filename) if os.path.exists(args.model_root) is False: os.makedirs(args.model_root) def write(self, msg): """ 書き込み関数 引数: - msg: str, ファイルに追加する文字列 """ if self.file_path is not None: with open(self.file_path, "a") as f: f.write(msg) def generate_args_map(self): """ 引数辞書の作成 """ args_keys_list = list(self.args.__dict__.keys()) args_values_list = list(self.args.__dict__.values()) pattern = r"__" refined_args_map = {} for i, args_key in enumerate(args_keys_list): is_meta = re.match(pattern, args_key) if is_meta is None: refined_args_map.update( {args_keys_list[i]: args_values_list[i]}) return refined_args_map def save(self): """ ファイルの保存 """ args_map = self.generate_args_map() self.write("\nTraining on: " + self.args.experiment_name + "\n") self.write("Using the specified args:" + "\n") for k, v in args_map.items(): self.write(str(k) + ": " + str(v) + "\n")<file_sep>/model/refinedet/layers/detection.py import torch from torch.autograd import Function from model.refinedet.utils.functions import decode_location_data, point_form, nms class Detect(Function): """At test time, Detect is the final layer of SSD. Decode location preds, apply non-maximum suppression to location predictions based on conf scores and threshold to a top_k number of output predictions for both confidence score and locations. """ @staticmethod def forward(ctx, arm_loc_data, arm_conf_data, odm_loc_data, odm_conf_data, prior_data, \ num_classes, background_label=0, top_k=1000, nms_thresh=0.45, \ conf_thresh=0.01, objectness_thresh=0.01, variance=[0.1, 0.2]): arm_object_conf = arm_conf_data.data[:, :, 1:] # [:, :, 0] == non-object conf, [:, :, 1] == object conf no_object_filter = arm_object_conf <= objectness_thresh odm_conf_data[no_object_filter.expand_as(odm_conf_data)] = 0 batch_size = odm_loc_data.size(0) num_priors = prior_data.size(0) result = torch.zeros(batch_size, num_classes, top_k, 5) # odm_conf_data.shape == [batch_size, num_priors, self.num_classes] # => odm_conf_preds.shape == [batch_size, self.num_classes, num_priors] conf_preds = odm_conf_data.view(batch_size, num_priors, num_classes).transpose(2, 1) # decode predictions into bboxs for i in range(batch_size): prior_data_decoded_by_arm = decode_location_data(arm_loc_data[i], prior_data, variance) prior_data_decoded_by_odm = decode_location_data(odm_loc_data[i], prior_data_decoded_by_arm, variance) prior_data_decoded_by_odm = point_form(prior_data_decoded_by_odm) # for each class, perform nms # odm_conf_scores.shape == [self.num_classes, num_priors] # classes = background_class + other_classes conf_scores = conf_preds[i].clone() for cls_lbl in range(1, num_classes): conf_scores_filter_per_cls = conf_scores[cls_lbl].gt(conf_thresh) filtered_conf_scores_per_cls = conf_scores[cls_lbl][conf_scores_filter_per_cls] if filtered_conf_scores_per_cls.size(0) == 0: continue prior_data_filter_per_cls = conf_scores_filter_per_cls.unsqueeze(1).expand_as(prior_data_decoded_by_odm) filtered_prior_data_per_cls = prior_data_decoded_by_odm[prior_data_filter_per_cls].view(-1, 4) # idx of highest scoring and non-overlapping boxes per class ids, count = nms(filtered_prior_data_per_cls, filtered_conf_scores_per_cls, nms_thresh, top_k) result[i, cls_lbl, :count] = torch.cat((filtered_conf_scores_per_cls[ids[:count]].unsqueeze(1), filtered_prior_data_per_cls[ids[:count]]), 1) flt = result.contiguous().view(batch_size, -1, 5) _, idx = flt[:, :, 0].sort(1, descending=True) _, rank = idx.sort(1) flt[(rank < (top_k / 2)).unsqueeze(-1).expand_as(flt)].fill_(0) return result <file_sep>/model/resnet/loss.py import torch import torch.nn as nn import torch.nn.functional as F class LabelSmoothingLoss(nn.CrossEntropyLoss): """ Label Smoothing Cross Entropy Loss """ def __init__(self, label_smoothing, num_classes, counts=None, knowledge=None, weight=None, size_average=None, reduction='mean'): """ init function Args: - label_smoothing: float, 0~1 - num_classes: int, insect class number - counts: np.array(dtype=int), shape == [num_classes], insect count - knowledge: np.array(dtype=float), shape == [num_classes, num_classes], softmax distribution - weight: torch.FloatTensor, shape == [num_classes] - size_average: bool - reduction: str, 'mean' or 'sum' """ super(LabelSmoothingLoss, self).__init__(weight, size_average, reduction=reduction) # initialize label smooth loss assert 0.0 < label_smoothing <= 1.0 self.label_smoothing = label_smoothing self.num_classes = num_classes self.counts = counts self.knowledge = knowledge self.confidence = 1.0 - label_smoothing self.softmax = nn.LogSoftmax(dim=1) self.cross_entropy = nn.CrossEntropyLoss() if self.counts is not None: one_hot = torch.Tensor(counts / counts.sum()) self.register_buffer('one_hot', one_hot.unsqueeze(0).cuda()) elif self.knowledge is not None: pass else: smoothing_value = 1.0 / num_classes one_hot = torch.full((num_classes, ), smoothing_value) self.register_buffer('one_hot', one_hot.unsqueeze(0).cuda()) def forward(self, output, target): """ forward function Args: - output: torch.FloatTensor, batchsize * num_classes - target: torch.Tensor, batchsize """ if self.knowledge is not None: output = self.softmax(output) model_prob = torch.Tensor([self.knowledge[y] for y in target]).cuda() model_prob = model_prob.scatter_(1, target.unsqueeze(1), 1.0) return F.kl_div(output, model_prob, reduction='batchmean') else: output = self.softmax(output) model_prob = self.one_hot.repeat(target.size(0), 1) model_prob = model_prob.scatter_(1, target.unsqueeze(1), self.confidence) return F.kl_div(output, model_prob, reduction='batchmean')<file_sep>/IO/create_bbox2size_ds.py import numpy as np import pandas as pd import os from os import getcwd as cwd from os.path import join as pj from IO.build_ds import load_anno, create_annotation """ use this script in working directory ==> Insect_Phenology_Detector/ """ def divide_target_and_body(new_anno): """ divide body size from new_anno, {image_id: {"target", "body"}} Args: - new_anno: {image_id: list(tuple(insect_name, coord))} """ new_anno_div_body = {} for image_id, values in new_anno.items(): target_list = [] body_list = [] for value in values: if value[0] == 'body size': body_list.append(value) else: target_list.append(value) new_anno_div_body.update({image_id: {"target": target_list, "body": body_list}}) return new_anno_div_body def get_feature_point_filter(target_bbox, body_bboxes): """ filtering features of the head and tail Args: - target_bbox: np.array(dtype=int), shape==[4] - body_bboxes: np.array(dtype=int), shape==[body_num, 4] """ x1_filter = body_bboxes[:, 0] >= target_bbox[0] x2_filter = body_bboxes[:, 2] <= target_bbox[2] y1_filter = body_bboxes[:, 1] >= target_bbox[1] y2_filter = body_bboxes[:, 3] <= target_bbox[3] feature_point_filter = x1_filter & x2_filter & y1_filter & y2_filter return feature_point_filter def calc_euclidean_distance(body_bboxes_filtered_feature_point): """ calculate euclidean distance between head and tail Args: - body_bboxes_filtered_feature_point: np.array(dtype=int), shape==[2, 4] """ p1 = np.array([ (body_bboxes_filtered_feature_point[0, 2] + body_bboxes_filtered_feature_point[0, 0]) / 2, (body_bboxes_filtered_feature_point[0, 3] + body_bboxes_filtered_feature_point[0, 1]) / 2, ]) p2 = np.array([ (body_bboxes_filtered_feature_point[1, 2] + body_bboxes_filtered_feature_point[1, 0]) / 2, (body_bboxes_filtered_feature_point[1, 3] + body_bboxes_filtered_feature_point[1, 1]) / 2, ]) return np.linalg.norm(p1 - p2) def get_new_anno_with_size(new_anno_div_body, return_feature_point=False): """ create new_anno with insect size, {image_id: list(tuple(insect_name, coord))} Args: - new_anno_div_body: {image_id: { "target": list(tuple(insect_name, coord)), "body": list(tuple(insect_name, coord)) }} - return_feature_point: bool, use if you create segmentation annotation """ new_anno_with_size = {} for image_id, values in new_anno_div_body.items(): target_list = values['target'] body_list = values['body'] body_bboxes = np.array([elem_body[1] for elem_body in body_list]) target_list_with_size = [] for elem_target in target_list: target_bbox = np.array(elem_target[1]) feature_point_filter = get_feature_point_filter(target_bbox, body_bboxes) if feature_point_filter.sum() == 2: body_bboxes_filtered_feature_point = body_bboxes[feature_point_filter] if return_feature_point is True: elem_target_with_size = list(elem_target) elem_target_with_size.append(body_bboxes_filtered_feature_point) elem_target_with_size = tuple(elem_target_with_size) target_list_with_size.append(elem_target_with_size) else: distance = calc_euclidean_distance(body_bboxes_filtered_feature_point) elem_target_with_size = list(elem_target) elem_target_with_size.append(distance) elem_target_with_size = tuple(elem_target_with_size) target_list_with_size.append(elem_target_with_size) new_anno_with_size.update({image_id: target_list_with_size}) return new_anno_with_size def get_bbox_df(new_anno_with_size): """ create bbox df, pd.DataFrame({"width", "height", "label", "size"}) Args: - new_anno_with_size: {image_id: list(tuple(insect_name, coord, size))} """ # create array width_array = [] height_array = [] label_array = [] size_array = [] for image_id, values in new_anno_with_size.items(): for value in values: width_array.append(value[1][2] - value[1][0]) height_array.append(value[1][3] - value[1][1]) label_array.append(value[0]) size_array.append(value[2]) width_array = np.array(width_array) height_array = np.array(height_array) label_array = np.array(label_array) size_array = np.array(size_array) # convert insect_name to label idx = np.unique(label_array) name_to_lbl = {} for i, elem_idx in enumerate(idx): name_to_lbl.update({elem_idx: i}) label_array = np.array([name_to_lbl[elem_label_array] for elem_label_array in label_array]) print(name_to_lbl) return pd.DataFrame({"width": width_array, "height": height_array, "label": label_array, "size": size_array}) if __name__ == "__main__": data_root = pj(cwd(), "data") bbox_data_path = pj(cwd(), "data/bbox_data", "target_only_20200806.csv") img_folder = "refined_images" anno_folders = ["annotations_0", "annotations_2", "annotations_3", "annotations_4", "annotations_20200806"] unused_labels = [']', 'Coleoptera', 'Hemiptera', 'Hymenoptera', 'Megaloptera', 'Unknown', 'unknown', 'medium insect', 'small insect', 'snail', 'spider'] images, anno = load_anno(data_root, img_folder, anno_folders, return_body=True) new_anno = create_annotation(images, anno, unused_labels, False, False) new_anno_div_body = divide_target_and_body(new_anno) new_anno_with_size = get_new_anno_with_size(new_anno_div_body) bbox_df = get_bbox_df(new_anno_with_size) if os.path.exists(os.path.dirname(bbox_data_path)) is False: os.makedirs(os.path.dirname(bbox_data_path)) bbox_df.to_csv(bbox_data_path) print("create data to " + bbox_data_path)<file_sep>/dataset.md ### 現在保有しているデータ - all_classification_data - classify_insect_std: 通常のデータセット 元のアノテーション: ["annotations_0", "annotations_2", "annotations_3", "annotations_4"] ラベルマップ: {'Diptera': 0, 'Ephemeridae': 1, 'Ephemeroptera': 2, 'Lepidoptera': 3, 'Plecoptera': 4, 'Trichoptera': 5} データ数: [408, 51, 178, 267, 130, 248] - classify_insect_std_resizeFAR: アスペクト比を固定してリサイズしたデータセット 元のアノテーション: ["annotations_0", "annotations_2", "annotations_3", "annotations_4"] ラベルマップ: {'Diptera': 0, 'Ephemeridae': 1, 'Ephemeroptera': 2, 'Lepidoptera': 3, 'Plecoptera': 4, 'Trichoptera': 5} データ数: [408, 51, 178, 267, 130, 248] - classify_insect_std_resize: アスペクト比を固定せずリサイズしたデータセット 元のアノテーション: ["annotations_0", "annotations_2", "annotations_3", "annotations_4"] ラベルマップ: {'Diptera': 0, 'Ephemeridae': 1, 'Ephemeroptera': 2, 'Lepidoptera': 3, 'Plecoptera': 4, 'Trichoptera': 5} データ数: [408, 51, 178, 267, 130, 248] - classify_insect_std_plus_other: 検出対象クラス+その他のクラスを分類するデータセット 元のアノテーション: ["annotations_0", "annotations_2", "annotations_3", "annotations_4"] ラベルマップ: {'Diptera': 0, 'Ephemeridae': 1, 'Ephemeroptera': 2, 'Lepidoptera': 3, 'Plecoptera': 4, 'Trichoptera': 5, 'Other': 6} データ数: [408, 51, 178, 267, 130, 248, 2238] - classify_insect_std_20200806: 通常のデータセット、2020/08/06にもらったデータまで 元のアノテーション: ["annotations_0", "annotations_2", "annotations_3", "annotations_4", "annotations_20200806"] ラベルマップ: {'Diptera': 0, 'Ephemeridae': 1, 'Ephemeroptera': 2, 'Lepidoptera': 3, 'Plecoptera': 4, 'Trichoptera': 5} データ数: [505, 143, 293, 1214, 493, 407] - classify_insect_only_20200806: 2020/08/06にもらったデータだけのデータセット 元のアノテーション: ["annotations_20200806"] ラベルマップ: {'Diptera': 0, 'Ephemeridae': 1, 'Ephemeroptera': 2, 'Lepidoptera': 3, 'Plecoptera': 4, 'Trichoptera': 5} データ数: [86, 92, 93, 944, 359, 157] - classify_insect_std_20200806_DBSCAN: classify_insect_std_20200806にDBSCANを適用したもの 元のアノテーション: ["annotations_0", "annotations_2", "annotations_3", "annotations_4", "annotations_20200806"] ラベルマップ: {'Diptera': 0, 'Ephemeridae': 1, 'Ephemeroptera': 2, 'Lepidoptera': 3, 'Plecoptera': 4, 'Trichoptera': 5} データ数: [502, 126, 282, 1205, 475, 399] - classify_insect_20200806: 通常のデータセット、2020/08/06にもらったデータまで、正規化してない 元のアノテーション: ["annotations_0", "annotations_2", "annotations_3", "annotations_4", "annotations_20200806"] ラベルマップ: {'Diptera': 0, 'Ephemeridae': 1, 'Ephemeroptera': 2, 'Lepidoptera': 3, 'Plecoptera': 4, 'Trichoptera': 5} データ数: [505, 143, 293, 1214, 493, 407] - train_detection_data - refinedet_all: 全クラスをinsectラベルに集約したデータセット 元のアノテーション: ["annotations_0", "annotations_2", "annotations_3"] ラベルマップ: {'insect': 0} - refinedet_each: 個々のラベルを用いたデータセット 元のアノテーション: ["annotations_0", "annotations_2", "annotations_3"] ラベルマップ: {'Coleoptera': 0, 'Diptera': 1, 'Ephemeridae': 2, 'Ephemeroptera': 3, 'Hemiptera': 4, 'Lepidoptera': 5, 'Plecoptera': 6, 'Trichoptera': 7, 'medium insect': 8, 'small insect': 9, 'snail': 10, 'spider': 11} (存在しないクラスもあるかもしれない) - refinedet_plus_other: 検出対象クラスを0、その他のクラスを1としたデータセット 元のアノテーション: ["annotations_0", "annotations_2", "annotations_3"] ラベルマップ: {'insect': 0, 'other': 1} - target_with_other: 評価用データセット、検出対象クラスに各ラベル、その他のクラスを6としたデータセット 元のアノテーション: ["annotations_0", "annotations_2", "annotations_3"] ラベルマップ: {'Diptera': 0, 'Ephemeridae': 1, 'Ephemeroptera': 2, 'Lepidoptera': 3, 'Plecoptera': 4, 'Trichoptera': 5, 'Other': 6} - refinedet_all_20200806: 全クラスをinsectラベルに集約したデータセット、2020/08/06にもらったデータまで、アノテーション修正版 元のアノテーション: ["annotations_0", "annotations_2", "annotations_3", "annotations_20200806"] ラベルマップ: {'insect': 0} - refinedet_plus_other_20200806: 検出対象クラスを0、その他のクラスを1としたデータセット、2020/08/06にもらったデータまで、アノテーション修正版 元のアノテーション: ["annotations_0", "annotations_2", "annotations_3", "annotations_20200806"] ラベルマップ: {'insect': 0, 'other': 1} - refinedet_all_test_20200806: 全クラスをinsectラベルに集約したデータセット、20200806をテストに使用、アノテーション修正版 元のアノテーション: ["annotations_0", "annotations_2", "annotations_3", "annotations_4"] ラベルマップ: {'insect': 0} - refinedet_all_20200806_DBSCAN: refinedet_all_20200806にDBSCANを適用したもの、ただしテストには適用しない 元のアノテーション: ["annotations_0", "annotations_2", "annotations_3", "annotations_20200806"] ラベルマップ: {'insect': 0} - test_detection_data - refinedet_all: 全クラスをinsectラベルに集約したデータセット 元のアノテーション: ["annotations_4"] ラベルマップ: {'insect': 0} - refinedet_each: 個々のラベルを用いたデータセット 元のアノテーション: ["annotations_4"] ラベルマップ: {'Coleoptera': 0, 'Diptera': 1, 'Ephemeridae': 2, 'Ephemeroptera': 3, 'Hemiptera': 4, 'Lepidoptera': 5, 'Plecoptera': 6, 'Trichoptera': 7, 'medium insect': 8, 'small insect': 9, 'snail': 10, 'spider': 11} (存在しないクラスもあるかもしれない) - refinedet_plus_other: 検出対象クラスを0、その他のクラスを1としたデータセット 元のアノテーション: ["annotations_4"] ラベルマップ: {'insect': 0, 'other': 1} - target_with_other: 評価用データセット、検出対象クラスに各ラベル、その他のクラスを6としたデータセット 元のアノテーション: ["annotations_4"] ラベルマップ: {'Diptera': 0, 'Ephemeridae': 1, 'Ephemeroptera': 2, 'Lepidoptera': 3, 'Plecoptera': 4, 'Trichoptera': 5, 'Other': 6} - refinedet_all_20200806: 全クラスをinsectラベルに集約したデータセット、2020/08/06にもらったデータまで、アノテーション修正版 元のアノテーション: ["annotations_4"] ラベルマップ: {'insect': 0} - refinedet_plus_other_20200806: 検出対象クラスを0、その他のクラスを1としたデータセット、2020/08/06にもらったデータまで、アノテーション修正版 元のアノテーション: ["annotations_4"] ラベルマップ: {'insect': 0, 'other': 1} - refinedet_all_test_20200806: 全クラスをinsectラベルに集約したデータセット、20200806をテストに使用、アノテーション修正版 元のアノテーション: ["annotations_20200806"] ラベルマップ: {'insect': 0} - refinedet_all_20200806_DBSCAN: refinedet_all_20200806にDBSCANを適用したもの、ただしテストには適用しない 元のアノテーション: ["annotations_4"] ラベルマップ: {'insect': 0} - target_with_other_alldata: 評価用データセット、検出対象クラスに各ラベル、その他のクラスを6としたデータセット、2020/08/06にもらったデータまで、アノテーション修正版 元のアノテーション: ["annotations_0", "annotations_2", "annotations_3", "annotations_4", "annotations_20200806"] ラベルマップ: {'Diptera': 0, 'Ephemeridae': 1, 'Ephemeroptera': 2, 'Lepidoptera': 3, 'Plecoptera': 4, 'Trichoptera': 5, 'Other': 6} <file_sep>/model/refinedet/layers/prior_box.py from __future__ import division from math import sqrt as sqrt from itertools import product as product import torch def get_prior_box(image_size, feature_sizes, other_aspect_ratio=[2], clip=True): """ compute prior anchor box. used for training and test. Args: - image_size: int, input image size, choice [320, 512, 1024] - feature_sizes: [int, ...], edge size of layer for each layer - clip: bool, clamp prior anchor box size to 0~1 """ num_priors = len(feature_sizes) steps = [image_size / size for size in feature_sizes] min_sizes = [4 * step for step in steps] mean = [] for k, feature_size in enumerate(feature_sizes): for y, x in product(range(feature_size), repeat=2): feature_step_k = image_size / steps[k] # unit center x,y cx = (x + 0.5) / feature_step_k cy = (y + 0.5) / feature_step_k # aspect_ratio: 1 # rel size: min_size normalized_min_size_k = min_sizes[k] / image_size mean += [cx, cy, normalized_min_size_k, normalized_min_size_k] # rest of aspect ratios for ar in other_aspect_ratio: mean += [cx, cy, normalized_min_size_k*sqrt(ar), normalized_min_size_k/sqrt(ar)] mean += [cx, cy, normalized_min_size_k/sqrt(ar), normalized_min_size_k*sqrt(ar)] # back to torch land output = torch.Tensor(mean).view(-1, 4) if clip: output.clamp_(max=1, min=0) return output <file_sep>/IO/visdom.py # -*- coding: utf-8 -*- import numpy as np import visdom def visualize(vis, phase, visualized_data, window): """ Visdomの可視化関数 引数: - vis: visdom.Visdom, visdomクラス - phase: int, 現在のエポック - visualized_data: float, 誤差や正答率などの可視化したいデータ - window: visdom.Visdom.line, 窓クラス """ vis.line( X=np.array([phase]), Y=np.array([visualized_data]), update='append', win=window )<file_sep>/IO/utils.py import numpy as np import os from os import listdir as ld from os.path import join as pj from PIL import Image import pandas as pd import torch def save_images_without_duplication(data_root, anno_folders, save_image_folder): """ unused """ if os.path.exists(save_image_folder) is False: os.makedirs(save_image_folder) annos, imgs = load_path(data_root, anno_folders) images = load_images(imgs) annotations_path = load_annotations_path(annos, images) images_path = load_images_path(imgs, annotations_path) for k,v in images_path.items(): Image.fromarray(images[k].astype(np.uint8)).save(pj(save_image_folder,k+".png")) else: print("folder is already exists") def make_imagelist(image_data_root, imagelist_path): """ unused """ image_list = ld(image_data_root) if ".ipynb_checkpoints" in image_list: image_list.remove(".ipynb_checkpoints") image_list = [pj(image_data_root,filename) for filename in image_list] with open(imagelist_path, "w") as f: for image_path in image_list: f.write(image_path+"\n") def format_output(coords, fid, width=4608, height=2592): """ formatter for labelImg XML Args: - coords: np.asarray([(label, coords), ...]) coords = [xmin, ymin, xmax, ymax] - fid: str, file id - width: int, image width - height: int, image height """ header = r"""<annotation> <folder>images</folder> <filename>{0}.JPG</filename> <path>C:\Users\ooe\Desktop\labelImg-master\images\{0}.JPG</path> <source> <database>Unknown</database> </source> <size> <width>{1}</width> <height>{2}</height> <depth>3</depth> </size> <segmented>0</segmented> """ obj_box = """ <object> <name>{}</name> <pose>Unspecified</pose> <truncated>0</truncated> <difficult>0</difficult> <bndbox> <xmin>{}</xmin> <ymin>{}</ymin> <xmax>{}</xmax> <ymax>{}</ymax> </bndbox> </object> """ footer = """ </annotation> """ content = header.format(fid, width, height) for name, (xmin, ymin, xmax, ymax) in coords: bbox = obj_box.format(name, xmin, ymin, xmax, ymax) content = content + bbox content = content + footer return content def output_formatter(result, label_map): """ formatting result to labelImg XML style Args: - result: {file id: {label: np.asarray([x1, y1, x2, y2, conf], ...)}} - label_map: {label_id: label_name} """ output = {} for file_id, elements in result.items(): formatted_result = [] for label, coords in elements.items(): coords_without_conf = [] for coord in coords: coords_without_conf.append([int(point) for point in coord[:-1]]) formatted_result.extend([(label, coord_without_conf) for coord_without_conf in coords_without_conf]) output.update({file_id: np.asarray([(label_map[label], coords) for label, coords in formatted_result])}) return output def write_output_xml(output, path): """ write labelImg XML using outputs Args: - output: {file id: np.asarray([(label, coords), ...])} - path: str """ if os.path.exists(path) is False: os.makedirs(path) for fid, coords in output.items(): content = format_output(coords, fid) fp = pj(path, fid + ".xml") with open(fp, "w") as f: f.write(content) def write_output_csv(output, path): """ write CSV using outputs Args: - output: {file id: np.asarray([(label, coords), ...])} - path: str """ if os.path.exists(path) is False: os.makedirs(path) for file_id, results in output.items(): df = pd.DataFrame(columns=["label", "x1", "x2", "y1", "y2"]) for result in results: result_se = pd.Series([result[0], result[1][0], result[1][2], result[1][1], result[1][3]], index=df.columns) df = df.append(result_se, ignore_index=True) df.to_csv(pj(path, file_id + ".csv")) def refine_result_by_ovthresh(result, ovthresh=0.3): """ refine result by ovthresh - result: {image_id: {label_id: np.asarray([[x1, y1, x2, y2, conf], ...])}} - ovthresh: float """ conf_refined_result = {} for image_id, result_per_label in result.items(): conf_refined_result_per_label = {} for label_id, res in result_per_label.items(): refined_result_per_res = [] for box in res: if box[4] > ovthresh: refined_result_per_res.append(box.tolist()) conf_refined_result_per_label.update({label_id: np.asarray(refined_result_per_res)}) conf_refined_result.update({image_id: conf_refined_result_per_label}) return conf_refined_result<file_sep>/dataset/classification/dataset.py import cv2 import numpy as np from sklearn.mixture import GaussianMixture as GMM import torch import torch.utils.data as data import imgaug.augmenters as iaa # evaluation from evaluation.classification.statistics import get_size_list_from_xte class insects_dataset(data.Dataset): def __init__(self, images, labels=None, training=False, method_aug=None, size_normalization=None): """ init function Args: - images: np.array, insect images - labels: np.array, insect labels - training: bool - method_aug: [str, ...], sequence of method name possible choices = [ HorizontalFlip, VerticalFlip, Rotate] - size_normalization: str, choice [None, "mu", "sigma", "mu_sigma", "uniform"] """ self.images = images self.labels = labels self.training = training self.method_aug = method_aug self.size_normalization = size_normalization if training is True: if method_aug is not None: print("augment == method_aug") print("---") self.aug_seq = self.create_aug_seq() print("---") else: print("augment == None") self.aug_seq = None if size_normalization in ["mu", "sigma", "mu_sigma", "uniform"]: print("size_normalization == {}".format(size_normalization)) if size_normalization == "uniform": self.resize_px = 50 print("resize_px == {}".format(self.resize_px)) insect_size_list, insect_size_dic = self.get_insect_size(images, labels) mu, sigma = self.calc_mu_sigma(insect_size_dic) self.insect_size_list = np.log2(insect_size_list) self.insect_size_dic = insect_size_dic self.mu = mu self.sigma = sigma else: print("size_normalization == None") else: self.aug_seq = None def __getitem__(self, index): image = self.images[index].astype("uint8") # adopt size normalization if self.training and self.size_normalization in ["mu", "sigma", "mu_sigma", "uniform"]: image = self.adopt_size_normalization(image, self.labels[index], self.insect_size_list[index]) # adopt augmentation if self.aug_seq is not None: image_aug = self.aug_seq(image=image) else: image_aug = image # normalize image_aug = image_aug.astype("float32") image_aug = cv2.normalize(image_aug, image_aug, alpha=0, beta=1, norm_type=cv2.NORM_MINMAX) # create pytorch image image_aug = image_aug.transpose(2,0,1).astype("float32") image_aug = torch.from_numpy(image_aug).clone() if self.training is True: label = self.labels[index] return image_aug, label else: return image_aug def __len__(self): return self.images.shape[0] def get_insect_size(self, X, Y): """ get list, dictionary of label to size Args: - X: np.array, shape==[insect_num, height, width, channels] - Y: np.array, shape==[insect_num] """ idx = np.unique(Y) X_size = np.array(get_size_list_from_xte(X)) insect_size_dic = {} for i in range(len(idx)): insect_filter = Y == i filtered_X_size = X_size[insect_filter] filtered_X_size = np.sort(filtered_X_size) insect_size_dic.update({i: filtered_X_size}) return X_size, insect_size_dic def calc_mu_sigma(self, insect_size_dic): """ calculate mu, sigma for each insect size distribution Args: - insect_size_dic: dict, {label: size_array} """ gmm = GMM(n_components=1, covariance_type="spherical") mu = [] sigma = [] for key, value in insect_size_dic.items(): x = np.log2(insect_size_dic[key]) gmm.fit(x.reshape(-1, 1)) mu.append(gmm.means_.reshape([-1])[0]) sigma.append(np.sqrt(gmm.covariances_)[0]) return np.array(mu), np.array(sigma) def adopt_size_normalization(self, image, label, size): """ adopt image to size normalization Args: - image: PIL.Image - label: int - size: int - mu: convert size distribution => mu = mu_average, sigma = keep Formula: 2 ** (mu_average - mu_each) - sigma: convert size distribution => mu = keep, sigma = 1 Formula: 2 ** ((1 - sigma_each) / sigma_each * (x - mu_each)) - mu_sigma: convert size distribution => mu = mu_average, sigma = 1 Formula: 2 ** ((1 - sigma_each) / sigma_each) * 2 ** ((mu_average * sigma_each - mu_each) / sigma_each) - uniform: random resize and padding """ mu_average = self.mu.mean() size_norm_augs = [] if self.size_normalization == "mu": for mu_each, sigma_each in zip(self.mu, self.sigma): correction_term = mu_average - mu_each size_norm_augs.append( iaa.Affine(scale=(np.sqrt(2 ** correction_term), np.sqrt(2 ** correction_term))) ) elif self.size_normalization == "sigma": for mu_each, sigma_each in zip(self.mu, self.sigma): correction_term = (1 - sigma_each) / sigma_each * (size - mu_each) size_norm_augs.append( iaa.Affine(scale=(np.sqrt(2 ** correction_term), np.sqrt(2 ** correction_term))) ) elif self.size_normalization == "mu_sigma": for mu_each, sigma_each in zip(self.mu, self.sigma): correction_term = ((1 - sigma_each) * size - mu_each + mu_average * sigma_each) / sigma_each size_norm_augs.append( iaa.Affine(scale=(np.sqrt(2 ** correction_term), np.sqrt(2 ** correction_term))) ) elif self.size_normalization == "uniform": for mu_each, sigma_each in zip(self.mu, self.sigma): size_norm_augs.append( iaa.CropAndPad( px=(-1 * self.resize_px, 0), sample_independently=False ) ) else: pass normed_image = size_norm_augs[label](image=image) return normed_image def create_aug_seq(self): aug_list = [] # create augmentation for augmentation in self.method_aug: if augmentation == "HorizontalFlip": print("HorizontalFlip") aug_list.append(iaa.Fliplr(0.5)) elif augmentation == "VerticalFlip": print("VerticalFlip") aug_list.append(iaa.Flipud(0.5)) elif augmentation == "CropandResize": print("CropandResize") aug_list.append(iaa.KeepSizeByResize( iaa.OneOf([ iaa.Crop((int(200/2), int(200/2)), keep_size=False), iaa.Crop((int(200/3 * 2), int(200/3 * 2)), keep_size=False), iaa.Crop((int(200/4 * 3), int(200/4 * 3)), keep_size=False) ]), interpolation=cv2.INTER_NEAREST )) elif augmentation == "CLAHE": print("CLAHE") aug_list.append(iaa.CLAHE()) elif augmentation == "Sharpen": print("Sharpen") aug_list.append(iaa.Sharpen(alpha=(0.0, 1.0), lightness=(0.0, 1.0))) elif augmentation == "Emboss": print("Emboss") aug_list.append(iaa.Emboss(alpha=(0.0, 1.0), strength=(0.0, 1.0))) elif augmentation == "Shear": print("Shear") aug_list.append(iaa.OneOf([ iaa.ShearX((-20, 20)), iaa.ShearY((-20, 20)) ])) elif augmentation == "Translate": print("Translate") aug_list.append(iaa.OneOf([ iaa.TranslateX(px=(-20, 20)), iaa.TranslateY(px=(-20, 20)) ])) elif augmentation == "Rotate": print("Rotate") aug_list.append(iaa.Rotate((-90, 90))) elif augmentation == "AutoContrast": print("AutoContrast") aug_list.append(iaa.pillike.Autocontrast()) elif augmentation == "Invert": print("Invert") aug_list.append(iaa.Invert(0.5)) elif augmentation == "Equalize": print("Equalize") aug_list.append(iaa.pillike.Equalize()) elif augmentation == "Solarize": print("Solarize") aug_list.append(iaa.Solarize(0.5, threshold=(32, 128))) elif augmentation == "Posterize": print("Posterize") aug_list.append(iaa.color.Posterize()) elif augmentation == "Contrast": print("Contrast") aug_list.append(iaa.pillike.EnhanceContrast()) elif augmentation == "Color": print("Color") aug_list.append(iaa.pillike.EnhanceColor()) elif augmentation == "Brightness": print("Brightness") aug_list.append(iaa.pillike.EnhanceBrightness()) elif augmentation == "Sharpness": print("Sharpness") aug_list.append(iaa.pillike.EnhanceSharpness()) elif augmentation == "Cutout": print("Cutout") aug_list.append(iaa.Cutout(nb_iterations=1)) elif augmentation == "All": # adjust to AutoAugment print("All") aug_list = [ iaa.OneOf([ iaa.ShearX((-20, 20)), iaa.ShearY((-20, 20)) ]), iaa.OneOf([ iaa.TranslateX(px=(-20, 20)), iaa.TranslateY(px=(-20, 20)) ]), iaa.Rotate((-90, 90)), iaa.pillike.Autocontrast(), iaa.Invert(0.5), iaa.pillike.Equalize(), iaa.Solarize(0.5, threshold=(32, 128)), iaa.color.Posterize(), iaa.pillike.EnhanceContrast(), iaa.pillike.EnhanceColor(), iaa.pillike.EnhanceBrightness(), iaa.pillike.EnhanceSharpness(), iaa.Cutout(nb_iterations=1), ] elif augmentation == "All_plus_alpha": # use All Augment print("All_plus_alpha") aug_list = [ iaa.OneOf([ iaa.ShearX((-20, 20)), iaa.ShearY((-20, 20)) ]), iaa.OneOf([ iaa.TranslateX(px=(-20, 20)), iaa.TranslateY(px=(-20, 20)) ]), iaa.Rotate((-90, 90)), iaa.pillike.Autocontrast(), iaa.Invert(0.5), iaa.pillike.Equalize(), iaa.Solarize(0.5, threshold=(32, 128)), iaa.color.Posterize(), iaa.pillike.EnhanceContrast(), iaa.pillike.EnhanceColor(), iaa.pillike.EnhanceBrightness(), iaa.pillike.EnhanceSharpness(), iaa.Cutout(nb_iterations=1), iaa.Fliplr(0.5), iaa.Flipud(0.5), iaa.CLAHE(), iaa.Sharpen(alpha=(0.0, 1.0), lightness=(0.0, 1.0)), iaa.Emboss(alpha=(0.0, 1.0), strength=(0.0, 1.0)), ] elif augmentation == "Coordinate": # use coordinate transform only print("Coordinate") aug_list = [ iaa.OneOf([ iaa.ShearX((-20, 20)), iaa.ShearY((-20, 20)) ]), iaa.OneOf([ iaa.TranslateX(px=(-20, 20)), iaa.TranslateY(px=(-20, 20)) ]), iaa.Rotate((-90, 90)), iaa.CropAndPad( px=(-1 * 60, 60), sample_independently=False ), iaa.Fliplr(0.5), iaa.Flipud(0.5), ] elif augmentation == "RandomResize": print("RandomResize") # imgaug function """ aug_list.append( iaa.CropAndPad( px=(-1 * 50, 0), sample_independently=False ) ) """ # self coded function aug_list.append( iaa.Lambda( func_images=aug_scale ) ) elif augmentation == "Jigsaw": print("Jigsaw") aug_list.append(iaa.Jigsaw(nb_rows=4, nb_cols=4)) else: print("not implemented!: insects_dataset.create_aug_seq") aug_seq = iaa.SomeOf((5, 6), aug_list, random_order=True) return aug_seq class maha_insects_dataset(data.Dataset): def __init__(self, images, labels): """ init function Args: - images: np.array, insect images - labels: np.array, insect labels """ self.images = images self.labels = labels self.sample() def __getitem__(self, index): image = self.sampled_images[index].astype("uint8") # normalize image = image.astype("float32") image = cv2.normalize(image, image, alpha=0, beta=1, norm_type=cv2.NORM_MINMAX) # create pytorch image image = image.transpose(2,0,1).astype("float32") image = torch.from_numpy(image).clone() return image def __len__(self): return self.sampled_images.shape[0] def sample(self, sample_num=30): sampled_images = [] sampled_labels = [] idx, counts = np.unique(self.labels, return_counts=True) for i in idx: sampled_id = np.random.choice(np.where(self.labels == i)[0], size=sample_num) sampled_images.extend(self.images[sampled_id]) sampled_labels.extend(self.labels[sampled_id]) self.sampled_images = np.array(sampled_images) self.sampled_labels = np.array(sampled_labels) def aug_scale(images, random_state, parents, hooks): image_array = [] for img in images: ratio = np.random.rand() + 1.0 # 1.0 <= ratio < 2.0 img = img.astype("float32") h, w = img.shape[:2] src = np.array([[0.0, 0.0],[0.0, 1.0],[1.0, 0.0]], np.float32) dest = src * ratio h_diff = (ratio - 1) * (h / 2) w_diff = (ratio - 1) * (w / 2) dest[:, 0] -= w_diff dest[:, 1] -= h_diff affine = cv2.getAffineTransform(src, dest) img = cv2.warpAffine(img, affine, (200, 200), cv2.INTER_LANCZOS4) image_array.append(img) images = np.array(image_array).astype("uint8") return images<file_sep>/dataset/detection/dataset.py import cv2 import copy import numpy as np from os import listdir as ld from os.path import join as pj from PIL import Image import warnings import torch import torch.utils.data as data import imgaug as ia import imgaug.augmenters as iaa from imgaug.augmentables.bbs import BoundingBox, BoundingBoxesOnImage class insects_dataset_from_voc_style_txt(data.Dataset): def __init__(self, image_root, resize_size, crop_num, training=False, target_root=None, method_crop="SPREAD_ALL_OVER", method_aug=None, model_detect_type="all", size_normalization=False, augment_target=False): """ initializer Args: - image_root: str, image folder - resize_size: int, resized size of image - crop_num: (int, int), (height_crop_num, width_crop_num) - training: bool - target_root: str, if training is True, this is must - method_crop: str, choice ["SPREAD_ALL_OVER", "RANDOM"] - method_aug: [str, ...], adopt augmentation list - model_detect_type: str, choice ["all", "each", "det2cls"] - size_normalizatioin: bool, resize cropped image or not - augment_target: bool, resize target box or not """ self.image_root = image_root self.resize_size = resize_size self.crop_num = crop_num self.training = training self.method_crop = method_crop self.method_aug = method_aug self.model_detect_type = model_detect_type self.size_normalization = size_normalization self.augment_target = augment_target if training is True: if target_root is None: warnings.warn("Error! if training is True, target_root is must.") else: self.target_root = target_root if method_aug is not None: print("training augment") print("---") self.aug_seq = self.create_aug_seq() print("---") if size_normalization is True: self.resize_px = 128 print("adopt size normalization, resize_px == {}".format(self.resize_px)) if augment_target is True: print("adopt target augment ... ") if model_detect_type=="all": self.lbl_to_name = { 0: "Insect" } self.name_to_lbl = { "Insect": 0 } elif model_detect_type=="each": print("not implemented! insect_dataset_from_voc_style_txt.__init__") elif model_detect_type=="det2cls": self.lbl_to_name = { 0: "Insect", 1: "Other" } self.name_to_lbl = { "Insect": 0, "Other": 1 } else: warnings.warn("Error! choice from [all, each, det2cls].") self.ids = self.get_ids() def __getitem__(self, index): """ get item with index Args: - index: int, index of ids """ # load image image, default_height, default_width = self.load_image(index) if self.training is True: # load annotation bbs_list = self.load_bbs_list(index, default_height, default_width) bbs = BoundingBoxesOnImage(bbs_list, shape=image.shape) # crop and resize image, annotation if self.method_crop == "SPREAD_ALL_OVER": image_crop, bbs_crop_list = self.crop_spread_all_over(image, bbs) bbs_crop = [BoundingBoxesOnImage(bbs_crop_list[idx], shape=image_crop[idx].shape) for idx in range(len(bbs_crop_list))] elif self.method_crop == "RANDOM": image_crop, bbs_crop_list = self.crop_random(image, bbs) bbs_crop = [BoundingBoxesOnImage(bbs_crop_list[idx], shape=image_crop[idx].shape) for idx in range(len(bbs_crop_list))] # adopt size normalization if self.size_normalization is True: image_crop, bbs_crop_list = self.adopt_size_normalization(image_crop, bbs_crop) bbs_crop = [BoundingBoxesOnImage(bbs_crop_list[idx], shape=image_crop[idx].shape) for idx in range(len(bbs_crop_list))] # augment image, annotation if self.method_aug is not None: image_crop_aug, bbs_crop_aug_list = self.adopt_augmentation(image_crop, bbs_crop) bbs_crop_aug = [BoundingBoxesOnImage(bbs_crop_aug_list[idx], shape=image_crop_aug[idx].shape) for idx in range(len(bbs_crop_aug_list))] else: image_crop_aug = image_crop bbs_crop_aug = bbs_crop # normalize image_crop_aug = image_crop_aug.astype("float32") image_crop_aug = np.array([cv2.normalize(image, image, alpha=0, beta=1, norm_type=cv2.NORM_MINMAX) for image in image_crop_aug]) # create pytorch image, annotation image_crop_aug = image_crop_aug.transpose(0, 3, 1, 2) target = self.create_pytorch_annotation(bbs_crop_aug) return image_crop_aug, target, default_height, default_width, self.ids[index] else: # crop and resize image image_crop = self.create_test_image(image) # normalize image_crop = image_crop.astype("float32") image_crop = np.array([cv2.normalize(image, image, alpha=0, beta=1, norm_type=cv2.NORM_MINMAX) for image in image_crop]) # create pytorch image image_crop = image_crop.transpose(0, 3, 1, 2) # set id for cropped_image data_ids = [] for i in range(self.crop_num[0]): for j in range(self.crop_num[1]): data_ids.append([self.ids[index], (i, j)]) return image_crop, default_height, default_width, data_ids def __len__(self): return len(self.ids) def create_aug_seq(self): aug_list = [] # create augmentation for augmentation in self.method_aug: if augmentation == "HorizontalFlip": print("HorizontalFlip") aug_list.append(iaa.Fliplr(0.5)) elif augmentation == "VerticalFlip": print("VerticalFlip") aug_list.append(iaa.Flipud(0.5)) elif augmentation == "CropandResize": print("CropandResize") aug_list.append(iaa.KeepSizeByResize( iaa.OneOf([ iaa.Crop((int(200/2), int(200/2)), keep_size=False), iaa.Crop((int(200/3 * 2), int(200/3 * 2)), keep_size=False), iaa.Crop((int(200/4 * 3), int(200/4 * 3)), keep_size=False) ]), interpolation=cv2.INTER_NEAREST )) elif augmentation == "CLAHE": print("CLAHE") aug_list.append(iaa.CLAHE()) elif augmentation == "Sharpen": print("Sharpen") aug_list.append(iaa.Sharpen(alpha=(0.0, 1.0), lightness=(0.0, 1.0))) elif augmentation == "Emboss": print("Emboss") aug_list.append(iaa.Emboss(alpha=(0.0, 1.0), strength=(0.0, 1.0))) elif augmentation == "Shear": print("Shear") aug_list.append(iaa.OneOf([ iaa.ShearX((-20, 20)), iaa.ShearY((-20, 20)) ])) elif augmentation == "Translate": print("Translate") aug_list.append(iaa.OneOf([ iaa.TranslateX(px=(-20, 20)), iaa.TranslateY(px=(-20, 20)) ])) elif augmentation == "Rotate": print("Rotate") aug_list.append(iaa.Rotate((-90, 90))) elif augmentation == "AutoContrast": print("AutoContrast") aug_list.append(iaa.pillike.Autocontrast()) elif augmentation == "Invert": print("Invert") aug_list.append(iaa.Invert(0.5)) elif augmentation == "Equalize": print("Equalize") aug_list.append(iaa.pillike.Equalize()) elif augmentation == "Solarize": print("Solarize") aug_list.append(iaa.Solarize(0.5, threshold=(32, 128))) elif augmentation == "Posterize": print("Posterize") aug_list.append(iaa.color.Posterize()) elif augmentation == "Contrast": print("Contrast") aug_list.append(iaa.pillike.EnhanceContrast()) elif augmentation == "Color": print("Color") aug_list.append(iaa.pillike.EnhanceColor()) elif augmentation == "Brightness": print("Brightness") aug_list.append(iaa.pillike.EnhanceBrightness()) elif augmentation == "Sharpness": print("Sharpness") aug_list.append(iaa.pillike.EnhanceSharpness()) elif augmentation == "Cutout": print("Cutout") aug_list.append(iaa.Cutout(nb_iterations=1)) elif augmentation == "All": # adjust to AutoAugment print("All") aug_list = [ iaa.OneOf([ iaa.ShearX((-20, 20)), iaa.ShearY((-20, 20)) ]), iaa.OneOf([ iaa.TranslateX(px=(-20, 20)), iaa.TranslateY(px=(-20, 20)) ]), iaa.Rotate((-90, 90)), iaa.pillike.Autocontrast(), iaa.Invert(0.5), iaa.pillike.Equalize(), iaa.Solarize(0.5, threshold=(32, 128)), iaa.color.Posterize(), iaa.pillike.EnhanceContrast(), iaa.pillike.EnhanceColor(), iaa.pillike.EnhanceBrightness(), iaa.pillike.EnhanceSharpness(), iaa.Cutout(nb_iterations=1), ] elif augmentation == "All_plus_alpha": # use All Augment print("All_plus_alpha") aug_list = [ iaa.OneOf([ iaa.ShearX((-20, 20)), iaa.ShearY((-20, 20)) ]), iaa.OneOf([ iaa.TranslateX(px=(-20, 20)), iaa.TranslateY(px=(-20, 20)) ]), iaa.Rotate((-90, 90)), iaa.pillike.Autocontrast(), iaa.Invert(0.5), iaa.pillike.Equalize(), iaa.Solarize(0.5, threshold=(32, 128)), iaa.color.Posterize(), iaa.pillike.EnhanceContrast(), iaa.pillike.EnhanceColor(), iaa.pillike.EnhanceBrightness(), iaa.pillike.EnhanceSharpness(), iaa.Cutout(nb_iterations=1), iaa.Fliplr(0.5), iaa.Flipud(0.5), iaa.CLAHE(), iaa.Sharpen(alpha=(0.0, 1.0), lightness=(0.0, 1.0)), iaa.Emboss(alpha=(0.0, 1.0), strength=(0.0, 1.0)), ] elif augmentation == "RandomResize": print("RandomResize") aug_list.append( iaa.CropAndPad( px=(-1 * 128, 0), sample_independently=False ) ) else: print("not implemented!: insects_dataset_from_voc_style_txt.create_aug_seq") aug_seq = iaa.SomeOf((0, 2), aug_list, random_order=True) return aug_seq def get_ids(self): """ load image id Args: - image_root: str, image folder """ # get ids from images image_list = ld(self.image_root) if ".ipynb_checkpoints" in image_list: image_list.remove(".ipynb_checkpoints") ids = [filename.split(".")[0] for filename in image_list] # filtering ids from targets filtered_ids = copy.copy(ids) if self.training is True: for data_id in ids: with open(pj(self.target_root, data_id + ".txt")) as f: target_lines = f.readlines() if len(target_lines) < 7: print("id = {}, target_num = {}, removed".format(data_id, len(target_lines))) filtered_ids.remove(data_id) return filtered_ids def load_image(self, index): """ load image with index Args: - index: int, index of ids """ data_id = self.ids[index] # load img image = np.asarray(Image.open(pj(self.image_root, data_id + ".png"))).astype("uint8") # get default height, width default_height, default_width, _ = image.shape return image, default_height, default_width def load_bbs_list(self, index, default_height, default_width): """ load bounding box with index Args: - index: int, index of ids - default_height: int - default_width: int """ data_id = self.ids[index] # load bounding box from file with open(pj(self.target_root, data_id + ".txt")) as f: target_lines = f.readlines() # create bbs_list bbs_list = [] for target_line in target_lines: target_line = target_line.split("\n")[0] target_list = target_line.split(" ") if self.augment_target is True: x1 = float(target_list[0]) * default_width + float(np.random.randint(0, 5)) x2 = float(target_list[2]) * default_width + float(np.random.randint(0, 5)) y1 = float(target_list[1]) * default_height + float(np.random.randint(0, 5)) y2 = float(target_list[3]) * default_height + float(np.random.randint(0, 5)) else: x1 = float(target_list[0]) * default_width x2 = float(target_list[2]) * default_width y1 = float(target_list[1]) * default_height y2 = float(target_list[3]) * default_height bbs_list.append(BoundingBox(x1 = x1, x2 = x2, y1 = y1, y2 = y2, label = self.lbl_to_name[int(target_list[4])])) return bbs_list def crop_spread_all_over(self, image, bbs=None): """ crop img, type == "SPREAD_ALL_OVER" *** this function must fix because train and test image become different *** Args: - img: np.array, shape == [height, width, channel] - bbs: imgaug BoundingBox """ height_mov_ratio_per_crop = 1.0 / float(self.crop_num[0] - 1) width_mov_ratio_per_crop = 1.0 / float(self.crop_num[1] - 1) image_crop_list = [] bbs_crop_list = [] # create crop image, bbs for i in range(self.crop_num[0]): for j in range(self.crop_num[1]): if i < (self.crop_num[0] - 1) and j < (self.crop_num[1] - 1): height_after_crop = int(image.shape[0] / self.crop_num[0]) + 100 width_after_crop = int(image.shape[1] / self.crop_num[1]) + 100 elif i < (self.crop_num[0] - 1): height_after_crop = int(image.shape[0] / self.crop_num[0]) + 100 width_after_crop = int(image.shape[1] / self.crop_num[1]) elif j < (self.crop_num[1] - 1): height_after_crop = int(image.shape[0] / self.crop_num[0]) width_after_crop = int(image.shape[1] / self.crop_num[1]) + 100 else: height_after_crop = int(image.shape[0] / self.crop_num[0]) width_after_crop = int(image.shape[1] / self.crop_num[1]) if j == self.crop_num[1] - 1: x_pos = 0.0 else: x_pos = 1.0 - width_mov_ratio_per_crop * j if i == self.crop_num[0] - 1: y_pos = 0.0 else: y_pos = 1.0 - height_mov_ratio_per_crop * i # set augmentations aug_seq = iaa.Sequential([ iaa.CropToFixedSize(width=width_after_crop, height=height_after_crop, position=(x_pos, y_pos)), iaa.Resize({"width": self.resize_size, "height": self.resize_size}, interpolation=cv2.INTER_NEAREST) ]) # augment img and target if bbs is not None: image_crop, bbs_crop = aug_seq(image=image, bounding_boxes=bbs) # check coord in img shape bbs_crop_before_check = bbs_crop.bounding_boxes bbs_crop_after_check = copy.copy(bbs_crop.bounding_boxes) for bb in bbs_crop_before_check: if bb.is_fully_within_image(image_crop.shape): pass else: bbs_crop_after_check.remove(bb) # append img and target if len(bbs_crop_after_check) > 0: image_crop_list.append(image_crop) bbs_crop_list.append(bbs_crop_after_check) else: image_crop = aug_seq(image=image) image_crop_list.append(image_crop) return np.array(image_crop_list), bbs_crop_list def crop_random(self, image, bbs=None): """ crop img, type == "RANDOM" Args: - img: np.array, shape == [height, width, channel] - bbs: imgaug BoundingBox """ height_after_crop = int(image.shape[0] / self.crop_num[0]) + 100 width_after_crop = int(image.shape[1] / self.crop_num[1]) + 100 image_crop_list = [] bbs_crop_list = [] # create crop image, bbs for i in range(self.crop_num[0] * self.crop_num[1]): # set augmentations aug_seq = iaa.Sequential([ iaa.CropToFixedSize(width=width_after_crop, height=height_after_crop, position="uniform"), iaa.Resize({"width": self.resize_size, "height": self.resize_size}, interpolation=cv2.INTER_NEAREST) ]) # augment img and target if bbs is not None: image_crop, bbs_crop = aug_seq(image=image, bounding_boxes=bbs) # check coord in img shape bbs_crop_before_check = bbs_crop.bounding_boxes bbs_crop_after_check = copy.copy(bbs_crop.bounding_boxes) for bb in bbs_crop_before_check: if bb.is_fully_within_image(image_crop.shape): pass else: bbs_crop_after_check.remove(bb) # append img and target if len(bbs_crop_after_check) > 0: image_crop_list.append(image_crop) bbs_crop_list.append(bbs_crop_after_check) else: image_crop = aug_seq(image=image) image_crop_list.append(image_crop) return np.array(image_crop_list), bbs_crop_list def adopt_size_normalization(self, image_crop, bbs_crop): """ adopt image to size normalization random resize and padding Args: - image_crop: np.array, shape == [crop_num, height, width, channels], cropped images - bbs_crop: [BoundingBoxesOnImage, ...], imgaug bounding box """ aug_seq = iaa.CropAndPad( px=(-1 * self.resize_px, 0), sample_independently=False ) image_crop_aug = [] bbs_crop_aug = [] # adopt augmentation for im_crop, bb_crop in zip(image_crop, bbs_crop): im_crop_aug, bb_crop_aug = aug_seq(image=im_crop, bounding_boxes=bb_crop) # check coord in im_crop_aug shape bb_crop_aug_before_check = bb_crop_aug.bounding_boxes bb_crop_aug_after_check = copy.copy(bb_crop_aug.bounding_boxes) for bb in bb_crop_aug_before_check: if bb.is_fully_within_image(im_crop_aug.shape): pass else: bb_crop_aug_after_check.remove(bb) # append im_crop_aug and bb_crop_aug if len(bb_crop_aug_after_check) > 0: image_crop_aug.append(im_crop_aug) bbs_crop_aug.append(bb_crop_aug_after_check) return np.array(image_crop_aug), bbs_crop_aug def adopt_augmentation(self, image_crop, bbs_crop): """ adopt augmentation to image_crop, bbs_crop Args: - image_crop: np.array, shape == [crop_num, height, width, channels], cropped images - bbs_crop: [BoundingBoxesOnImage, ...], imgaug bounding box """ image_crop_aug = [] bbs_crop_aug = [] # adopt augmentation for im_crop, bb_crop in zip(image_crop, bbs_crop): im_crop_aug, bb_crop_aug = self.aug_seq(image=im_crop, bounding_boxes=bb_crop) # check coord in im_crop_aug shape bb_crop_aug_before_check = bb_crop_aug.bounding_boxes bb_crop_aug_after_check = copy.copy(bb_crop_aug.bounding_boxes) for bb in bb_crop_aug_before_check: if bb.is_fully_within_image(im_crop_aug.shape): pass else: bb_crop_aug_after_check.remove(bb) # append im_crop_aug and bb_crop_aug if len(bb_crop_aug_after_check) > 0: image_crop_aug.append(im_crop_aug) bbs_crop_aug.append(bb_crop_aug_after_check) return np.array(image_crop_aug), bbs_crop_aug def create_pytorch_annotation(self, bbs_crop_aug): """ extract bounding box and convert to pytorch style Args: - bbs_crop_aug: [BoundingBoxesOnImage, ...], imgaug bounding box """ target = [] for bb_crop_aug in bbs_crop_aug: target_per_image = [] for elem_bb in bb_crop_aug: x1 = elem_bb.x1 / float(self.resize_size) y1 = elem_bb.y1 / float(self.resize_size) x2 = elem_bb.x2 / float(self.resize_size) y2 = elem_bb.y2 / float(self.resize_size) lbl = int(self.name_to_lbl[elem_bb.label]) target_per_image.append([x1, y1, x2, y2, lbl]) target.append(torch.Tensor(target_per_image)) return target def create_test_image(self, image): """ create image for evaluation (default crop code doesn't work right when evaluation) """ height_after_crop = int(image.shape[0] / self.crop_num[0]) width_after_crop = int(image.shape[1] / self.crop_num[1]) image_crop_list = [] # create crop image for i in range(self.crop_num[0]): for j in range(self.crop_num[1]): # crop and resize crop_image = image[ height_after_crop * i: height_after_crop * (i + 1) + 100, width_after_crop * j: width_after_crop * (j + 1) + 100, :] crop_resize_image = cv2.resize(crop_image, dsize=(self.resize_size, self.resize_size), interpolation=cv2.INTER_NEAREST) image_crop_list.append(crop_resize_image) return np.array(image_crop_list) def collate_fn(batch): return tuple(zip(*batch))<file_sep>/model/unet/unet.py import torch import torch.nn as nn import torch.nn.functional as F import math import torch.utils.model_zoo as model_zoo __all__ = ["unet"] class Unet(nn.Module): """Unet segmentation network.""" def __init__(self, in_channels, out_channels): """Init Unet fields.""" super(Unet, self).__init__() self.in_channels = in_channels self.conv11 = nn.Conv2d(in_channels, 64, kernel_size=3, padding=1) self.bn11 = nn.BatchNorm2d(64) self.conv12 = nn.Conv2d(64, 64, kernel_size=3, padding=1) self.bn12 = nn.BatchNorm2d(64) self.conv21 = nn.Conv2d(64, 128, kernel_size=3, padding=1) self.bn21 = nn.BatchNorm2d(128) self.conv22 = nn.Conv2d(128, 128, kernel_size=3, padding=1) self.bn22 = nn.BatchNorm2d(128) self.conv31 = nn.Conv2d(128, 256, kernel_size=3, padding=1) self.bn31 = nn.BatchNorm2d(256) self.conv32 = nn.Conv2d(256, 256, kernel_size=3, padding=1) self.bn32 = nn.BatchNorm2d(256) self.conv33 = nn.Conv2d(256, 256, kernel_size=3, padding=1) self.bn33 = nn.BatchNorm2d(256) self.conv41 = nn.Conv2d(256, 512, kernel_size=3, padding=1) self.bn41 = nn.BatchNorm2d(512) self.conv42 = nn.Conv2d(512, 512, kernel_size=3, padding=1) self.bn42 = nn.BatchNorm2d(512) self.conv43 = nn.Conv2d(512, 512, kernel_size=3, padding=1) self.bn43 = nn.BatchNorm2d(512) self.conv51 = nn.Conv2d(512, 512, kernel_size=3, padding=1) self.bn51 = nn.BatchNorm2d(512) self.conv52 = nn.Conv2d(512, 512, kernel_size=3, padding=1) self.bn52 = nn.BatchNorm2d(512) self.conv53 = nn.Conv2d(512, 512, kernel_size=3, padding=1) self.bn53 = nn.BatchNorm2d(512) self.upconv5 = nn.ConvTranspose2d(512, 512, kernel_size=2, stride=2) self.conv53d = nn.ConvTranspose2d(1024, 512, kernel_size=3, padding=1) self.bn53d = nn.BatchNorm2d(512) self.conv52d = nn.ConvTranspose2d(512, 512, kernel_size=3, padding=1) self.bn52d = nn.BatchNorm2d(512) self.conv51d = nn.ConvTranspose2d(512, 512, kernel_size=3, padding=1) self.bn51d = nn.BatchNorm2d(512) self.upconv4 = nn.ConvTranspose2d(512, 512, kernel_size=2, stride=2, output_padding=1) # padding 1 self.conv43d = nn.ConvTranspose2d(1024, 512, kernel_size=3, padding=1) self.bn43d = nn.BatchNorm2d(512) self.conv42d = nn.ConvTranspose2d(512, 512, kernel_size=3, padding=1) self.bn42d = nn.BatchNorm2d(512) self.conv41d = nn.ConvTranspose2d(512, 256, kernel_size=3, padding=1) self.bn41d = nn.BatchNorm2d(256) self.upconv3 = nn.ConvTranspose2d(256, 256, kernel_size=2, stride=2) self.conv33d = nn.ConvTranspose2d(512, 256, kernel_size=3, padding=1) self.bn33d = nn.BatchNorm2d(256) self.conv32d = nn.ConvTranspose2d(256, 256, kernel_size=3, padding=1) self.bn32d = nn.BatchNorm2d(256) self.conv31d = nn.ConvTranspose2d(256, 128, kernel_size=3, padding=1) self.bn31d = nn.BatchNorm2d(128) self.upconv2 = nn.ConvTranspose2d(128, 128, kernel_size=2, stride=2) self.conv22d = nn.ConvTranspose2d(256, 128, kernel_size=3, padding=1) self.bn22d = nn.BatchNorm2d(128) self.conv21d = nn.ConvTranspose2d(128, 64, kernel_size=3, padding=1) self.bn21d = nn.BatchNorm2d(64) self.upconv1 = nn.ConvTranspose2d(64, 64, kernel_size=2, stride=2) self.conv12d = nn.ConvTranspose2d(128, 64, kernel_size=3, padding=1) self.bn12d = nn.BatchNorm2d(64) self.conv11d = nn.ConvTranspose2d(64, out_channels, kernel_size=3, padding=1) for m in self.modules(): if isinstance(m, nn.Conv2d): n = m.kernel_size[0] * m.kernel_size[1] * m.out_channels m.weight.data.normal_(0, math.sqrt(2. / n)) elif isinstance(m, nn.BatchNorm2d): m.weight.data.fill_(1) m.bias.data.zero_() elif isinstance(m, nn.Linear): m.bias.data.zero_() def forward(self, x): """Forward method.""" # Stage 1 x11 = F.relu(self.bn11(self.conv11(x))) x12 = F.relu(self.bn12(self.conv12(x11))) x1p = F.max_pool2d(x12, kernel_size=2, stride=2) # Stage 2 x21 = F.relu(self.bn21(self.conv21(x1p))) x22 = F.relu(self.bn22(self.conv22(x21))) x2p = F.max_pool2d(x22, kernel_size=2, stride=2) # Stage 3 x31 = F.relu(self.bn31(self.conv31(x2p))) x32 = F.relu(self.bn32(self.conv32(x31))) x33 = F.relu(self.bn33(self.conv33(x32))) x3p = F.max_pool2d(x33, kernel_size=2, stride=2) # Stage 4 x41 = F.relu(self.bn41(self.conv41(x3p))) x42 = F.relu(self.bn42(self.conv42(x41))) x43 = F.relu(self.bn43(self.conv43(x42))) x4p = F.max_pool2d(x43, kernel_size=2, stride=2) # Stage 5 x51 = F.relu(self.bn51(self.conv51(x4p))) x52 = F.relu(self.bn52(self.conv52(x51))) x53 = F.relu(self.bn53(self.conv53(x52))) x5p = F.max_pool2d(x53, kernel_size=2, stride=2) # Stage 5d x5d = torch.cat((self.upconv5(x5p), x53), 1) x53d = F.relu(self.bn53d(self.conv53d(x5d))) x52d = F.relu(self.bn52d(self.conv52d(x53d))) x51d = F.relu(self.bn51d(self.conv51d(x52d))) # Stage 4d x4d = torch.cat((self.upconv4(x51d), x43), 1) x43d = F.relu(self.bn43d(self.conv43d(x4d))) x42d = F.relu(self.bn42d(self.conv42d(x43d))) x41d = F.relu(self.bn41d(self.conv41d(x42d))) # Stage 3d x3d = torch.cat((self.upconv3(x41d), x33), 1) x33d = F.relu(self.bn33d(self.conv33d(x3d))) x32d = F.relu(self.bn32d(self.conv32d(x33d))) x31d = F.relu(self.bn31d(self.conv31d(x32d))) # Stage 2d x2d = torch.cat((self.upconv2(x31d), x22), 1) x22d = F.relu(self.bn22d(self.conv22d(x2d))) x21d = F.relu(self.bn21d(self.conv21d(x22d))) # Stage 1d x1d = torch.cat((self.upconv1(x21d), x12), 1) x12d = F.relu(self.bn12d(self.conv12d(x1d))) x11d = self.conv11d(x12d) return x11d def load_pretrained_weights(self): vgg16_weights = model_zoo.load_url("https://download.pytorch.org/models/vgg16_bn-6c64b313.pth") count_vgg = 0 count_this = 0 vggkeys = list(vgg16_weights.keys()) thiskeys = list(self.state_dict().keys()) corresp_map = [] while(True): vggkey = vggkeys[count_vgg] thiskey = thiskeys[count_this] if "classifier" in vggkey: break while vggkey.split(".")[-1] not in thiskey: count_this += 1 thiskey = thiskeys[count_this] corresp_map.append([vggkey, thiskey]) count_vgg+=1 count_this += 1 mapped_weights = self.state_dict() for k_vgg, k_segnet in corresp_map: if (self.in_channels != 3) and "features" in k_vgg and "conv11." not in k_segnet: mapped_weights[k_segnet] = vgg16_weights[k_vgg] elif (self.in_channels == 3) and "features" in k_vgg: mapped_weights[k_segnet] = vgg16_weights[k_vgg] try: self.load_state_dict(mapped_weights) print("Loaded VGG-16 weights in UNet !") except: print("Error VGG-16 weights in UNet !") raise def load_from_filename(self, model_path): """Load weights from filename.""" th = torch.load(model_path) # load the weigths self.load_state_dict(th) def load_from_filename(self, model_path): """Load weights from filename.""" th = torch.load(model_path) # .state_dict() # load the weigths self.load_state_dict(th) def Unet_(in_channels, out_channels, pretrained=False, **kwargs): """Constructs a ResNet-34 model. Args: pretrained (bool): If True, returns a model pre-trained on ImageNet """ model = Unet(in_channels, out_channels) if pretrained: model.load_pretrained_weights() return model
f15893d59f72ecd474ad6c2c0610b69ec264fed8
[ "Markdown", "Python" ]
40
Python
keiiti975/Insect_Phenology_Detector
1a32b4967a079dd41c888706902e8ec98968dbf0
029999fb0fc310e6b9fd38201ac12003f25db63e
refs/heads/master
<repo_name>zack-cpp/McCulloch-Pitts<file_sep>/main.c #include <stdio.h> #include <stdlib.h> short int loop = 0; struct MCP{ // OR dan AND short int www; short int ttt; short int xxx[3]; short int yyy; unsigned short int hasil; // XOR short int w1, w2, w3, w4, w5, w6; short int o1, o2, o3, z1, z2; }pitts; void orr(short int jml_input){ pitts.www = 2; pitts.ttt = 2; printf("Operasi OR\n"); for(loop = 0; loop < jml_input; loop++){ printf("Input x[%d]: ",loop+1); scanf("%d",&pitts.xxx[loop]); } if(jml_input == 2){ pitts.yyy = pitts.www*pitts.xxx[0] + pitts.www*pitts.xxx[1]; }else{ pitts.yyy = pitts.www*pitts.xxx[0] + pitts.www*pitts.xxx[1] + pitts.www*pitts.xxx[2]; } if(pitts.yyy >= pitts.ttt){ pitts.hasil = 1; }else{ pitts.hasil = 0; } printf("Hasil: %d",pitts.hasil); } void xorr(short int jml_input){ pitts.w1 = 2; pitts.w2 = -1; pitts.w3 = pitts.w1; pitts.w4 = pitts.w2; pitts.w5 = 2; pitts.w6 = pitts.w5; pitts.ttt = 2; for(loop = 0; loop < 3; loop++){ printf("Input x[%d]: ",loop+1); scanf("%d",&pitts.xxx[loop]); } pitts.o1 = pitts.w1*pitts.xxx[0] + pitts.w2*pitts.xxx[1]; if(pitts.o1 >= pitts.ttt){ pitts.z1 = 1; }else{ pitts.z1 = 0; } pitts.o2 = pitts.w2*pitts.xxx[0] + pitts.w3*pitts.xxx[1]; if(pitts.o2 >= pitts.ttt){ pitts.z2 = 1; }else{ pitts.z2 = 0; } pitts.o3 = pitts.w5*pitts.z1 + pitts.w6*pitts.z2; if(pitts.o3 >= pitts.ttt){ pitts.yyy = 1; }else{ pitts.yyy = 0; } if(jml_input == 3){ pitts.o1 = pitts.w1*pitts.yyy + pitts.w2*pitts.xxx[2]; if(pitts.o1 >= pitts.ttt){ pitts.z1 = 1; }else{ pitts.z1 = 0; } pitts.o2 = pitts.w2*pitts.yyy + pitts.w3*pitts.xxx[2]; if(pitts.o2 >= pitts.ttt){ pitts.z2 = 1; }else{ pitts.z2 = 0; } pitts.o3 = pitts.w5*pitts.z1 + pitts.w6*pitts.z2; if(pitts.o3 >= pitts.ttt){ pitts.hasil = 1; }else{ pitts.hasil = 0; } printf("Hasil: %d",pitts.hasil); }else{ printf("Hasil: %d",pitts.yyy); } } void andd(short int jml_input){ pitts.www = 1; pitts.ttt = jml_input; for(loop = 0; loop < 3; loop++){ printf("Input x[%d]: ",loop+1); scanf("%d",&pitts.xxx[loop]); } if(jml_input == 2){ pitts.yyy = pitts.www*pitts.xxx[0] + pitts.www*pitts.xxx[1]; }else{ pitts.yyy = pitts.www*pitts.xxx[0] + pitts.www*pitts.xxx[1] + pitts.www*pitts.xxx[2]; } if(pitts.yyy >= pitts.ttt){ pitts.hasil = 1; }else{ pitts.hasil = 0; } printf("Hasil: %d",pitts.hasil); } int main() { //orr(3); //xorr(3); andd(3); return 0; }
dad6d6ec9635f9e9b0e1349101319a84d3720284
[ "C" ]
1
C
zack-cpp/McCulloch-Pitts
969a948d7a5708350535e7a68df3a71d02b76a7d
e4f15a3442eeb53bcc38ac52341b5333a00830d1
refs/heads/master
<file_sep>module.exports = { // 启动指令,默认为 F12 launchDirect: 123, // 是否覆盖 window.console,默认为否 overwriteConsole: false, // 是否设为全局变量(window.Xlog),默认为否 isGlobalParameter: false, // 初始是否显示默认为否 display: false };<file_sep>var VirtualElement = require('./virtual-element'); var VirtualBody = function () { VirtualElement.call(this); this.tagName = 'VIRTUALBODY'; }; VirtualBody.prototype = new VirtualElement(); module.exports = VirtualBody;<file_sep>var VirtualElement = require('./virtual-element'); var VirtualLiDetailContent = function () { VirtualElement.call(this); this.tagName = 'VIRTUALLIDETAILCONTENT'; this.display = 'show'; }; VirtualLiDetailContent.prototype = new VirtualElement(); module.exports = VirtualLiDetailContent;<file_sep>#### 引用 ``` UMD var Xlog = require('.../xlog'); Client <script src='.../xlog-client.js'></script> ``` #### 初始化 ``` Xlog.init({ launchDirect: 123, overwriteConsole: false, isGlobalParameter: false, display: false }); ``` #### 参数说明 | Name | Default | Description | | ------------- |-----------| ---------------------| | launchDirect | 123 | 启动指令 | | overwriteConsole | false | 是否覆盖 window.console | | isGlobalParameter | false | 是否设为全局变量(window.Xlog) | | display| false | 初始是否显示 | #### Api - log —— Xlog.log(msg), 同console.log(msg) - debug —— Xlog.debug(msg), 同console.debug(msg) - info —— Xlog.info(msg), 同console.info(msg) - warn —— Xlog.warn(msg), 同console.warn(msg) - error —— Xlog.error(msg), 同console.error(msg) #### Example ``` var Xlog = require('.../xlog'); Xlog.log({a: 1, b: [2, 3]}); Xlog.log({a: 1, b: {c: 2, d: 3}}); Xlog.info([1, 2]); Xlog.info('ffffffffffffffeeeeeee'); Xlog.warn(3); Xlog.error(4); ``` <file_sep>var VirtualElement = require('./virtual-element'); var VirtualEntity = function () { VirtualElement.call(this); this.tagName = 'VIRTUALENTITY'; }; VirtualEntity.prototype = new VirtualElement(); VirtualEntity.prototype.clean = function () { this.children.length = 0; }; module.exports = VirtualEntity;<file_sep>var VirtualElement = require('./virtual-element'); var VirtualContainer = function () { VirtualElement.call(this); this.tagName = 'VIRTUALCONTAINER'; this.display = 'hidden'; this.offsetWidth = 0; this.offsetHeight = 0; this.offsetLeft = 0; this.offsetTop = 0; this.marginLeft = 0; }; VirtualContainer.prototype = new VirtualElement(); module.exports = VirtualContainer;<file_sep>var webpack = require('webpack'); var config = require('../config/client'); var merge = require('webpack-merge'); var baseWebpackConfig = require('./webpack.base.conf'); module.exports = merge(baseWebpackConfig, { output: { filename: '[name]-client.js' }, plugins: [ new webpack.DefinePlugin({ __CONFIG__: JSON.stringify(config) }) ] });<file_sep>var VirtualElement = require('./virtual-element'); var VirtualLiDetailTitle = require('./virtual-li-detail-title'); var VirtualLiDetailContent = require('./virtual-li-detail-content'); var VirtualLiDetail = function (key, value) { VirtualElement.call(this); this.tagName = 'VIRTUALLIDETAIL'; this.key = key; this.value = value; this.appendChild( new VirtualLiDetailTitle(), new VirtualLiDetailContent() ); }; VirtualLiDetail.prototype = new VirtualElement(); VirtualLiDetail.prototype.mapTitle = function () { var el = this.nativeElement; var title = this.getElmentsByTagName('virtuallidetailtitle')[0]; title.nativeElement = el.querySelector('.figure'); }; VirtualLiDetail.prototype.mapContent = function () { var el = this.nativeElement; var content = this.getElmentsByTagName('virtuallidetailcontent')[0]; content.nativeElement = el.querySelector('ul'); }; module.exports = VirtualLiDetail;<file_sep>module.exports = { codingMode: 'client' }<file_sep>var util = require('../util'); var dom = require('../dom'); var Bus = require('../bus'); var virtualCache = require('../virtual-dom/virtual-cache'); var VirtualLi = require('../virtual-dom/virtual-li'); var VirtualLiDetail = require('../virtual-dom/virtual-li-detail'); var VirtualLiDetailTitle = require('../virtual-dom/virtual-li-detail-title'); var VirtualLiDetailContent = require('../virtual-dom/virtual-li-detail-content'); var virtualContainer = virtualCache.container; var virtualEntity = virtualCache.entity; var _generateVirtualTree = function (parent, key, value) { if (!value) { return; } var virtualLiDetail = new VirtualLiDetail(key, value); var virtualDetailTitle = virtualLiDetail.getElmentsByTagName('virtuallidetailtitle')[0]; var virtualDetailContent = virtualLiDetail.getElmentsByTagName('virtuallidetailcontent')[0]; if (value.constructor === Array) { for (var i = 0, j = value.length; i < j; i++) { _generateVirtualTree(virtualDetailContent, i, value[i]); } } else if (value.constructor === Object) { for (var i in value) { _generateVirtualTree(virtualDetailContent, i, value[i]); } } parent.appendChild(virtualLiDetail); }; util.on(dom.entity, 'click', '.figure', function (evt) { var e = evt || event; var target = e.target || e.srcElement; var liDetail = util.closest(target, '.xlog-list-detail'); var virtualId = liDetail.getAttribute('data-virtual-id'); var virtualDetail = virtualContainer.getElementById(virtualId); var virtualDetailTitle = virtualDetail.getElmentsByTagName('virtuallidetailtitle')[0]; var virtualDetailContent = virtualDetail.getElmentsByTagName('virtuallidetailcontent')[0]; var title = virtualDetailTitle.nativeElement; var content = virtualDetailContent.nativeElement; if (!content) { dom.generateDetail(liDetail, virtualDetail); virtualDetail.map(liDetail); virtualDetail.mapTitle(); virtualDetail.mapContent(); title = virtualDetailTitle.nativeElement; content = virtualDetailContent.nativeElement; } if (virtualDetailTitle.toggle === 'on') { util.removeClass(title, 'on'); content.style.display = 'none'; virtualDetailTitle.toggle = 'off'; virtualDetailContent.display = 'hidden'; } else { util.addClass(title, 'on'); content.style.display = 'block'; virtualDetailTitle.toggle = 'on'; virtualDetailContent.display = 'show'; } }); Bus.on('WRITE', function (level, fmt, li) { var virtualLi = new VirtualLi(level); virtualEntity.appendChild(virtualLi); virtualLi.map(li); if (fmt.instance === 'string' || fmt.instance === 'other') { return; } var liDetail = li.querySelector('.xlog-list-detail'); if (!liDetail) { return; } _generateVirtualTree(virtualLi, null, fmt.content); var virtualLiDetail = virtualLi.getElmentsByTagName('virtualLiDetail')[0]; liDetail.setAttribute('data-virtual-id', virtualLiDetail.id); virtualLiDetail.map(liDetail); virtualLiDetail.mapTitle(); });<file_sep>var dom = require('../dom'); var Bus = require('../bus'); var VirtualContainer = require('./virtual-container'); var VirtualHead = require('./virtual-head'); var VirtualDropbar = require('./virtual-dropbar'); var VirtualBody = require('./virtual-body'); var VirtualEntiny = require('./virtual-entity'); var virtualCache = require('./virtual-cache'); var virtualContainer = new VirtualContainer(); var virtualHead = new VirtualHead(); var virtualDropbar = new VirtualDropbar(); var virtualBody = new VirtualBody(); var virtualEntiny = new VirtualEntiny(); virtualContainer.map(dom.container); virtualHead.map(dom.head); virtualDropbar.map(dom.dropbar); virtualBody.map(dom.body); virtualEntiny.map(dom.entity); virtualContainer.appendChild(virtualHead, virtualBody); virtualHead.appendChild(virtualDropbar); virtualBody.appendChild(virtualEntiny); virtualCache.container = virtualContainer; virtualCache.head = virtualHead; virtualCache.dropbar = virtualDropbar; virtualCache.body = virtualBody; virtualCache.entity = virtualEntiny; Bus.once('CONTAINER_SHOW', function () { virtualContainer.syncProperty('offsetWidth', 'offsetHeight'); virtualContainer.syncStyle('marginLeft', 'left', 'top'); virtualHead.syncProperty('offsetHeight'); virtualBody.syncStyle('paddingTop', 'paddingRight', 'paddingBottom', 'paddingLeft', 'height'); }); Bus.on('DROPBAR_SHOW', function () { virtualDropbar.syncProperty('offsetHeight'); }); <file_sep>module.exports = { codingMode: 'umd' }<file_sep>var util = require('../util'); var dom = require('../dom'); var Bus = require('../bus'); var setting = require('../setting'); var virtualCache = require('../virtual-dom/virtual-cache'); var virtualContainer = virtualCache.container; var _show = function () { dom.show(); virtualContainer.display = 'show'; Bus.dispatch('CONTAINER_SHOW'); }; var _hide = function () { dom.hide(); virtualContainer.display = 'hidden'; }; if (setting.display) { _show(); } util.on(document, 'keydown', function (evt) { var e = evt || event; var keyCode = e.keyCode; if (keyCode === setting.launchDirect) { if (virtualContainer.display === 'hidden') { _show(); } else { _hide(); } } if (keyCode === 123) { if (e.preventDefault){ e.preventDefault(); } else{ e.returnValue = false; } } }); util.on(dom.closeButton, 'click', _hide);<file_sep>var webpack = require('webpack'); var chalk = require('chalk'); exports.webpackToPromise = function (config, alias) { return new Promise(function (resolve, reject) { webpack(config, function (err, stats) { if (err) { throw err; reject(); } process.stdout.write(stats.toString({ colors: true, modules: false, children: false, chunks: false, chunkModules: false }) + '\n\n'); console.log(chalk.cyan(' ' + alias + ' Build complete.\n')); resolve(); }); }); }
cc50c4742a87df1ccc37e52e20873a8c04be4195
[ "JavaScript", "Markdown" ]
14
JavaScript
tedtse/xlog
4e3902c6b364b35de371682a5de378af7162a3f6
a7f568addc661c321781251e417c3955cdcbb9e1
refs/heads/master
<repo_name>yuki5647/block-braekar<file_sep>/Assets/ball.cs using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; public class ball : MonoBehaviour { public float speed = 5.0f; private Rigidbody myRigidbody; private float coefficient = 0.9f; private bool isEnd = false; private float visiblePosZ = -7f; private GameObject GameOvertext; private GameObject cleartext; GameObject[] tagObjects; // Use this for initialization void Start() { this.GameOvertext = GameObject.Find("GameOvertext"); this.cleartext = GameObject.Find("cleartext"); myRigidbody = this.GetComponent<Rigidbody>(); myRigidbody.AddForce((transform.forward + transform.right) * speed, ForceMode.VelocityChange); } // Update is called once per frame void Update() { if (this.transform.position.z < this.visiblePosZ) { this.GameOvertext.GetComponent<Text>().text = "GameOver"; } } void Check(string tagname) { tagObjects = GameObject.FindGameObjectsWithTag("blocktag"); Debug.Log(tagObjects.Length); //tagObjects.Lengthはオブジェクトの数 if (tagObjects.Length == 2) { this.cleartext.GetComponent<Text>().text = "clear"; } } void OnCollisionEnter(Collision other) { if (other.gameObject.tag == "blocktag") { this.cleartext.GetComponent<Text>().text = "clear"; } if (other.gameObject.tag == "blocktag") { GetComponent<ParticleSystem>().Play(); } } }
0b30ea9a182065ce5bdc735f3118433de2ab5b66
[ "C#" ]
1
C#
yuki5647/block-braekar
b0c2703a4644469bc0e1fa40ccf399c039674056
0905f78b885232214edc1dd2af1c8c1e238782b5
refs/heads/main
<repo_name>prabal4546/Instafilter<file_sep>/Instafilter/ContentView.swift // // ContentView.swift // Instafilter // // Created by <NAME> on 18/11/20. // import CoreImage import CoreImage.CIFilterBuiltins import SwiftUI struct ContentView: View { @State private var image:Image? @State private var filterIntensity = 0.5 @State private var showingImagePicker = false @State private var inputImage: UIImage? @State var currentFilter:CIFilter = CIFilter.sepiaTone() let context = CIContext() var body: some View { let intensity = Binding<Double>{ get: do { self.filterIntensity }, set:do { self.filterIntensity = $0 self.applyProcessing() } } return NavigationView{ VStack{ ZStack{ Rectangle() .fill(Color.secondary) if image != nil{ image? .resizable() .scaledToFit() } else{ Text("Tap to select a picture") .foregroundColor(.white) .font(.headline) } } .onTapGesture { //select an image self.showingImagePicker = true } HStack{ Text("Intensity") .padding(.horizontal) Slider(value: intensity) } .padding(.vertical) HStack{ Button("Change Filter"){ //change filter } Spacer() Button("Save"){ //save the picture } } } } .padding([.horizontal,.bottom]) .navigationBarTitle("Instafilter") .sheet(isPresented: $showingImagePicker,onDismiss: loadImage){ ImagePicker(image: self.$inputImage) } } func applyProcessing(){ currentFilter.intensity = Float(filterIntensity) guard let outputImage = currentFilter.outputImage else{return} if let cgimg = context.createCGImage(outputImage, from: outputImage.extent){ let uiImage = UIImage(cgImage: cgimg) image = Image(uiImage: uiImage) } } func loadImage(){ guard let inputImage = inputImage else {return} let beginImage = CIImage(image: inputImage) currentFilter.setValue(beginImage, forKey: kCIInputImageKey) applyProcessing() } } struct ContentView_Previews: PreviewProvider { static var previews: some View { ContentView() } }
168362fc6efcdc37777d1456eec9c0bd536d5edc
[ "Swift" ]
1
Swift
prabal4546/Instafilter
8c196531becb738337c91a3a507e1e15af378c32
8c6d4e0220f960bf528456b61a381452450f5345
refs/heads/master
<repo_name>MikleGod/WiseTechProdMatrix<file_sep>/src/main/java/model/Matrix.java package model; import java.util.ArrayList; import java.util.List; public class Matrix { public List<List<String>> matrix; public List<String> markets; public List<String> assort; public Matrix(){ markets = new ArrayList<String>(); assort = new ArrayList<String>(); matrix = new ArrayList<List<String>>(); } } <file_sep>/README.md # javafx-maven-example Sample application using JavaFX and Maven
50b42a24a15b0b9a8b986353ae1a8a4c74d00f82
[ "Markdown", "Java" ]
2
Java
MikleGod/WiseTechProdMatrix
84b576beabb658d4a3f6642357be5abeb1501633
36e4ad4dae01b2b8b7b2daac2e0fc6b189a140d8
refs/heads/master
<file_sep>import { Component, OnInit } from '@angular/core'; import { Observable } from 'rxjs'; import { HttpClient } from '@angular/common/http'; import { Sound } from '@shared/sound.interface'; import { trigger, transition, style, animate } from '@angular/animations'; @Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.scss'], animations: [ trigger('fadeInOut', [ transition(':enter', [ // :enter is alias to 'void => *' style({ opacity: 0 }), animate(200, style({ opacity: 1 })) ]), transition(':leave', [ // :leave is alias to '* => void' animate(200, style({ opacity: 0 })) ]) ]) ] }) export class AppComponent implements OnInit { public soundList!: Sound[]; public showModal = false; constructor(private http: HttpClient) { } ngOnInit(): void { this.loadSounds(); } public openEditorModal(): void { this.showModal = true; } public closeEditorModal(): void { this.showModal = false; } // Sounds related functions loadSounds(): void { this.getSoundList().subscribe({ next: data => { this.soundList = data; }, error: error => { alert('Couldn\'t load sound list! (' + error.status + ' ' + error.statusText + ')'); } }); } getSoundList(): Observable<any> { return this.http.get('./assets/soundlist.json'); } muteAllSounds(): void { this.soundList.forEach(sound => { (document.getElementById(sound.filename) as HTMLAudioElement).pause(); sound.playing = false; }); } } <file_sep>import { animate, style, transition, trigger } from '@angular/animations'; import { Component, EventEmitter, OnInit, Output } from '@angular/core'; import * as DecoupledEditor from '@ckeditor/ckeditor5-build-decoupled-document'; import { debounceTime, Subject } from 'rxjs'; @Component({ selector: 'app-ckeditor-modal', templateUrl: './ckeditor-modal.component.html', styleUrls: ['./ckeditor-modal.component.scss'], animations: [ trigger('fadeInOut', [ transition(':enter', [ // :enter is alias to 'void => *' style({ opacity: 0 }), animate(400, style({ opacity: 1 })) ]), transition(':leave', [ // :leave is alias to '* => void' animate(400, style({ opacity: 0 })) ]) ]) ] }) export class CkeditorModalComponent implements OnInit { public Editor = DecoupledEditor; public textTitle!: string; public textContent!: string; @Output() closeModal = new EventEmitter<void>(); private storageSubject: Subject<void> = new Subject(); public textSaved = false; constructor() { this.resetEditor(); } ngOnInit(): void { this.loadEditorFromStorage(); this.initializeContinuousStorage(); } initializeContinuousStorage(): void { this.storageSubject.pipe(debounceTime(1000)).subscribe(() => { localStorage.setItem('textEditor', JSON.stringify({ title: this.textTitle, content: this.textContent })); this.textSaved = true; setTimeout(() => { this.textSaved = false; }, 1000); }); } resetEditor(): void { this.textTitle = 'Your title'; this.textContent = 'Your ideas.'; } closeEditorModal(): void { this.closeModal.emit(); } loadEditorFromStorage(): void { if (localStorage.getItem('textEditor') != null) { this.textTitle = JSON.parse(localStorage.getItem('textEditor')!).title; this.textContent = JSON.parse(localStorage.getItem('textEditor')!).content; } } updateStorage(): void { this.storageSubject.next(); } editorReady(editor: any): void { editor.ui.getEditableElement().parentElement.insertBefore( editor.ui.view.toolbar.element, editor.ui.getEditableElement() ); } // Printing text to the browser print UI printText(): void { const printWindow: Window = window.open('', 'Noizee', 'height=720,width=1280')!; printWindow.document.write('<html><head><title>' + this.textTitle + '</title>'); printWindow.document.write('</head><body >'); printWindow.document.write('<h1>' + this.textTitle + '</h1>'); printWindow.document.write(this.textContent); printWindow.document.write('</body></html>'); printWindow.document.close(); printWindow.focus(); printWindow.print(); printWindow.close(); } } <file_sep><div class="header"> <div> <img alt="Noizee" src="./assets/logo.png" class="logo" /> </div> <div class="mute-btn" (click)="muteAllSounds()" title="Stop all sounds"> <i class="material-icons">volume_off</i> <br /> </div> <div class="editor-btn" (click)="openEditorModal()" title="Open text editor"> <i class="material-icons">edit</i> <br /> </div> </div> <div class="list-container"> <app-soundbox *ngFor="let sound of soundList" [sound]="sound" class="sound-box"></app-soundbox> <br /><br /> <small class="text-1 footer"> Icons by <a rel="noopener" target="_blank" href="https://www.flaticon.com/br/autores/eucalyp" title="Eucalyp">Eucalyp</a> <br /> Sounds by unknown <br /> Developed by <a rel="noopener" target="_blank" href="https://github.com/pedrocx486">pedroCX486</a> <br /><br /> Issues playing? Our sounds are in MP3 format.<br />Linux users may need to install extra codecs to play them. </small> </div> <app-ckeditor-modal *ngIf="showModal" (closeModal)="closeEditorModal()" class="editor-modal" [@fadeInOut]></app-ckeditor-modal> <file_sep>export interface Sound { filename: string; screenname: string; icon: string; playing?: boolean } <file_sep># Noizee An alternative to Noisli made in [Angular](https://github.com/angular/angular-cli). You can also check the Vue3 version, [here](https://github.com/pedroCX486/noizee-vue3/). ## Development Run `npm start` for a dev server. Navigate to `http://localhost:4200/` or wait until the compiler opens a window. The app will automatically reload if you change any of the source files. ## Build Run `npm run build` to build the project. The build artifacts will be stored in the `dist/` directory. If you wish to run the project inside a subfolder, run the command `npm run subfolder-build` to build it to run under the `\noizee\` subfolder in your server. ## Contributing Just do a pull request! ## License Code is licensed under the ISC. Icons are by Eucalyp. Sound files I have no credits currently since I got on a torrent dump with not much info. <file_sep>import { trigger, transition, style, animate } from '@angular/animations'; import { AfterViewInit, Component, Input } from '@angular/core'; import { Sound } from '@shared/sound.interface'; @Component({ selector: 'app-soundbox', templateUrl: './soundbox.component.html', styleUrls: ['./soundbox.component.scss'], animations: [ trigger('fadeInOut', [ transition(':enter', [ // :enter is alias to 'void => *' style({ opacity: 0 }), animate(300, style({ opacity: 1 })) ]), transition(':leave', [ // :leave is alias to '* => void' animate(300, style({ opacity: 0 })) ]) ]) ] }) export class SoundboxComponent implements AfterViewInit { @Input() sound!: Sound; public soundVolume = 0.30; private audioElement!: HTMLAudioElement; private volumeControl!: HTMLInputElement; private audioCtx!: AudioContext; private track!: MediaElementAudioSourceNode; private gainNode!: GainNode; constructor() { } ngAfterViewInit() { this.audioElement = (document.getElementById(this.sound.filename) as HTMLAudioElement); this.volumeControl = (document.getElementById(this.sound.filename + "-volume") as HTMLInputElement) } audioControls(sound: Sound): void { if (!this.track) { this.audioCtx = new AudioContext(); this.track = this.audioCtx.createMediaElementSource(this.audioElement); this.gainNode = this.audioCtx.createGain(); this.gainNode.gain.value = this.soundVolume; this.track.connect(this.gainNode).connect(this.audioCtx.destination); this.audioCtx.resume(); } if (this.audioElement.paused) { this.volumeControls(); sound.playing = true; this.audioElement.play(); } else { sound.playing = false; this.audioElement.pause(); } } volumeControls(): void { this.volumeControl.addEventListener('input', (e) => { if (this.gainNode) { this.gainNode.gain.value = Number((e.target as HTMLInputElement).value); } }, false); } }
60f19a27c3979ce33eeb4dd19e9955487e739a30
[ "Markdown", "TypeScript", "HTML" ]
6
TypeScript
pedroCX486/noizee
4b228b93b1462a7d0d4b69c8ebb7196ee6d13652
9c1a676c2a7f1023e881d9039662b03a004cd3b9
refs/heads/master
<file_sep>package construct_binary_tree_from_inorder_and_postorder_traversal import ( "fmt" ) const ( ) type TreeNode struct { leftNode *TreeNode rightNode *TreeNode value int } func BuildTree(preOrder []int, inOrder []int)(root *TreeNode){ if len(preOrder) != len(inOrder) { panic("The number "+len(preOder) +" of preorder "+preOrder+" doesn't match the number "+ len(inOrder) +" of "+inOrder) } if len(preOrder) == 0{ return nil } orderMap := OrderMap(inOrder) ValueOfRoot := preOrder[0] pos,ok := ordermap[ValueOfRoot] if !ok { panic("Failed to find the root"+ValueOfRoot +" in perorder") } leftSubTree_inOrder := inOrder[0:pos] leftSubTree_preOrder := preOrder[1: 2+ len(leftSubTree_inOrder)] rightSubTree_inOrder := make([]int,0) if pos != len(inOrder) - 1{ rightSubTree_inOrder = inOrder[pos+1:len(inOrder)] } rightSubTree_preOrder := make([]int,0) if 2+ len(leftSubTree_inOrder) < len(preOrder){ rightSubTree_preOrder = preOrder[2+ len(leftSubTree_inOrder):len(preOrder)] } root = &TreeNode{leftNode: BuildTree(leftSubTree_preOrder, leftSubTree_inOrder), rightNode: BuildTree(rightSubTree_preOrder, rightSubTree_inOrder), value: ValueOfRoot} return root } /**Map the order as [value]i */ func OrderMap(order []int) (orderMap map[int]int){ orderMap = make(map[int]int, len(order)) for i, v := order { orderMap[v]=i } return orderMap }<file_sep>package search_insert_position_35 import ( "testing" . "github.com/smartystreets/goconvey/convey" ) func Test_SearchInsertTarget(t *testing.T) { Convey("Search Insert Target Test", t , func(){ Convey("compare [1,3,5,6], 5 → 2", func(){ pos := SearchInsertTarget([]int{1,3,5,6}, 5) So(pos, ShouldEqual, 2) }) Convey("compare [1,3,5,6], 3 → 2", func(){ pos := SearchInsertTarget([]int{1,3,5,6}, 5) So(pos, ShouldEqual, 2) }) Convey("compare [1,3,5,6], 4 → 2", func(){ pos := SearchInsertTarget([]int{1,3,5,6}, 4) So(pos, ShouldEqual, 2) }) Convey("compare [1,3,5,6], 2 → 1", func(){ pos := SearchInsertTarget([]int{1,3,5,6}, 2) So(pos, ShouldEqual, 1) }) Convey("compare [1,3,5,6], 7 → 4", func(){ pos := SearchInsertTarget([]int{1,3,5,6}, 7) So(pos, ShouldEqual, 4) }) Convey("compare [1,3,5,6], 0 → 0 ", func(){ pos := SearchInsertTarget([]int{1,3,5,6}, 0) So(pos, ShouldEqual, 0) }) Convey("compare [1,3,5,6], 6 → 3 ", func(){ pos := SearchInsertTarget([]int{1,3,5,6}, 6) So(pos, ShouldEqual, 3) }) }) } <file_sep>package merge_sorted_array_88 import ( "testing" . "github.com/smartystreets/goconvey/convey" ) func Test_MergeSortedArray(t *testing.T) { Convey("Merge Sorted Array", t, func(){ Convey("Merge Sorted Array 1", func(){ result := MergeSortedArray([]int{1,3,5,7,9,0,0,0,0,0},5, []int{2,4,6,8,10},5) So(result, ShouldResemble, []int{1,2,3,4,5,6,7,8,9,10}) }) Convey("Merge Sorted Array 2", func(){ result := MergeSortedArray([]int{1,3,5,7,0,0,0,0,0,0},4, []int{2,4,6,8,9,10},6) So(result, ShouldResemble, []int{1,2,3,4,5,6,7,8,9,10}) }) }) } <file_sep>package add_two_numbers_002 import ( "testing" . "github.com/smartystreets/goconvey/convey" ) func Test_AddTwoNumbers(t *testing.T) { Convey("Add two numbers", t, func() { ln1 := &linkedNode{ value: 2, next: &linkedNode{ value: 4, next: &linkedNode{ value: 3, }, }, } l1 := linkedList{first: ln1} ln2 := &linkedNode{ value: 5, next: &linkedNode{ value: 6, next: &linkedNode{ value: 4, }, }, } l2 := linkedList{first: ln2} list := AddTwoNumbers(l1, l2) node := list.first So(node.value, ShouldEqual, 7) So(node.next, ShouldNotBeNil) node = node.next So(node.value, ShouldEqual, 0) So(node.next, ShouldNotBeNil) node = node.next So(node.value, ShouldEqual, 8) So(node.next, ShouldBeNil) }) } <file_sep>package search_for_a_range_34 import ( ) func SearchRange(array []int, target int) (result []int){ mid := len(array)/2 start := 0 end := len(array) - 1 result = []int{-1, -1} for mid>start && mid<end { if array[mid] > target{ end = mid -1 }else{ start = mid } mid = start + (end - start)/2 } switch target { case array[start]: if start - 1 >= 0 && array[start - 1] == target{ result[0] = start -1 result[1] = start } else if start + 1 < len(array) && array[start+1] == target{ result[0] = start result[1] = start + 1 }else{ result[0] = start } case array[end]: if end + 1 < len(array) && array[end+1] == target { result[0] = end result[1] = end + 1 }else if end - 1 < len(array) && array[end -1] == target{ result[0] = end - 1 result[1] = end }else{ result[0] = end } } return }<file_sep>package add_two_numbers_002 import ( "fmt" ) type linkedNode struct { value int next *linkedNode } type linkedList struct { first *linkedNode } func (l *linkedList) printList() { node := l.first for node != nil { fmt.Println(node) node = node.next } fmt.Println("=============================") return } // https://leetcode.com/problems/add-two-numbers/ func AddTwoNumbers(listA, listB linkedList) linkedList { var listC linkedList = linkedList{&linkedNode{-1, nil}} // the pointer for list C var currentC *linkedNode = listC.first nodeA := listA.first nodeB := listB.first vCNext := 0 for nodeA != nil || nodeB != nil { vA := 0 vB := 0 if nodeA != nil { vA = nodeA.value } if nodeB != nil { vB = nodeB.value } valueC := (vA + vB + vCNext) % 10 vCNext = (vA + vB + vCNext) / 10 if listC.first.value == -1 { (*currentC).value = valueC } else { temp := &linkedNode{value: valueC, next: nil} (*currentC).next = temp currentC = temp } nodeA = nodeA.next nodeB = nodeB.next } return listC } <file_sep>package find_minimum_in_rotated_sorted_array_153 func FindMin(nums []int) (min int) { mid := len(nums) / 2 array := nums for mid > 0 && mid+1 < len(array) { num_1 := smaller(array[0], array[mid]) num_2 := smaller(array[mid+1], array[len(array)-1]) if num_1 < num_2 { array = array[:mid+1] } else { array = array[mid+1:] } mid = len(array) / 2 } if mid == 0 { min = array[mid] } else { min = smaller(array[0], array[mid]) } return min } func smaller(a, b int) (v int) { v = a if a > b { v = b } return } <file_sep>package find_minimum_in_rotated_sorted_array_153 import ( "testing" . "github.com/smartystreets/goconvey/convey" ) func Test_FindMin(t *testing.T) { Convey("Find MIN", t , func(){ Convey("Find MIN in sorted array", func(){ num := FindMin([]int{0,1,2,3,4,5,6,7,8,9,10}) So(num, ShouldEqual, 0) }) Convey("Find MIN in rotated sorted array1", func(){ num := FindMin([]int{6,7,8,9,10,0,1,2,3,4,5}) So(num, ShouldEqual, 0) }) Convey("Find MIN in rotated sorted array2", func(){ num := FindMin([]int{1,2,3,4,5,6,7,8,9,10,0}) So(num, ShouldEqual, 0) }) }) } <file_sep>package plus_one_66 import ( "testing" . "github.com/smartystreets/goconvey/convey" ) func Test_PlusOne(t *testing.T) { Convey("Plus One", t, func() { Convey("Plus One without carry-over", func() { result := PlusOne([]int{1, 2, 3, 4, 5}) expect_data := []int{1, 2, 3, 4, 6} So(expect_data[0], ShouldEqual, result[0]) So(expect_data[1], ShouldEqual, result[1]) So(expect_data[2], ShouldEqual, result[2]) So(expect_data[3], ShouldEqual, result[3]) So(expect_data[4], ShouldEqual, result[4]) }) Convey("Plus One with carry-over", func() { result := PlusOne([]int{9, 9, 9, 9}) expect_data := []int{1, 0, 0, 0, 0} So(expect_data[0], ShouldEqual, result[0]) So(expect_data[1], ShouldEqual, result[1]) So(expect_data[2], ShouldEqual, result[2]) So(expect_data[3], ShouldEqual, result[3]) So(expect_data[4], ShouldEqual, result[4]) }) }) } <file_sep>package maximum_depth_of_binary_tree_104 import ( "math" ) type BinaryTreeNode struct{ value int left *BinaryTreeNode right *BinaryTreeNode } func MaxDepth(root *BinaryTreeNode) int{ if root == nil ||(root.left == nil && root.right == nil){ return 0 }else{ return math.Max(MaxDepth(root.left) + 1, MaxDepth(root.right) + 1 ) } }<file_sep>package remove_duplicates_from_sorted_array_26 import ( "testing" . "github.com/smartystreets/goconvey/convey" ) func Test_RemoveDuplicates(t *testing.T) { Convey("remove Duplicated", t, func() { length := RemoveDuplicates([]int{1,1,2}) So(length, ShouldEqual, 2) }) } func Test_RemoveDuplicates1(t *testing.T) { Convey("remove Duplicated 1", t, func() { length := RemoveDuplicates([]int{1,1,2,3,3}) So(length, ShouldEqual, 3) }) }<file_sep>package remove_element_27 import ( . "github.com/smartystreets/goconvey/convey" "testing" ) func Test_RemoveElement(t *testing.T) { Convey("remove elements", t, func() { length := RemoveElement([]int{2, 7, 11, 15}, 9) So(length, ShouldEqual, 4) }) } func Test_RemoveElement1(t *testing.T) { Convey("remove elements", t, func() { length := RemoveElement([]int{1, 2, 7, 9, 11, 15}, 9) So(length, ShouldEqual, 5) }) } func Test_RemoveElement2(t *testing.T) { Convey("remove elements", t, func() { length := RemoveElement([]int{1, 9, 9, 9, 11, 9}, 9) So(length, ShouldEqual, 2) }) } <file_sep>package remove_element_27 import () func RemoveElement(array []int, value int) (currentLen int) { var startPos int = 0 for startPos < len(array) { if array[startPos] != value { currentLen++ } startPos++ } return } <file_sep>package search_for_a_range_34 import ( "testing" . "github.com/smartystreets/goconvey/convey" ) func Test_SearchRange(t *testing.T) { Convey("Search Range ", t, func(){ Convey("Search Range middle", func(){ result := SearchRange([]int{5, 7, 7, 8, 8, 10}, 8) So(result, ShouldResemble, []int{3,4}) }) Convey("Search Range 2", func(){ result := SearchRange([]int{5, 7, 7, 8, 8, 10}, 5) So(result, ShouldResemble, []int{0,-1}) }) Convey("Search Range 3", func(){ result := SearchRange([]int{5, 7, 7, 8, 8, 10}, 7) So(result, ShouldResemble, []int{1,2}) }) }) } <file_sep>package merge_sorted_array_88 //package main import ( "fmt" ) func main(){ fmt.Println(MergeSortedArray([]int{1,3,5,7,9,0,0,0,0,0},5, []int{2,4,6,8,10},5)) fmt.Println(MergeSortedArray([]int{1,3,5,7,0,0,0,0,0,0},4, []int{2,4,6,8,9,10},6)) } /** *Given two sorted integer arrays nums1 and nums2, merge nums2 into nums1 as one sorted array. */ func MergeSortedArray(nums1 []int, m int, nums2 []int, n int) []int { pos1 := m - 1 pos2 := n - 1 i := n+m-1 for i > -1 { if pos2 < 0 { break }else if pos1 < 0{ copy(nums1[0:], nums2[0:pos2+1]) break } if nums1[pos1] > nums2[pos2]{ nums1[i] = nums1[pos1] pos1 -- }else{ nums1[i] = nums2[pos2] pos2 -- } i-- } return nums1 } <file_sep>package plus_one_66 import ( ) func PlusOne(input []int) []int { carry := 1 var output []int = make([]int, len(input) + 1) copy(output[1:], input) for i := len(input) - 1; i > -1; i-- { value := input[i] + carry if value >= 10 { carry = 1 output[i+1] = value - 10 } else { carry = 0 output[i+1] = value break } } var result []int if carry == 1 { output[0] = 1 result = output[:] } else { result = output[1:] } return result } <file_sep>package two_sum_001 import ( "errors" "strconv" ) //O(2n) func TwoSum(array []int, target int) ([2]int, error) { indexes := [2]int{-1, -1} found := false for i, v := range array { search_v := target - v if pos, e := contain(array, search_v); e == nil { indexes[0] = i + 1 indexes[1] = pos + 1 found = true break } } if found { return indexes, nil } else { return indexes, errors.New("Not found two sum to equal " + strconv.Itoa(target)) } } func contain(array []int, value int) (int, error) { found := false pos := -1 for i, v := range array { if v == value { pos = i found = true break } } if found { return pos, nil } else { return pos, errors.New("Failed to find " + strconv.Itoa(value) + " in array ") } } <file_sep>package longest_substring_without_repeating_characters_003 import ( "testing" . "github.com/smartystreets/goconvey/convey" ) func Test_lengthOfLongestSubstring(t *testing.T) { Convey("longest substring 1", t , func(){ strs,length := lengthOfLongestSubstring("abcabcbb") So(length, ShouldEqual, 3) So(len(strs), ShouldEqual, "abc") So(strs[0], ShouldEqual, "abc") So(strs[1], ShouldEqual, "bca") So(strs[2], ShouldEqual, "cab") }) Convey("longest substring 2", t , func(){ strs,length := lengthOfLongestSubstring("bbbbb") So(length, ShouldEqual, 1) So(strs[0], ShouldEqual, "b") }) } <file_sep>package remove_duplicates_from_sorted_array_26 import ( "fmt" ) func RemoveDuplicates(array []int) (length int){ if array == nil|| len(array) == 0 { return } pos := 0 currentValue := array[0] length = 1 for pos < len(array){ if array[pos] != currentValue { length ++ currentValue = array[pos] } pos ++ } return } <file_sep>package remove_duplicates_from_sorted_array_ii_80 import ( ) func RemoveDuplicates(array []int)(length int){ if array == nil || len(array) ==0{ return 0 } duplicateMap := make(map[int]int, len(array)) pos := 0 for pos < len(array){ if v, ok := duplicateMap[array[pos]]; ok{ v++ if v <= 2{ length ++ } duplicateMap[array[pos]] = v }else{ duplicateMap[array[pos]] = 1 length ++ } pos ++ } return }<file_sep>package two_sum_001_optimzed import ( "errors" "strconv" ) // https://leetcode.com/problems/two-sum/ // O(n) func TwoSum(array []int, target int) ([2]int, error) { indexes := [2]int{-1, -1} found := false search_map := make(map[int]int, len(array)) for i, v := range array { search_map[v]=i + 1 } for k, v := range search_map{ another_k := target - k if another_v, ok := search_map[another_k]; ok { if (another_v > v){ indexes[0] = v indexes[1] = another_v }else{ indexes[0] = another_v indexes[1] = v } found = true break } } if found { return indexes, nil } else { return indexes, errors.New("Not found two sum to equal " + strconv.Itoa(target)) } } func contain(array []int, value int) (int, error) { found := false pos := -1 for i, v := range array { if v == value { pos = i found = true break } } if found { return pos, nil } else { return pos, errors.New("Failed to find " + strconv.Itoa(value) + " in array ") } } <file_sep>package two_sum_001_optimzed import ( "testing" . "github.com/smartystreets/goconvey/convey" ) func Test_TwoSum(t *testing.T) { Convey("Add Two Sum", t , func(){ if idxs,e := TwoSum([]int{2, 7, 11, 15}, 9); e != nil{ So(e, ShouldBeNil) So(idxs[0], ShouldEqual, 1) So(idx[1], ShouldEqual, 2) } }) } }<file_sep># leetcode.go My Golang solutions to https://leetcode.com/ <file_sep>package remove_duplicates_from_sorted_array_ii_80 import ( "testing" . "github.com/smartystreets/goconvey/convey" ) func Test_RemoveDuplicates(t *testing.T) { Convey("remove elements", t, func() { Convey("remove elements with duplicate data", func(){ length := RemoveDuplicates([]int{1,1,1,2,2,3}) So(length, ShouldEqual, 5) }) Convey("remove elements without duplicate data", func(){ length := RemoveDuplicates([]int{1,2,3}) So(length, ShouldEqual, 3) }) }) } <file_sep>package search_insert_position_35 import ( // "fmt" ) func SearchInsertTarget(nums []int, target int) (pos int) { pos = -1 start := 0 end := len(nums) - 1 mid := (start + end) / 2 i := 0 for end > start { // fmt.Println(i, "start:", start, ",value:", nums[start], ", end:", end, ",value:",nums[end],", mid:", mid,",value:",nums[mid], "target:", target) if nums[mid] == target{ return mid } if nums[mid] > target{ end = mid -1 }else{ start = mid + 1 } mid = (start + end) / 2 } if nums[start] < target{ pos = start + 1 }else{ pos = start } return pos } <file_sep>package longest_substring_without_repeating_characters_003 import ( "fmt" "strconv" ) type LongSubstring struct { start, end, length int } //https://leetcode.com/problems/longest-substring-without-repeating-characters/ func lengthOfLongestSubstring(str string) (longestStrs []string, longestLength int) { longestStrs = make([]string, 1, len(str)) // key is byte, value is last pos during iterate word_map := make(map[byte]int, len(str)) var longestSubstringSlice []LongSubstring = make([]LongSubstring, 1) strSlice := []byte(str) fmt.Println(strSlice) startPos := 0 endPos := 0 for i, k := range strSlice { fmt.Println("For order ", i, " value k", string(k)) if v, ok := word_map[k]; ok { fmt.Println("found last pos of word_map [", string(k), "] is ", strconv.Itoa(v)) // if the duplicate element is between current startPos and endPos, then the current length of the no duplicate substring is endPos - startpos + 1 if startPos <= v { var substringCandidate LongSubstring if strSlice[startPos] == strSlice[endPos] && startPos != endPos { substringCandidate = LongSubstring{start: startPos, end: endPos - 1, length: endPos - startPos} } else { substringCandidate = LongSubstring{start: startPos, end: endPos, length: endPos - startPos + 1} } fmt.Println(string(strSlice[substringCandidate.start : substringCandidate.end+1])) if substringCandidate.length > longestLength { longestSubstringSlice = make([]LongSubstring, 1) longestSubstringSlice[0] = substringCandidate longestLength = substringCandidate.length fmt.Println("Make longestSubstringSlice: ", longestSubstringSlice, " with the length ",strconv.Itoa(longestLength) ) } else if substringCandidate.length == longestLength { longestSubstringSlice = append(longestSubstringSlice, substringCandidate) fmt.Println("Append ", string(strSlice[substringCandidate.start : substringCandidate.end+1])) } startPos = v + 1 } if len(str)-startPos < longestLength { break } } else { fmt.Println("Not found value of word_map [", string(k), "]") } word_map[k] = i endPos = i } encountered := map[string]bool{} for _, longestSubstring := range longestSubstringSlice { tempStr := string(strSlice[longestSubstring.start : longestSubstring.end+1]) if _, ok := encountered[tempStr]; ok == false { longestStrs = append(longestStrs, tempStr) encountered[tempStr] = true } } return longestStrs, longestLength }
548642bbcb5ec49b84ad8678ce3277a5edd681aa
[ "Markdown", "Go" ]
26
Go
cheyang/leetcode.go
5a37c829b9f5c8ab51929170a5473a562acb10fe
8e1178d72c6590c1c3bd234d8a90f891ecbcbd26
refs/heads/master
<repo_name>ishawakankar/CircleCI-Github<file_sep>/test/test.js /* eslint import/no-unresolved: 0 */ /* global it describe beforeEach: true */ const chai = require('chai'); chai.should(); const supertest = require('supertest'); const chaiHttp = require('chai-http'); const serverObject = require('../server'); const { app } = serverObject; chai.use(chaiHttp); const request = supertest(app); describe('Test server routes:', () => { beforeEach(() => { }); it('Home route', (done) => { request.get('/') .end((err, res) => { if (err) throw err; // console.log(res.text); res.should.status(200); done(); }); }); it('Dash route', (done) => { request.get('/dash') .end((err, res) => { if (err) throw err; // console.log(res.text); res.should.status(200); done(); }); }); it('Exit test cases', (done) => { process.exit(); done(); }) // it('Undefined route', (done) => { // request.get('/random') // .end((err, res) => { // if (err) throw err; // res.should.status(200); // done(); // }); // }); }); <file_sep>/README.md # CircleCI-Github <b> Continuous Integration: </b> - Write a .circleci/config.yml file. - Signup on CircleCI using Github. - Add project > Set up project > Start building. <file_sep>/server.js /* eslint import/no-unresolved: 0 */ const express = require('express'); const app = express(); app.listen(5000, () => { console.log('App listening on port 5000'); }); app.get('/', (req, res) => { res.send('On Home'); }); app.get('/dash', (req, res) => { res.send('On Dashboard'); }); module.exports.app = app;
0641820c529fde3f246746751f9195ae7e6093d7
[ "JavaScript", "Markdown" ]
3
JavaScript
ishawakankar/CircleCI-Github
447645d81a4af6b41c3d072f4f6e748262d1c619
f3264d42f52176b072448eedd6c38c5c3ff935d8
refs/heads/master
<file_sep>import React from 'react'; import { ThemeProvider } from 'styled-components'; // Responsável por receber o tema que configuramos globalmente e disponiblizá-lo para toda aplicação import { Reset } from 'styled-reset'; import Home from './pages/Home'; import theme from './theme'; function App() { return ( <ThemeProvider theme={theme}> <Reset /> <Home /> </ThemeProvider> ); } export default App;
0be2407c1159037948158d7c13ae21a807158b48
[ "JavaScript" ]
1
JavaScript
guilherme25alves/restaurants-search
0b334b62c189bcec02bc10e425d3c2096616be23
47662eab274f387e0f83e7e160bb22edc6897dbe
refs/heads/master
<repo_name>orbitwhitex/sfdclearning<file_sep>/app/controllers/accounts_controller.rb class AccountsController < ApplicationController def index client = Restforce.new(username: ENV['SALESFORCE_USERNAME'], password: ENV['<PASSWORD>'], security_token: ENV['SALESFORCE_SECURITY_TOKEN'], client_id: ENV['SALESFORCE_CLIENT_ID'], client_secret: ENV['SALESFORCE_CLIENT_SECRET'], api_version: ENV['SALESFORCE_API_VERSION']) @accounts = client.query_all("select name FROM Account") end def show end end
9b2abb9f58b2e954acdece96be331a8012d0479d
[ "Ruby" ]
1
Ruby
orbitwhitex/sfdclearning
d1c6a70d782d119fe8f7aee8df189067670972c9
fd8f299b546199fd8133aa0beac02e81dddcf94a
refs/heads/development
<repo_name>erezfree29/Tic_Tac_toe<file_sep>/spec/player_spec.rb require_relative '../lib/player' describe Player do describe 'create player' do it 'check that a player can be created with a name and a symbol' do player = Player.new('David', 'X') expect(player.name).to eql('David') expect(player.symbol).to eql('X') end end end <file_sep>/README.md # Tic-Tac-Toe ![tictactoe-example](https://cdn.pixabay.com/photo/2017/02/25/10/53/board-2097446_1280.jpg) ## Built With - Ruby - Vscode - Rubocop ## How to Play 'Tic Tac Toe' is a traditional game for two players played on a board with 9 squares. Each player is represented by a symbol, either 'X' or 'O'. The players then take turns to place their respective symbols in an empty square on the board, with O's going first - in our version of the game, these squares are represented by the numbers 1 to 9. The aim of the game is to have three of your symbols form a line, be it vertically, horizontally or diagonally, as illustrated in the image below. In the event that all 9 squares are taken without either player getting three of their symbols in a line, a draw is declared. ## Runing the TEST instructions Install -After installing RSpec, run gem install terminal-table Test -In order to run the test on the table file the user need to install the terminal-table gem on his local machine. -To run the tests just type rspec. ### Prerequisites If you intend to download the project, you will need to have Ruby already installed on your machine. For more information on how to install Ruby, follow [this link](https://www.ruby-lang.org/en/downloads/). ### Installation Instructions To get your own copy of our project simply clone the repository to your local machine. **Step 1**: Using the Command Line, navigate into the location where you would like to have the repository. Then enter the following line of code: ``` `git clone https://github.com/erezfree29/Ruby-code2.git ``` **Step 2**: Once the repo has been cloned, navigate inside it by entering the following command: `cd Ruby-code2` **Step 3**: Once in the root directory of the repository, simply enter the following line of code to start a game: `bin/main` From there, the game will begin, and the user need only follow the subsequent instructions that appear in the Terminal. ## Repository Contents The code for the project is divided into two main directories: **./bin** and **./lib**. The **./bin** folder contains the executable **main.rb** file. This is the only file that contains the Kernel.puts and Kernel.gets methods, allowing for interaction with the game via the Terminal. _This is the only file that should be run if you want to play the game._ The **./lib** folder contains subsidiary files that set up all of the classes and methods used in bin/main.rb - **player.rb**, where the Player class is defined. - **board.rb**, where the Board class is defined. In addition to the above, the repo also contains .rubocop.yml for linting. ## ✒️ Author <a name = "author"></a> 👤 **<NAME>** - Github: [@erezfree29](https://github.com/erezfree29) - Linkedin: [<NAME>](https://www.linkedin.com/in/mert-gunduz-875280202/) 👤 **<NAME>** - GitHub: [@CollinsTatang](https://github.com/CollinsTatang) - Twitter: [@CollinsTatang1](https://twitter.com/CollinsTatang1) - LinkedIn: [makungong-collins](https://www.linkedin.com/in/makungong-collins-b43260190/) ## Show your support ⭐️⭐️ If you've read this far....give a star to this project ⭐️! ## 📝 License This project has no licence. <file_sep>/bin/main #!/usr/bin/env ruby require_relative '../lib/player' require_relative '../lib/board' require 'bundler/inline' gemfile do source 'https://rubygems.org' gem 'colorize', '~> 0.8.1' end def introduction print 'Hello welcome to the game <NAME> '.light_magenta puts 'Would you like to play a new game? press y if you do'.light_magenta start = gets.chomp until start.casecmp('y').zero? puts 'press y if you want to play'.light_magenta start = gets.chomp end end def player_name puts 'Hello please enter your name'.light_magenta name = gets.chomp.capitalize until name.match?(/\A[a-zA-Z'-]*\z/) puts 'please enter a valid name which includes only letters'.red name = gets.chomp end name end def player_symbol puts '1)press 1 to play as X'.blue puts '2)press 2 to play as O'.blue selection = gets.chomp while selection != '1' && selection != '2' puts 'wrong selection please re-enter'.red selection = gets.chomp end selection == '1' ? 'X' : 'O' end def presentation(player1, player2) puts "#{player1.name} will be start the game and will be playing with the #{player1.symbol}'s" puts "#{player2.name} will play second and will be playing with the #{player2.symbol}'s" end def choose_number(board, player) available = board.square.select { |element| element.instance_of?(Integer) } puts "#{player.name} Please choose a an available cell avilable cells are cells number" available.each { |cell| print "#{cell} " } puts number = gets.chomp.to_i until number.between?(1, 9) puts 'wrong entery please re-enter'.red number = gets.chomp.to_i end until board.square[number - 1] == number puts 'the cell is taken please re-enter' number = gets.chomp.to_i end board.square[number - 1] = player.symbol end introduction name = player_name symbol = player_symbol player1 = Player.new(name, symbol) name = player_name symbol = symbol == 'X' ? 'O' : 'X' player2 = Player.new(name, symbol) presentation(player1, player2) tic_tac_toe_board = Board.new tic_tac_toe_table = tic_tac_toe_board.create_table puts tic_tac_toe_table while !tic_tac_toe_board.victory && !tic_tac_toe_board.draw choose_number(tic_tac_toe_board, player1) tic_tac_toe_table = tic_tac_toe_board.create_table puts tic_tac_toe_table if tic_tac_toe_board.victory puts "#{player1.name} has won" break elsif tic_tac_toe_board.draw puts "it's a draw" break end choose_number(tic_tac_toe_board, player2) tic_tac_toe_table = tic_tac_toe_board.create_table puts tic_tac_toe_table if tic_tac_toe_board.victory puts "#{player2.name} has won" break elsif tic_tac_toe_board.draw puts "it's a draw" break end end <file_sep>/lib/table.rb require 'terminal-table' module Table def create_table Terminal::Table.new do |t| t << [square[0], square[1], square[2]] t << :separator t.add_row [square[3], square[4], square[5]] t.add_separator t.add_row [square[6], square[7], square[8]] t.style = { border_top: false, border_bottom: false, border_left: false, border_right: false } end end end <file_sep>/spec/table_spec.rb require_relative '../lib/board' require_relative '../lib/table' describe Table do describe 'create table' do it 'check that a table is created correctly in accordance with the board' do board = Board.new board.square[0] = 'O' board.square[1] = 'O' board.square[2] = 'X' board.square[3] = 'O' board.square[4] = 'X' board.square[5] = 'O' board.square[6] = 'O' board.square[7] = 'X' board.square[8] = 1 table = board.create_table expect { print table }.to output(" O | O | X\n---+---+---\n O | X | O\n---+---+---\n O | X | 1").to_stdout end end end <file_sep>/spec/board_spec.rb require_relative '../lib/board' describe Board do describe 'create board with square' do it 'check that a board with a square is created' do board = Board.new expect(board.square).to eql([1, 2, 3, 4, 5, 6, 7, 8, 9]) end end describe 'victory' do it 'check that the method returns true when condition one is met' do board = Board.new board.square[0] = 'X' board.square[1] = 'X' board.square[2] = 'X' expect(board.victory).to be true end it 'check that the method returns false when condition one is not met' do board = Board.new board.square[0] = 'O' board.square[1] = 'X' board.square[2] = 'X' expect(board.victory).to be false end it 'check that the method returns true when condition two is met' do board = Board.new board.square[0] = 'O' board.square[3] = 'O' board.square[6] = 'O' expect(board.victory).to be true end it 'check that the method returns false when condition two is not met' do board = Board.new board.square[0] = 'X' board.square[3] = 'O' board.square[6] = 'O' expect(board.victory).to be false end it 'check that the method returns true when condition three is met' do board = Board.new board.square[0] = 'O' board.square[4] = 'O' board.square[8] = 'O' expect(board.victory).to be true end it 'check that the method returns false when condition three is not met' do board = Board.new board.square[0] = 'X' board.square[4] = 'O' board.square[8] = 'O' expect(board.victory).to be false end it 'check that the method returns true when condition four is met' do board = Board.new board.square[1] = 'X' board.square[4] = 'X' board.square[7] = 'X' expect(board.victory).to be true end it 'check that the method returns false when condition four is not met' do board = Board.new board.square[1] = 'O' board.square[4] = 'X' board.square[7] = 'X' expect(board.victory).to be false end it 'check that the method returns true when condition five is met' do board = Board.new board.square[2] = 'X' board.square[5] = 'X' board.square[8] = 'X' expect(board.victory).to be true end it 'check that the method returns false when condition five is not met' do board = Board.new board.square[2] = 'O' board.square[5] = 'X' board.square[8] = 'X' expect(board.victory).to be false end it 'check that the method returns true when condition six is met' do board = Board.new board.square[2] = 'X' board.square[4] = 'X' board.square[6] = 'X' expect(board.victory).to be true end it 'check that the method returns false when condition six is not met' do board = Board.new board.square[2] = 'X' board.square[4] = 'O' board.square[6] = 'X' expect(board.victory).to be false end it 'check that the method returns true when condition seven is met' do board = Board.new board.square[3] = 'X' board.square[4] = 'X' board.square[5] = 'X' expect(board.victory).to be true end it 'check that the method returns false when condition seven is not met' do board = Board.new board.square[3] = 'X' board.square[4] = 'X' board.square[5] = 'O' expect(board.victory).to be false end it 'check that the method returns true when condition eight is met' do board = Board.new board.square[6] = 'X' board.square[7] = 'X' board.square[8] = 'X' expect(board.victory).to be true end it 'check that the method returns false when no condition eight is not met' do board = Board.new board.square[6] = 'O' board.square[7] = 'X' board.square[8] = 'X' expect(board.victory).to be false end end describe 'draw' do it 'check that method returns true when board is full of symbols' do board = Board.new board.square[0] = 'O' board.square[1] = 'O' board.square[2] = 'X' board.square[3] = 'O' board.square[4] = 'X' board.square[5] = 'O' board.square[6] = 'O' board.square[7] = 'X' board.square[8] = 'X' expect(board.draw).to be true end it 'check that method returns false when board has a number on it' do board = Board.new board.square[0] = 'O' board.square[1] = 'O' board.square[2] = 'X' board.square[3] = 'O' board.square[4] = 'X' board.square[5] = 'O' board.square[6] = 3 board.square[7] = 2 board.square[8] = 1 expect(board.draw).to be false end end end <file_sep>/lib/board.rb # rubocop: disable Metrics/PerceivedComplexity, Metrics/CyclomaticComplexity # there is one board with 9 squares require_relative '../lib/table' class Board include Table attr_reader :square def initialize @square = [1, 2, 3, 4, 5, 6, 7, 8, 9] end def condition1 @square[0] == @square[1] && @square[0] == @square[2] ? true : false end def condition2 @square[0] == @square[3] && @square[0] == @square[6] ? true : false end def condition3 @square[0] == @square[4] && @square[0] == @square[8] ? true : false end def condition4 @square[1] == @square[4] && @square[1] == @square[7] ? true : false end def condition5 @square[2] == @square[5] && @square[2] == @square[8] ? true : false end def condition6 @square[2] == @square[4] && @square[2] == @square[6] ? true : false end def condition7 @square[3] == @square[4] && @square[3] == @square[5] ? true : false end def condition8 @square[6] == @square[7] && @square[6] == @square[8] ? true : false end def victory if (condition1 || condition2) || (condition3 || condition4) || (condition5 || condition6) || (condition7 || condition8) return true end false end def draw @square.each do |val| return false if val.is_a? Integer end true end end # rubocop: enable Metrics/PerceivedComplexity, Metrics/CyclomaticComplexity
8d74f9f61e5f906eabacf7f23cc3cc8e862c7299
[ "Markdown", "Ruby" ]
7
Ruby
erezfree29/Tic_Tac_toe
452005382c9f47bebe50b128907d66d797adaa3e
febeec38f46a733d0d9d7fe1523c798431452f79
refs/heads/master
<repo_name>linfeique/UserAPI<file_sep>/UserAPI/Controllers/TipoUsuarioPermissao01Controller.cs using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc; using Microsoft.EntityFrameworkCore; using UserAPI.Domains; namespace UserAPI.Controllers { [Route("api/[controller]")] [ApiController] public class TipoUsuarioPermissao01Controller : ControllerBase { private readonly UserContext _context; public TipoUsuarioPermissao01Controller(UserContext context) { _context = context; } // GET: api/TipoUsuarioPermissao01 [HttpGet] public IEnumerable<TipoUsuarioPermissao01> GetTipoUsuarioPermissao01() { return _context.TipoUsuarioPermissao01; } // GET: api/TipoUsuarioPermissao01/5 [HttpGet("{id}")] public async Task<IActionResult> GetTipoUsuarioPermissao01([FromRoute] int id) { if (!ModelState.IsValid) { return BadRequest(ModelState); } var tipoUsuarioPermissao01 = await _context.TipoUsuarioPermissao01.FindAsync(id); if (tipoUsuarioPermissao01 == null) { return NotFound(); } return Ok(tipoUsuarioPermissao01); } // PUT: api/TipoUsuarioPermissao01/5 [HttpPut("{id}")] public async Task<IActionResult> PutTipoUsuarioPermissao01([FromRoute] int id, [FromBody] TipoUsuarioPermissao01 tipoUsuarioPermissao01) { if (!ModelState.IsValid) { return BadRequest(ModelState); } if (id != tipoUsuarioPermissao01.Id) { return BadRequest(); } _context.Entry(tipoUsuarioPermissao01).State = EntityState.Modified; try { await _context.SaveChangesAsync(); } catch (DbUpdateConcurrencyException) { if (!TipoUsuarioPermissao01Exists(id)) { return NotFound(); } else { throw; } } return NoContent(); } // POST: api/TipoUsuarioPermissao01 [HttpPost] public async Task<IActionResult> PostTipoUsuarioPermissao01([FromBody] TipoUsuarioPermissao01 tipoUsuarioPermissao01) { if (!ModelState.IsValid) { return BadRequest(ModelState); } _context.TipoUsuarioPermissao01.Add(tipoUsuarioPermissao01); await _context.SaveChangesAsync(); return CreatedAtAction("GetTipoUsuarioPermissao01", new { id = tipoUsuarioPermissao01.Id }, tipoUsuarioPermissao01); } // DELETE: api/TipoUsuarioPermissao01/5 [HttpDelete("{id}")] public async Task<IActionResult> DeleteTipoUsuarioPermissao01([FromRoute] int id) { if (!ModelState.IsValid) { return BadRequest(ModelState); } var tipoUsuarioPermissao01 = await _context.TipoUsuarioPermissao01.FindAsync(id); if (tipoUsuarioPermissao01 == null) { return NotFound(); } _context.TipoUsuarioPermissao01.Remove(tipoUsuarioPermissao01); await _context.SaveChangesAsync(); return Ok(tipoUsuarioPermissao01); } private bool TipoUsuarioPermissao01Exists(int id) { return _context.TipoUsuarioPermissao01.Any(e => e.Id == id); } } }<file_sep>/UserAPI/Contexts/UserContext.cs using System; using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.Metadata; namespace UserAPI.Domains { public partial class UserContext : DbContext { public UserContext() { } public UserContext(DbContextOptions<UserContext> options) : base(options) { } public virtual DbSet<TipoUsuarioPermissao01> TipoUsuarioPermissao01 { get; set; } public virtual DbSet<TipoUsuarioPermissao02> TipoUsuarioPermissao02 { get; set; } public virtual DbSet<Usuarios> Usuarios { get; set; } protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) { optionsBuilder.UseSqlServer("Data Source=.\\SqlExpress01;Initial Catalog=UserAPI;User ID=sa;Password=<PASSWORD>"); } protected override void OnModelCreating(ModelBuilder modelBuilder) { modelBuilder.Entity<TipoUsuarioPermissao01>(entity => { entity.ToTable("TIPO_USUARIO_PERMISSAO01"); entity.HasIndex(e => e.Tipo) .HasName("UQ__TIPO_USU__B6FCAAA2AC4AA431") .IsUnique(); entity.Property(e => e.Id).HasColumnName("ID"); entity.Property(e => e.Tipo) .IsRequired() .HasColumnName("TIPO") .HasMaxLength(150) .IsUnicode(false); }); modelBuilder.Entity<TipoUsuarioPermissao02>(entity => { entity.ToTable("TIPO_USUARIO_PERMISSAO02"); entity.HasIndex(e => e.Tipo) .HasName("UQ__TIPO_USU__B6FCAAA2C1AF210C") .IsUnique(); entity.Property(e => e.Id).HasColumnName("ID"); entity.Property(e => e.Tipo) .IsRequired() .HasColumnName("TIPO") .HasMaxLength(150) .IsUnicode(false); }); modelBuilder.Entity<Usuarios>(entity => { entity.ToTable("USUARIOS"); entity.HasIndex(e => e.Email) .HasName("UQ__USUARIOS__161CF724F13B5C82") .IsUnique(); entity.Property(e => e.Id).HasColumnName("ID"); entity.Property(e => e.Email) .IsRequired() .HasColumnName("EMAIL") .HasMaxLength(150) .IsUnicode(false); entity.Property(e => e.Nome) .IsRequired() .HasColumnName("NOME") .HasMaxLength(150) .IsUnicode(false); entity.Property(e => e.Senha) .IsRequired() .HasColumnName("SENHA") .HasMaxLength(150) .IsUnicode(false); entity.Property(e => e.TipoUsuarioPermissao).HasColumnName("TIPO_USUARIO_PERMISSAO"); entity.Property(e => e.TipoUsuarioPermissaoAcesso).HasColumnName("TIPO_USUARIO_PERMISSAO_ACESSO"); entity.HasOne(d => d.TipoUsuarioPermissaoNavigation) .WithMany(p => p.Usuarios) .HasForeignKey(d => d.TipoUsuarioPermissao) .HasConstraintName("FK__USUARIOS__TIPO_U__5441852A"); entity.HasOne(d => d.TipoUsuarioPermissaoAcessoNavigation) .WithMany(p => p.Usuarios) .HasForeignKey(d => d.TipoUsuarioPermissaoAcesso) .HasConstraintName("FK__USUARIOS__TIPO_U__5535A963"); }); } } } <file_sep>/UserAPI/Domains/TipoUsuarioPermissao01.cs using System; using System.Collections.Generic; namespace UserAPI.Domains { public partial class TipoUsuarioPermissao01 { public TipoUsuarioPermissao01() { Usuarios = new HashSet<Usuarios>(); } public int Id { get; set; } public string Tipo { get; set; } public ICollection<Usuarios> Usuarios { get; set; } } } <file_sep>/UserAPI/Domains/Usuarios.cs using System; using System.Collections.Generic; namespace UserAPI.Domains { public partial class Usuarios { public int Id { get; set; } public string Nome { get; set; } public string Email { get; set; } public string Senha { get; set; } public int? TipoUsuarioPermissao { get; set; } public int? TipoUsuarioPermissaoAcesso { get; set; } public TipoUsuarioPermissao02 TipoUsuarioPermissaoAcessoNavigation { get; set; } public TipoUsuarioPermissao01 TipoUsuarioPermissaoNavigation { get; set; } } }
bff0f24edbe61eca0ffa737141d013c02dad80a6
[ "C#" ]
4
C#
linfeique/UserAPI
ec8101901e7578aa8115ba0c65031e69e8032e90
f8846d53b427291bfcb745708a6639b130066c94
refs/heads/main
<repo_name>Roberto-spec/practice-generics<file_sep>/src/main/java/org/itstep/step01/ObjectPairDriver.java package org.itstep.step01; import org.itstep.step01.exeption.*; /** * Класс для тестирования кортежа ObjectPair * * @author <NAME> * @version V1, 8/2016 */ public class ObjectPairDriver { /** * Создайте несколько пар стадионов, затем распечатайте название стадиона с наибольшей вместимостью. * * @param args Не используется */ public static void main(String[] args) throws StadiumException { ObjectPair[] stadiums = new ObjectPair[3]; stadiums[0] = new ObjectPair("Bridgeforth Stadium", 25000); stadiums[1] = new ObjectPair("Michigan Stadium", 109901); //stadiums[2] = new ObjectPair("Lane Stadium", "66,233"); System.out.println(stadiums[0]); System.out.println(largestStadium(stadiums)); // БОНУСНЫЙ ВОПРОС: Почему компилируется эта строка кода? // stadiums[0] = new ObjectPair("Bridgeforth Stadium", 25000); // БОНУСНЫЙ ОТВЕТ: ПОТОМУ ЧТО 25000 это Int и чтобы все сработал // нужно привести 25000 к Integer } /** * Возвращает название стадиона с наибольшей вместимостью. * * @param stadiums Массив ObjectPairs, где каждая пара содержит название стадиона, за которым следует целое число * @return Название стадиона с наибольшей вместимостью */ public static String largestStadium(ObjectPair[] stadiums) throws StadiumException { // TODO: реализуйте это метод в соответствии с комментариями if (stadiums==null||stadiums.length==0){ throw new EmptyArrayException("В данном массиве нет ни одного объекта"); } if(stadiums.length==1){ if(stadiums[0]==null){ throw new EmptyObjectException("В найденом объекте нет информации"); } return stadiums[0].getFirst().toString(); } int max=0; int index=-1; for(int i=0;i<stadiums.length;i++){ if(stadiums[i]==null){ continue; } if(stadiums[i].getSecond().getClass().getName()=="java.lang.Integer"){ if((int)(stadiums[i].getSecond())>max){ max=(int)(stadiums[i].getSecond()); index=i; } } else { throw new InvalidTypeException("Неподходящий тип данных"); } } if (index==-1) { throw new NotFoundStadiumException("Мы не смогли найти подхоящий стадион"); } return stadiums[index].getFirst().toString(); } } <file_sep>/src/main/java/org/itstep/step03/exception/NoSuchElementException.java package org.itstep.step03.exception; public class NoSuchElementException extends PairsException{ public NoSuchElementException() { } public NoSuchElementException(String message) { super(message); } } <file_sep>/src/main/java/org/itstep/step01/exeption/NotFoundStadiumException.java package org.itstep.step01.exeption; public class NotFoundStadiumException extends StadiumException{ public NotFoundStadiumException() { } public NotFoundStadiumException(String message) { super(message); } }
17036089871d4db64201ef8a1401ed8d79ad9d9b
[ "Java" ]
3
Java
Roberto-spec/practice-generics
3974b9ccfb4938691d72e84004c1811648e52c4a
7e423f92b6d891cf2425f0cb634a2939fdcb18c6
refs/heads/master
<repo_name>OlavHN/tfweb<file_sep>/tfweb/model.py import tensorflow as tf import numpy as np import aiohttp import functools import tempfile import io from zipfile import ZipFile from urllib.parse import urlparse dir(tf.contrib) # contrib ops lazily loaded class Model: default_tag = tf.saved_model.tag_constants.SERVING def __init__(self, loop): self.loop = loop self.sess = None self.graph_def = None async def set_model(self, path, tags=[tf.saved_model.tag_constants.SERVING]): try: with tempfile.TemporaryDirectory() as tmpdirname: if path.startswith('http'): async with aiohttp.ClientSession() as session: async with session.get(path) as r: zipped = ZipFile(io.BytesIO(await r.read())) zipped.extractall(tmpdirname) path = tmpdirname session = tf.compat.v1.Session() self.graph_def = tf.saved_model.loader.load(session, tags, path) if self.sess: self.sess.close() self.sess = session except Exception as e: raise IOError('Couldn\'t load saved_model', e) async def parse(self, method, request, validate_batch): signature = self.graph_def.signature_def[method] inputs = signature.inputs outputs = signature.outputs query_params = {} batch_length = 0 for key, value in inputs.items(): if key not in request: raise ValueError( 'Request missing required key %s for method %s' % (key, method)) input_json = request[key] # input_json = list(map(base64.b64decode, input_json)) dtype = tf.as_dtype(inputs[key].dtype).as_numpy_dtype try: tensor = np.asarray(input_json, dtype=dtype) except ValueError as e: raise ValueError( 'Incompatible types for key %s: %s' % (key, e)) correct_shape = tf.TensorShape(inputs[key].tensor_shape) input_shape = tf.TensorShape(tensor.shape) if not correct_shape.is_compatible_with(input_shape): raise ValueError( 'Shape of input %s %s not compatible with %s' % (key, input_shape.as_list(), correct_shape.as_list())) if validate_batch: try: if batch_length > 0 and \ batch_length != input_shape.as_list()[0]: raise ValueError( 'The outer dimension of tensors did not match') batch_length = input_shape.as_list()[0] except IndexError: raise ValueError( '%s is a scalar and cannot be batched' % key) query_params[value.name] = tensor result_params = { key: self.sess.graph.get_tensor_by_name(val.name) for key, val in outputs.items() } return query_params, result_params async def query(self, query_params, result_params): ''' TODO: Interface via FIFO queue ''' return await self.loop.run_in_executor( None, functools.partial( self.sess.run, result_params, feed_dict=query_params)) def list_signatures(self): if not self.graph_def: return [] signatures = [] signature_def_map = self.graph_def.signature_def for key, signature_def in signature_def_map.items(): signature = {} signature['name'] = key signature['inputs'] = {} signature['outputs'] = {} for key, tensor_info in signature_def.inputs.items(): signature['inputs'][key] = { 'type': tf.as_dtype(tensor_info.dtype).name if tensor_info.dtype else 'unknown', 'shape': 'unkown' if tensor_info.tensor_shape.unknown_rank else [dim.size for dim in tensor_info.tensor_shape.dim] } for key, tensor_info in signature_def.outputs.items(): signature['outputs'][key] = { 'type': tf.as_dtype(tensor_info.dtype).name if tensor_info.dtype else 'unknown', 'shape': 'unkown' if tensor_info.tensor_shape.unknown_rank else [dim.size for dim in tensor_info.tensor_shape.dim] } signatures.append(signature) return signatures <file_sep>/PUBLISH.md ## Reminder - Make sure ~/.pypirc is setup with pypi url: repository = https://upload.pypi.org/legacy/ - Change version number in `setup.py` - `git tag v{VERSION} master && git push --tags` - `python setup.py sdist` - `twine upload dist/*` <file_sep>/tests/test.py import unittest import tensorflow as tf import numpy as np import asyncio from aiohttp import ClientSession import sys sys.path.append("../tfweb") from tfweb.model import Model from tfweb.batcher import Batcher from grpclib.client import Channel from tfweb.service_pb2 import PredictRequest from tfweb.service_grpc import ModelStub class Test(unittest.TestCase): def setUp(self): pass def test_tensorflow(self): with tf.Graph().as_default(), tf.Session() as sess: self.assertEqual( sess.run(tf.constant(5) + tf.constant(5)), np.array(10)) class TestModel(unittest.TestCase): def setUp(self): self.model = Model( path='examples/basic/model', tags=['serve'], loop=asyncio.get_event_loop()) def tearDown(self): for task in asyncio.Task.all_tasks(): task.cancel() def test_model_parse_valid(self): parsed = self.model.parse( method='add', request={'x1': [[1]], 'x2': [[1]]}, validate_batch=True) query_params, result_params = (asyncio.get_event_loop() .run_until_complete(parsed)) self.assertEqual( query_params, { 'x2:0': np.array([[1.]], dtype=np.float32), 'x1:0': np.array([[1.]], dtype=np.float32) }) self.assertEqual(result_params['result'].name, 'add:0') self.assertEqual(result_params['result'].shape.as_list(), [None, 1]) self.assertEqual(result_params['result'].dtype, tf.float32) def test_model_parse_invalid(self): parsed = self.model.parse( method='add', request={'x1': [[1]], 'x2': [[1], [2]]}, validate_batch=True) self.assertRaises(ValueError, asyncio.get_event_loop().run_until_complete, parsed) def test_model_query_session(self): parsed = self.model.parse( method='add', request={'x1': [[1]], 'x2': [[1]]}, validate_batch=True) query_params, result_params = (asyncio.get_event_loop() .run_until_complete(parsed)) result = asyncio.get_event_loop().run_until_complete( self.model.query(query_params, result_params)) self.assertEqual(result['result'], np.array([[2.]])) class TestBatcher(unittest.TestCase): def setUp(self): self.loop = asyncio.get_event_loop() self.model = Model( path='examples/basic/model', tags=['serve'], loop=asyncio.get_event_loop()) self.batcher = Batcher(self.model, self.loop) def tearDown(self): for task in asyncio.Task.all_tasks(): task.cancel() def test_find_batched_methods(self): batched_methods, direct_methods = self.batcher.find_batched_methods() self.assertEqual(direct_methods, []) self.assertEqual(len(batched_methods), 2) def test_batch_query(self): resultTask = self.batcher.batch_query( method='add', data={ 'x1': [[1], [3]], 'x2': [[1], [-9]] }) result = asyncio.get_event_loop().run_until_complete(resultTask) self.assertTrue((np.array([[2.], [-6.]]) == result['result']).all()) @unittest.skip("Skipping integration tests. Requires spinning up a server") class TestIntegration(unittest.TestCase): def test_10000_json(self): num_requests = 10000 loop = asyncio.get_event_loop() async def fetch(url, data, session): async with session.post(url, json=data) as response: self.assertEqual(response.status, 200) return await response.read() async def bound_fetch(sem, url, data, session): # Getter function with semaphore. async with sem: return await fetch(url, data, session) async def run(r): url = "http://localhost:8080/{}" tasks = [] sem = asyncio.Semaphore(1000) async with ClientSession() as session: for i in range(r): data = {'x1': [[1], [2]], "x2": [[1], [2]]} # pass Semaphore and session to every GET request task = asyncio.ensure_future( bound_fetch(sem, url.format("multiply"), data, session)) tasks.append(task) return await asyncio.gather(*tasks) future = asyncio.ensure_future(run(num_requests)) print(loop.run_until_complete(future)) print(future.result()) self.assertTrue(True) def test_10000_grpc(self): num_requests = 10000 loop = asyncio.get_event_loop() channel = Channel(host='127.0.0.1', port=50051, loop=loop) stub = ModelStub(channel) async def make_request(): tensors = { 'x1': tf.make_tensor_proto([[1], [3]], tf.float32, [2, 1]), 'x2': tf.make_tensor_proto([[1], [2]], tf.float32, [2, 1]) } request = PredictRequest(inputs=tensors) request.model_spec.signature_name = 'add' return await stub.Predict(request) async def run(n): tasks = [] sem = asyncio.Semaphore( 100) # grpc lib needs one socet per request for i in range(n): async def bound(): async with sem: return await make_request() tasks.append(asyncio.ensure_future(bound())) return await asyncio.gather(*tasks) future = asyncio.ensure_future(run(num_requests)) for result in loop.run_until_complete(future): print({k: tf.make_ndarray(v) for k, v in result.result.items()}) self.assertTrue(True) if __name__ == '__main__': unittest.main() <file_sep>/tfweb/service_grpc.py # Generated by the Protocol Buffers compiler. DO NOT EDIT! # source: service.proto # plugin: grpclib.plugin.main import abc import grpclib.const import grpclib.client import tensorflow.core.framework.tensor_pb2 import google.protobuf.wrappers_pb2 import service_pb2 class ModelBase(abc.ABC): @abc.abstractmethod async def Predict(self, stream): pass def __mapping__(self): return { '/Model/Predict': grpclib.const.Handler( self.Predict, grpclib.const.Cardinality.UNARY_UNARY, service_pb2.PredictRequest, service_pb2.PredictResponse, ), } class ModelStub: def __init__(self, channel: grpclib.client.Channel) -> None: self.Predict = grpclib.client.UnaryUnaryMethod( channel, '/Model/Predict', service_pb2.PredictRequest, service_pb2.PredictResponse, ) <file_sep>/bin/tfweb #!python import sys from tfweb import tfweb tfweb.main(args=sys.argv[1:]) <file_sep>/examples/basic/example.py import tensorflow as tf x1 = tf.placeholder(dtype=tf.float32, shape=[None, 1], name="x1") x2 = tf.placeholder(dtype=tf.float32, shape=[None, 1], name="x2") y1 = x1 + x2 y2 = x1 * x2 builder = tf.saved_model.builder.SavedModelBuilder('./model') with tf.Session() as sess: sess.run(tf.global_variables_initializer()) builder.add_meta_graph_and_variables(sess, [tf.saved_model.tag_constants.SERVING], signature_def_map={ 'add': tf.saved_model.signature_def_utils.predict_signature_def( inputs= {"x1": x1, "x2": x2}, outputs= {"result": y1}), 'multiply': tf.saved_model.signature_def_utils.predict_signature_def( inputs= {"x1": x1, "x2": x2}, outputs= {"result": y2})}) builder.save() print(sess.run([y1, y2], feed_dict={x1: [[1]], x2: [[0]]})) <file_sep>/tfweb/tfweb.py import sys import argparse import asyncio from aiohttp import web import aiohttp_cors from model import Model from batcher import Batcher from json_handler import JsonHandler from grpc_handler import GrpcHandler from grpclib.server import Server async def on_shutdown(app): for task in asyncio.Task.all_tasks(): task.cancel() async def init(loop, args): if args.tags: tags = args.tags.split(',') else: tags = [Model.default_tag] model = Model(loop) if args.model: await model.set_model(args.model, tags) batcher = Batcher(model, loop, args.batch_size) web_app = web.Application(loop=loop, client_max_size=args.request_size) web_app.on_shutdown.append(on_shutdown) web_app.router.add_get('/stats', batcher.stats_handler) json_handler = JsonHandler(model, batcher, args.batch_transpose) if args.no_cors: web_app.router.add_get('/', batcher.info_handler) web_app.router.add_post('/{method}', json_handler.handler) web_app.router.add_post('/', json_handler.handler) else: cors = aiohttp_cors.setup( web_app, defaults={ "*": aiohttp_cors.ResourceOptions( allow_credentials=True, expose_headers="*", allow_headers="*") }) get_resource = cors.add(web_app.router.add_resource('/')) cors.add(get_resource.add_route("GET", batcher.info_handler)) post_resource = cors.add(web_app.router.add_resource('/{method}')) cors.add(post_resource.add_route("POST", json_handler.handler)) post_resource = cors.add(web_app.router.add_resource('/')) cors.add(post_resource.add_route("POST", json_handler.handler)) if args.static_path: web_app.router.add_static( '/web/', path=args.static_path, name='static') grpc_app = Server([GrpcHandler(model, batcher)], loop=loop) return web_app, grpc_app def main(args): parser = argparse.ArgumentParser(description='tfweb') parser.add_argument( '--model', type=str, help='path to saved_model directory (can be GCS)') parser.add_argument( '--tags', type=str, default=None, help='Comma separated SavedModel tags. Defaults to `serve`') parser.add_argument( '--batch_size', type=int, default=32, help='Maximum batch size for batchable methods') parser.add_argument( '--static_path', type=str, default=None, help='Path to static content, eg. html files served on GET') parser.add_argument( '--batch_transpose', action='store_true', help='Provide and return each example in batches separately') parser.add_argument( '--no_cors', action='store_true', help='Accept HTTP requests from all domains') parser.add_argument( '--request_size', type=int, default=10 * 1024**2, help='Max size per request') parser.add_argument( '--grpc_port', type=int, default=50051, help='Port accepting grpc requests') parser.add_argument( '--port', type=int, default=8080, help='tfweb model access port') args = parser.parse_args(args) loop = asyncio.get_event_loop() web_app, grpc_app = loop.run_until_complete(init(loop, args)) loop.run_until_complete(grpc_app.start('0.0.0.0', args.grpc_port)) try: web.run_app(web_app, port=args.port) except asyncio.CancelledError: pass if __name__ == '__main__': main(args=sys.argv[1:]) <file_sep>/examples/inception/model.py import tensorflow as tf from tensorflow.contrib import slim from tensorflow.python.ops import sparse_ops from tensorflow.contrib.slim.python.slim.nets import inception from tensorflow.python.saved_model import builder as saved_model_builder from tensorflow.python.saved_model.signature_def_utils import build_signature_def from tensorflow.python.saved_model import utils import os from os import listdir from os.path import isfile, join slim = tf.contrib.slim num_classes = 6012 checkpoint = 'data/2016_08/model.ckpt' def process_images(serialized_images): def decode(jpeg_str, central_fraction=0.875, image_size=299): decoded = tf.cast( tf.image.decode_jpeg(jpeg_str, channels=3), tf.float32) cropped = tf.image.central_crop( decoded, central_fraction=central_fraction) resized = tf.squeeze( tf.image.resize_bilinear( tf.expand_dims(cropped, [0]), [image_size, image_size], align_corners=False), [0]) resized.set_shape((image_size, image_size, 3)) normalized = tf.subtract(tf.multiply(resized, 1.0 / 127.5), 1.0) return normalized def process(images, image_size=299): images = tf.map_fn(decode, images, dtype=tf.float32) return images images = process(serialized_images) with slim.arg_scope(inception.inception_v3_arg_scope()): logits, end_points = inception.inception_v3( images, num_classes=num_classes, is_training=False) features = tf.reshape(end_points['PreLogits'], [-1, 2048]) class_predictions = tf.nn.sigmoid(logits) return features, class_predictions serialized_images = tf.placeholder(tf.string, shape=[None], name="images") features, predictions = process_images(serialized_images) pred, indices = tf.nn.top_k(predictions, k=5) features = tf.identity(features, name="features") labels = tf.constant("labels.txt") tf.add_to_collection(tf.GraphKeys.ASSET_FILEPATHS, labels) table = tf.contrib.lookup.index_to_string_table_from_file( vocabulary_file=labels, default_value="UNKNOWN") values = table.lookup(tf.to_int64(indices)) preddy = tf.identity(values, name="predictions") saver = tf.train.Saver() with tf.Session() as sess: sess.run([ tf.local_variables_initializer(), tf.global_variables_initializer(), tf.tables_initializer() ]) #tf.initialize_all_tables().run() saver.restore(sess, checkpoint) # this part specified the saved model feature_sig = build_signature_def( { 'image': utils.build_tensor_info(serialized_images) }, {'features': utils.build_tensor_info(features)}, 'features') # this part specified the saved model name_sig = build_signature_def( { 'image': utils.build_tensor_info(serialized_images) }, {'names': utils.build_tensor_info(preddy)}, 'names') builder = saved_model_builder.SavedModelBuilder('savedmodel') builder.add_meta_graph_and_variables( sess, [tf.saved_model.tag_constants.SERVING], signature_def_map={'features': feature_sig, 'names': name_sig}, assets_collection=tf.get_collection(tf.GraphKeys.ASSET_FILEPATHS), legacy_init_op=tf.tables_initializer()) builder.save() # Here we load the saved graph as a sanity check graph = tf.Graph() with tf.Session(graph=graph) as sess: tf.saved_model.loader.load(sess, [tf.saved_model.tag_constants.SERVING], 'savedmodel') with open('img.jpg', 'rb') as f: res = sess.run( [ graph.get_tensor_by_name('features:0'), graph.get_tensor_by_name('predictions:0') ], feed_dict={ graph.get_tensor_by_name('images:0'): [f.read()] }) print(res) <file_sep>/tfweb/batcher.py import numpy as np import asyncio from aiohttp import web class Batcher: def __init__(self, model, loop, batch_size=32): self.loop = loop self.batch_size = batch_size self.model = model self.tasks = [] self.set_model() def set_model(self): while len(self.tasks): self.tasks.pop().cancel() batched_methods, direct_methods = self.find_batched_methods() self.direct_methods = set(map(lambda x: x['name'], direct_methods)) self.batched_queues = { signature['name']: asyncio.Queue( maxsize=self.batch_size, loop=self.loop) for signature in batched_methods } for queue in self.batched_queues: self.tasks.append(self.loop.create_task( self.batch(self.batched_queues[queue], self.batch_size))) def find_batched_methods(self): batched_methods = [] direct_methods = [] for signature in self.model.list_signatures(): for _, tensor in list(signature['inputs'].items()) + list( signature['outputs'].items()): if isinstance(tensor['shape'], list) and len( tensor['shape']) and tensor['shape'][0] == -1: continue else: direct_methods.append(signature) break else: batched_methods.append(signature) return batched_methods, direct_methods async def batch_query(self, method, data): query_params, result_params = await self.model.parse( method, data, True) task = asyncio.Queue(loop=self.loop) # Split in into examples and pass them through! keys, values = zip(*sorted(query_params.items())) num_items = 0 for example in zip(*values): num_items += 1 await self.batched_queues[method].put((keys, example, result_params, task)) # Get results back results = [] for _ in range(num_items): result = await task.get() if result is None: # Run them through individually instead! return None results.append(result) # Massage individual results into a batched response keys, examples = zip(*results) batch_result = { key: np.stack(val) for key, val in zip(keys[0], zip(*examples)) } return batch_result async def batch(self, queue, max_batch_size): ''' Greedily fills up batch before processing, but processes partial batch if the input queue is empty. ''' batch = [] while True: if queue.empty() and len(batch) == 0: batch.append(await queue.get()) if not queue.empty() and len(batch) < max_batch_size: batch.append(await queue.get()) continue keys, examples, result_params, queues = zip(*batch) batched_examples = zip(*examples) query_params = { key: np.stack(val) for key, val in zip(keys[0], batched_examples) } try: result = await self.model.query(query_params, result_params[0]) keys, values = zip(*sorted(result.items())) for result_value, q in zip(zip(*values), queues): q.put_nowait((keys, result_value)) except Exception as e: print(e) for q in queues: q.put_nowait(None) batch = [] async def info_handler(self, request): signatures = self.model.list_signatures() return web.json_response(signatures) async def stats_handler(self, request): ''' TODO: Implement runtime stats ''' signatures = self.model.list_signatures() return web.json_response(signatures) <file_sep>/README.md # tfweb Web server for Tensorflow model inference in python. ## Quickstart ``` $ pip install tensorflow $ pip install tfweb $ tfweb --model s3://tfweb-models/hotdog --batch_transpose $ curl -d '{"image": {"url": "https://i.imgur.com/H37kxPH.jpg"}}' localhost:8080/predict { "class": ["no hotdog"], "prediction": [0.7314095497131348] } ``` Might take some time to download the model from `s3://tfweb-models`. ``` $ tfweb -h usage: tfweb [-h] [--model MODEL] [--tags TAGS] [--batch_size BATCH_SIZE] [--static_path STATIC_PATH] [--batch_transpose] [--no_cors] [--request_size REQUEST_SIZE] [--grpc_port GRPC_PORT] tfweb optional arguments: -h, --help show this help message and exit --model MODEL path to saved_model directory (can also be S3, GCS or hdfs) --tags TAGS Comma separated SavedModel tags. Defaults to `serve` --batch_size BATCH_SIZE Maximum batch size for batchable methods --static_path STATIC_PATH Path to static content, eg. html files served on GET --batch_transpose Provide and return each example in batches separately --no_cors Accept HTTP requests from all domains --request_size REQUEST_SIZE Max size per request --grpc_port GRPC_PORT Port accepting grpc requests ``` ## Why? tfweb aims to be easier to setup, easier to tinker with and easier to integrate with than tf-serving. Thanks to being written in pure python 3 it's possible to interact with tensorflow though it's flexible python bindings. ## Usage Tensorflow has a standard format for persisting models called SavedModel. Any model persisted in this format which specifies it signatures can then automatically be exposed as a web service with tfweb. Create a SavedModel that contains signature_defs (Look in the `examples` folder) then start a server exposing the model over JSON with `$ tfweb --model s3://tfweb-models/openimages --batch_transpose` To see what sort of APIs the model exposes one can query it to get its type information: `$ curl localhost:8080 | python -m json.tool` ``` [ { "name": "features", "inputs": { "image": { "type": "string", "shape": [ -1 ] } }, "outputs": { "features": { "type": "float32", "shape": [ -1, 2048 ] } } }, { "name": "names", "inputs": { "image": { "type": "string", "shape": [ -1 ] } }, "outputs": { "names": { "type": "string", "shape": [ -1, 5 ] } } } ] ``` Here we see the model has exposed two methods, `features` and `names` which accepts batches of strings. The model is in fact Inception v3 trained on OpenImages, meaning those batches of strings are batches of JPEG images. We cannot encode JPEG data as JSON, so we can either let the server fetch the data from a URL or we can base64 encode the image data before sending. Thus we can query the method `names` like this: `curl -d '{"image": {"url": "https://i.imgur.com/ekNNNjN.jpg"}}' localhost:8080/names | python -m json.tool` ``` { "names": [ "mammal", "animal", "pet", "cat", "vertebrate" ] } ``` And we received 5 strings corresponding to the best inception matches. ## Batching By default tfweb doesn't do any batching, but if a method (signature definition) has a variable outer dimension for all inputs and outputs (i.e. shape is [-1, ..]) then the method is assumed to be batchable and tfweb will optimistically queue up requests for batching while the tensorflow session is busy doing other stuff (like running the previous batch). If a method accepts batches we can also send multiple queries in the same request: `curl -d '[{"image": {"url": "https://i.imgur.com/ekNNNjN.jpg"}}, {"image": {"url": "https://i.imgur.com/JNo5tHj.jpg"}}]' localhost:8080/names | python -m json.tool` ``` [ { "names": [ "mammal", "animal", "pet", "cat", "vertebrate" ] }, { "names": [ "mammal", "animal", "pet", "vertebrate", "dog" ] } ] ``` ## Functionality - Pure python - same as the most mature tensorflow API! - Reads tensorflow saved_model and exposes a HTTP API based on type information in the signature definitions - Batches across multiple requests for GPU utilization without delay - Can read binary data over JSON either wrapped in `{"b64": "..."}` or `{"url": "..."}` - Also base64 encodes JSON results that aren't valid UTF-8 - Also accepts the Predict gRPC signature. Check out `test.py` for an example. ## TODO - More tests (both coded and real world!) - Drop requests when - expose metrics for auto scaling - when downloading URLs, keep track of content size <file_sep>/tfweb/grpc_handler.py import tensorflow as tf from service_pb2 import PredictResponse from service_grpc import ModelBase # from predict_service_pb2 import PredictResponse # from predict_service_grpc import PredictionServiceBase class GrpcHandler(ModelBase): def __init__(self, model, batcher): self.model = model self.batcher = batcher async def Predict(self, stream): request = await stream.recv_message() method = request.model_spec.signature_name data = { key: tf.make_ndarray(val) for key, val in request.inputs.items() } if method in self.batcher.direct_methods: result = await self.single_query(method, data) else: result = await self.batch_query(method, data) if not result: await stream.send_message(PredictResponse()) return result = { key: tf.make_tensor_proto(val) for key, val in result.items() } await stream.send_message(PredictResponse(result=result)) async def single_query(self, method, data): try: query_params, result_params = await self.model.parse( method, data, False) return await self.model.query(query_params, result_params) except Exception as e: print(e) return None async def batch_query(self, method, data): try: result = await self.batcher.batch_query(method, data) if not result: result = await self.single_query(method, data) except Exception as e: print(e) return None return result <file_sep>/tfweb/json_handler.py import base64 import json import urllib.request import numpy as np from aiohttp import web import asyncio class JsonHandler(object): def __init__(self, model, batcher, batch_transpose=False): self.model = model self.batcher = batcher self.batch_transpose = batch_transpose def decoder(self, data_str): def hook(d): if 'b64' in d: return base64.b64decode(d['b64']) if 'url' in d: return urllib.request.urlopen(d['url']).read() return d return json.loads(data_str, object_hook=hook) def encoder(self, data): class JSONBase64Encoder(json.JSONEncoder): ''' Base64 encodes strings that aren't valid UTF-8 ''' def default(self, obj): def test_utf8(obj): try: return obj.decode('utf-8') except UnicodeDecodeError: return base64.b64encode(obj).decode('ascii') if isinstance(obj, (np.ndarray, np.generic)): if obj.dtype == np.dtype(object): obj = np.vectorize(test_utf8)(obj) return obj.tolist() return json.JSONEncoder.default(self, obj) return json.dumps(data, ensure_ascii=False, cls=JSONBase64Encoder) def shutdown(self): for task in asyncio.Task.all_tasks(): task.cancel() async def handler(self, request): try: method = request.match_info.get('method', 'serving_default') if method == 'set_model': data = await request.json() path = data['path'] await self.model.set_model(path) self.batcher.set_model() return web.json_response({'status': 'model updated'}) if method not in self.batcher.batched_queues and \ method not in self.batcher.direct_methods: return web.json_response( { 'error': 'Method %s not found' % method }, status=400) data = await request.json(loads=self.decoder) if method in self.batcher.direct_methods: query_params, result_params = await self.model.parse( method, data, False) result = await self.model.query(query_params, result_params) return web.json_response(result, dumps=self.encoder) unwrapped_example = False if self.batch_transpose: if type(data) == dict: unwrapped_example = True data = [data] # https://stackoverflow.com/questions/5558418/list-of-dicts-to-from-dict-of-lists data = dict(zip(data[0], zip(*[d.values() for d in data]))) batch_result = await self.batcher.batch_query(method, data) if not batch_result: query_params, result_params = await self.model.parse( method, data, False) batch_result = await self.model.query(query_params, result_params) if not batch_result: return web.json_response( { 'error': 'Batch request failed' }, status=400) if self.batch_transpose: batch_result = [ dict(zip(batch_result, t)) for t in zip(*batch_result.values()) ] if unwrapped_example: batch_result = batch_result.pop() return web.json_response(batch_result, dumps=self.encoder) except ValueError as e: return web.json_response({'error': str(e)}, status=400) except TypeError as e: return web.json_response({'error': str(e)}, status=400) except Exception as e: return web.json_response({'error': str(e)}, status=500) <file_sep>/setup.py from setuptools import setup, find_packages # Always prefer setuptools over distutils from codecs import open # To use a consistent encoding from os import path print(find_packages()) here = path.abspath(path.dirname(__file__)) # Get the long description from the relevant file with open(path.join(here, 'README.md'), encoding='utf-8') as f: long_description = f.read() setup(name='tfweb', version='0.4.11', description='Server for exposing tensorflow models though HTTP JSON API', long_description=long_description, long_description_content_type='text/markdown', url='https://github.com/olavhn/tfweb', author='<NAME>', author_email='<EMAIL>', license='MIT', classifiers=[ 'Development Status :: 3 - Alpha', 'Intended Audience :: Developers', 'Topic :: Software Development :: Build Tools', 'License :: OSI Approved :: MIT License', 'Programming Language :: Python :: 3.6', ], keywords=['serving', 'tensorflow', 'asyncio', 'aiohttp', 'grpc'], packages=["tfweb"], install_requires=['aiohttp>=2', 'aiohttp_cors>=0.7', 'grpclib>=0.1'], python_requires='>=3.5', scripts=['bin/tfweb'])
77efa15f2d300318e680b5578f8fa1b658106b0e
[ "Markdown", "Python" ]
13
Python
OlavHN/tfweb
815e5c67b79b2057fdfe6ccb38a5c721836085a3
9f1559a45683caed2702d16a07aa552e4728d60d
refs/heads/master
<file_sep>#!/bin/bash cp target/JenkinsWar.war /opt/tomcat/apache-tomcat-9.0.46/webapps
285d85aa45fbdf4ac919d0aad08d5e728492f04d
[ "Shell" ]
1
Shell
sree1786/maven1
4b29bec160dda08b2eed57c614a3881e1a36dc30
11da822ffd9e84e4d812165fb707a8a59b2022e0
refs/heads/master
<repo_name>raggsokk/GraphiteSharp<file_sep>/GraphiteSharp/CarbonClientOptions.cs #region License // // CarbonClientOptions.cs // // The MIT License (MIT) // // Copyright (c) 2015 <NAME> // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. // #endregion using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace GraphiteSharp { /// <summary> /// An option class with optionale behavours for the CarbonClient. /// </summary> //TODO: rename this to just CarbonOptions? public class CarbonClientOptions { /// <summary> /// Convert timestamps to utc before transmit to a graphite server? /// </summary> public bool ConvertToUtc { get; set; } /// <summary> /// Sanitize Metric Names to valid names only? /// </summary> public bool SanitizeMetricNames { get; set; } /// <summary> /// If Sanitize is enabled, convert text to lower case? /// </summary> public bool SanitizeToLowerCase { get; set; } /// <summary> /// Default options used when not otherwise specified. /// </summary> public static readonly CarbonClientOptions DefaultOptions = new CarbonClientOptions() { ConvertToUtc = true, SanitizeMetricNames = true, SanitizeToLowerCase = true, }; } } <file_sep>/GraphiteSharp/SocketAwaitable.cs #region License // // SocketAwaitable.cs // // The MIT License (MIT) // // Based on code from http://blogs.msdn.com/b/pfxteam/archive/2011/12/15/10248293.aspx // So Copyright (c) 2011 <NAME> // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. // #endregion #if !NOFANCYASYNC using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Net; using System.Net.Sockets; using System.Threading; using System.Runtime.CompilerServices; namespace GraphiteSharp { /// <summary> /// Based on code from http://blogs.msdn.com/b/pfxteam/archive/2011/12/15/10248293.aspx /// </summary> internal sealed class SocketAwaitable : INotifyCompletion { /// <summary> /// Dummy no action action. /// </summary> private readonly static Action SENTINEL = () => { }; /// <summary> /// Was this task already completed? /// </summary> internal bool pWasCompleted; /// <summary> /// Action to do when we are completed. /// </summary> internal Action pContinuation; /// <summary> /// reference to SocketAsyncEventArgs we are wrapping. /// </summary> internal SocketAsyncEventArgs pEventArgs; /// <summary> /// Wraps a SocketAsyncEventArgs into awaitable interface. /// </summary> /// <param name="eventArgs"></param> public SocketAwaitable(SocketAsyncEventArgs eventArgs) { if (eventArgs == null) throw new ArgumentNullException(nameof(eventArgs)); this.pEventArgs = eventArgs; eventArgs.Completed += delegate { // not actually sure what happens here... var prev = pContinuation ?? Interlocked.CompareExchange( ref pContinuation, SENTINEL, null); if (prev != null) prev(); }; } /// <summary> /// Resets object for reuse. /// </summary> public void Reset() { pWasCompleted = false; pContinuation = null; } public SocketAwaitable GetAwaiter() { return this; } /// <summary> /// Is this awaitable completed? /// </summary> public bool IsCompleted { get { return pWasCompleted; } } /// <summary> /// Func called after action is completed. /// </summary> /// <param name="continuation"></param> public void OnCompleted(Action continuation) { if(pContinuation == SENTINEL || Interlocked.CompareExchange( ref pContinuation, continuation, null) == SENTINEL) { Task.Run(continuation); } } /// <summary> /// Return the result from this await task. /// </summary> public void GetResult() { if (pEventArgs.SocketError != SocketError.Success) throw new SocketException((int)pEventArgs.SocketError); } //public bool I } } #endif<file_sep>/GraphiteSharp/CarbonClient.cs #region License // // CarbonClient.cs // // The MIT License (MIT) // // Copyright (c) 2015 <NAME> // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. // #endregion using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Net; using System.Net.Sockets; using System.Reflection; namespace GraphiteSharp { /// <summary> /// Abstract class with common functionality for sending data to a Graphite Carbon Backend. /// </summary> public abstract class CarbonClient : IDisposable { /// <summary> /// This is the ip endpoint (ipaddress:port) where Carbon server listens. /// </summary> public IPEndPoint Endpoint { get; protected set; } /// <summary> /// Gets or Sets a common prefix for all Metric Names used during send to carbon backend. /// </summary> public string MetricPrefix { get; set; } /// <summary> /// Options for alternative CarbonClient behaviour. /// Changing values after CarbonClient creation is undefined. /// </summary> public CarbonClientOptions Options { get; protected set; } /// <summary> /// Protected socket for implementators. /// </summary> protected Socket pSocket; /// <summary> /// Base Constructor which sets the CarbonClient in known state. /// </summary> /// <param name="endPoint"></param> /// <param name="metrixPrefix"></param> /// <param name="options"></param> protected CarbonClient(IPEndPoint endPoint, string metrixPrefix, CarbonClientOptions options = null) { this.Endpoint = endPoint; //this.MetricPrefix = metrixPrefix; this.MetricPrefix = SanitizeMetricName(metrixPrefix); if (options == null) this.Options = CarbonClientOptions.DefaultOptions; else this.Options = options; } #region Public Api /// <summary> /// Send data based on which protocol is used. (tcp/udp). /// </summary> /// <param name="MetricName">The name to store values as. Optinally prefixed.</param> /// <param name="value">The value to write.</param> /// <param name="timestamp">Optional the timestamp to write. Default is now.</param> public virtual void Send(string MetricName, object value, DateTime? timestamp = null) { var payloads = GeneratePayloads(MetricName, value, timestamp); Send(payloads); } /// <summary> /// Sends data async based on which protocol class was created. /// </summary> /// <param name="MetricName">The name to store values as. Optinally prefixed.</param> /// <param name="value">The value to write.</param> /// <param name="timestamp">Optional the timestamp to write. Default is now.</param> /// <returns></returns> public virtual async Task SendAsync(string MetricName, object value, DateTime? timestamp = null) { var payloads = GeneratePayloads(MetricName, value, timestamp); await SendAsync(payloads); } #endregion #region Worker Functions handling actuall calls /// <summary> /// The actuall worker func implementations has to implent. /// Default uses async path with wait, so please override! /// </summary> /// <param name="payloads"></param> protected virtual void Send(List<byte[]> payloads) { SendAsync(payloads).Wait(); } /// <summary> /// The actuall async worker func implementations has to implent. /// </summary> /// <param name="payloads"></param> /// <returns></returns> protected abstract Task SendAsync(List<byte[]> payloads); #endregion #region Utility functions /// <summary> /// Generates the byte[] payloads to send to carbon. /// </summary> /// <param name="MetricName"></param> /// <param name="value"></param> /// <param name="timestamp"></param> /// <returns></returns> protected virtual List<byte[]> GeneratePayloads(string MetricName, object value, DateTime? timestamp = null) { if (timestamp == null || !timestamp.HasValue) timestamp = DateTime.Now; var list = new List<byte[]>(); var t = value.GetType(); if(t.IsPrimitive) // assumes single value type. { list.Add(GeneratePayload(MetricName, value, timestamp.Value)); } else { // fancy anon type thingy. // currently uses reflection directly which is very slow. // it doesn't cache this data per call so.. very slow. var reuse = new StringBuilder(); var tinfo = t.GetTypeInfo(); var props = tinfo.GetProperties(BindingFlags.Instance | BindingFlags.Public); foreach (var p in props) { if (!p.CanRead) continue; if (p.GetIndexParameters()?.Length > 0) continue; // disable indexers. //list.Add(GeneratePayload(string.Join(".", MetricName, p.Name), p.GetValue(null), timestamp, reuse)); list.Add(GeneratePayload(p.Name, p.GetValue(null), timestamp.Value, reuse, MetricName)); } //var fields = tinfo.GetRuntimeFields(); var fields = tinfo.GetFields(BindingFlags.Instance | BindingFlags.Public); foreach (var f in fields) { //if(!f.) list.Add(GeneratePayload(f.Name, f.GetValue(null), timestamp.Value, reuse, MetricName)); //list.Add(GeneratePayload(string.Join(".", MetricName, f.Name), f.GetValue(null), timestamp, reuse)); } } return list; } /// <summary> /// Generates a single byte[] payload to send to carbon. /// </summary> /// <param name="MetricName"></param> /// <param name="value"></param> /// <param name="timestamp"></param> /// <param name="reuse"></param> /// <param name="AdditionalPrefix"></param> /// <returns></returns> protected virtual byte[] GeneratePayload(string MetricName, object value, DateTime timestamp, StringBuilder reuse = null, string AdditionalPrefix = null) { if (reuse == null) reuse = new StringBuilder(); else reuse.Length = 0; if (!string.IsNullOrWhiteSpace(this.MetricPrefix)) { reuse.Append(this.MetricPrefix); reuse.Append("."); } if (!string.IsNullOrWhiteSpace(AdditionalPrefix)) { reuse.Append(AdditionalPrefix); reuse.Append("."); } reuse.Append(MetricName); //TODO: Handle invariant floating point conversion better. Aka Graphite requires "#.#" format, but default norwegian converson is "#,#". Handle this. var v = value.ToString(); if (v.Contains(",")) // bad hack conversion. v.Replace(',', '.'); reuse.AppendFormat(" {0} ", v); reuse.Append(DateTimeToUnixEpoch(timestamp)); reuse.Append(" \n"); //TODO: prevent sanatize already sanatized prefix. var bytes = ASCIIEncoding.ASCII.GetBytes(SanitizeMetricName(reuse.ToString())); //var bytes = ASCIIEncoding.ASCII.GetBytes(reuse.ToString()); //var bytes = UTF8Encoding.UTF8.GetBytes(reuse.ToString()); return bytes; } /// <summary> /// Used for calculating Unix Epoch int32 timestamps. /// Would have been constant if possible. /// </summary> private static readonly DateTime UNIX1970 = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc); /// <summary> /// Sanitizes Metric names obeing CarbonClientOptions. /// </summary> /// <param name="MetricName"></param> /// <param name="reuse"></param> /// <returns></returns> protected virtual string SanitizeMetricName(string MetricName, StringBuilder reuse = null) { if (!Options.SanitizeMetricNames) return MetricName; if (reuse == null) reuse = new StringBuilder(); else reuse.Length = 0; var charArray = MetricName.ToCharArray(); bool flagLowerCase = Options.SanitizeToLowerCase; foreach(var c in charArray) { switch(c) { case '\\': case '/': reuse.Append('.'); break; case ' ': case '_': reuse.Append('_'); break; default: if (flagLowerCase && char.IsLetter(c)) reuse.Append(char.ToLowerInvariant(c)); else reuse.Append(c); break; } } return reuse.ToString(); } /// <summary> /// Converts DateTime to Unix Epic time. /// It respects CarbonClientOptions.ConvertToUtc /// </summary> /// <param name="dt"></param> /// <returns></returns> protected virtual long DateTimeToUnixEpoch(DateTime dt) { if (this.Options.ConvertToUtc) dt = dt.ToUniversalTime(); return (long)(dt.Subtract(UNIX1970)).TotalSeconds; //return (int)(dt.ToUniversalTime().Subtract(UNIX1970)).TotalSeconds; } /// <summary> /// Responsible for converting ip or hostname into a valid IPEndPoint class. /// </summary> /// <param name="IpOrHostname"></param> /// <param name="port"></param> /// <returns></returns> protected static IPEndPoint CreateIpEndpoint(string IpOrHostname, int port = 2003) { return new IPEndPoint(GetIpAddress(IpOrHostname), port); } /// <summary> /// Responsible for converting ip or hostname into a valid IPAddress class. /// </summary> /// <param name="IpOrHostname"></param> /// <returns></returns> protected static IPAddress GetIpAddress(string IpOrHostname) { IPAddress address = null; if(!IPAddress.TryParse(IpOrHostname, out address)) { //TODO: not async. address = Dns.GetHostEntry(IpOrHostname)?.AddressList.First(); } return address; } #endregion #region Properties /// <summary> /// The IpAddress to send carbon data to. /// </summary> public IPAddress IpAddress { get { return Endpoint.Address; } } /// <summary> /// Protocol to use when sending carbon data. /// </summary> public AddressFamily AddressFamily { get { return Endpoint.AddressFamily; } } /// <summary> /// The port to contact carbon backend at. /// </summary> public int Port { get { return Endpoint.Port; } } #endregion #region IDisposable Implementation /// <summary> /// Dispose this object. /// </summary> public void Dispose() { this.Dispose(true); GC.SuppressFinalize(this); } /// <summary> /// The actuall disposing function. /// </summary> /// <param name="Disposing">Are we explicit disposing?</param> protected virtual void Dispose(bool Disposing) { if(Disposing) { if (pSocket != null && pSocket.Connected && pSocket.SocketType != SocketType.Dgram) pSocket.Disconnect(true); } pSocket?.Dispose(); } /// <summary> /// Implicit disposing. /// </summary> ~CarbonClient() { this.Dispose(false); } #endregion } } <file_sep>/GraphiteSharp/TcpCarbonClient.cs #region License // // TcpCarbonClient.cs // // The MIT License (MIT) // // Copyright (c) 2015 <NAME> // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. // #endregion using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Net; using System.Net.Sockets; namespace GraphiteSharp { /// <summary> /// A CarbonClient implementation using TCP Protocol for communication with a Graphite Carbon Backend. /// </summary> public class TcpCarbonClient : CarbonClient { /// <summary> /// Creates a new TcpCarbonClient with specific IPEndPoint. /// </summary> /// <param name="endpoint">Already created IPEndPoint pointing to Carbon backend.</param> /// <param name="MetricPrefix">Optionally set a default MetricPrefix for all send operations.</param> /// <param name="options">Option object with possible alternative behaviour.</param> public TcpCarbonClient(IPEndPoint endpoint, string MetricPrefix = null, CarbonClientOptions options = null) : base(endpoint, MetricPrefix, options) { } /// <summary> /// Creates a new TcpCarbonClient with IpOrHostname and default port 2003. /// </summary> /// <param name="IpOrHostname">Ip or Hostname of host where carbon backend is.</param> /// <param name="Port">Optionally override carbon backed port listens on.</param> /// <param name="MetricPrefix">Optionally set a default MetricPrefix for all send operations.</param> /// <param name="options">Option object with possible alternative behaviour.</param> public TcpCarbonClient(string IpOrHostname, int Port = 2003, string MetricPrefix = null, CarbonClientOptions options = null) : base(CarbonClient.CreateIpEndpoint(IpOrHostname, Port), MetricPrefix, options) { } /// <summary> /// The actuall function responsible for sending Payloads with TCP to a Carbon Backend. /// </summary> /// <param name="payloads"></param> protected override void Send(List<byte[]> payloads) { if (pSocket == null) pSocket = new Socket(Endpoint.AddressFamily, SocketType.Stream, ProtocolType.IP); if (!pSocket.Connected) pSocket.Connect(Endpoint); //TODO: Batch up to 512 (ipv6: 1500) bytes which should be minimum safe batch number. foreach (var msg in payloads) { pSocket.Send(msg); } } /// <summary> /// The actuall async function responsible for sending Payloads with TCP to a Carbon Backend. /// </summary> /// <param name="payloads"></param> /// <returns></returns> protected override async Task SendAsync(List<byte[]> payloads) { if (pSocket == null) pSocket = new Socket(Endpoint.AddressFamily, SocketType.Stream, ProtocolType.IP); #if !NOFANCYASYNC var args = new SocketAsyncEventArgs(); var awaitable = new SocketAwaitable(args); if (!pSocket.Connected) { //pSocket.Connect(Endpoint); args.RemoteEndPoint = Endpoint; await pSocket.ConnectAsync(awaitable); } foreach(var msg in payloads) { args.SetBuffer(msg, 0, msg.Length); await pSocket.SendAsync(awaitable); } #else if (!pSocket.Connected) { //await Task. await Task.Factory.FromAsync( pSocket.BeginConnect, pSocket.EndConnect, Endpoint, null); } foreach(var msg in payloads) { // no fromasync accepts 4 args. var result = pSocket.BeginSend(msg, 0, msg.Length, SocketFlags.None, null, pSocket); await Task.Factory.FromAsync(result, pSocket.EndSend); } #endif } } } <file_sep>/README.md # GraphiteSharp A simple C# lib for talking to the Graphite Stack. ### Features * Udp and Tcp Client * Async/Await Functions. ## TODO * ~~Async/Await Functions~~ DONE * ~~Sanitize Metric Names. (' ' => '_', ['/','\',..] => '.'~~ * ~~Turn Utc Conversion on/off.~~ * ~~Document classes and functions.~~ * Validate Valuetypes, short, int, long, float, ... aka not string or class. * Create usage documentation. * Cache Reflect based value to string converter. * GraphiteWebClient to wrap render url api. ## License See the [LICENSE](LICENSE.md) file for license rights and limitations (MIT)
b30143a9436d83a82fc38e7fedb365d3de8f3790
[ "Markdown", "C#" ]
5
C#
raggsokk/GraphiteSharp
2fa3c1a20c1611c6aa3a38eb24052609143e54b8
0664315d66f0f1ef67b29a0493ab65dafcc771ba
refs/heads/master
<file_sep>import torch import CI_utils.CI_utils.graphs def visualize_model(model, train_loader, device): model.eval() model.to(device) lbls = [] encodings = [] with torch.no_grad(): for inputs, labels in train_loader: inputs = inputs.to(device) labels = labels.to(device) encoding = model.feature_extractor(inputs) lbls.extend(labels.cpu().tolist()) encodings.extend(encoding.cpu().tolist()) return encodings, lbls<file_sep>import torch import torch.nn as nn import torch.nn.functional as F import torch.optim as optim class ConvAE(nn.Module): def __init__(self, kd, ks, n_layers, dim_hidden, bn_eps, stride): super(ConvAE, self).__init__() # (kernel_size - 1) * dilation_size # W: Necessary to define new objects for different learning parameters or can the structures be reused? self.conv1 = nn.Conv1d(1, 2 * kd, ks, stride=4, padding=ks // 4) self.bn1 = nn.BatchNorm1d(2 * kd, eps=bn_eps) self.conv_enc1 = nn.Conv1d(kd * 2, kd, ks, stride=2, padding=(ks // 2)-1) self.bn_enc1 = nn.BatchNorm1d(kd, eps=bn_eps) self.conv_enc = nn.ModuleList( [nn.Conv1d(kd, kd, ks, stride=stride, padding=(ks // 2)-1) for i in range(n_layers-1)]) self.bn_enc = nn.ModuleList([nn.BatchNorm1d(kd, eps=bn_eps) for i in range(n_layers-1)]) self.conv_code = nn.Conv1d(kd, dim_hidden, 1, stride=1) self.bn_code = nn.BatchNorm1d(dim_hidden, eps=bn_eps) self.conv_dec1 = nn.ConvTranspose1d(dim_hidden, kd, ks, stride=2, padding=(ks // 2)-1) self.bn_dec1 = nn.BatchNorm1d(kd, eps=bn_eps) self.conv_dec = nn.ModuleList( [nn.ConvTranspose1d(kd, kd, ks, stride=2, padding=(ks // 2)-1) for i in range(n_layers - 1)]) self.bn_dec = nn.ModuleList([nn.BatchNorm1d(kd, eps=bn_eps) for i in range(n_layers-1)]) self.conv_dec_last = nn.ConvTranspose1d(kd, kd * 2, ks, stride=4, padding=ks // 4) self.bn_dec_last = nn.BatchNorm1d(kd * 2, eps=bn_eps) self.conv_rec = nn.ConvTranspose1d(kd * 2, 1, ks + 1, stride=1,padding=ks // 2) def forward(self, x): x = self.bn1(F.leaky_relu(self.conv1(x))) x = self.bn_enc1(F.leaky_relu(self.conv_enc1(x))) for lyr_i in range(len(self.conv_enc)): x = self.bn_enc[lyr_i](F.leaky_relu(self.conv_enc[lyr_i](x))) x = self.bn_code(self.conv_code(x)) x = self.bn_dec1(F.leaky_relu(self.conv_dec1(x))) for lyr_i in range(len(self.conv_dec)): x = self.bn_dec[lyr_i](F.leaky_relu(self.conv_dec[lyr_i](x))) x = self.bn_dec_last(F.leaky_relu(self.conv_dec_last(x))) x = torch.sigmoid(self.conv_rec(x)) return x<file_sep># CI_utils General utilities <file_sep>import numpy as np import copy import torch import torch.nn as nn import torch.optim as optim import torchvision from torchvision import datasets, models, transforms import torch.utils.data as utils from torch.utils.data.sampler import SubsetRandomSampler def train(model, epochs, criterion, optimizer, dataloader, scheduler=None, device = 'cuda:0', save_path = None): ''' :param model: :param epochs: :param criterion: :param optimizer: :param dataloader: :param FLAGS: :param scheduler: :param device: :param save_path: :return: ''' val_acc_history = [] train_acc_history = [] loss_train_history = [] loss_val_history = [] best_model_wts = copy.deepcopy(model.state_dict()) best_acc = 0.0 for epoch in range(epochs): print('Epoch {}/{}'.format(epoch + 1, epochs)) print('-' * 30) #if scheduler is not None: # scheduler.step() # Each epoch has train n validation set for phase in ['train', 'validation']: if phase == 'train': model.train() else: model.eval() running_loss = 0 running_corrects = 0 total = 0 # Iterate over data. for inputs, labels in dataloader[phase]: inputs = inputs.to(device) labels = labels.to(device) optimizer.zero_grad() with torch.set_grad_enabled(phase == 'train'): # FwrdPhase: # Loss = sum final output n aux output (in InceptionNet) # BUT while testing, only final output considered. outputs = model(inputs) loss = criterion(outputs, labels) _, preds = torch.max(outputs, 1) # BwrdPhase: if phase == 'train': loss.backward() optimizer.step() # statistics running_loss += loss.item() * inputs.size(0) running_corrects += (preds == labels).sum().item() total += labels.size(0) epoch_loss = running_loss / total epoch_acc = running_corrects / total print('{} Loss: {:.4f} Acc: {:.4f}'.format(phase, epoch_loss, epoch_acc)) # Deep copy of the model if phase == 'validation' and epoch_acc > best_acc: best_acc = epoch_acc best_model_wts = copy.deepcopy(model.state_dict()) if phase == 'validation': val_acc_history.append(epoch_acc) loss_val_history.append(epoch_loss) # TODO: Differenciate between the different kind of schedulers and their position in the train if scheduler is not None: scheduler.step(epoch_acc) if phase == 'train': train_acc_history.append(epoch_acc) loss_train_history.append(epoch_loss) print() print('Best Val Acc: {:.4f}'.format(best_acc)) # load best model weights model.load_state_dict(best_model_wts) if save_path is not None: torch.save(model.state_dict(), save_path) return model, val_acc_history, loss_val_history, train_acc_history, loss_train_history<file_sep> def dict_as_pickle(dict, filename): ''' :param dict: dictionary to be saved :param filename: Requires to be .pkl ''' assert('.pkl' in filename) import pickle with open(filename, 'wb') as pickle_file: pickle.dump(dict, pickle_file) pickle_file.close() def from_pickle(filename): ''' :param filename: Requires to be .pkl :return: loaded object ''' assert ('.pkl' in filename) import pickle with open(filename, 'rb') as pickle_file: obj = pickle.load(pickle_file) pickle_file.close() return obj <file_sep>from collections import Counter import numpy as np def accuracy(labels, predictions, pr=True): ''' Calculates accuracy between predictions and true labels :param labels: :param predictions: :param pr: Bool. Print accuracy value :return: ''' assert(len(labels)==len(predictions)) counter = Counter(labels == predictions) acc = counter[True]/float(len(predictions)) if pr: print('Prediction Accuracy: {}'.format(acc)) return acc def error(labels, predictions): ''' Calculates error between predictions and true labels :param labels: :param predictions: :return: ''' assert(len(labels)==len(predictions)) err = 1 - accuracy(labels, predictions, False) print('Prediction Error: {}'.format(err)) return err<file_sep>import torch import torch.nn as nn import torch.nn.functional as F import torch.optim as optim from DR.CI_utils.CI_utils.nets.autoencoders import ConvAE class ConvAE_Classif(ConvAE): def __init__(self, n_classes, kd, ks, n_layers, dim_hidden, bn_eps, stride): super(ConvAE_Classif, self).__init__(kd, ks, n_layers, dim_hidden, bn_eps, stride) self.code_comp = nn.Conv1d(dim_hidden, 1, 1, stride=1) self.bn_classif = nn.BatchNorm1d(1, eps=bn_eps) self.classif = nn.Sequential( nn.Linear(1 * 128, 128 * 2), nn.ReLU(True), nn.Linear(128 * 2, 2) ) def forward(self, x): x = self.bn1(F.leaky_relu(self.conv1(x))) x = self.bn_enc1(F.leaky_relu(self.conv_enc1(x))) for lyr_i in range(len(self.conv_enc)): x = self.bn_enc[lyr_i](F.leaky_relu(self.conv_enc[lyr_i](x))) x = self.bn_code(self.conv_code(x)) x_recon = self.bn_dec1(F.leaky_relu(self.conv_dec1(x))) for lyr_i in range(len(self.conv_dec)): x_recon = self.bn_dec[lyr_i](F.leaky_relu(self.conv_dec[lyr_i](x_recon))) x_recon = self.bn_dec_last(F.leaky_relu(self.conv_dec_last(x_recon))) x_recon = torch.sigmoid(self.conv_rec(x_recon)) x_classif = self.bn_classif(F.relu(self.code_comp(x))) x_classif = x_classif.view(-1, 1 * 128) x_classif = self.classif(x_classif) return x_recon, F.softmax(x_classif)<file_sep>import itertools import numpy as np import seaborn as sns import matplotlib.pyplot as plt from matplotlib.ticker import MaxNLocator import matplotlib.patheffects as PathEffects from matplotlib.font_manager import FontProperties from sklearn import svm, datasets from sklearn.model_selection import train_test_split from sklearn.metrics import confusion_matrix from sklearn.manifold import TSNE def plot_confusion_matrix(y_pred, y_true, classes, normalize=False, title='Confusion matrix', sideLabels=False, cmap=plt.cm.Purples): ''' :param cm: NumPy Array -- Confusion Matrix to be shown. :param classes: List -- class_names :param normalize: bool :param title: :param sideLabels: If true, the axis labels [trueLabel, predictedLabels] will appear in the image. :param cmap: colormaps type. See plt.cm for more information :return: Confusion Matrix ''' from sklearn.metrics import confusion_matrix cm = confusion_matrix(y_true, y_pred) plt.figure(dpi=1000) if normalize: cm = cm.astype('float') / cm.sum(axis=1)[:, np.newaxis] print("Normalized confusion matrix") else: print('Confusion matrix, without normalization') plt.imshow(cm, interpolation='nearest', cmap=cmap) if title is not '': plt.title(title) plt.colorbar() tick_marks = np.arange(len(classes)) plt.xticks(tick_marks, classes, rotation=-45, horizontalalignment = 'left') plt.yticks([]) #plt.yticks(tick_marks, classes) fmt = '.2f' if normalize else 'd' thresh = cm.max() / 2. for i, j in itertools.product(range(cm.shape[0]), range(cm.shape[1])): plt.text(j, i, format(cm[i, j], fmt), horizontalalignment="center", color="white" if cm[i, j] > thresh else "black") if sideLabels: plt.ylabel('True label') plt.xlabel('Predicted label') plt.tight_layout() plt.show() def plot_series(x, y, title, x_label='', y_label='', graph_labels=None, graph_markers=None, graph_linetypes=None, graph_linecolors=None, integer_thicks = False, grid=False): ''' Plots the data series contained in y vs x. :param x: NumPy Array :param y: List of NumPy Arrays :param title: :param x_label: :param y_label: :param graph_labels: Labels per {x,y} plot pairs. :param graph_markers: https://matplotlib.org/api/markers_api.html :param graph_linetypes: https://matplotlib.org/gallery/lines_bars_and_markers/line_styles_reference.html :param graph_linecolors: https://matplotlib.org/2.1.1/api/_as_gen/matplotlib.pyplot.plot.html :param integer_thicks: bool - Force integer tick labels :param grid: bool :return: Returns graph containing y vs x. ''' if title is not '': plt.title(title) for i in range(len(y)): label = graph_labels[i] if graph_labels else '' marker = graph_markers[i] if graph_markers else '' line_color = graph_linecolors[i] if graph_linecolors else None line_type = graph_linetypes[i] if graph_linetypes else '-' plt.plot(x, y[i], marker=marker, color=line_color, linestyle=line_type,label=label) plt.xlabel(x_label) plt.ylabel(y_label) plt.grid(grid) plt.xlim(x.min(), x.max()) if graph_labels: plt.legend() plt.tight_layout() ax = plt.gca() ax.xaxis.set_major_locator(MaxNLocator(integer=integer_thicks)) def plot_acc_vs_epochs(acc_list, title, graph_labels=None, graph_markers=None, graph_linetypes=None, graph_linecolors=None, grid=False): ''' Returns plot of multiple accuracies vs epochs :param acc_list: List of NumPy Arrays - Accuracies for multiple classifiers :param title: :param graph_labels: Labels per {x,y} plot pairs. :param graph_markers: https://matplotlib.org/api/markers_api.html :param graph_linetypes: https://matplotlib.org/gallery/lines_bars_and_markers/line_styles_reference.html :param graph_linecolors: https://matplotlib.org/2.1.1/api/_as_gen/matplotlib.pyplot.plot.html :param grid: bool :return: ''' x = np.linspace(1, len(acc_list[0]), num=len(acc_list[0])) plot_series(x, acc_list, title, 'Epoch', 'Classification Accuracy', graph_labels, graph_markers, graph_linetypes, graph_linecolors, True, grid) def plot_err_vs_epochs(acc_list, title, graph_labels=None, graph_markers=None, graph_linetypes=None, graph_linecolors=None, grid=False): ''' Returns plot of multiple accuracies vs epochs :param acc_list: List of NumPy Arrays - Accuracies for multiple classifiers :param title: :param graph_labels: Labels per {x,y} plot pairs. :param graph_markers: https://matplotlib.org/api/markers_api.html :param graph_linetypes: https://matplotlib.org/gallery/lines_bars_and_markers/line_styles_reference.html :param graph_linecolors: https://matplotlib.org/2.1.1/api/_as_gen/matplotlib.pyplot.plot.html :param grid: bool :return: ''' acc_list = 1 - np.array(acc_list) x = np.linspace(1, len(acc_list[0]), num=len(acc_list[0])) plot_series(x, acc_list, title, 'Epoch', 'Classification Error', graph_labels, graph_markers, graph_linetypes, graph_linecolors, True, grid) def plot_loss_vs_epochs(loss_list, title, graph_labels=None, graph_markers=None, graph_linetypes=None, graph_linecolors=None, grid=False): ''' Returns plot of multiple accuracies vs epochs :param loss_list: List of NumPy Arrays - Loss for multiple classifiers per epoch :param title: :param graph_labels: Labels per {x,y} plot pairs. :param graph_markers: https://matplotlib.org/api/markers_api.html :param graph_linetypes: https://matplotlib.org/gallery/lines_bars_and_markers/line_styles_reference.html :param graph_linecolors: https://matplotlib.org/2.1.1/api/_as_gen/matplotlib.pyplot.plot.html :param grid: bool :return: ''' x = np.linspace(1, len(loss_list[0]), num=len(loss_list[0])) plot_series(x, loss_list, title, 'Epoch', 'Epoch Loss', graph_labels, graph_markers, graph_linetypes, graph_linecolors, True, grid) def plot_learning_curve(train_samples, error_list, title, y_label, graph_labels=None, graph_markers=None, graph_linetypes=None, graph_linecolors=None, grid=False): ''' :param train_samples: list with the number of samples per point. :param error_list: list of train, test errors :param title: :param graph_labels: Labels per {x,y} plot pairs. :param graph_markers: https://matplotlib.org/api/markers_api.html :param graph_linetypes: https://matplotlib.org/gallery/lines_bars_and_markers/line_styles_reference.html :param graph_linecolors: https://matplotlib.org/2.1.1/api/_as_gen/matplotlib.pyplot.plot.html :param grid: bool :return: ''' plot_series(train_samples, error_list, title, 'Number of samples', y_label, graph_labels, graph_markers, graph_linetypes, graph_linecolors, True, grid) def _scatter(x, labels, title='', graph_labels=None, legend=True, median_labels=True): ''' :param x: 2 dimensional array {x,y} coordinates :param labels: Labels of the corresponding points :param title: :param graph_labels: class names array :param legend: Bool :param median_labels: Bool - Prints the numerical label i.e. {0, ..., N} in the median of the corresponding generated per-class point cloud. :return: ''' # choose a color palette with seaborn. num_classes = len(np.unique(labels)) palette = np.array(sns.color_palette("hls", num_classes)) class_based = [[] for x in range(num_classes)] f = plt.figure(dpi=1000) ax = plt.subplot(aspect='equal') sc = ax.scatter(x[:, 0], x[:, 1], lw=0, s=40, c=palette[labels.astype(np.int)]) for i in range(len(labels)): class_based[labels[i]].append(x[i]) for i in range(num_classes): X = np.array(class_based[i]) print(i, '- # samples:', X.shape) if graph_labels == None: plt.scatter(X[:, 0], X[:, 1], lw=0, s=40, alpha=0.5, c=palette[i], label=i) else: label = str(i)+' - '+graph_labels[i] plt.scatter(X[:, 0], X[:, 1], lw=0, s=40, alpha = 0.5, c=palette[i], label=label) #plt.xlim(-25, 25) #plt.ylim(-25, 25) plt.axis('off') if title is not '': plt.title(title) if legend: plt.legend(fontsize='small', bbox_to_anchor=(1.0, .95), handletextpad=0.1) plt.axis('tight') if median_labels: #add the labels for each digit corresponding to the label txts = [] for i in range(num_classes): # Position of each label at median of data points. (xtext, ytext) = np.median(x[labels == i, :], axis=0) txt = ax.text(xtext, ytext, str(i), fontsize=24) txt.set_path_effects([ PathEffects.Stroke(linewidth=5, foreground="w"), PathEffects.Normal()]) txts.append(txt) plt.tight_layout() plt.show() def tSNE_visualization(x, y, title='', graph_labels=None, legend=True, median_labels=True): ''' Generates a t-SNE visualization of the high-dimensional input space. :param x: 2 dimensional array {x,y} coordinates :param labels: Labels of the corresponding points :param title: :param graph_labels: class names array :param legend: Bool :param median_labels: Bool - Prints the numerical label i.e. {0, ..., N} in the median of the corresponding generated per-class point cloud. :return: ''' sns.set_style('darkgrid') sns.set_palette('muted') sns.set_context("notebook", font_scale=1.5, rc={"lines.linewidth": 2.5}) tsne = TSNE(n_components=2, perplexity=50, init='random', random_state=0).fit_transform(x,y) _scatter(tsne, y, title, graph_labels, legend, median_labels) if __name__ == '__main__': y_true = [2, 0, 2, 2, 0, 1] y_pred = [0, 0, 2, 2, 0, 2] #conf_matrix_ccm = np.array([[216, 2, 14, 0, 2, 26, 0, 0], [0, 214, 0, 0, 9, 2, 0, 3], [7, 0, 141, 3, 2, 4, 3, 0], # [3, 1, 5, 165, 0, 5, 11, 18], [8, 16, 5, 0, 215, 24, 2, 4], # [43, 14, 10, 3, 13, 217, 7, 3], # [0, 2, 4, 6, 2, 1, 170, 7], [1, 4, 0, 19, 6, 2, 1, 223]]) class_names = ['coast', 'forest', 'highway']#, 'insidecity', 'mountain', 'opencountry', 'street', 'tallbuilding'] # Compute confusion matrix # cnf_matrix = confusion_matrix(y_test, y_pred) np.set_printoptions(precision=2) # Plot non-normalized confusion matrix color = plt.cm.Purples plt.figure() plot_confusion_matrix(y_pred, y_true, classes=class_names, title='Confusion matrix - CCM', sideLabels=True) #plt.savefig('confMatrix_CCM.png', format='png', dpi=1000) #plt.show() plt.figure() y = [np.array([3,4,5,6,7,9,10]), np.array([4,5,6,7,9,10,1])] x = np.linspace(2.0, 3.0, num=len(y[0])) plot_series(x, y, 'Example','x_label', 'y_label', ['a', 'b'], ['.', 'o'], ['-','--'], ['b', 'c'], integer_thicks=False, grid=True) plt.show() plt.figure() y = [np.array([3, 4, 5, 6, 7, 9, 10])] plot_acc_vs_epochs(y, 'Classification Performance', ['classif_a'], grid=True) plt.show() plt.figure() y = [np.array([3, 4, 5, 6, 7, 9, 10])] plot_loss_vs_epochs(y, 'Classification Performance', ['classif_a'],grid=True) plt.show() <file_sep>import torch import torch.nn as nn import torch.optim as optim import torch.utils.data as data import torch.nn.functional as F import torch.utils.data as utils from torch.utils.data.sampler import SubsetRandomSampler import torchvision from torchvision import datasets, models, transforms import numpy as np import random def split_dataset(dataset, validation_split = 0.2): ''' splits dataset into training and validation subsets randomly. NOTE!: number of samples can differ per class. :param dataset: Training Dataset which is to be split. :return: Returns indices for training and validation ''' print('Validation Split: ', validation_split) dataset_size = len(dataset) indices = list(range(dataset_size)) split = int(np.floor(validation_split * dataset_size)) np.random.shuffle(indices) train_indices, val_indices = indices[split:], indices[:split] print('Sizes are respectively {} and {} samples for train and val respectively'.format( len(train_indices), len(val_indices))) return train_indices, val_indices def split_dataset_balanced(dataset, validation_split=0.2): ''' splits dataset into training and validation subsets in a balanced manner. i.e. len(class_i)=len(class_j) \forall {i,j} \in Classes. :param dataset: Training Dataset which is to be split. :return: Returns indices for training and validation ''' print('Validation Split: ', validation_split) dataset_size = len(dataset) indices = list(range(dataset_size)) labels = dataset.targets indices_per_label = [[] for i in range(len(np.unique(labels)))] [indices_per_label[labels[i]].append(indices[i]) for i in range(len(indices))] split = int(np.floor(validation_split * len(indices_per_label[0]))) val_indices = [] for i in indices_per_label: val_indices.extend(random.sample(i, split)) train_indices = list(set(indices).symmetric_difference(set(val_indices))) print('Sizes are respectively {} and {} samples for train and val respectively'.format( len(train_indices), len(val_indices))) return train_indices, val_indices def createRandomSampler_multiple(train_indices, val_indices): ''' :param train_indices: sampled indexes for training :param val_indices: sampled indexes for validation :return: returns tuple of SubsetRandomSampler (train_sampler, val_sampler) (see Torch for more info) ''' train_sampler = createRandomSampler(train_indices) val_sampler = createRandomSampler(val_indices) return train_sampler, val_sampler def createRandomSampler(train_indices): ''' :param train_indices: sampled indexes for training :param val_indices: sampled indexes for validation :return: returns tuple of SubsetRandomSampler (train_sampler, val_sampler) (see Torch for more info) ''' train_sampler = SubsetRandomSampler(train_indices) return train_sampler def normalize(samples, std_dev, mean): pass def unnormalize(samples, std_dev, mean): ''' :param samples: normalized samples :param std_dev: estimated std_dev :param mean: :return: Returns unnormalized samples by x = x_norm * std_dev + mean ''' un_samples = samples * std_dev + mean return un_samples def to_NNlabels(labels): ''' :param labels: receives labels with numerical orderings [1, ... , N_max, ..., 2] :return: returns numpy array with labels of the form [[1, 0, ...], ... , [0, ..., 1] , ... , [0, 1, ...]] (see input form) ''' max_class = max(labels) NNlabels = np.zeros((len(labels), max_class), dtype=np.float) for i in range(len(labels)): NNlabels[i, labels[i]-1] = 1. return NNlabels def dataset_from_dict(dict): ''' Creates a tuple (samples, label) adequate for CNN training. :param dict: Dict from which to extract the labels. Structure: {label_i:[samples_class_i]} :return: tuple (samples, label) adequate for CNN training. ''' samples = [] labels = [] key_mapping = {key:i for i, key in enumerate(dict.keys(),0)} [samples.extend(i) for _,i in dict.items()] [labels.extend([key_mapping[key]] * len(dict[key])) for key in dict.keys()] samples = np.array(samples) #labels = to_NNlabels(labels) --- Apparently nn_loss requires hot-coded vector with class indices labels = np.array(labels) return samples, labels def create_Dataset_for_classif(data, labels): ''' Creates a Dataset out of a list, which can directly be used by PyTorch. :param data: :param labels: :return: torch.Dataset ''' data = torch.from_numpy(data).transpose(2, 1) labels = np.expand_dims(labels, axis=1) labels = torch.from_numpy(labels).transpose(2, 1) return utils.TensorDataset(data, labels) def create_Dataset_for_reconstr(data): ''' Creates a Dataset out of a list, which can directly be used by PyTorch. For econstruction tasks. :param data: :return: torch.Dataset ''' data = torch.from_numpy(data).transpose(2, 1) dataset = utils.TensorDataset(data, data) return utils.TensorDataset(dataset, dataset) def create_Dataset_for_classif_and_reconstr(data, labels): ''' Creates a Dataset out of a list, which can directly be used by PyTorch. For combined classification/reconstruction tasks. :param data: :param labels: :return: torch.Dataset ''' labels = np.expand_dims(labels, axis=1) labels = np.expand_dims(labels, axis=2) data = torch.from_numpy(data).transpose(2, 1) labels_reconstr = torch.from_numpy(np.concatenate((data, labels), axis=1)).transpose(2, 1) return utils.TensorDataset(data, labels_reconstr) <file_sep>import torch.nn as nn import torch.nn.functional as F class VGG_Small(nn.Module): """ This class implements a small version of the popular VGG network, which won the ImageNet 2014 challenge. """ def __init__(self, n_channels, n_classes): """ Initializes ConvNet object. :param n_channels: number of input channels :param n_classes: umber of classes of the classification problem """ super(VGG_Small, self).__init__() # Internal Params kernel_size = 3 padding = 1 self.conv1 = nn.Conv2d(n_channels, 64, kernel_size, padding=padding) self.bn1 = nn.BatchNorm2d(64) self.max1 = nn.MaxPool2d(3, stride=2, padding=padding) self.conv2 = nn.Conv2d(64, 128, kernel_size, padding=padding) self.bn2 = nn.BatchNorm2d(128) self.max2 = nn.MaxPool2d(3, stride=2, padding=padding) self.conv3_a = nn.Conv2d(128, 256, kernel_size, padding=padding) self.bn3_a = nn.BatchNorm2d(256) self.conv3_b = nn.Conv2d(256, 256, kernel_size, padding=padding) self.bn3_b = nn.BatchNorm2d(256) self.max3 = nn.MaxPool2d(3, stride=2, padding=padding) self.conv4_a = nn.Conv2d(256, 512, kernel_size, padding=padding) self.bn4_a = nn.BatchNorm2d(512) self.conv4_b = nn.Conv2d(512, 512, kernel_size, padding=padding) self.bn4_b = nn.BatchNorm2d(512) self.max4 = nn.MaxPool2d(3, stride=2, padding=padding) self.conv5_a = nn.Conv2d(512, 512, kernel_size, padding=padding) self.bn5_a = nn.BatchNorm2d(512) self.conv5_b = nn.Conv2d(512, 512, kernel_size, padding=padding) self.bn5_b = nn.BatchNorm2d(512) self.max5 = nn.MaxPool2d(3, stride=2, padding=padding) self.avg = nn.AvgPool2d(1, stride=1, padding=0) self.linear = nn.Linear(512, n_classes) def forward(self, x): """ Performs forward pass of the input. Here an input tensor x is transformed through several layer transformations. :param x: input to the network :return out: outputs of the network """ x = self.feature_extractor(x) x = self.linear(x) return x def feature_extractor(self, x): """ Performs forward pass of the input. Here an input tensor x is transformed through several layer transformations. :param x: input to the network :return out: outputs of the network """ x = self.max1(F.relu(self.bn1(self.conv1(x)))) x = self.max2(F.relu(self.bn2(self.conv2(x)))) x = F.relu(self.bn3_a(self.conv3_a(x))) x = self.max3(F.relu(self.bn3_b(self.conv3_b(x)))) x = F.relu(self.bn4_a(self.conv4_a(x))) x = self.max4(F.relu(self.bn4_b(self.conv4_b(x)))) x = F.relu(self.bn5_a(self.conv5_a(x))) x = self.max5(F.relu(self.bn5_b(self.conv5_b(x)))) x = self.avg(x) x = x.view(-1, 512) return x <file_sep>import torch import torch.nn as nn import torch.optim as optim import torchvision import torchvision.transforms as transforms import matplotlib.pyplot as plt import seaborn as sns from sklearn import manifold, datasets from sklearn.linear_model import LogisticRegression from sklearn.neighbors import KNeighborsClassifier from sklearn.ensemble import RandomForestClassifier import code.CI_utils.CI_utils.data_preparation as data_prep import code.CI_utils.CI_utils.graphs as graphs import code.CI_utils.CI_utils.metrics as metrics import code.CI_utils.CI_utils.networks_classif as nets import code.CI_utils.CI_utils.networks_classif_train as nets_train import code.CI_utils.CI_utils.networks_classif_test as nets_test import code.CI_utils.CI_utils.networks_classif_visualize as nets_visual import numpy as np import cv2 # ------ Global Variables ------ CLASSES = ('plane', 'car', 'bird', 'cat', 'deer', 'dog', 'frog', 'horse', 'ship', 'truck') # ------ Functions ------ def get_hog() : winSize = (32,32) blockSize = (16,16) blockStride = (8,8) cellSize = (8,8) nbins = 9 derivAperture = 1 winSigma = -1. histogramNormType = 0 L2HysThreshold = 0.2 gammaCorrection = 1 nlevels = 64 signedGradient = False hog = cv2.HOGDescriptor(winSize,blockSize,blockStride,cellSize,nbins, derivAperture,winSigma,histogramNormType,L2HysThreshold, gammaCorrection,nlevels, signedGradient) return hog def imshow(img): img = img / 2 + 0.5 # unnormalize npimg = img.numpy() plt.imshow(np.transpose(npimg, (1, 2, 0))) plt.show() def extract_hog_labels_from_loader(dataloader, hog): hog_descr = [] labels = [] for input, label in dataloader: un_img = data_prep.unnormalize(input[0], 64, 128) inputs = un_img.numpy().transpose(1, 2, 0).astype(np.uint8) hog_descr.append(hog.compute(inputs)) labels.append(label) return hog_descr, labels def direct_features(dataloader): descr = [] labels = [] for input, label in dataloader: input = input[0].numpy().transpose(1, 2, 0).reshape(-1) descr.append(input) labels.append(label) return descr, labels def logisticRegression(x_train, y_train, x_test, y_test, colors=plt.cm.Purples): print('Logistic Regression') logreg = LogisticRegression(C=1e5, solver='lbfgs', multi_class='multinomial', max_iter=100) logreg.fit(x_train, y_train) Yhat_train = logreg.predict(x_train) Yhat = logreg.predict(x_test) #graphs.plot_confusion_matrix(Yhat, y_test, CLASSES, False, '', cmap=colors) err_train = metrics.error(y_train, Yhat_train) err_test = metrics.error(y_test, Yhat) return err_train, err_test def knn(x_train, y_train, x_test, y_test, colors=plt.cm.Purples): print('kNN') neigh = KNeighborsClassifier(n_neighbors=5, weights='distance') neigh.fit(x_train, y_train) Yhat_train = neigh.predict(x_train) Yhat = neigh.predict(x_test) #graphs.plot_confusion_matrix(Yhat, y_test, CLASSES, False, '', cmap=colors) err_train = metrics.error(y_train, Yhat_train) err_test = metrics.error(y_test, Yhat) return err_train, err_test def randomForest(x_train, y_train, x_test, y_test, colors=plt.cm.Purples): print('Random Forest') rf = RandomForestClassifier(n_estimators=128) rf.fit(x_train, y_train) Yhat_train = rf.predict(x_train) Yhat = rf.predict(x_test) #graphs.plot_confusion_matrix(Yhat, y_test, CLASSES, False, '', cmap=colors) err_train = metrics.error(y_train, Yhat_train) err_test = metrics.error(y_test, Yhat) return err_train, err_test if __name__ == '__main__': transform = transforms.Compose( [transforms.ToTensor(), transforms.Normalize((0.5, 0.5, 0.5), (0.5, 0.5, 0.5))]) # Define datasets trainset = torchvision.datasets.CIFAR10(root='./data', train=True, download=True, transform=transform) testset = torchvision.datasets.CIFAR10(root='./data', train=False, download=True, transform=transform) # Define train, val, test set: _, subset_train = data_prep.split_dataset(trainset, 0.005) # obtain 0.1% of the dataset subset_train, subset_val = data_prep.split_dataset(subset_train, 0.2) _, subset_test = data_prep.split_dataset(testset, 0.01) val_split = 0.006 fraction_of_dataset = 0.01 #val_splits = np.linspace(0.001, 0.2, 20) val_splits = [0.08] errors_raw = {} errors_hog = {} no_samples = [] for i in ('logreg', 'knn', 'rf'): errors_raw[i] = [[], []] errors_hog[i] = [[], []] for val_split in val_splits: print('val_split: {}\n'.format(val_split)) _, subset_train = data_prep.split_dataset_balanced(trainset, val_split) # obtain 0.1% of the dataset _, subset_val = data_prep.split_dataset(subset_train, val_split) _, subset_test = data_prep.split_dataset_balanced(testset, 0.1) train_sampler, val_sampler = data_prep.createRandomSampler_multiple(subset_train, subset_val) test_sampler = data_prep.createRandomSampler(subset_test) # Define loaders: train_loader = torch.utils.data.DataLoader(trainset, batch_size=1, sampler=train_sampler, shuffle=False, num_workers=2) val_loader = torch.utils.data.DataLoader(trainset, batch_size=1, sampler=val_sampler, shuffle=False, num_workers=2) #test_loader = torch.utils.data.DataLoader(testset, batch_size=32, sampler=test_sampler, # shuffle=False, num_workers=2) test_loader = torch.utils.data.DataLoader(testset, batch_size=32, shuffle=False, num_workers=2) print('\nDataset sizes: Train: {}, Val: {}, Test: {}'. format(len(subset_train), len(subset_val), len(subset_test))) no_samples.append(len(subset_train)) # 1. --- Initial Representation for the dataset [Features, Dissimilarities] # 1.a - Pixelwise value # --- Train/Val direct_feats, train_lbls = direct_features(train_loader) direct_feats = np.array(direct_feats).squeeze() train_lbls = np.array(train_lbls) #graphs.tSNE_visualization(direct_feats, train_lbls, '', CLASSES, False) # --- Test direct_feats_t, test_lbls = direct_features(test_loader) direct_feats_t = np.array(direct_feats_t).squeeze() test_lbls = np.array(test_lbls) # 1.b - Histogram of Gradients representation hog = get_hog() train_hog, train_lbls = extract_hog_labels_from_loader(train_loader, hog) train_hog = np.array(train_hog).squeeze() train_lbls = np.array(train_lbls) #graphs.tSNE_visualization(train_hog, train_lbls, '', CLASSES, True) # --- Test test_hog, test_lbls = extract_hog_labels_from_loader(test_loader, hog) test_hog = np.array(test_hog).squeeze() test_lbls = np.array(test_lbls) # 2. --- Study three different classifiers [Learning Curves, Confusion Matrices] --- # --- Logistic Regression # Pixelwise values print('\t raw') err_train, err_test = logisticRegression(direct_feats, train_lbls, direct_feats_t, test_lbls, plt.cm.Blues) errors_raw['logreg'][0].append(err_train) errors_raw['logreg'][1].append(err_test) # HOG features print('\t hog') err_train, err_test = logisticRegression(train_hog, train_lbls, test_hog, test_lbls) errors_hog['logreg'][0].append(err_train) errors_hog['logreg'][1].append(err_test) # --- k-NN Classifier # Pixelwise values print('\t raw') err_train, err_test = knn(direct_feats, train_lbls, direct_feats_t, test_lbls, plt.cm.Blues) errors_raw['knn'][0].append(err_train) errors_raw['knn'][1].append(err_test) # HOG features print('\t hog') err_train, err_test = knn(train_hog, train_lbls, test_hog, test_lbls) errors_hog['knn'][0].append(err_train) errors_hog['knn'][1].append(err_test) # --- Random Forest (512) # Pixelwise values print('\t raw') err_train, err_test = randomForest(direct_feats, train_lbls, direct_feats_t, test_lbls, plt.cm.Blues) errors_raw['rf'][0].append(err_train) errors_raw['rf'][1].append(err_test) # HOG features print('\t hog') err_train, err_test = randomForest(train_hog, train_lbls, test_hog, test_lbls) errors_hog['rf'][0].append(err_train) errors_hog['rf'][1].append(err_test) if val_split == 0.08: # Comparison with neural network conv_net = nets.VGG_Small(3, len(CLASSES)) subset_val, subset_train = data_prep.split_dataset_balanced(trainset, val_split) print('CNN: length train-set: {} and val-set: {}'.format(len(subset_train), len(subset_val))) # Define loaders: dataloaders = {} dataloaders['train'] = torch.utils.data.DataLoader(trainset, batch_size=32, sampler=train_sampler, shuffle=False, num_workers=2) dataloaders['validation'] = torch.utils.data.DataLoader(trainset, batch_size=32, sampler=val_sampler, shuffle=False, num_workers=2) criterion = nn.CrossEntropyLoss() optimizer = optim.Adam(conv_net.parameters(), lr=1e-3) # , weight_decay=5e-4) scheduler = optim.lr_scheduler.ReduceLROnPlateau(optimizer, 'min', patience=10) device = torch.device("cuda" if torch.cuda.is_available() else "cpu") conv_net.to(device) _, av, lv, at, lt = nets_train.train(conv_net, 100, criterion, optimizer, dataloaders, scheduler, device, "CONV-Model.pth") acc, lbls, pred = nets_test.test_model(conv_net, test_loader, device, return_pred=True, load=True, path="CONV-Model.pth") print('CNN Accuracy: {}'.format(acc)) graphs.plot_confusion_matrix(pred, lbls, CLASSES, title='', cmap=plt.cm.Oranges) encodings, labels = nets_visual.visualize_model(conv_net, dataloaders['train'], device) print(np.array(encodings).shape) graphs.tSNE_visualization(np.array(encodings), np.array(labels), '', CLASSES, True) print('\n\n') label = ['Raw', 'HOG'] for index, error_array in enumerate([errors_raw, errors_hog]): plt.figure(dpi=1000) colors = {'logreg':'r', 'knn':'g', 'rf':'b'} for i in error_array.keys(): colors_i = [colors[i], colors[i]] y_label = 'Classif. Error - '+ label[index] + ' Features' graphs.plot_learning_curve(np.array(no_samples), np.array(error_array[i]), '', graph_linecolors=colors_i, graph_linetypes=['--','-'], graph_markers=['.', 'o'], grid=False, graph_labels=[i+' - train', i+' - test'], y_label=y_label) plt.show() <file_sep>import torch def test_model(model, test_loader, device, load=False, path=None, return_pred=False): if load: assert(path is not None) model.load_state_dict(torch.load(path)) model.eval() model.to(device) lbls = [] pred = [] correct = 0 total = 0 with torch.no_grad(): for inputs, labels in test_loader: inputs = inputs.to(device) labels = labels.to(device) outputs = model(inputs) _, predicted = torch.max(outputs.data, 1) if return_pred: #print(predicted) lbls.extend(labels.cpu().tolist()) pred.extend(predicted.cpu().squeeze().tolist()) total += labels.size(0) correct += (predicted == labels).sum().item() print('Accuracy of the network on the {} test images: {}'.format( total, (100 * correct / total))) return correct/total, lbls, pred<file_sep>import numpy as np import matplotlib.pyplot as plt from sklearn.linear_model import LogisticRegression
1cc4d101559ee07386d6d0d0442fb54cb3d904fd
[ "Markdown", "Python" ]
13
Python
ci-group/CI_utils
1102425eeab194bd5390273909c8437a1c102d68
63dba00d7a4e2590cda2c21a58c2dc7f4bb4c9c2
refs/heads/master
<file_sep>droidconNL2013 ============== Presentation for droidcon NL 2013 Developement Tools ------------------ This presentation uses [reveal.js][revealjs] which advocates itself as > HTML Presentations Made Easy Furthermore we use [bower][] to install packages for the web. bower depends on [npm][] for its installation. npm comes installed with [node][]. Go to [node's download][node-download] page to retrieve a distribution. After that running `[sudo] npm install -g bower` will install bower globally on your system. This allows one to execute the following command to install all web packages needed by this presentation. ```shell bower install ``` [revealjs]: http://lab.hakim.se/reveal-js/#/ [bower]: bower.io [npm]: https://npmjs.org/ [node]: http://nodejs.org/ [node-download]: http://nodejs.org/download/ <file_sep>(function(Reveal, io){ var Percentage = function(){ this.observers = []; this.value = 0.0; } Percentage.prototype.set = function(value){ this.value = Math.max(0, Math.min(100, Math.floor(value))); this.notify(); } Percentage.prototype.notify = function(){ this.observers.forEach(function(observer){ observer.call(this, this, this.value); }.bind(this)); } Percentage.prototype.addListener = function(callback){ this.observers.push(callback); } var PercentageView = function(id, percentage) { this.element = document.getElementById(id); this.percentage = percentage; this.percentage.addListener(this.update.bind(this)); this.update(); } PercentageView.prototype.update = function(){ this.element.textContent = this.percentage.value; } var percentages = ['pi-single', 'pi-multi', 'pi-child'].map(function(id){ var percentage = new Percentage(); new PercentageView(id, percentage); return percentage; }); var socket = io.connect(window.location.origin); socket.on('data', function(data){ percentages.forEach(function(percentage){ percentage.set(data.value); }); }); Reveal.initialize({ controls: true, progress: true, history: true, center: true, theme: 'default', transition: 'default', dependencies: [ { src: 'bower_components/reveal.js/plugin/highlight/highlight.js', async: true, callback: function() { hljs.initHighlightingOnLoad(); } } ] }); })(Reveal, io); <file_sep>var express = require('express'); var app = express(); var server = require('http').createServer(app); var io = require('socket.io').listen(server); app.set('port', process.env.PORT || 3435); app.use('/static', express.static(__dirname + '/public')); app.get('/', function(request, response) { response.redirect('/static/'); }); server.listen(app.get('port')); console.log('server started at port %s', app.get('port')); io.sockets.on('connection', function(socket){ console.log('socket %s connected', socket.id); socket.on('data', function(data){ var max = 70; var value = Math.max(0, Math.min(max, data.beta)); var percentage = 100 * value / max; io.sockets.emit('data', { value: percentage }); }); })
bf8ab7a667bd5f5e768140df0099fc718921b1b4
[ "Markdown", "JavaScript" ]
3
Markdown
androidpi/droidconNL2013
b8b2fbbe9bc177896233e28068606d7782d704fd
3ee416a6f5ec72d2075081c0ad10d6c40f5f7bdc
refs/heads/master
<file_sep>draft_cm = require(GetScriptDirectory()..'/CM/handle') function Think() if (GetGameMode() == GAMEMODE_CM) then draft_cm.Handle() else print('Other mode launched, bypass') end end <file_sep>require(GetScriptDirectory()..'/utils/hero_bot_data') M = {} local cm_draft = { [HEROPICK_STATE_CM_INTRO] = 'nop', [HEROPICK_STATE_CM_CAPTAINPICK] = function () return HandleCaptainPick() end, [HEROPICK_STATE_CM_BAN1] = function () return HandleBan(1) end, [HEROPICK_STATE_CM_BAN2] = function () return HandleBan(2) end, [HEROPICK_STATE_CM_BAN3] = function () return HandleBan(3) end, [HEROPICK_STATE_CM_BAN4] = function () return HandleBan(4) end, [HEROPICK_STATE_CM_BAN5] = function () return HandleBan(5) end, [HEROPICK_STATE_CM_BAN6] = function () return HandleBan(6) end, [HEROPICK_STATE_CM_BAN7] = function () return HandleBan(7) end, [HEROPICK_STATE_CM_BAN8] = function () return HandleBan(8) end, [HEROPICK_STATE_CM_BAN9] = function () return HandleBan(9) end, [HEROPICK_STATE_CM_BAN10] = function () return HandleBan(10) end, [HEROPICK_STATE_CM_SELECT1] = function () return HandlePick(1) end, [HEROPICK_STATE_CM_SELECT2] = function () return HandlePick(2) end, [HEROPICK_STATE_CM_SELECT3] = function () return HandlePick(3) end, [HEROPICK_STATE_CM_SELECT4] = function () return HandlePick(4) end, [HEROPICK_STATE_CM_SELECT5] = function () return HandlePick(5) end, [HEROPICK_STATE_CM_SELECT6] = function () return HandlePick(6) end, [HEROPICK_STATE_CM_SELECT7] = function () return HandlePick(7) end, [HEROPICK_STATE_CM_SELECT8] = function () return HandlePick(8) end, [HEROPICK_STATE_CM_SELECT9] = function () return HandlePick(9) end, [HEROPICK_STATE_CM_SELECT10] = function () return HandlePick(10) end, [HEROPICK_STATE_CM_PICK] = function () return HandleSelect() end, } function M.Handle() if (GetGameState() ~= GAME_STATE_HERO_SELECTION) then print('Not hero selection phase, exitting') return end local action = cm_draft[GetHeroPickState()] if type(action) == 'function' then action() elseif action == nil then print('Unknown pick state!!') end end local captain_picked = false local use_drafter_bot = false function HandleCaptainPick() if not HasHumanInTeam() or (DotaTime() > -1) then if not captain_picked then captain_picked = true local first_bot = GetFirstBotPlayer() if first_bot ~= nil then SetCMCaptain(first_bot) use_drafter_bot = true print(GetTeamName()..': Using drafter bot') end end end end local has_human_in_team function HasHumanInTeam() if has_human_in_team ~= nil then return has_human_in_team end local players = GetTeamPlayers(GetTeam()) for i, player_id in pairs(players) do if not IsPlayerBot(player_id) then has_human_in_team = true print(GetTeamName()..': Has human in team') return has_human_in_team end end has_human_in_team = false print(GetTeamName()..': Hasn\'t human in team') return has_human_in_team end local first_bot_player local got_first_bot function GetFirstBotPlayer() if got_first_bot == true then return first_bot_player end got_first_bot = true local players = GetTeamPlayers(GetTeam()) for i, player_id in pairs(players) do if IsPlayerBot(player_id) then first_bot_player = player_id return first_bot_player end end first_bot_player = nil return first_bot_player end local bans = {} local enemy_picks = {} local my_picks = {} local state_refreshed = {} function RefreshDraftState() if state_refreshed[GetHeroPickState()] ~= nil then return end for hero, data in pairs(hero_bot_data.heroes) do if bans[hero] == nil then if IsCMBannedHero(hero) then bans[hero] = true else if (my_picks[hero] == nil) and (enemy_picks[hero] == nil) then if IsCMPickedHero(GetEnemyTeam(), hero) then enemy_picks[hero] = true elseif IsCMPickedHero(GetTeam(), hero) then my_picks[hero] = true end end end end end end local team_composition local available_heroes = {} for hero, data in pairs(hero_bot_data.heroes) do available_heroes[hero] = data end function CreateTeamComposition() -- Should be based on currently made picks local new_comp = {} for hero, _ in pairs(my_picks) do new_comp[hero] = true end -- Refresh available heroes for hero, data in pairs(hero_bot_data.heroes) do if (bans[hero] ~= nil) or (enemy_picks[hero] ~= nil) or (my_picks[hero] ~= nil) then available_heroes[hero] = nil else available_heroes[hero] = data end end -- TODO: Not so dummy team filling for idx = #new_comp + 1, 5 do local hero, data = next(available_heroes) if hero == nil then break end available_heroes[hero] = nil new_comp[hero] = true end --[[local str_comp = '' for hero, _ in pairs(new_comp) do str_comp = str_comp..hero..', ' end print(string.format('%s: new composition is %s', GetTeamName(), str_comp))]]-- return new_comp end function ValidateTeamComposition() if team_composition == nil then return end local need_invalidate = false for hero, _ in pairs(team_composition) do if (bans[hero] ~= nil) or (enemy_picks[hero] ~= nil) then --print(string.format('%s: hero %s is banned or stolen, invalidating composition', GetTeamName(), hero)) need_invalidate = true break end end if need_invalidate then team_composition = nil end end function GetBan() -- TODO: Evaluate enemy strategy and do more clever bans for hero, data in pairs(hero_bot_data.heroes) do if (bans[hero] == nil) and (enemy_picks[hero] == nil) and (team_composition[hero] == nil) then return hero end end end function GetPick() for hero, _ in pairs(team_composition) do if my_picks[hero] == nil then my_picks[hero] = true return hero end end end function HandleBan(idx) RefreshDraftState() if not use_drafter_bot or not IsPlayerInHeroSelectionControl(GetCMCaptain()) then return end --print(string.format('%s: HandleBan %d', GetTeamName(), idx)) ValidateTeamComposition() if team_composition == nil then team_composition = CreateTeamComposition() end CMBanHero(GetBan()) end function HandlePick(idx) RefreshDraftState() if not use_drafter_bot or not IsPlayerInHeroSelectionControl(GetCMCaptain()) then return end --print(string.format('%s: HandlePick %d', GetTeamName(), idx)) ValidateTeamComposition() if team_composition == nil then team_composition = CreateTeamComposition() end CMPickHero(GetPick()) end function AreHumansSelectedHeroes() local my_boyz = GetTeamPlayers(GetTeam()) for _, player_id in pairs(my_boyz) do if not IsPlayerBot(player_id) then local selected_hero = GetSelectedHeroName(player_id) if (selected_hero == nil) or (selected_hero == '') then return false end end end return true end local team_selected = false function HandleSelect() RefreshDraftState() if (not team_selected) and (AreHumansSelectedHeroes() or (GetCMPhaseTimeRemaining() < 1)) then local my_boyz = GetTeamPlayers(GetTeam()) --print(string.format('%s: Handle Select', GetTeamName())) local undecided_boyz = {} for _, player_id in pairs(my_boyz) do local selected_hero = GetSelectedHeroName(player_id) if (selected_hero ~= nil) and (selected_hero ~= '') then my_picks[selected_hero] = false else table.insert(undecided_boyz, player_id) end end local idx = 1 for hero, is_free in pairs(my_picks) do if is_free then SelectHero(undecided_boyz[idx], hero) idx = idx + 1 end end team_selected = true end end function GetEnemyTeam() if GetTeam() == TEAM_RADIANT then return TEAM_DIRE else return TEAM_RADIANT end end local team_to_text function GetTeamName() if not team_to_text then team_to_text = { [TEAM_RADIANT] = 'RADIANT', [TEAM_DIRE] = 'DIRE', [TEAM_NEUTRAL] = 'NEUTRAL', [TEAM_NONE] = 'NONE' } end return team_to_text[GetTeam()] or 'Unknown' end return M<file_sep># DotA2 Draft Bot Draft bot based on DotA 2 bot API # Description Enables draft logic in bot games for modes besides AP. Contains tool for game data extraction and conversion to LUA table for further usage. ## Restrictions - only CM mode is supported for now; - random heroes used for bans and picks. # Usage Copy files to <Dota2 directory>\game\dota\scripts\vscripts\bots\ and launch game in lobby with Local scripts enabled. <file_sep>import vdf implemented_bots = set([ 'npc_dota_hero_axe', 'npc_dota_hero_bane', 'npc_dota_hero_bounty_hunter', 'npc_dota_hero_bloodseeker', 'npc_dota_hero_bristleback', 'npc_dota_hero_chaos_knight', 'npc_dota_hero_crystal_maiden', 'npc_dota_hero_dazzle', 'npc_dota_hero_death_prophet', 'npc_dota_hero_dragon_knight', 'npc_dota_hero_drow_ranger', 'npc_dota_hero_earthshaker', 'npc_dota_hero_jakiro', 'npc_dota_hero_juggernaut', 'npc_dota_hero_kunkka', 'npc_dota_hero_lich', 'npc_dota_hero_lina', 'npc_dota_hero_lion', 'npc_dota_hero_luna', 'npc_dota_hero_necrolyte', 'npc_dota_hero_omniknight', 'npc_dota_hero_oracle', 'npc_dota_hero_phantom_assassin', 'npc_dota_hero_pudge', 'npc_dota_hero_razor', 'npc_dota_hero_sand_king', 'npc_dota_hero_nevermore', 'npc_dota_hero_skywrath_mage', 'npc_dota_hero_sniper', 'npc_dota_hero_sven', 'npc_dota_hero_tidehunter', 'npc_dota_hero_tiny', 'npc_dota_hero_vengefulspirit', 'npc_dota_hero_viper', 'npc_dota_hero_warlock', 'npc_dota_hero_windrunner', 'npc_dota_hero_witch_doctor', 'npc_dota_hero_skeleton_king', 'npc_dota_hero_zuus', ]) heroes = vdf.load(open(r'D:\games\steamapps\common\dota 2 beta\game\dota\scripts\npc\npc_heroes.txt')) with open('hero_bot_data.lua', 'w') as output: # Write module exporting stuff #1 output.write('_G._savedEnv = getfenv()\n') output.write('module("hero_bot_data", package.seeall)\n') output.write('\n') # Collect all hero types hero_types = set() hero_type_ids = {} for name, data in heroes['DOTAHeroes'].iteritems(): if isinstance(data, dict) and 'Bot' in data: this_hero_type = data['Bot']['HeroType'].split('|') for hero_type in this_hero_type: hero_types.add(hero_type.strip()) idx = 1 for hero_type in hero_types: hero_type_ids[hero_type] = idx output.write('%s = %d\n' % (hero_type, idx)) idx *= 2 output.write('\n') # Fill LaningInfo and HeroType output.write('heroes = {\n') supported_list = [] not_supported_list = [] for name, data in heroes['DOTAHeroes'].iteritems(): if isinstance(data, dict) and data.get('CMEnabled', '0') == '1': human_name = data['url'].replace('_', ' ') if 'Bot' not in data: not_supported_list.append(human_name) continue laning_info = [] try: for key, value in data['Bot']['LaningInfo'].iteritems(): laning_info.append('[\'%s\'] = %s' % (key, value)) this_hero_type = 0 this_hero_type_raw = data['Bot']['HeroType'].split('|') for hero_type in this_hero_type_raw: this_hero_type |= hero_type_ids[hero_type.strip()] if ('Loadout' not in data['Bot']) or (name not in implemented_bots): not_supported_list.append(human_name) else: output.write(' [\'%s\'] = {[\'HeroType\'] = %s, [\'LaningInfo\'] = {%s}},\n' % (name, this_hero_type, ', '.join(laning_info))) supported_list.append(human_name) except KeyError as ex: not_supported_list.append(human_name) output.write('}\n\n') # Write module exporting stuff #2 output.write('for k,v in pairs(hero_bot_data) do _G._savedEnv[k] = v end\n') supported_list.sort() print 'Fully operational:' for hero in supported_list: print ' - %s' % hero not_supported_list.sort() print '\nNot supported:' for hero in not_supported_list: print ' - %s' % hero
9d73efdd1039e218ee884c11f4fe33125f16ecab
[ "Markdown", "Python", "Lua" ]
4
Lua
Dalanar/DotA2DraftBot
6ff222782a6c40d99004eeee101ca912e6e8dd11
4b3591b389b56e70729bf95d0b5509f9b00fafeb
refs/heads/main
<file_sep>package com.service.openapi.trade.naverapi.entity.naver; import java.io.Serializable; import javax.persistence.*; import com.service.openapi.trade.naverapi.entity.EntityBaseAudit; import lombok.*; @Entity @Table(name = "naver_shopping_category") @NoArgsConstructor(access = AccessLevel.PROTECTED) @Getter public class NaverShoppingCategory extends EntityBaseAudit implements Serializable { @Id @Column(name = "code", length = 20, nullable = false, columnDefinition = "varchar(20) default '' comment '카테고리 코드'") private String code; @Column(name = "category_1", length = 128, nullable = false, columnDefinition = "varchar(128) default '' comment '1차 카테고리 정보'") private String category1; @Column(name = "category_2", length = 128, columnDefinition = "varchar(128) comment '2차 카테고리 정보'") private String category2; @Column(name = "category_3", length = 128, columnDefinition = "varchar(128) comment '3차 카테고리 정보'") private String category3; @Column(name = "category_4", length = 128, columnDefinition = "varchar(128) comment '4차 카테고리 정보'") private String category4; @Builder private NaverShoppingCategory(final String code, final String category1, final String category2, final String category3, final String category4) { this.code = code; this.category1 = category1; this.category2 = category2; this.category3 = category3; this.category4 = category4; } } <file_sep>package com.service.openapi.trade.naverapi.repository.naver; import com.service.openapi.trade.naverapi.entity.naver.NaverShoppingCategory; import org.springframework.data.jpa.repository.JpaRepository; public interface NaverShoppingCategoryRepository extends JpaRepository<NaverShoppingCategory, String> { } <file_sep>package com.service.openapi.trade.naverapi.model.client; import java.util.List; import lombok.Builder; import lombok.Getter; @Builder @Getter public class CategoryTrendRequest { private final String startDate; private final String endDate; private final String timeUnit; private final String device; private final String gender; private final List<String> ages; private final List<DtoCategory> category; /** * startDate string Y 조회 기간 시작 날짜(yyyy-mm-dd 형식). 2017년 8월 1일부터 조회할 수 있습니다. * endDate string Y 조회 기간 종료 날짜(yyyy-mm-dd 형식) * timeUnit string Y 구간 단위 * - date: 일간 * - week: 주간 * - month: 월간 * category array(JSON) Y 분야 이름과 분야 코드 쌍의 배열. 최대 3개의 쌍을 배열로 설정할 수 있습니다. * category.name string Y 쇼핑 분야 이름 * category.param array(string) Y 쇼핑 분야 코드. 네이버쇼핑에서 카테고리를 선택했을 때의 URL에 있는 cat_id 파라미터의 값으로 분야 코드를 확인할 수 있습니다. * device string N 기기. 검색 환경에 따른 조건입니다. * - 설정 안 함: 모든 기기에서의 검색 클릭 추이 * - pc: PC에서의 검색 클릭 추이 * - mo: 모바일 기기에서의 검색 클릭 추이 * gender string N 성별. 검색 사용자의 성별에 따른 조건입니다. * - 설정 안 함: 모든 성별 * - m: 남성 * - f: 여성 * ages array(JSON) N 연령. 검색 사용자의 연령에 따른 조건입니다. * - 설정 안 함: 모든 연령 * - 10: 10∼19세 * - 20: 20∼29세 * - 30: 30∼39세 * - 40: 40∼49세 * - 50: 50∼59세 * - 60: 60세 이상 */ } <file_sep>package com.service.openapi.trade.naverapi.util; import com.fasterxml.jackson.core.type.TypeReference; import com.google.gson.Gson; import com.google.gson.JsonSyntaxException; import lombok.AccessLevel; import lombok.NoArgsConstructor; import lombok.extern.slf4j.Slf4j; import org.springframework.stereotype.Component; @Component @NoArgsConstructor(access = AccessLevel.PROTECTED) @Slf4j public class JsonConvert { private static final Gson gson = new Gson(); public static <T> String toString(final T object) { return gson.toJson(object); } public static <T> T toObject(final String jsonString, final TypeReference<T> reference) { try { return gson.fromJson(jsonString, reference.getType()); } catch (JsonSyntaxException e) { log.error(e.getMessage()); return null; } } } <file_sep>package com.service.openapi.trade.naverapi.config.client; import com.service.openapi.trade.naverapi.model.customproperty.NaverProperty; import feign.RequestInterceptor; import lombok.RequiredArgsConstructor; import org.springframework.context.annotation.Bean; @RequiredArgsConstructor public class NaverApiConfig { private final NaverProperty naverProperty; @Bean public RequestInterceptor requestTemplate() { return requestTemplate -> requestTemplate .header("X-Naver-Client-Id", naverProperty.getClientId()) .header("X-Naver-Client-Secret", naverProperty.getClientSecret()); } } <file_sep>package com.service.openapi.trade.naverapi.config.customproperty; import com.service.openapi.trade.naverapi.model.customproperty.NaverProperty; import org.springframework.boot.context.properties.ConfigurationProperties; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; @Configuration public class NaverCustomPropertyConfig { @Bean @ConfigurationProperties(prefix = "naver") public NaverProperty naverProperty() { return NaverProperty.builder().build(); } }
dd6be38c1b1008a33ab3213bdcb00acfcb3f3017
[ "Java" ]
6
Java
Yabamui/trade-information-naver-service
8da6a9afb8043d6934f46d4eccfa0be9328cddef
39d6321d8136018765e2f87a522c60bbcea4f9e9
refs/heads/master
<repo_name>franciscocabral/courses<file_sep>/01-getting-started-with-angular2/src/introduction-to-pipes/lesson.ts import {Component} from "@angular/core"; import {bootstrap} from "@angular/platform-browser-dynamic"; import {SortPipe} from "./sort.pipe"; @Component({ selector: 'app', pipes: [SortPipe], template: ` <div class="pipe-example"> <label>Uppercase Pipe: {{ message | uppercase }}</label> </div> <div class="pipe-example"> <label>Lowercase Pipe: {{ message | lowercase }}</label> </div> <div class="pipe-example"> <label>Slice Pipe: {{ message | slice:0:5 }}</label> </div> <div class="pipe-example"> <label>Replace Pipe: {{ message | replace:'World':'Angular 2 World' }}</label> </div> <div class="pipe-example"> <label>Date Pipe: {{ date | date:'yyyy-MMM-dd' }}</label> </div> <div class="pipe-example"> <label>Number Formatting: {{ pi | number:'5.1-2' }}</label> </div> <div class="pipe-example"> <label>Percent Pipe: {{ percentage | percent:'2.1-2' }}</label> </div> <div class="pipe-example"> <label>Currency Pipe: {{ amount | currency:'USD':true:'2.1-2' }}</label> </div> <div class="pipe-example"> <label>Custom Pipe: {{ data | sort:'DESC'}}</label> </div> ` }) export class App { message = 'Hello World !'; date = new Date(); pi = 3.14159265359; percentage = 0.0234; amount = 12.1234; data = ['A', 'B', 'H', 'C']; } bootstrap(App); <file_sep>/01-getting-started-with-angular2/src/05-template-syntax-components-essentials/color_picker.ts import {Component, Output, EventEmitter, Input} from "@angular/core"; import {BLUE, RED} from "./constants"; @Component({ selector: 'color-picker', template: ` <div class="color-title" [ngStyle]="{color:color}">Pick a Color:</div> <div class="color-picker"> <div class="color-sample color-sample-blue" (click)="choose('${BLUE}')"></div> <div class="color-sample color-sample-red" (click)="choose('${RED}')"></div> </div> ` }) export class ColorPicker { @Input() color:string; @Output("color") colorOutput = new EventEmitter(); choose(color) { this.colorOutput.emit(color); } reset() { this.colorOutput.emit('black'); } }<file_sep>/01-getting-started-with-angular2/src/01-mvc-hello-world/hello_world.ts import {Component} from "@angular/core"; import {bootstrap} from "@angular/platform-browser-dynamic"; @Component({ selector: 'hello-world', template: `<input #input (keydown)="updateModel(input.value)">{{model.message}}` }) export class HelloWorld { model = { message: 'Hello World !' }; updateModel(newMessage) { this.model.message = ''; } } bootstrap(HelloWorld); <file_sep>/01-getting-started-with-angular2/src/introduction-to-pipes/sort.pipe.ts import {Pipe, PipeTransform} from "@angular/core"; @Pipe({ name: 'sort' }) export class SortPipe implements PipeTransform { transform(array: any[], args): any[] { let sorted = array.sort(); if (args.length > 0 && args === 'DESC' ) { sorted = sorted.reverse(); } return sorted; } }<file_sep>/01-getting-started-with-angular2/src/core-directives-ngstyle-ngclass/lesson.ts import {Component} from "@angular/core"; import {bootstrap} from "@angular/platform-browser-dynamic"; import {Hero} from "./hero"; import {Heroes} from "./heroes"; @Component({ selector: 'app', directives: [Hero, Heroes], template: ` <heroes> <hero id="1" name="Superman"></hero> <hero id="2" [name]="'Batman'"></hero> <hero id="3" [name]="'Spiderman'" marvel="true"></hero> <hero id="4" name="Batgirl"></hero> <hero id="3" name="Hulk" marvel="true"></hero> <hero id="5" name="Robin"></hero> <hero id="6" name="Flash"></hero> </heroes> ` }) export class App { } bootstrap(App); <file_sep>/01-getting-started-with-angular2/tsconfig.json { "compilerOptions": { "emitDecoratorMetadata": true, "experimentalDecorators": true, "target": "es5", "module": "system", "moduleResolution": "node", "removeComments": true, "sourceMap": true, "outDir": "dist" }, "files": [ "typings/main.d.ts", "src/01-mvc-hello-world/hello_world.ts", "src/02-template-syntax-properties/lesson_2.ts", "src/03-template-syntax-interpolation/lesson.ts", "src/04-template-syntax-events/lesson_4.ts", "src/05-template-syntax-components-essentials/lesson.ts", "src/core-directives-ng-for/lesson.ts", "src/core-directives-ngstyle-ngclass/lesson.ts", "src/core-directives-ngif/lesson.ts", "src/directives/lesson.ts", "src/introduction-to-pipes/lesson.ts" ] } <file_sep>/01-getting-started-with-angular2/src/core-directives-ng-for/heroes.ts import {Component, ContentChildren, QueryList} from "@angular/core"; import {Hero} from "./hero"; const HEROES = [ {id: 1, name:'Superman'}, {id: 2, name:'Batman'}, {id: 5, name:'BatGirl'}, {id: 3, name:'Robin'}, {id: 4, name:'Flash'} ]; @Component({ selector:'heroes', template: ` <table> <thead> <th>Name</th> <th>Index</th> </thead> <tbody> <tr *ngFor="let hero of heroes; let i = index"> <td>{{hero.name}}</td> <td>{{i}}</td> </tr> </tbody> </table> ` }) export class Heroes { @ContentChildren(Hero) heroes: QueryList<Hero>; }<file_sep>/01-getting-started-with-angular2/src/core-directives-ng-for/hero.ts import {Directive, Input} from "@angular/core"; @Directive({ selector: 'hero', }) export class Hero { @Input() id: number; @Input() name:string; }<file_sep>/01-getting-started-with-angular2/src/05-template-syntax-components-essentials/color_previewer.ts import {Component, Input} from "@angular/core"; @Component({ selector: 'color-previewer', template: ` <div class="color-previewer" [ngStyle]="{color:color}"> Preview Text Color </div> ` }) export class ColorPreviewer { @Input() color:string; }<file_sep>/01-getting-started-with-angular2/README.md # Installation Instructions No Global dependencies are needed. To install the code, you can run the following command in a terminal window: npm install The installation should take a few minutes. When its done, you can build the project and start a server using the followinf code: npm start Once the server is running, you can access the lessons page via the following url: [http://localhost:8080](http://localhost:8080) Note: For Udemy students, this code is available also at the following location - https://github.com/angular-academy/courses/tree/master/01-getting-started-with-angular2 <file_sep>/01-getting-started-with-angular2/src/core-directives-ngif/lesson.ts import {Component} from "@angular/core"; import {bootstrap} from "@angular/platform-browser-dynamic"; @Component({ selector: 'app', template: ` <div class="toggle-panel" *ngIf="show" [hidden]="hidden" [style.visibility]="visibility">Toggle Me</div> <button (click)="toggleShow()">Show</button> <button (click)="toggleHidden()">Hidden</button> <button (click)="toggleVisible()">Visible</button> ` }) export class App { show = true; hidden = false; visibility = 'visible'; toggleShow() { this.show = !this.show; } toggleHidden() { this.hidden = !this.hidden; } toggleVisible() { this.visibility = this.visibility == 'visible' ? 'hidden' : 'visible'; } } bootstrap(App); <file_sep>/01-getting-started-with-angular2/src/05-template-syntax-components-essentials/lesson.ts import {Component} from "@angular/core"; import {bootstrap} from "@angular/platform-browser-dynamic"; import {ColorPicker} from "./color_picker"; import {ColorPreviewer} from "./color_previewer"; @Component({ selector: 'app', directives: [ColorPreviewer, ColorPicker], template: ` <color-picker #picker [color]="color" (color)="color = $event"> </color-picker> <color-previewer #previewer [color]="color"></color-previewer> <button (click)="picker.reset()">Reset</button> ` }) export class App { color:string; } bootstrap(App); <file_sep>/01-getting-started-with-angular2/src/05-template-syntax-components-essentials/constants.ts export const BLUE = '#b13138'; export const RED = '#1976d2'; <file_sep>/01-getting-started-with-angular2/src/minimal-setup-typescript-systemjs/src/main.ts import {Component} from "@angular/core"; import {bootstrap} from "@angular/platform-browser-dynamic"; @Component({ selector: 'app', template: `<input placeholder="Type hello world !" (keyup)="hello(input.value)" #input>{{message}}` }) export class App { private message = ""; hello(value) { this.message = value; } } bootstrap(App, []); <file_sep>/01-getting-started-with-angular2/src/directives/show-one-trigger.ts import {Directive, HostListener, HostBinding, Input} from "@angular/core"; import {ShowOneContainer} from "./show-one-container"; @Directive({ selector: '[showOneTrigger]' }) export class ShowOneTrigger { @Input("showOneTrigger") id: string; @Input() active = false; constructor(private showOneContainer: ShowOneContainer) { showOneContainer.add(this); } @HostListener('click') click() { this.showOneContainer.show(this.id); } @HostBinding('class.selected') get selected() { return this.active; } }<file_sep>/01-getting-started-with-angular2/src/04-template-syntax-events/lesson_4.ts import {Component} from "@angular/core"; import {bootstrap} from "@angular/platform-browser-dynamic"; @Component({ selector: 'app', template: ` <input value="Hello World !" #input>{{input.value}} <button (click)="onClick()">Click Me</button> ` }) export class App { onClick() { alert("Hello !"); debugger; } } bootstrap(App); <file_sep>/01-getting-started-with-angular2/src/directives/show-one.ts import {Directive, HostBinding, Input} from "@angular/core"; @Directive({ selector: '[showOne]' }) export class ShowOne { @Input("showOne") id:string; @Input() active = false; @HostBinding('hidden') get hidden() { return !this.active; } }<file_sep>/01-getting-started-with-angular2/src/directives/lesson.ts import {Component} from "@angular/core"; import {bootstrap} from "@angular/platform-browser-dynamic"; import {ShowOneContainer} from "./show-one-container"; import {ShowOne} from "./show-one"; import {ShowOneTrigger} from "./show-one-trigger"; @Component({ selector: 'app', directives: [ShowOne, ShowOneContainer, ShowOneTrigger], template: ` <div class="tab-container" showOneContainer> <ul class="tab-buttons"> <li showOneTrigger="superman" [active]="true">Superman</li> <li showOneTrigger="batman">Batman</li> <li showOneTrigger="flash">Flash</li> </ul> <div class="tab-panel" showOne="superman" [active]="true"> <div class="logo superman"></div> </div> <div class="tab-panel" showOne="batman"> <div class="logo batman"></div> </div> <div class="tab-panel" showOne="flash"> <div class="logo flash"></div> </div> </div> ` }) export class App { } bootstrap(App); <file_sep>/01-getting-started-with-angular2/src/core-directives-ngstyle-ngclass/heroes.ts import {Component, ContentChildren, QueryList} from "@angular/core"; import {Hero} from "./hero"; export const BLUE = '#b13138'; export const RED = '#1976d2'; @Component({ selector:'heroes', template: ` <table> <thead> <th>Name</th> <th>Index</th> </thead> <tbody> <tr *ngFor="let hero of heroes; let i = index" [ngClass]="classes(hero)"> <td>{{hero.name}}</td> <td>{{i}}</td> </tr> </tbody> </table> ` }) export class Heroes { @ContentChildren(Hero) heroes: QueryList<Hero>; get styles() { return { color: 'blue', 'text-decoration': 'underline' }; } classes(hero: Hero) { return { marvel:hero.marvel, hulk: hero.name === 'Hulk' }; } }<file_sep>/01-getting-started-with-angular2/src/directives/show-one-container.ts import {Directive, ContentChildren, QueryList} from "@angular/core"; import {ShowOne} from "./show-one"; import {ShowOneTrigger} from "./show-one-trigger"; @Directive({ selector: '[showOneContainer]' }) export class ShowOneContainer { triggers: ShowOneTrigger[] = []; @ContentChildren(ShowOne) items: QueryList<ShowOne>; add(trigger: ShowOneTrigger) { this.triggers.push(trigger); } show(id:string) { this.items.forEach(item => item.active = item.id == id); this.triggers.forEach( (trigger:ShowOneTrigger) => trigger.active = trigger.id == id); } }<file_sep>/01-getting-started-with-angular2/src/02-template-syntax-properties/lesson_2.ts import {Component} from "@angular/core"; import {bootstrap} from "@angular/platform-browser-dynamic"; @Component({ selector: 'app', template: ` <div class="color-sample" [style.background]="'red'"> Color Sample</div> <button [disabled]="true">Disabled</button> <input [required]="true" value="Hello World !"> ` }) export class App { } bootstrap(App); <file_sep>/01-getting-started-with-angular2/src/03-template-syntax-interpolation/lesson.ts import {Component} from "@angular/core"; import {bootstrap} from "@angular/platform-browser-dynamic"; @Component({ selector: 'app', template: ` <label>Message:</label>{{ model?.message }} ` }) export class App { message = 'Hello World !'; condition = true; model = { message: 'Hello World !' }; get calculatedValue() { return "Calculated Value"; } } bootstrap(App);
efc0a2d441d1f76713fe8c6c5e511bdf0754b06b
[ "Markdown", "TypeScript", "JSON with Comments" ]
22
TypeScript
franciscocabral/courses
6b5748af5a3a45a23af02073ee68ac74fadb62e8
12bbbec24b43ef30d97f7941b32ed8478bd31b92
refs/heads/master
<repo_name>Nilsen89/AStar<file_sep>/a_star.py import sys class AStar: def __init__(self): return 0 class Data: tree = list() goal = [0,0] start = [0,0] def __init__(self): with open(sys.argv[1], 'r') as my_file: row = 0 for word in my_file: temp_arr = list() col = 0 for char in word: temp_arr.append(Cell(row, col, char)) if char == 'A': self.start[0] = row self.start[1] = col if char == 'B': self.goal[0] = row self.goal[1] = col col += 1 self.tree.append(temp_arr) row += 1 def printTree(self): print("Start: " + str(self.start[0]) + "-" + str(self.start[1])) print("Goal: " + str(self.goal[0]) + "-" + str(self.goal[1])) for row in self.tree: for col in row: sys.stdout.write(col.char) sys.stdout.flush() class Cell: x = 0 # row cord y = 0 # col cord h = 0 # approx. dist to goal wall = False # if cell is wall char = '' # displayed character def __init__(self,row, col, char): x = row y = col self.char = char if(char == '#'): wall = True def main(): data = Data() data.printTree() main()
8a60077da2de423c5f97c26468731a387baf6bd2
[ "Python" ]
1
Python
Nilsen89/AStar
a9862d1afcb389ed7b71f9724b3c4446b37e9feb
888fb88fa0ddb0befcb38f0c0ba9e76fd6470368
refs/heads/master
<repo_name>Mirage20/cloudbox-provider-app<file_sep>/app/Http/Controllers/ClientController.php <?php namespace App\Http\Controllers; use Illuminate\Support\Facades\DB; class ClientController extends Controller { public function addClient() { $client_id = request()->input('client_id'); $client_name = request()->input('client_name'); $client_address = request()->input('client_address'); $client_email = request()->input('client_email'); $client = \DB::table('clients')->where('client_id', $client_id)->first(); if (empty($client_id)) { return response()->json([ 'error' => true, 'msg' => 'Client ID is required.' ]); } if (empty($client_name)) { return response()->json([ 'error' => true, 'msg' => 'Client Name is required.' ]); } if (empty($client_address)) { return response()->json([ 'error' => true, 'msg' => 'Client Address is required.' ]); } if (isset($client)) { return response()->json([ 'error' => true, 'msg' => 'Client ID already exists.' ]); } DB::table('clients')->insert( [ 'client_id' => $client_id, 'client_name' => $client_name, 'client_address' => $client_address, 'client_emailaddress' => $client_email, ] ); $newClient = \DB::table('clients')->where('client_id', $client_id)->first(); if (!isset($newClient)) { return response()->json([ 'error' => true, 'msg' => 'Error adding new client.' ]); } return response()->json([ 'error' => false, 'msg' => "success" ]); } public function getclientinfo($id) { $client = DB::table('clients')->where('client_id', $id)->first(); return ['client' => $client]; } }
32520477ad12c1cbb10c0e2f4e63f7080eca47d6
[ "PHP" ]
1
PHP
Mirage20/cloudbox-provider-app
fc2618424c7fc65c3eb07ebd24c0f3185cb7c2bb
76e495f83d3437bb2f62379339fb6428b4a50720
refs/heads/master
<file_sep>using UnityEngine; using UnityEngine.Events; using UnityStandardAssets.Characters.FirstPerson; namespace AppartementTemoins { using UI; using Definitions; /// <summary> /// Game Global State Singleton. /// </summary> public class GameState : MonoBehaviour { [SerializeField] private FirstPersonController FirstPersonController; [SerializeField] private DescriptionWindow DescriptionWindow; [SerializeField] private SavesText SavesText; [SerializeField] private Transform InteractionAlert; [SerializeField] private UnityEvent StartEvent; private IWallet wallet; private static GameState _instance; public static GameState GetInstance() { return _instance; } public FirstPersonController Player { private set { } get => this.FirstPersonController; } public IWallet Wallet { private set { } get => this.wallet; } public DescriptionWindow DescriptionModal { private set { } get => this.DescriptionWindow; } public SavesText UISaves { private set { } get => this.SavesText; } public Transform UIInteractionAlert { private set { } get => this.InteractionAlert; } private void Start() { this.wallet = this.GetComponent<IWallet>(); _instance = this; this.StartEvent.Invoke(); } } } <file_sep>namespace AppartementTemoins.Interactions.Definitions { using Common; /// <summary> /// Define an Interaction /// </summary> public interface IInteraction { /// <summary> /// All Interaction Data. /// </summary> InteractionData Data { get; } /// <summary> /// Interact with the Object. /// </summary> void Interact(); /// <summary> /// Show Interaction Description. /// </summary> void ShowDescription(); } } <file_sep>using UnityEngine; using TMPro; namespace AppartementTemoins.UI { public class SavesText : MonoBehaviour { public string Saves { get => this.transform .GetComponent<TextMeshProUGUI>() .text; set => this.transform .GetComponent<TextMeshProUGUI>() .text = value; } } } <file_sep>using UnityEngine; namespace AppartementTemoins.Interactions.Common { [CreateAssetMenu(fileName = "Interaction", menuName = "Appartement Témoins/Interaction")] public class InteractionData : ScriptableObject { [Header("Interaction Name.")] public string Name; [Header("Interaction Description.")] [TextArea] public string Description; [Header("Price saved Description with this Interaction.")] [TextArea] public string PriceSavedText; [Header("Price Savec / Year.")] public float PriceSaved; } } <file_sep> namespace AppartementTemoins.Definitions { /// <summary> /// Define Wallet Object. /// </summary> public interface IWallet { /// <summary> /// Current Wallet Saves. /// </summary> float CurrentSaves { get; } /// <summary> /// Add Saves in Wallet. /// </summary> void AddSaves(float saves); /// <summary> /// Remove Saves from Wallet. /// </summary> void RemoveSaves(float saves); } }<file_sep>using UnityEngine; using UnityEngine.Events; namespace AppartementTemoins { using Interactions.Definitions; /// <summary> /// Handle Interactions /// </summary> public class InteractionCamera : MonoBehaviour { private Camera cam; private void Start() { this.cam = this.GetComponent<Camera>(); } private void FixedUpdate() { this.CheckForInteraction(); } private void CheckForInteraction() { IInteraction interaction = this.GetTargetInteraction(); GameState.GetInstance().UIInteractionAlert.gameObject.SetActive( interaction != null ); if (Input.GetMouseButtonDown(0) && !GameState.GetInstance().Player.IsStatic) { if (interaction != null) interaction.Interact(); } if (Input.GetMouseButtonDown(1) && !GameState.GetInstance().Player.IsStatic) { if (interaction != null) interaction.ShowDescription(); } } private IInteraction GetTargetInteraction() { RaycastHit hit; if (Physics.Raycast(this.transform.position, this.transform.forward, out hit, 1.5f)) { IInteraction interaction = hit.transform.GetComponent<IInteraction>(); return interaction; } return null; } } } <file_sep>using UnityEngine; using UnityEngine.Events; namespace AppartementTemoins.Interactions { using Definitions; using Common; /// <summary> /// Basic Object Interaction. /// </summary> public class BasicInteraction : MonoBehaviour, IInteraction { [SerializeField] [Header("Interaction Settings.")] private InteractionData Settings = null; [SerializeField] [Header("Interaction Event.")] private UnityEvent InteractionEvent; [SerializeField] [Header("Description Event.")] private UnityEvent DescriptionEvent; public InteractionData Data => this.Settings; public void Interact() { GameState.GetInstance().Wallet.AddSaves(this.Settings.PriceSaved); if (this.InteractionEvent != null) this.InteractionEvent.Invoke(); } public void ShowDescription() { GameState.GetInstance().DescriptionModal.Title = this.Settings.Name; GameState.GetInstance().DescriptionModal.Description = this.Settings.Description; GameState.GetInstance().DescriptionModal.Savings = this.Settings.PriceSavedText; if (this.DescriptionEvent != null) this.DescriptionEvent.Invoke(); } } } <file_sep>using UnityEngine; using UnityEngine.Events; namespace AppartementTemoins { using Definitions; public class Wallet : MonoBehaviour, IWallet { private readonly string PRICE_SAVED_SUFFIX = "/ans"; [SerializeField] private float saves = 0f; [SerializeField] private UnityEvent NewSaveEvent; public float CurrentSaves => this.saves; public void AddSaves(float saves) { this.saves += saves; GameState.GetInstance().UISaves.Saves = this.saves.ToString() + this.PRICE_SAVED_SUFFIX; if (this.NewSaveEvent != null) this.NewSaveEvent.Invoke(); } public void RemoveSaves(float saves) { this.saves -= saves; GameState.GetInstance().UISaves.Saves = this.saves.ToString() + this.PRICE_SAVED_SUFFIX; } } } <file_sep>using UnityEngine; using TMPro; namespace AppartementTemoins.UI { /// <summary> /// Interaction Description Window /// </summary> public class DescriptionWindow : MonoBehaviour { public string Title { get => this.transform.Find("Content") .Find("Title Bar") .Find("Title") .GetComponent<TextMeshProUGUI>() .text; set => this.transform.Find("Content") .Find("Title Bar") .Find("Title") .GetComponent<TextMeshProUGUI>() .text = value; } public string Description { get => this.transform.Find("Content") .Find("Tabs") .Find("Tab 1") .Find("Text") .GetComponent<TextMeshProUGUI>() .text; set => this.transform.Find("Content") .Find("Tabs") .Find("Tab 1") .Find("Text") .GetComponent<TextMeshProUGUI>() .text = value; } public string Savings { get => this.transform.Find("Content") .Find("Tabs") .Find("Tab 2") .Find("Text") .GetComponent<TextMeshProUGUI>() .text; set => this.transform.Find("Content") .Find("Tabs") .Find("Tab 2") .Find("Text") .GetComponent<TextMeshProUGUI>() .text = value; } } }
de4cd32501f83bebc3bb9e10fdbd10cc70c3d49c
[ "C#" ]
9
C#
Zusoy/AppartementTemoin
93fb0f590dfe45d350ae907a88115ebe21998aa9
4aa700b0ae5802e3ed811f755ed4f039eefaf71f
refs/heads/main
<file_sep>require "ruby2d" set background: "navy" set fps_cap: 20 #width = 640/20 = 32 #height = 480/20 = 24 GRID_SIZE = 20 GRID_WIDTH = Window.width/ GRID_SIZE GRID_HEIGHT = Window.height/ GRID_SIZE class Snake attr_writer :direction def initialize @positions = [[2, 0], [2, 1],[2, 2],[2, 3]] @direction = 'down' @growing = false end def draw @positions.each do |position| Square.new(x: position[0] * GRID_SIZE, y:position[1] * GRID_SIZE, size: GRID_SIZE - 1, color: 'white') end end def move if !@growing @positions.shift end case @direction when 'down' @positions.push(new_coords(head[0], head[1] + 1)) when 'up' @positions.push(new_coords(head[0], head[1] - 1)) when 'left' @positions.push(new_coords(head[0] - 1, head[1])) when 'right' @positions.push(new_coords(head[0] + 1, head[1])) end @growing = false end def can_change_direction_to?(new_direction) case @direction when 'up' then new_direction != 'down' when 'down' then new_direction != 'up' when 'left' then new_direction != 'right' when 'right' then new_direction != 'left' end end def x head[0] end def y head[1] end def grow @growing = true end def hit_itself? @positions.uniq.length != @positions.length end private def new_coords(x, y) [x % GRID_WIDTH, y % GRID_HEIGHT] end private def head @positions.last end end class Game def initialize @score = 0 @apple_x = rand(GRID_WIDTH) @apple_y = rand(GRID_HEIGHT) @finished = false end def draw unless finished? Square.new(x: @apple_x * GRID_SIZE, y:@apple_y * GRID_SIZE, size: GRID_SIZE, color: 'red') end Text.new(text_message, color: 'yellow', x: 10, y: 10, size: 25) end def snake_eat_food?(x,y) @apple_x == x && @apple_y == y end def record_hit @score += 1 @apple_x = rand(GRID_WIDTH) @apple_y = rand(GRID_HEIGHT) end def finish @finished = true end def finished? @finished end private def text_message if finished? "Game Over! Your Score was #{@score}. Press R to restart." else "Score: #{@score}" end end end snake = Snake.new game = Game.new update do clear unless game.finished? snake.move end snake.draw game.draw if game.snake_eat_food?(snake.x, snake.y) game.record_hit snake.grow end if snake.hit_itself? game.finish end end on :key_down do |event| if ['up', 'left', 'right', 'down'].include?(event.key) if snake.can_change_direction_to?(event.key) snake.direction = event.key end elsif event.key == 'r' snake = Snake.new game = Game.new end end show
63e8a8ee303ac301a7bd5fe4bee0b97d6b6e0b84
[ "Ruby" ]
1
Ruby
QuatroQuatros/Ruby_SnakeGame
2666b7fa73c9429b70d88ab4af672610f97ebe2c
a3aa6fcef7ecf081d427c29b31ac99c852ac0e69
refs/heads/master
<repo_name>amogh-git09/TinyJSCompiler<file_sep>/demo3.js var a = new Array(1); var fib = function(x) { if (x > 1) { a[x] = fib(x-1) + fib(x-2); return fib(x-1) + fib(x-2); } else { a[x] = 1; return 1; } } fib(7); <file_sep>/script.sh for i in {1..4} do time node tjscompiler.js "demo$i.js" done <file_sep>/tjs-c/tjscompiler.c // // tjscompiler.c // SSJS project, iwasaki-lab, UEC, Japan // // <NAME>, 2011-2013 // <NAME>, 2013 // <NAME>, 2013 // #include <stdio.h> #include <stdlib.h> #include <string.h> #include <stdint.h> #include <stdbool.h> #include <unistd.h> #include <inttypes.h> #include <jsapi.h> #include <jsparse.h> #include <jsscan.h> #include <jsstr.h> #include <jsatom.h> #include <jsfun.h> #include <jsscope.h> #include <jsinterp.h> #include <jsregexp.h> //#define FL_MAX 200 // REGISTER_MAX と同義? #define FL_MAX 1500 //2011/05/30追記 #define VARIABLE_MAX 100 #define ENVTABLE_MAX 300 #define DEBUG1 0 #define DEBUG2 0 #define DEBUG3 0 #define DEBUG4 0 #define REG_A 9999 #define MAX_BYTECODE 10000 #define F_REGEXP_NONE (0x0) #define F_REGEXP_GLOBAL (0x1) #define F_REGEXP_IGNORE (0x2) #define F_REGEXP_MULTILINE (0x4) #define release_reg(curr_tbl,n) //(used_reg_tbl[(n)] = 0) /* 2013/08/20 Iwasaki */ #define OUTPUT_SBC 0 #define OUTPUT_SEXPR 1 int output_format = OUTPUT_SBC; #define FLEN 128 char *output_filename = NULL; char *input_filename = NULL; char filename[FLEN]; /* 関数呼出し後のaddsp を setflに breakとcontinueを考えてなかった 配列にぶち込んでおいてあとでまとめて解決でいいか でもそうするとネストはどうするんだ? ネストを適当に書いておけばいいか グローバル変数でいいか ラベル番号どうするか */ /* from jsscan.h */ const char * TOKENS[81] = { "EOF", "EOL", "SEMI", "COMMA", "ASSIGN", "HOOK", "COLON", "OR", "AND", "BITOR", "BITXOR", "BITAND", "EQOP", "RELOP", "SHOP", "PLUS", "MINUS", "STAR", "DIVOP", "UNARYOP", "INC", "DEC", "DOT", "LB", "RB", "LC", "RC", "LP", "RP", "NAME", "NUMBER", "STRING", "OBJECT", "PRIMARY", "FUNCTION", "EXPORT", "IMPORT", "IF", "ELSE", "SWITCH", "CASE", "DEFAULT", "WHILE", "DO", "FOR", "BREAK", "CONTINUE", "IN", "VAR", "WITH", "RETURN", "NEW", "DELETE", "DEFSHARP", "USESHARP", "TRY", "CATCH", "FINALLY", "THROW", "INSTANCEOF", "DEBUGGER", "XMLSTAGO", "XMLETAGO", "XMLPTAGC", "XMLTAGC", "XMLNAME", "XMLATTR", "XMLSPACE", "XMLTEXT", "XMLCOMMENT", "XMLCDATA", "XMLPI", "AT", "DBLCOLON", "ANYNAME", "DBLDOT", "FILTER", "XMLELEM", "XMLLIST", "RESERVED", "LIMIT", }; const int NUM_TOKENS = sizeof(TOKENS) / sizeof(TOKENS[0]); JSContext * context; typedef int regexpFlag; char *gStringObject = "Object"; char *gStringArray = "Array"; typedef enum { LOC_ARGUMENTS, LOC_REGISTER, LOC_CATCH, LOC_LOCAL, LOC_ARG, LOC_GLOBAL } Location; typedef enum { NUMBER, FIXNUM, STRING, REGEXP, CONST, SPECCONST, ADD, SUB, MUL, DIV, MOD, BITAND, BITOR, JUMPTRUE, JUMPFALSE, JUMP, LEFTSHIFT, RIGHTSHIFT, UNSIGNEDRIGHTSHIFT, LESSTHAN, LESSTHANEQUAL, EQ, EQUAL, GETPROP, SETPROP, SETARRAY, GETARG, SETARG, GETLOCAL, SETLOCAL, GETGLOBAL, SETGLOBAL, MOVE, CALL, SEND, TAILCALL, TAILSEND, NEWSEND, RET, MAKECLOSURE, MAKEITERATOR, NEXTPROPNAME, TRY, THROW, FINALLY, NEW, INSTANCEOF, TYPEOF, NOT, NEWARGS, SETFL, ADDSP, SUBSP, GETIDX, // 2011/05/30追記 ISUNDEF, ISOBJECT, SETA, GETA, GETERR, GETGLOBALOBJ, ERROR, UNKNOWN } Nemonic; typedef enum { TRUE, FALSE, UNDEFINED, Null } Const; typedef struct environment { char *name; Location location; int level; int offset; int index; struct environment* next; } *Environment; typedef int Register; typedef struct function_tbl{ JSParseNode *node; Environment rho; bool existClosure; int level; int call_entry; int send_entry; } Function_tbl; typedef struct bytecope { Nemonic nemonic; int label; int flag; int call_entry; int send_entry; union { struct { Register dst; double val; } dval; struct { Register dst; int64_t val; } ival; struct { Register dst; char *str; } str; struct { Register dst; char *str; regexpFlag flag; } regexp; struct { Register dst; Const cons; } cons; struct { int n1; } num; struct { int n1; int n2; Register r1; } var; struct { Register r1; int n1; } regnum; struct { Register r1; } unireg; struct { Register r1; Register r2; } bireg; struct { Register r1; Register r2; Register r3; } trireg; } bc_u; } Bytecode; char *regexp_to_string(JSAtom *atom, regexpFlag *flag); char * atom_to_string(JSAtom *atom); int fl=100; int curr_tbl=0; int used_reg_tbl[FL_MAX]; //2011/05/30追記 //int used_reg_tbl[200]; int touch_reg_tbl[FL_MAX]; //2011/05/30追記 //int touch_reg_tbl[200]; int fl_tbl[201]; Function_tbl func_tbl[201] = {}; int var_num[201]; int curr_func = 1; int code_num[201]; int curr_label = 1; int curr_code_num = 0; int curr_code = 0; Bytecode bytecode[201][MAX_BYTECODE]; int max_func_fl; bool searchFunctionDefinition(JSParseNode *root) { if (root == NULL || root == (JSParseNode *)0xffffffff || root == (JSParseNode*)0xdadadadadadadada) { return false; } if (root->pn_type >= NUM_TOKENS) { return false; } switch (root->pn_type) { case TOK_PLUS: case TOK_MINUS: case TOK_STAR: case TOK_DIVOP: case TOK_BITAND: case TOK_BITOR: { if (root->pn_arity == PN_BINARY) { return searchFunctionDefinition(root->pn_left) || searchFunctionDefinition(root->pn_right); } else if (root->pn_arity == PN_LIST) { bool f = false; JSParseNode *p; f = searchFunctionDefinition(root->pn_head); for (p = root->pn_head->pn_next; p != NULL && !f; p = p->pn_next) { f = searchFunctionDefinition(p); } return f; } else { return false; } } case TOK_ASSIGN: if (root->pn_left->pn_type == TOK_LB) { return searchFunctionDefinition(root->pn_left) || searchFunctionDefinition(root->pn_right); } else { return searchFunctionDefinition(root->pn_right); } case TOK_DOT: return searchFunctionDefinition(root->pn_expr); case TOK_LB: case TOK_WHILE: case TOK_DO: return searchFunctionDefinition(root->pn_left) || searchFunctionDefinition(root->pn_right); case TOK_UNARYOP: case TOK_RETURN: return searchFunctionDefinition(root->pn_kid); case TOK_AND: case TOK_OR: case TOK_RELOP: case TOK_EQOP: return searchFunctionDefinition(root->pn_left) || searchFunctionDefinition(root->pn_right); case TOK_HOOK: case TOK_IF: return searchFunctionDefinition(root->pn_kid1) || searchFunctionDefinition(root->pn_kid2) || searchFunctionDefinition(root->pn_kid3); case TOK_FOR: if (root->pn_left->pn_arity == PN_TERNARY) { return searchFunctionDefinition(root->pn_left->pn_kid1) || searchFunctionDefinition(root->pn_left->pn_kid2) || searchFunctionDefinition(root->pn_left->pn_kid3) || searchFunctionDefinition(root->pn_right); } else { return searchFunctionDefinition(root->pn_left->pn_right) || searchFunctionDefinition(root->pn_right); } case TOK_LP: { bool f = false; JSParseNode *p; if (root->pn_head->pn_type == TOK_DOT) { f = searchFunctionDefinition(root->pn_head->pn_expr); } else if (root->pn_head->pn_type == TOK_LB) { f = searchFunctionDefinition(root->pn_head->pn_left) || searchFunctionDefinition(root->pn_head->pn_right); } for (p = root->pn_head->pn_next; p != NULL && !f; p = p->pn_next) { f = searchFunctionDefinition(p); } return f; } case TOK_NEW: { bool f; JSParseNode *p; for (p = root->pn_head, f = false; p != NULL && !f; p = p->pn_next) { f = searchFunctionDefinition(p); } return f; } case TOK_VAR: { bool f; JSParseNode *p; for (p = root->pn_head, f = false; p != NULL && !f; p = p->pn_next) { if (p->pn_expr != NULL) { f = searchFunctionDefinition(p->pn_expr); } } return f; } /*TOK_NEWから実装を再開すること!*/ case TOK_FUNCTION: return true; case TOK_NUMBER: case TOK_STRING: case TOK_PRIMARY: case TOK_NAME: case TOK_INC: case TOK_DEC: return false; default: switch (root->pn_arity) { case PN_UNARY: return searchFunctionDefinition(root->pn_kid); case PN_BINARY: return searchFunctionDefinition(root->pn_left) || searchFunctionDefinition(root->pn_right); case PN_TERNARY: return searchFunctionDefinition(root->pn_kid1) || searchFunctionDefinition(root->pn_kid2) || searchFunctionDefinition(root->pn_kid3); case PN_LIST: { bool f; JSParseNode *p; for (p = root->pn_head, f = false; p != NULL && !f; p = p->pn_next) { f = searchFunctionDefinition(p); } return f; } case PN_NAME: if (root->pn_expr != NULL) { return searchFunctionDefinition(root->pn_expr); } case PN_FUNC: return true; case PN_NULLARY: default: return false; } } } bool searchUseArguments(JSParseNode *root) { if (root == NULL) { return false; } if (root->pn_type >= NUM_TOKENS) { return false; } switch (root->pn_type) { case TOK_DOT: return searchUseArguments(root->pn_expr); case TOK_FUNCTION: return false; case TOK_NUMBER: case TOK_STRING: case TOK_PRIMARY: return false; case TOK_NAME: { char *str = atom_to_string(root->pn_atom); // fprintf(stderr, "searchUseArguments:TOK_NAME:ENTER\n"); // fprintf(stderr, "searchUseArguments:TOK_NAME:atom=%s\n", str); if (strcmp(str, "arguments") == 0) { return true; } else { return false; } } default: switch (root->pn_arity) { case PN_UNARY: return searchUseArguments(root->pn_kid); case PN_BINARY: return searchUseArguments(root->pn_left) || searchUseArguments(root->pn_right); case PN_TERNARY: return searchUseArguments(root->pn_kid1) || searchUseArguments(root->pn_kid2) || searchUseArguments(root->pn_kid3); case PN_LIST: { bool f; JSParseNode *p; for (p = root->pn_head, f = false; p != NULL && !f; p = p->pn_next) { f = searchUseArguments(p); } return f; } case PN_NAME: if (root->pn_expr != NULL) { return searchUseArguments(root->pn_expr); } case PN_FUNC: return false; case PN_NULLARY: default: return false; } } } void set_bc_ival(Nemonic nemonic, int flag, Register dst, int64_t ival){ bytecode[curr_code][curr_code_num].nemonic = nemonic; bytecode[curr_code][curr_code_num].flag = flag; bytecode[curr_code][curr_code_num].bc_u.ival.dst = dst; bytecode[curr_code][curr_code_num++].bc_u.ival.val = ival; } // op:NUMBER only // dst レジスタに dval を格納 // という命令を刻む void set_bc_dval(Nemonic nemonic, int flag, Register dst, double dval){ bytecode[curr_code][curr_code_num].nemonic = nemonic; bytecode[curr_code][curr_code_num].flag = flag; bytecode[curr_code][curr_code_num].bc_u.dval.dst = dst; bytecode[curr_code][curr_code_num++].bc_u.dval.val = dval; } // op:STRING only // dst レジスタに str のアドレスを格納 // という命令を刻む void set_bc_str(Nemonic nemonic, int flag, Register dst, char *str){ bytecode[curr_code][curr_code_num].nemonic = nemonic; bytecode[curr_code][curr_code_num].flag = flag; bytecode[curr_code][curr_code_num].bc_u.str.dst = dst; bytecode[curr_code][curr_code_num++].bc_u.str.str = str; } void set_bc_regexp(Nemonic nemonic, int flag, Register dst, char* str, regexpFlag regflag){ bytecode[curr_code][curr_code_num].nemonic = nemonic; bytecode[curr_code][curr_code_num].flag = flag; bytecode[curr_code][curr_code_num].bc_u.regexp.dst = dst; bytecode[curr_code][curr_code_num].bc_u.regexp.str = str; bytecode[curr_code][curr_code_num++].bc_u.regexp.flag = regflag; } // op:CONST only // dst レジスタに TRUE, FALUSE, UNDEFINED, NULL のいずれかを格納 // という命令を刻む void set_bc_cons(Nemonic nemonic, int flag, Register dst, Const cons){ bytecode[curr_code][curr_code_num].nemonic = nemonic; bytecode[curr_code][curr_code_num].flag = flag; bytecode[curr_code][curr_code_num].bc_u.cons.dst = dst; bytecode[curr_code][curr_code_num++].bc_u.cons.cons = cons; } // op:SETFL, JUMP // FL を num にセット, pc+num へジャンプ // のいずれかの命令を刻む void set_bc_num(Nemonic nemonic, int flag, int num){ bytecode[curr_code][curr_code_num].nemonic = nemonic; bytecode[curr_code][curr_code_num].flag = flag; bytecode[curr_code][curr_code_num++].bc_u.num.n1 = num; } // op:JUMPTRUE, JUMPFALSE, SEND, TAILSEND, CALL, TAILCALL, MAKECLOSURE // dst が TRUE なら label:n1 へジャンプ // dst が FALSE なら label:n1 へジャンプ // args.length == n1 な関数 r1 のレシーバのある呼び出し // args.length == n1 な関数 r1 のレシーバのある末尾呼び出し // args.length == n1 な関数 r1 のレシーバのない呼び出し // args.length == n1 な関数 r1 のレシーバのない末尾呼び出し // func_tbl[n1] の関数クロージャを dst に格納 // のいずれかの命令を刻む void set_bc_regnum(Nemonic nemonic, int flag, Register r1, int n1){ bytecode[curr_code][curr_code_num].nemonic = nemonic; bytecode[curr_code][curr_code_num].flag = flag; bytecode[curr_code][curr_code_num].bc_u.regnum.r1 = r1; bytecode[curr_code][curr_code_num++].bc_u.regnum.n1 = n1; } // op:RET , SETA, GETA // void set_bc_unireg(Nemonic nemonic, int flag, Register r1){ bytecode[curr_code][curr_code_num].nemonic = nemonic; bytecode[curr_code][curr_code_num].flag = flag; bytecode[curr_code][curr_code_num++].bc_u.unireg.r1 = r1; } // op:GETGLOBAL, SETGLOBAL, TYPEOF, MOVE, NEW, NEWARGS void set_bc_bireg(Nemonic nemonic, int flag, Register r1, Register r2){ bytecode[curr_code][curr_code_num].nemonic = nemonic; bytecode[curr_code][curr_code_num].flag = flag; bytecode[curr_code][curr_code_num].bc_u.bireg.r1 = r1; bytecode[curr_code][curr_code_num++].bc_u.bireg.r2 = r2; } // op:ARITHMATIC, SETPROP, GETPROP void set_bc_trireg(Nemonic nemonic, int flag, Register r1, Register r2, Register r3){ bytecode[curr_code][curr_code_num].nemonic = nemonic; bytecode[curr_code][curr_code_num].flag = flag; bytecode[curr_code][curr_code_num].bc_u.trireg.r1 = r1; bytecode[curr_code][curr_code_num].bc_u.trireg.r2 = r2; bytecode[curr_code][curr_code_num++].bc_u.trireg.r3 = r3; } // op:SETLOCAL, SETARG, GETLOCAL, GETARG void set_bc_var(Nemonic nemonic, int flag, int n1, int n2, Register r1){ bytecode[curr_code][curr_code_num].nemonic = nemonic; bytecode[curr_code][curr_code_num].flag = flag; bytecode[curr_code][curr_code_num].bc_u.var.n1 = n1; bytecode[curr_code][curr_code_num].bc_u.var.n2 = n2; bytecode[curr_code][curr_code_num++].bc_u.var.r1 = r1; } void set_label(int label) { bytecode[curr_code][curr_code_num].label = label; } Environment env_empty(void) { return NULL; } Environment env_expand(char *name, Location loc, int level, int offset, int index, Environment rho) { Environment e = malloc(sizeof(struct environment)); e->name = name; e->location = loc; e->level = level; e->offset = offset; e->index = index; e->next = rho; return e; } int search_unuse() { int i; for(i=0; used_reg_tbl[i] && i<FL_MAX; i++); used_reg_tbl[i] = 1; touch_reg_tbl[i] = 1; return i; } void init_reg_tbl(int curr_level) { int i; for (i = 0; i < FL_MAX; i++) { release_reg(curr_tbl,i); used_reg_tbl[i] = 0; // 2011/05/31追記 release_reg の代わりに解放 touch_reg_tbl[i] = 0; } used_reg_tbl[0] = 1; touch_reg_tbl[0] = 1; used_reg_tbl[1] = 1; touch_reg_tbl[1] = 1; } Location env_lookup(Environment rho, int curr_level, char *name, int *level, int *offset, int *index) { while (rho != NULL){ if (strcmp(name, rho->name) == 0) { *level = curr_level - rho->level; *offset = rho->offset; *index = rho->index; return rho->location; } rho = rho->next; } return LOC_GLOBAL; } char *nemonic_to_str(Nemonic nemonic) { switch (nemonic) { case NUMBER: return "number"; case FIXNUM: return "fixnum"; case STRING: return "string"; case REGEXP: return "regexp"; case CONST: return "const"; case SPECCONST: return "specconst"; case ADD: return "add"; case SUB: return "sub"; case MUL: return "mul"; case DIV: return "div"; case MOD: return "mod"; case BITAND: return "bitand"; case BITOR: return "bitor"; case JUMPTRUE: return "jumptrue"; case JUMPFALSE: return "jumpfalse"; case JUMP: return "jump"; case LEFTSHIFT: return "leftshift"; case RIGHTSHIFT: return "rightshift"; case UNSIGNEDRIGHTSHIFT: return "unsignedrightshift"; case LESSTHAN: return "lessthan"; case LESSTHANEQUAL: return "lessthanequal"; case EQ: return "eq"; case EQUAL: return "equal"; case GETPROP: return "getprop"; case SETPROP: return "setprop"; case SETARRAY: return "setarray"; case GETARG: return "getarg"; case SETARG: return "setarg"; case GETLOCAL: return "getlocal"; case SETLOCAL: return "setlocal"; case GETGLOBAL: return "getglobal"; case SETGLOBAL: return "setglobal"; case MOVE: return "move"; case CALL: return "call"; case SEND: return "send"; case TAILCALL: return "tailcall"; case TAILSEND: return "tailsend"; case NEWSEND: return "newsend"; case RET: return "ret"; case MAKECLOSURE: return "makeclosure"; case MAKEITERATOR: return "makeiterator"; case NEXTPROPNAME: return "nextpropname"; case TRY: return "try"; case THROW: return "throw"; case FINALLY: return "finally"; case NEW: return "new"; case INSTANCEOF: return "instanceof"; case TYPEOF: return "typeof"; case NOT: return "not"; case NEWARGS: return "newargs"; case SETFL: return "setfl"; case ADDSP: return "addsp"; case SUBSP: return "subsp"; case GETIDX: return "getidx"; // 2011/05/30追記 case ISUNDEF: return "isundef"; case ISOBJECT: return "isobject"; case SETA: return "seta"; case GETA: return "geta"; case GETERR: return "geterr"; case GETGLOBALOBJ: return "getglobalobj"; case ERROR: return "error"; case UNKNOWN: return "unknown"; default: return "nemonic_to_str???"; } } char *const_to_str(Const cons){ switch (cons) { case TRUE: return "true"; case FALSE: return "false"; case UNDEFINED: return "undefined"; case Null: return "null"; default: return "const_to_str???"; } } Nemonic arith_nemonic(int type) { switch (type) { case TOK_PLUS: return ADD; case TOK_MINUS: return SUB; case TOK_STAR: return MUL; case TOK_DIVOP: return DIV; default: return UNKNOWN; } } Nemonic shift_nemonic(int type) { switch (type) { case JSOP_LSH: return LEFTSHIFT; case JSOP_RSH: return RIGHTSHIFT; case JSOP_URSH: return UNSIGNEDRIGHTSHIFT; default: return UNKNOWN; } } Nemonic divop_nemonic(int type) { switch (type) { case 30: return DIV; case 31: return MOD; default: return UNKNOWN; } } Nemonic arith_nemonic_prefix(int type) { switch (type) { case TOK_INC: return ADD; case TOK_DEC: return SUB; default: return UNKNOWN; } } Nemonic arith_nemonic_assignment(int type) { switch (type) { case JSOP_LSH: return LEFTSHIFT; case JSOP_RSH: return RIGHTSHIFT; case JSOP_URSH: return UNSIGNEDRIGHTSHIFT; case 15: return BITOR; case 17: return BITAND; case 27: return ADD; case 28: return SUB; case 29: return MUL; case 30: return DIV; case 31: return MOD; default: return UNKNOWN; } } Nemonic bitwise_nemonic(int type) { switch (type) { case TOK_BITAND: return BITAND; case TOK_BITOR: return BITOR; default: return UNKNOWN; } } regexpFlag getFlag(char* flagStart, char* flagEnd) { regexpFlag flag = F_REGEXP_NONE; while(flagStart <= flagEnd){ switch(*flagStart){ case 'g': flag |= F_REGEXP_GLOBAL; break; case 'i': flag |= F_REGEXP_IGNORE; break; case 'm': flag |= F_REGEXP_MULTILINE; break; } flagStart++; } return flag; } char *regexp_to_string(JSAtom *atom, regexpFlag *flag) { jsval val; int length; JSString *string; char *str, *start, *end, *trueend; int i; js_regexp_toString(context, ATOM_TO_OBJECT(atom), 0, NULL, &val); string = JSVAL_TO_STRING(val); length = string->length; str = malloc(sizeof(char) * (length + 1)); for (i=0;i < length ;i++) { str[i] = string->chars[i]; } str[i] = '\0'; start = str + 1; trueend = end = str + length; while (*end != '/' && start <= end) { end--; } if (*end == '/') { *end = '\0'; end--; } // fprintf(stderr, "rts:%s, %c\n", start, *end); *flag = getFlag(end + 2, trueend); return start; } char * atom_to_string(JSAtom *atom) { JSString * strings = ATOM_TO_STRING(atom); int i; char * str; int length = strings->length; str = malloc(sizeof(char) * (length + 1)); for(i=0;i < length ;i++){ str[i] = strings->chars[i]; } str[i]='\0'; return str; } void compile_assignment(char *str, Environment rho, Register src, int curr_level) { int level, offset, index; switch (env_lookup(rho, curr_level, str, &level, &offset, &index)) { case LOC_REGISTER: { set_bc_bireg(MOVE, 0, index, src); } break; case LOC_LOCAL: { set_bc_var(SETLOCAL, 0, level, offset, src); // printf("setlocal %d %d $%d\n", level, offset, src); } break; case LOC_ARG: { set_bc_var(SETARG, 0, level, index, src); // printf("setarg %d %d $%d\n", level, index, src); } break; case LOC_GLOBAL: { Register tn = search_unuse(); set_bc_str(STRING, 0, tn, str); set_bc_bireg(SETGLOBAL, 0, tn, src); // printf("string $%d \"%s\"\n", tn, str); // printf("setglobal $%d $%d\n", tn, src); release_reg(curr_tbl, tn); } break; default: fprintf(stderr, "compile_assignment: unexpected case\n"); } } int highest_touch_reg() { int i; for (i = 0; touch_reg_tbl[i]; i++); return i - 1; } int add_function_tbl(JSParseNode *node, Environment rho, int level){ func_tbl[curr_func].node = node; func_tbl[curr_func].rho = rho; func_tbl[curr_func].level = level; func_tbl[curr_func].existClosure = level > 1; return curr_func++ - 1; } int calc_fl() { //なんだかバグがあるので関数呼び出しがなくても //関数呼び出し用のレジスタを確保する仕様にしておく // if (max_func_fl != 0) { return highest_touch_reg() + max_func_fl + 4; // } else { // return highest_touch_reg(); // } } void set_bc_fl() { int i; for (i = 0; i < curr_code_num; i++) { if (bytecode[curr_code][i].flag == 2) { switch (bytecode[curr_code][i].nemonic) { case MOVE: bytecode[curr_code][i].flag = 0; bytecode[curr_code][i].bc_u.bireg.r1 += fl_tbl[curr_code]; break; case SETFL: bytecode[curr_code][i].flag = 0; bytecode[curr_code][i].bc_u.num.n1 += fl_tbl[curr_code]; break; default: fprintf(stderr, "set_bc_fl: unexpeted instruction %s\n", nemonic_to_str(bytecode[curr_code][i].nemonic)); } } } } void dispatch_label(int jump_line, int label_line) { switch (bytecode[curr_code][jump_line].nemonic) { case JUMPTRUE: case JUMPFALSE: bytecode[curr_code][jump_line].flag = 0; bytecode[curr_code][jump_line].bc_u.regnum.n1 = label_line - jump_line; break; case JUMP: case TRY: bytecode[curr_code][jump_line].flag = 0; bytecode[curr_code][jump_line].bc_u.num.n1 = label_line - jump_line; break; default: fprintf(stderr, "dispatch_label: unexpeted instruction %s\n", nemonic_to_str(bytecode[curr_code][jump_line].nemonic)); // perror("dispatch failed!"); } } void compile_bytecode(JSParseNode *root, Environment rho, Register dst, int tailflag, int curr_level) { if (root == NULL) { return; } if (root->pn_type >= NUM_TOKENS) { return; } switch (root->pn_type) { case TOK_NUMBER: { double v = root->pn_dval; if(v == (double)(long long)v && v < (double)0xffffffff && v > (double) -0x100000000) { set_bc_ival(FIXNUM, 0, dst, (int64_t)v); } else { set_bc_dval(NUMBER, 0, dst, v); } #if DEBUG4 printf("dval = %lf\n", bytecode[curr_code][curr_code_num-1].bc_u.dval.val); #endif // printf("number $%d %lf\n", dst, v); } break; case TOK_OBJECT: { if (root->pn_op == JSOP_REGEXP) { char *str; regexpFlag flag; str = regexp_to_string(root->pn_atom, &flag); set_bc_regexp(REGEXP, 0, dst, str, flag); } } break; case TOK_SHOP: { if (root->pn_arity == PN_BINARY) { Register t1 = search_unuse(); Register t2 = search_unuse(); compile_bytecode(root->pn_left, rho, t1, 0, curr_level); compile_bytecode(root->pn_right, rho, t2, 0, curr_level); set_bc_trireg(shift_nemonic(root->pn_op), 0, dst, t1, t2); // fprintf(stderr, "%d:%d %d %d\n", shift_nemonic(root->pn_op), dst, t1, t2); // printf("%s $%d $%d $%d\n", arith_nemonic(root->pn_type), dst, t1, t2); release_reg(curr_tbl, t1); release_reg(curr_tbl, t2); } else if (root->pn_arity == PN_LIST) { JSParseNode * p; Register tmp; compile_bytecode(root->pn_head, rho, dst, 0, curr_level); for (p = root->pn_head->pn_next; p != NULL; p = p->pn_next) { tmp = search_unuse(); compile_bytecode(p, rho, tmp, 0, curr_level); set_bc_trireg(shift_nemonic(root->pn_op), 0, dst, dst, tmp); // printf("%s $%d $%d $%d\n", arith_nemonic(root->pn_type), dst, dst, tmp); release_reg(curr_tbl, tmp); } } } break; case TOK_PLUS: case TOK_MINUS: case TOK_STAR: { if (root->pn_arity == PN_BINARY) { Register t1 = search_unuse(); Register t2 = search_unuse(); compile_bytecode(root->pn_left, rho, t1, 0, curr_level); compile_bytecode(root->pn_right, rho, t2, 0, curr_level); set_bc_trireg(arith_nemonic(root->pn_type), 0, dst, t1, t2); // printf("%s $%d $%d $%d\n", arith_nemonic(root->pn_type), dst, t1, t2); release_reg(curr_tbl, t1); release_reg(curr_tbl, t2); } else if (root->pn_arity == PN_LIST) { JSParseNode * p; Register tmp; compile_bytecode(root->pn_head, rho, dst, 0, curr_level); for (p = root->pn_head->pn_next; p != NULL; p = p->pn_next) { tmp = search_unuse(); compile_bytecode(p, rho, tmp, 0, curr_level); set_bc_trireg(arith_nemonic(root->pn_type), 0, dst, dst, tmp); // printf("%s $%d $%d $%d\n",arith_nemonic(root->pn_type), dst, dst, tmp); release_reg(curr_tbl, tmp); } } } break; case TOK_DIVOP: { if (root->pn_arity == PN_BINARY) { Register t1 = search_unuse(); Register t2 = search_unuse(); compile_bytecode(root->pn_left, rho, t1, 0, curr_level); compile_bytecode(root->pn_right, rho, t2, 0, curr_level); set_bc_trireg(divop_nemonic(root->pn_op), 0, dst, t1, t2); // printf("%s $%d $%d $%d\n", arith_nemonic(root->pn_type), dst, t1, t2); release_reg(curr_tbl, t1); release_reg(curr_tbl, t2); } else if (root->pn_arity == PN_LIST) { JSParseNode * p; Register tmp; compile_bytecode(root->pn_head, rho, dst, 0, curr_level); for (p = root->pn_head->pn_next; p != NULL; p = p->pn_next) { tmp = search_unuse(); compile_bytecode(p, rho, tmp, 0, curr_level); set_bc_trireg(divop_nemonic(root->pn_op), 0, dst, dst, tmp); // printf("%s $%d $%d $%d\n",arith_nemonic(root->pn_type), dst, dst, tmp); release_reg(curr_tbl, tmp); } } } break; case TOK_BITAND: case TOK_BITOR: { if (root->pn_arity == PN_BINARY) { Register t1 = search_unuse(); Register t2 = search_unuse(); compile_bytecode(root->pn_left, rho, t1, 0, curr_level); compile_bytecode(root->pn_right, rho, t2, 0, curr_level); set_bc_trireg(bitwise_nemonic(root->pn_type), 0, dst, t1, t2); // printf("%s $%d $%d $%d\n", arith_nemonic(root->pn_type), dst, t1, t2); release_reg(curr_tbl, t1); release_reg(curr_tbl, t2); } else if (root->pn_arity == PN_LIST) { JSParseNode * p; Register tmp; compile_bytecode(root->pn_head, rho, dst, 0, curr_level); for (p = root->pn_head->pn_next; p != NULL; p = p->pn_next) { tmp = search_unuse(); compile_bytecode(p, rho, tmp, 0, curr_level); set_bc_trireg(bitwise_nemonic(root->pn_type), 0, dst, dst, tmp); // printf("%s $%d $%d $%d\n",arith_nemonic(root->pn_type), dst, dst, tmp); release_reg(curr_tbl, tmp); } } } break; case TOK_STRING: { char *str = atom_to_string(root->pn_atom); set_bc_str(STRING, 0, dst, str); // printf("string $%d \"%s\"\n", dst, str); } break; case TOK_PRIMARY: { int opcode = root->pn_op; switch (opcode) { case 64: set_bc_cons(SPECCONST, 0, dst, Null); break; case 65: set_bc_bireg(MOVE, 0, dst, 1); break; case 66: /*false*/ set_bc_cons(SPECCONST, 0, dst, FALSE); // printf("const %d %s\n", dst,"False"); break; case 67: /*true*/ set_bc_cons(SPECCONST, 0, dst, TRUE); // printf("const %d %s\n", dst,"True"); break; } } break; case TOK_NAME: { char *str = atom_to_string(root->pn_atom); int level, offset, index; Register tn = search_unuse(); switch (env_lookup(rho, curr_level, str, &level, &offset, &index)) { case LOC_REGISTER: set_bc_bireg(MOVE, 0, dst, index); break; case LOC_LOCAL: set_bc_var(GETLOCAL, 0, level, offset, dst); // printf("getlocal $%d %d %d\n", dst, level, offset); break; case LOC_ARG: set_bc_var(GETARG, 0, level, index, dst); // printf("getarg $%d %d %d\n", dst, level, index); break; case LOC_GLOBAL: set_bc_str(STRING, 0, tn, str); set_bc_bireg(GETGLOBAL, 0, dst, tn); // printf("string $%d \"%s\"\n", tn, str); // printf("getglobal $%d $%d\n", dst, tn); break; default: fprintf(stderr, "compile_bytecode: unexpected case in TOK_NAME\n"); } release_reg(curr_tbl, tn); } break; case TOK_ASSIGN: { if (root->pn_left->pn_type == TOK_NAME) { char *str = atom_to_string(root->pn_left->pn_atom); Register t1 = search_unuse(); Register t2 = search_unuse(); if (root->pn_op == 0) { compile_bytecode(root->pn_right, rho, dst, 0, curr_level); compile_assignment(str, rho, dst, curr_level); } else { compile_bytecode(root->pn_left, rho, t1, 0, curr_level); compile_bytecode(root->pn_right, rho, t2, 0, curr_level); set_bc_trireg(arith_nemonic_assignment(root->pn_op), 0, dst, t1, t2); // printf("%s $%d $%d $%d\n", // arith_nemonic_assignment(root->pn_op), dst, t1, t2); compile_assignment(str, rho, dst, curr_level); } release_reg(curr_tbl, t1); release_reg(curr_tbl, t2); } else if (root->pn_left->pn_type == TOK_DOT) { Register t1 = search_unuse(); Register t2 = search_unuse(); Register t3 = search_unuse(); Register t4 = search_unuse(); // fprintf(stderr, "q!"); char *str = atom_to_string(root->pn_left->pn_atom); if (root->pn_op == 0) { // C[[ e1.x = e2 ]] rho d f compile_bytecode(root->pn_left->pn_expr, rho, t1, 0, curr_level); compile_bytecode(root->pn_right, rho, dst, 0, curr_level); set_bc_str(STRING, 0, t3, str); set_bc_trireg(SETPROP, 0, t1, t3, dst); // printf("string $%d \"%s\"\n", t3, str); // printf("setprop $%d $%d $%d\n", t1, t3, t2); } else { // C[[ e1.x [arith]= e2 ]] rho d f = // C[[ e1 ]] rho t1 False compile_bytecode(root->pn_left->pn_expr, rho, t1, 0, curr_level); // string t2 name_of(x) set_bc_str(STRING, 0, t2, str); // getprop t3 t1 t2 set_bc_trireg(GETPROP, 0, t3, t1, t2); // printf("string $%d \"%s\"\n", t2, str); // printf("getprop $%d $%d $%d\n", t3, t1, t2); // C[[ e2 ]] rho t4 False compile_bytecode(root->pn_right, rho, t4, 0, curr_level); // [arith] t3 t3 t4 set_bc_trireg(arith_nemonic_assignment(root->pn_op), 0, dst, t3, t4); // setprop t1 t2 t3 set_bc_trireg(SETPROP, 0, t1, t2, dst); // printf("%s $%d $%d $%d\n", // arith_nemonic_assignment( root->pn_op ), t3, t3, t4); // printf("setprop $%d $%d $%d\n", t1, t2, t3); } release_reg(curr_tbl, t1); release_reg(curr_tbl, t2); release_reg(curr_tbl, t3); release_reg(curr_tbl, t4); } else if (root->pn_left->pn_type == TOK_LB) { // fprintf(stderr, "p!"); // todo:else if (root->-pn_left->pn_type == TOK_LB){...} // C[[ e1[e2] = e3 ]] rho d f Register t1 = search_unuse(); Register t2 = search_unuse(); Register t3 = search_unuse(); Register t4 = search_unuse(); Register t5 = search_unuse(); Register f_getidx = search_unuse(); if (root->pn_op == 0) { // C[[ e1 ]] rho t1 False compile_bytecode(root->pn_left->pn_left, rho, t1, 0, curr_level); // C[[ e2 ]] rho t3 False compile_bytecode(root->pn_left->pn_right, rho, t3, 0, curr_level); // C[[ e3 ]] rho t2 False compile_bytecode(root->pn_right, rho, t2, 0, curr_level); // gettoidx f_getidx t3 set_bc_bireg(GETIDX, 0, f_getidx, t3); // move $FL t3 set_bc_bireg(MOVE, 2, 0, t3); // send f_getidx 0 set_bc_regnum(SEND, 0, f_getidx, 0); // setfl FL set_bc_num(SETFL, 2, 0); // move t4 $A set_bc_unireg(GETA, 0, t4); //set_bc_bireg(MOVE, 0, t4, REG_A); // setprop t1 t4 t2 set_bc_trireg(SETPROP, 0, t1, t4, t2); } else { // C[[ e1[e2] [arith]= e3 ]] rho d f // C[[ e1 ]] rho t1 False compile_bytecode(root->pn_left->pn_left, rho, t1, 0, curr_level); // C[[ e2 ]] rho t3 False compile_bytecode(root->pn_left->pn_right, rho, t3, 0, curr_level); // C[[ e3 ]] rho t2 False compile_bytecode(root->pn_right, rho, t2, 0, curr_level); // gettoidx f_getidx t3 set_bc_bireg(GETIDX, 0, f_getidx, t3); // move $FL t3 set_bc_bireg(MOVE, 2, 0, t3); // send f_getidx 0 set_bc_regnum(SEND, 0, f_getidx, 0); // setfl FL set_bc_num(SETFL, 2, 0); // move t4 $A **t4 is property name** //set_bc_bireg(MOVE, 0, t4, REG_A); set_bc_unireg(GETA, 0, t4); // getprop t5 t1 t4 set_bc_trireg(GETPROP, 0, t5, t1, t4); // [arith] t5 t5 t2 set_bc_trireg(arith_nemonic_assignment(root->pn_op), 0, t5, t5, t4); // setprop t1 t4 t5 set_bc_trireg(SETPROP, 0, t1, t4, t5); } } } break; case TOK_DOT: { Register t1 = search_unuse(); Register t2 = search_unuse(); char *str = atom_to_string(root->pn_atom); compile_bytecode(root->pn_expr, rho, t1, 0, curr_level); set_bc_str(STRING, 0, t2, str); set_bc_trireg(GETPROP, 0, dst, t1, t2); // printf("string $%d \"%s\"\n", t2, str); // printf("getprop $%d $%d $%d\n", dst, t1, t2); release_reg(curr_tbl, t1); release_reg(curr_tbl, t2); } break; case TOK_RC: { Register objConsStr = search_unuse(); Register objCons = search_unuse(); Register propdst = search_unuse(); Register pstr = search_unuse(); Register f_getidx = search_unuse(); JSParseNode *p; set_bc_str(STRING, 0, objConsStr, gStringObject); set_bc_bireg(GETGLOBAL, 0, objCons, objConsStr); set_bc_bireg(NEW, 0, dst, objCons); set_bc_bireg(MOVE, 2, 0, dst); set_bc_regnum(NEWSEND, 0, objCons, 0); //set_bc_num(ADDSP, 0, root->pn_count + 3); set_bc_num(SETFL, 2, 0); set_bc_unireg(GETA, 0, dst); for (p = root->pn_head; p != NULL; p = p->pn_next) { switch(p->pn_left->pn_type){ case TOK_NAME: case TOK_STRING: { char *name = atom_to_string(p->pn_left->pn_atom); compile_bytecode(p->pn_right, rho, propdst, 0, curr_level); set_bc_str(STRING, 0, pstr, name); set_bc_trireg(SETPROP, 0, dst, pstr, propdst); } break; case TOK_NUMBER: { compile_bytecode(p->pn_right, rho, propdst, 0, curr_level); double v = p->pn_left->pn_dval; if (v == (double)(long long)v && v < (double)0xffffffff && v > (double) -0x100000000) { set_bc_ival(FIXNUM, 0, pstr, (int64_t)v); } else { set_bc_dval(NUMBER, 0, pstr, v); } set_bc_bireg(GETIDX, 0, f_getidx, pstr); set_bc_bireg(MOVE, 2, 0, pstr); set_bc_regnum(SEND, 0, f_getidx, 0); set_bc_num(SETFL, 2, 0); set_bc_unireg(GETA, 0, pstr); set_bc_trireg(SETPROP, 0, dst, pstr, propdst); } break; } } if (root->pn_count > max_func_fl) { max_func_fl = root->pn_count; } } break; case TOK_LB: { Register r1 = search_unuse(); Register r2 = search_unuse(); Register f_getidx = search_unuse(); Register r3 = search_unuse(); compile_bytecode(root->pn_left, rho, r1, 0, curr_level); compile_bytecode(root->pn_right, rho, r2, 0, curr_level); // 2011/05/30追記 ここから set_bc_bireg(GETIDX, 0, f_getidx, r2); set_bc_bireg(MOVE, 2, 0, r2); // flag==2 FL+0 に r2 のデータを移す set_bc_regnum(SEND, 0, f_getidx, 0); set_bc_num(SETFL, 2, 0); //set_bc_bireg(MOVE, 0, r3, REG_A); set_bc_unireg(GETA, 0, r3); set_bc_trireg(GETPROP, 0, dst, r1, r3); //set_bc_trireg(GETPROP, 0, dst, r1, r2); if(max_func_fl == 0) max_func_fl+=1; // 2011/05/30追記 ここまで release_reg(curr_tbl, r1); release_reg(curr_tbl, r2); } break; case TOK_RB: { Register objConsStr = search_unuse(); Register objCons = search_unuse(); Register propdst = search_unuse(); Register dlen = search_unuse(); JSParseNode *p; int count = root->pn_count; int i = 0; set_bc_ival(FIXNUM, 0, dlen, count); set_bc_str(STRING, 0, objConsStr, gStringArray); set_bc_bireg(GETGLOBAL, 0, objCons, objConsStr); set_bc_bireg(NEW, 0, dst, objCons); set_bc_bireg(MOVE, 2, 0, dlen); set_bc_bireg(MOVE, 2, -1, dst); set_bc_regnum(NEWSEND, 0, objCons, 1); //set_bc_num(ADDSP, 0, root->pn_count + 3); set_bc_num(SETFL, 2, 0); set_bc_unireg(GETA, 0, dst); for (p = root->pn_head; p != NULL; p = p->pn_next, i++) { if (p->pn_type == TOK_COMMA) { set_bc_cons(SPECCONST, 0, propdst, UNDEFINED); } else { compile_bytecode(p, rho, propdst, 0, curr_level); } set_bc_trireg(SETARRAY, 0, dst, i, propdst); } if (1 > max_func_fl) { max_func_fl = 1; } } break; case TOK_INC: case TOK_DEC: { switch (root->pn_op) { case JSOP_INCNAME: case JSOP_DECNAME: { Register t1 = search_unuse(); Register tone = search_unuse(); char *str = atom_to_string(root->pn_kid->pn_atom); double one = 1.0; compile_bytecode(root->pn_kid, rho, t1, 0, curr_level); set_bc_ival(FIXNUM, 0, tone, (int64_t)one); set_bc_trireg(arith_nemonic_prefix(root->pn_type), 0, dst, t1, tone); // printf("number $%d %lf\n", tone, one); // printf("%s $%d $%d $%d\n", arith_nemonic_prefix(root->pn_type), dst, t1, tone); compile_assignment(str, rho, dst, curr_level); release_reg(curr_tbl, t1); release_reg(curr_tbl, tone); release_reg(curr_tbl, tn); } break; case JSOP_INCPROP: case JSOP_DECPROP: { Register t1 = search_unuse(); Register t2 = search_unuse(); Register tone = search_unuse(); Register tn = search_unuse(); char *str = atom_to_string(root->pn_kid->pn_atom); double one = 1.0; compile_bytecode(root->pn_kid->pn_expr, rho, t2, 0, curr_level); set_bc_str(STRING, 0, tn, str); set_bc_trireg(GETPROP, 0, t1, t2, tn); set_bc_ival(FIXNUM, 0, tone, (int64_t)one); //set_bc_dval(FIXNUM, 0, tone, one); set_bc_trireg(arith_nemonic_prefix(root->pn_type), 0, dst, t1, tone); set_bc_trireg(SETPROP, 0, t2, tn, dst); /* printf("string $%d \"%s\"\n", tn, str); printf("getprop $%d $%d $%d\n", t1, t2, tn); printf("number $%d %lf\n", tone, one); printf("%s $%d $%d $%d\n", arith_nemonic_prefix(root->pn_type), dst, t1, tone); printf("setprop $%d $%d $%d\n", t2, tn, dst); */ release_reg(curr_tbl, t1); release_reg(curr_tbl, t2); release_reg(curr_tbl, t3); release_reg(curr_tbl, tone); release_reg(curr_tbl, tn); } break; case JSOP_NAMEINC: case JSOP_NAMEDEC: { Register t1 = search_unuse(); Register tone = search_unuse(); char *str = atom_to_string(root->pn_kid->pn_atom); double one = 1.0; compile_bytecode(root->pn_kid, rho, dst, 0, curr_level); set_bc_ival(FIXNUM, 0, tone, (int64_t)one); // set_bc_dval(FIXNUM, 0, tone, one); set_bc_trireg(arith_nemonic_prefix(root->pn_type), 0, t1, dst, tone); // printf("number $%d %lf\n", tone, one); // printf("%s $%d $%d $%d\n", // arith_nemonic_prefix(root->pn_type), t1, dst, tone); compile_assignment(str, rho, t1, curr_level); release_reg(curr_tbl, t1); release_reg(curr_tbl, tone); release_reg(curr_tbl, tn); } break; case JSOP_PROPINC: case JSOP_PROPDEC: { Register t1 = search_unuse(); Register t2 = search_unuse(); Register tone = search_unuse(); Register tn = search_unuse(); char *str = atom_to_string(root->pn_kid->pn_atom); double one = 1.0; compile_bytecode(root->pn_kid->pn_expr, rho, t2, 0, curr_level); set_bc_str(STRING, 0, tn, str); set_bc_trireg(GETPROP, 0, dst, t2, tn); set_bc_ival(FIXNUM, 0, tone, (int64_t)one); //set_bc_dval(FIXNUM, 0, tone, one); set_bc_trireg(arith_nemonic_prefix(root->pn_type), 0, t1, dst, tone); set_bc_trireg(SETPROP, 0, t2, tn, t1); /* printf("string $%d \"%s\"\n", tn, str); printf("getprop $%d $%d $%d\n", dst, t2, tn); printf("number $%d %lf\n", tone, one); printf("%s $%d $%d $%d\n", arith_nemonic_prefix(root->pn_type), t1, dst, tone); printf("setprop $%d $%d $%d\n", t2, tn, t1); */ release_reg(curr_tbl, t1); release_reg(curr_tbl, t2); release_reg(curr_tbl, t3); release_reg(curr_tbl, tone); release_reg(curr_tbl, tn); } break; default: break; } } break; case TOK_UNARYOP: switch (root->pn_op) { case JSOP_NOT: { Register t1 = search_unuse(); compile_bytecode(root->pn_kid, rho, t1, 0, curr_level); set_bc_bireg(NOT, 0, dst, t1); } break; case JSOP_NEG: { Register t1 = search_unuse(); Register tone = search_unuse(); double mone = -1.0; compile_bytecode(root->pn_kid, rho, t1, 0, curr_level); set_bc_ival(FIXNUM, 0, tone, (int64_t)mone); //set_bc_dval(FIXNUM, 0, tone, mone); set_bc_trireg(MUL, 0, dst, t1, tone); //printf("number $%d %lf\n", tone, mone); //printf("mul $%d $%d $%d\n", dst, t1, tone); release_reg(curr_tbl, t1); release_reg(curr_tbl, tone); } break;//2011/07/13 追記 break忘れ; case JSOP_TYPEOF: { compile_bytecode(root->pn_kid, rho, dst, 0, curr_level); set_bc_bireg(TYPEOF, 0, dst, dst); //printf("typeof $%d $%d\n", dst, dst); } break; case JSOP_VOID: { compile_bytecode(root->pn_kid, rho, dst, 0, curr_level); set_bc_cons(SPECCONST, 0, dst, UNDEFINED); //printf("const $%d undefined\n", dst); } break; default: compile_bytecode(root->pn_kid, rho, dst, 0, curr_level); } break; case TOK_AND: { int l1; int j1; int label = curr_label++; compile_bytecode(root->pn_left, rho, dst, 0, curr_level); j1 = curr_code_num; set_bc_regnum(JUMPFALSE, 1, dst, label); //printf("jumpfalse $%d L\n", dst); compile_bytecode(root->pn_right, rho, dst, tailflag, curr_level); l1 = curr_code_num; dispatch_label(j1, l1); //set_label(label); #if DEBUG4 printf("%d %d\n", curr_code, curr_code_num); printf("%d\n", bytecode[curr_code][curr_code_num].label); #endif //printf("L:\n"); } break; case TOK_OR: { int l1; int j1; int label = curr_label++; compile_bytecode(root->pn_left, rho, dst, 0, curr_level); j1 = curr_code_num; set_bc_regnum(JUMPTRUE, 1, dst, label); //printf("jumptrue $%d L\n", dst); compile_bytecode(root->pn_right, rho, dst, tailflag, curr_level); l1 = curr_code_num; dispatch_label(j1, l1); //set_label(label); //printf("L:\n"); } break; case TOK_RELOP: { Register t1 = search_unuse(); Register t2 = search_unuse(); switch (root->pn_op) { case JSOP_LT: case JSOP_LE: compile_bytecode(root->pn_left, rho, t1, 0, curr_level); compile_bytecode(root->pn_right, rho, t2, 0, curr_level); set_bc_trireg(root->pn_op == JSOP_LT ? LESSTHAN : LESSTHANEQUAL, 0, dst, t1, t2); // printf("%s $%d $%d $%d\n", // root->pn_op == JSOP_LT ? "lessthan" : "lessthanequal", // dst, t1, t2); break; case JSOP_GT: case JSOP_GE: compile_bytecode(root->pn_left, rho, t1, 0, curr_level); compile_bytecode(root->pn_right, rho, t2, 0, curr_level); set_bc_trireg(root->pn_op == JSOP_GT ? LESSTHAN : LESSTHANEQUAL, 0, dst, t2, t1); // printf("%s $%d $%d $%d\n", // root->pn_op == JSOP_GT ? "lessthan" : "lessthanequal", // dst, t2, t1); break; } release_reg(curr_tbl, t1); release_reg(curr_tbl, t2); } break; case TOK_EQOP: { Register t1 = search_unuse(); Register t2 = search_unuse(); compile_bytecode(root->pn_left, rho, t1, 0, curr_level); compile_bytecode(root->pn_right, rho, t2, 0, curr_level); if ( root->pn_op == JSOP_EQ ) { int ffin1, ffin2, fconvb, fsecond; int tfin1, tfin2, tconvb, tsecond; int lfin1 = curr_label++; int lfin2 = curr_label++; int lconvb = curr_label++; int lsecond = curr_label++; Register ts = search_unuse(); Register vs = search_unuse(); Register to = search_unuse(); Register fc = search_unuse(); Register ca = search_unuse(); Register cb = search_unuse(); set_bc_trireg(EQUAL, 0, dst, t1, t2); set_bc_bireg(ISUNDEF, 0, ts, dst); ffin1 = curr_code_num; set_bc_regnum(JUMPFALSE, 1, ts, lfin1); set_bc_str(STRING, 0, vs, "valueOf"); set_bc_bireg(ISOBJECT, 0, to, t1); fconvb = curr_code_num; set_bc_bireg(JUMPFALSE, 1, to, lconvb); set_bc_trireg(GETPROP, 0, fc, t1, vs); set_bc_bireg(MOVE, 2, 0, t1); set_bc_regnum(SEND, 0, fc, 0); //set_bc_bireg(MOVE, 0, ca, REG_A); set_bc_unireg(GETA, 0, ca); set_bc_bireg(MOVE, 0, cb, t2); fsecond = curr_code_num; set_bc_num(JUMP, 1, lsecond); //convb tconvb = curr_code_num; set_bc_trireg(GETPROP, 0, fc, t2, vs); set_bc_bireg(MOVE, 2, 0, t2); set_bc_regnum(SEND, 0, fc, 0); //set_bc_bireg(MOVE, 0, cb, REG_A); set_bc_unireg(GETA, 0, cb); set_bc_bireg(MOVE, 0, ca, t1); //tsecond tsecond = curr_code_num; set_bc_trireg(EQUAL, 0, dst, ca, cb); set_bc_bireg(ISUNDEF, 0, ts, dst); ffin2 = curr_code_num; set_bc_regnum(JUMPFALSE, 1, ts, lfin2); set_bc_str(ERROR, 0, dst, "EQUAL_GETTOPRIMITIVE"); // tfin tfin1 = tfin2 = curr_code_num; dispatch_label(ffin1, tfin1); dispatch_label(ffin2, tfin2); dispatch_label(fconvb, tconvb); dispatch_label(fsecond, tsecond); } else { set_bc_trireg(EQ, 0, dst, t1, t2); } // printf("%s $%d $%d $%d\n", root->pn_op == JSOP_EQ ? "equal" : "eq", // dst, t1, t2); } break; case TOK_HOOK: { Register t = search_unuse(); int label1 = curr_label++; int label2 = curr_label++; int j1, j2,l1,l2; compile_bytecode(root->pn_kid1, rho, t, 0, curr_level); j1 = curr_code_num; set_bc_regnum(JUMPFALSE, 1, t, label1); //printf("jumpfalse $%d L1\n",t);/*label*/ l1 = curr_code_num; //set_label(l1); //printf("L1:\n"); compile_bytecode(root->pn_kid2, rho, dst, tailflag, curr_level); j2 = curr_code_num; set_bc_num(JUMP, 1, label2); //printf("jump L2\n"); compile_bytecode(root->pn_kid3, rho, dst, tailflag, curr_level); l2 = curr_code_num; //set_label(l2); //printf("L2:\n"); release_reg(curr_tbl, t); dispatch_label(j1, l1); dispatch_label(j2, l2); } break; case TOK_IF: { int elseflag = (int)(intptr_t)(root->pn_kid3); Register t = search_unuse(); int l1 = curr_label++; int l2 = curr_label++; int j1, j2; compile_bytecode(root->pn_kid1, rho, t, 0, curr_level); j1 = curr_code_num; set_bc_regnum(JUMPFALSE, 1, t, l1); //printf("jumpfalse $%d L1\n",t); compile_bytecode(root->pn_kid2, rho, dst, 0, curr_level); if (elseflag) { j2 = curr_code_num; set_bc_num(JUMP, 1, l2); //printf("jump L2\n"); } l1 = curr_code_num; //set_label(l1); //printf("L1:\n"); if (elseflag) { compile_bytecode(root->pn_kid3, rho, dst, 0, curr_level); l2 = curr_code_num; //set_label(l2); //printf("L2:\n"); } dispatch_label(j1, l1); if (elseflag) { dispatch_label(j2, l2); } release_reg(curr_tbl, t); } break; case TOK_FOR: if (root->pn_left->pn_type == TOK_RESERVED) { Register t = search_unuse(); int l1 = curr_label++; int l2 = curr_label++; int j1, j2; compile_bytecode(root->pn_left->pn_kid1, rho, t, 0, curr_level); j1 = curr_code_num; set_bc_num(JUMP, 1, l1); //printf("jump L1\n"); l2 = curr_code_num; //set_label(l2); //printf("L2:\n"); compile_bytecode(root->pn_right, rho, dst, 0, curr_level); compile_bytecode(root->pn_left->pn_kid3, rho, t, 0, curr_level); l1 = curr_code_num; //set_label(l1); //printf("L1:\n"); compile_bytecode(root->pn_left->pn_kid2, rho, t, 0, curr_level); j2 = curr_code_num; set_bc_regnum(JUMPTRUE, 1, t, l2); //printf("jumptrue $%d L2\n",t); release_reg(curr_tbl, t); dispatch_label(j1, l1); dispatch_label(j2, l2); } else { if (func_tbl[curr_code].existClosure) { fprintf(stderr, "hogehoge"); } else { fprintf(stderr, "fugafuga"); Register obj, iter, name, namep; int l1 = curr_label++; int l2 = curr_label++; int f1, f2; obj = search_unuse(); iter = search_unuse(); name = search_unuse(); namep = search_unuse(); compile_bytecode(root->pn_left->pn_right, rho, obj, 0, curr_level); char *str = atom_to_string(root->pn_left->pn_left->pn_atom); rho = env_expand(str, LOC_REGISTER, curr_level, 1, name, rho); set_bc_bireg(MAKEITERATOR, 0, obj, iter); l1 = curr_code_num; set_bc_trireg(NEXTPROPNAME, 0, obj, iter, name); set_bc_bireg(ISUNDEF, 0, namep, name); f2 = curr_code_num; set_bc_regnum(JUMPTRUE, 1, namep, l2); compile_bytecode(root->pn_right, rho, dst, 0, curr_level); f1 = curr_code_num; set_bc_num(JUMP, 1, l1); l2 = curr_code_num; dispatch_label(f1, l1); dispatch_label(f2, l2); } } break; case TOK_WHILE: { Register t = search_unuse(); int l1 = curr_label++; int l2 = curr_label++; int j1, j2; j1 = curr_code_num; set_bc_num(JUMP, 1, l1); //printf("jump L1\n"); l2 = curr_code_num; //set_label(l2); //printf("L2:\n"); compile_bytecode(root->pn_right, rho, dst, 0, curr_level); l1 = curr_code_num; //set_label(l1); //printf("L1:\n"); compile_bytecode(root->pn_left, rho, t, 0, curr_level); j2 = curr_code_num; set_bc_regnum(JUMPTRUE, 1, t, l2); //printf("jumptrue $%d L2\n", t); release_reg(curr_tbl, t); dispatch_label(j1, l1); dispatch_label(j2, l2); } break; case TOK_DO: { Register t = search_unuse(); int l1 = curr_label++; int j1; l1 = curr_code_num; //set_label(l1); //printf("L1:\n"); compile_bytecode(root->pn_left, rho, dst, 0, curr_level); compile_bytecode(root->pn_right, rho, t, 0, curr_level); j1 = curr_code_num; set_bc_regnum(JUMPTRUE, 1, t, l1); //printf("jumptrue $%d L1\n", t); release_reg(curr_tbl, t); dispatch_label(j1, l1); } break; case TOK_LP: { if (root->pn_head->pn_type == TOK_DOT) { int count = root->pn_count; Register tm = search_unuse(); Register ts = search_unuse(); Register *tmp = malloc(sizeof(Register) * (count)); int i; JSParseNode *p; JSParseNode *methodnode = root->pn_head; char *m_name = atom_to_string(methodnode->pn_atom); for (i = 0; i < root->pn_count; i++) tmp[i] = search_unuse(); compile_bytecode(methodnode->pn_expr, rho, tmp[0], 0, curr_level); set_bc_str(STRING, 0, ts, m_name); set_bc_trireg(GETPROP, 0, tm, tmp[0], ts); for (p = root->pn_head->pn_next, i = 1; p != NULL; p = p->pn_next, i++) { compile_bytecode(p, rho, tmp[i], 0, curr_level); } if (tailflag) { set_bc_bireg(MOVE, 0, 1, tmp[0]); for (i = 0; i < root->pn_count - 1; i++) { set_bc_bireg(MOVE, 0, i+2, tmp[i+1]); //printf("move $%d $%d\n", i+2, tmp[i+1]); } set_bc_regnum(TAILSEND, 0, tm, root->pn_count - 1); //printf("tailcall $%d %d\n", tmp[0], root->pn_count - 1); } else { set_bc_bireg(MOVE, 2, -root->pn_count + 1, tmp[0]); for (i = 0; i < root->pn_count - 1; i++) { set_bc_bireg(MOVE, 2, -root->pn_count + 2 + i, tmp[i+1]); //printf("move $%d $%d\n", // fl_tbl[curr_tbl] - root->pn_count +2 + i, tmp[i+1]); } set_bc_regnum(SEND, 0, tm, root->pn_count - 1); //set_bc_num(ADDSP, 0, root->pn_count + 3); set_bc_num(SETFL, 2, 0); //set_bc_bireg(MOVE, 0, dst, REG_A); set_bc_unireg(GETA, 0, dst); /* printf("call $%d %d\n", tmp[0], root->pn_count - 1); printf("addsp %d\n", root->pn_count + 3); printf("move $%d $A\n", dst, REG_A); */ if (root->pn_count > max_func_fl) { max_func_fl = root->pn_count; } } for (i = 0; i < root->pn_count; i++) { release_reg(curr_tbl, i); } free(tmp); } else { int count = root->pn_count; Register *tmp = malloc(sizeof(Register) * (count)); int i; JSParseNode *p; for (i = 0; i < root->pn_count; i++) tmp[i] = search_unuse(); for (p = root->pn_head, i=0; p != NULL; p = p->pn_next, i++) { compile_bytecode(p, rho, tmp[i], 0, curr_level); } if (tailflag) { for (i = 0; i < root->pn_count - 1; i++) { set_bc_bireg(MOVE, 0, i+2, tmp[i+1]); //printf("move $%d $%d\n", i+2, tmp[i+1]); } set_bc_regnum(TAILCALL, 0, tmp[0], root->pn_count - 1); //printf("tailcall $%d %d\n", tmp[0], root->pn_count - 1); } else { for (i = 0; i < root->pn_count - 1; i++) { set_bc_bireg(MOVE, 2, -root->pn_count + 2 + i, tmp[i+1]); // printf("move $%d $%d\n", // fl_tbl[curr_tbl] - root->pn_count +2 + i, tmp[i+1]); } set_bc_regnum(CALL, 0, tmp[0], root->pn_count - 1); //set_bc_num(ADDSP, 0, root->pn_count + 3); set_bc_num(SETFL, 2, 0); //set_bc_bireg(MOVE, 0, dst, REG_A); set_bc_unireg(GETA, 0, dst); /* printf("call $%d %d\n", tmp[0], root->pn_count - 1); printf("addsp %d\n", root->pn_count + 3); printf("move $%d $A\n", dst, REG_A); */ if (root->pn_count > max_func_fl) { max_func_fl = root->pn_count; } } for (i = 0; i < root->pn_count; i++) { release_reg(curr_tbl, i); } free(tmp); } } break; case TOK_TRY: { int j1, j2; int l1 = curr_label++; int l2 = curr_label++; int level, offset, index; char* str; Environment rho2; Register err = search_unuse(); Location loc; j1 = curr_code_num; set_bc_num(TRY, 1, l1); compile_bytecode(root->pn_kid1, rho, dst, 0, curr_level); set_bc_unireg(FINALLY, 0, 0); j2 = curr_code_num; set_bc_num(JUMP, 1, l2); str = atom_to_string(root->pn_kid2->pn_kid1->pn_atom); loc = &func_tbl[curr_code] == func_tbl ? LOC_LOCAL : func_tbl[curr_code].existClosure ? LOC_LOCAL : LOC_REGISTER; l1 = curr_code_num; set_bc_num(SETFL, 2, 0); set_bc_unireg(GETERR, 0, err); if (loc == LOC_LOCAL) { rho2 = env_expand(str, loc, curr_level, ++var_num[curr_code], 1, rho); env_lookup(rho2, curr_level, str, &level, &offset, &index); set_bc_var(SETLOCAL, 0, level, offset, err); } else { rho2 = env_expand(str, loc, curr_level, 1, err, rho); } compile_bytecode(root->pn_kid2->pn_kid3, rho2, dst, 0, curr_level); l2 = curr_code_num; compile_bytecode(root->pn_kid3, rho, dst, 0, curr_level); dispatch_label(j1, l1); dispatch_label(j2, l2); } break; case TOK_THROW: { Register th = search_unuse(); compile_bytecode(root->pn_kid, rho, th, 0, curr_level); set_bc_unireg(THROW, 0, th); } break; case TOK_FUNCTION: { set_bc_regnum(MAKECLOSURE, 0, dst, add_function_tbl(root, rho, curr_level+1)); // printf("makeclosure $%d %d\n", dst, // add_function_tbl(root, rho, curr_level+1)); } break; case TOK_NEW: { Register *tmp = malloc(sizeof(Register) * (root->pn_count)); Register ts = search_unuse(); Register tg = search_unuse(); Register tins = search_unuse(); Register retr = search_unuse(); int i; JSParseNode *p; int l1 = curr_label++; int j1; for (i = 0; i < root->pn_count; i++) tmp[i] = search_unuse(); for (p = root->pn_head, i=0; p != NULL; p = p->pn_next, i++) { compile_bytecode(p, rho, tmp[i], 0, curr_level); } for (i = 0; i < root->pn_count - 1; i++) { set_bc_bireg(MOVE, 2, -root->pn_count + 2 + i, tmp[i + 1]); //printf("move $%d $%d\n", fl_tbl[curr_tbl] - root->pn_count + 2 + i, // tmp[i + 1]); } set_bc_bireg(NEW, 0, dst, tmp[0]); set_bc_bireg(MOVE, 2, -(root->pn_count - 1), dst); set_bc_regnum(NEWSEND, 0, tmp[0], root->pn_count - 1); //set_bc_num(ADDSP, 0, root->pn_count + 3); set_bc_num(SETFL, 2, 0); set_bc_str(STRING, 0, ts, "Object"); set_bc_bireg(GETGLOBAL, 0, tg, ts); set_bc_unireg(GETA, 0, retr); set_bc_trireg(INSTANCEOF, 0, tins, retr, tg); j1 = curr_code_num; set_bc_regnum(JUMPFALSE, 1, tins, l1); //set_bc_bireg(MOVE, 0, dst, REG_A); set_bc_unireg(GETA, 0, dst); l1 = curr_code_num; if (root->pn_count > max_func_fl) { max_func_fl = root->pn_count; } //set_label(l1); /* printf("new $%d $%d\n", dst, tmp[0]); printf("move $%d $%d\n", fl_tbl[curr_tbl] - (root->pn_count - 1), dst); printf("send $%d %d\n", tmp[0], root->pn_count - 1); printf("addsp %d\n", root->pn_count + 3); printf("string $%d \"%s\"\n", ts, "Object"); printf("instanceof $%d $A $%d\n", tins, ts); printf("jumpfalse $%d L\n", tins); printf("move $%d $A\n", dst); printf("L:\n"); */ dispatch_label(j1, l1); } break; case TOK_RETURN: { Register t; t = search_unuse(); compile_bytecode(root->pn_kid, rho, t, 1, curr_level); //set_bc_bireg(MOVE, 0, REG_A, t); set_bc_unireg(SETA, 0, t); set_bc_unireg(RET, 0, -1); //printf("ret\n"); } break; case TOK_VAR: { JSParseNode *p; for (p = root->pn_head; p != NULL; p = p->pn_next) { if (p->pn_expr != NULL) { if (root->pn_left->pn_type == TOK_NAME) { char *str = atom_to_string(root->pn_left->pn_atom); compile_bytecode(p->pn_expr, rho, dst, 0, curr_level); compile_assignment(str, rho, dst, curr_level); /* if (p->pn_op == 0) { compile_bytecode(p->pn_expr, rho, dst, 0, curr_level); compile_assignment(str, rho, dst, curr_level); } else { compile_bytecode(p, rho, t1, 0, curr_level); compile_bytecode(p->pn_expr, rho, t2, 0, curr_level); printf("%s $%d $%d $%d\n", arith_nemonic_assignment(p->pn_op), dst, t1, t2); compile_assignment(str, rho, dst, curr_level); } */ release_reg(curr_tbl, t1); release_reg(curr_tbl, t2); } } } } break; default: switch (root->pn_arity) { case PN_UNARY: compile_bytecode(root->pn_kid, rho, dst, tailflag, curr_level); break; case PN_BINARY: compile_bytecode(root->pn_left, rho, dst, tailflag, curr_level); compile_bytecode(root->pn_right, rho, dst, tailflag, curr_level); break; case PN_TERNARY: compile_bytecode(root->pn_kid1, rho, dst, tailflag, curr_level); compile_bytecode(root->pn_kid2, rho, dst, tailflag, curr_level); compile_bytecode(root->pn_kid3, rho, dst, tailflag, curr_level); break; case PN_LIST: { JSParseNode * p; for (p = root->pn_head; p != NULL; p = p->pn_next) { compile_bytecode(p, rho, dst, tailflag, curr_level); } } break; case PN_FUNC: case PN_NAME: if (root->pn_expr != NULL) { compile_bytecode(root->pn_expr, rho, dst, tailflag, curr_level); } break; case PN_NULLARY: break; } break; } } void compile_function(Function_tbl func_tbl, int index) { Environment rho = func_tbl.rho; curr_code = index; curr_code_num = 0; max_func_fl = 0; Register retu; bool existClosure; bool useArguments; // printf("call_entry_%d:\n", index); existClosure = func_tbl.existClosure || searchFunctionDefinition(func_tbl.node->pn_body); useArguments = searchUseArguments(func_tbl.node->pn_body); #ifndef OPT_FFRAME existClosure = true; #endif set_bc_unireg(GETGLOBALOBJ, 0, 1); // set_bc_cons(SPECCONST, 0, 1, Null); if (existClosure || useArguments) { set_bc_unireg(NEWARGS, 0, 0); func_tbl.existClosure = true; } //set_bc_bireg(NEWARGS, 0, REG_A, REG_A); set_bc_num(SETFL, 2, 0); //set_bc_var(SETLOCAL, 0, 0, 1, REG_A); /* printf("const $%d %s\n", 1, "null"); printf("send_entry_%d:\n", index); printf("newargs $%d $%d\n", REG_A, REG_A); printf("setfl FL\n"); printf("setlocal %d %d $%d\n", 0, 1, REG_A); */ init_reg_tbl(func_tbl.level); // fprintf(stderr, "compile_function:function_%d:func_tbl.existClosure?%d\n", // index, (int)func_tbl.existClosure); // fprintf(stderr, "compile_function:function_%d:existClosure?%d\n", // index, (int)existClosure); // fprintf(stderr, "compile_function:function_%d:useArguments?%d\n", // index, (int)useArguments); /*引数をrhoに登録*/ { JSObject * object = ATOM_TO_OBJECT(func_tbl.node->pn_funAtom); JSFunction * function = (JSFunction *) JS_GetPrivate(context, object); JSAtom ** params = malloc(function->nargs * sizeof(JSAtom *)); int i; for (i = 0; i < function->nargs; i++) { params[i] = NULL; } JSScope * scope = OBJ_SCOPE(object); JSScopeProperty * scope_property; for (scope_property = SCOPE_LAST_PROP(scope); scope_property != NULL; scope_property = scope_property->parent) { if (scope_property->getter != js_GetArgument) { continue; } params[(uint16) scope_property->shortid] = JSID_TO_ATOM(scope_property->id); } for (i = 0; i < function->nargs; i++) { char *name = atom_to_string(params[i]); if (existClosure || useArguments) { rho = env_expand(name, LOC_ARG, func_tbl.level, 1, i, rho); } else { Register r = search_unuse(); rho = env_expand(name, LOC_REGISTER, func_tbl.level, 1, r, rho); // fprintf(stderr, "compile_function:a%d:%s -> r_%d\n", i, name, r); } } free(params); } /*変数をrhoに登録*/ { //var_to_rho(func_tbl.node->pn_body, rho, ); JSParseNode *p; int i; for (p = func_tbl.node->pn_body->pn_head, i = 2; p != NULL; p = p->pn_next) { if (p->pn_type == TOK_VAR) { JSParseNode *q; for (q = p->pn_head; q != NULL; q = q->pn_next) { char *name = atom_to_string(q->pn_atom); if (existClosure || useArguments) { rho = env_expand(name, LOC_LOCAL, func_tbl.level, i++, 1, rho); } else { Register r = search_unuse(); rho = env_expand(name, LOC_REGISTER, func_tbl.level, 1, r, rho); // fprintf(stderr, "compile_function:v%d:%s -> r_%d\n", i, name, r); } } } } // i を保存 var_num[index] = i; } compile_bytecode(func_tbl.node->pn_body, rho, search_unuse(), 0, func_tbl.level); retu = search_unuse(); set_bc_cons(SPECCONST, 1, retu, UNDEFINED); set_bc_unireg(SETA, 0, retu); set_bc_unireg(RET, 0, 0); /* printf("const $%d %s\n", REG_A, "undefined"); printf("ret\n"); */ } #define ENCODESTRLEN 1024 static char encoded_string[ENCODESTRLEN]; #define ddd(x) (*d++ = '\\', *d++ = (x)) char *encode_str(char* src) { int c; char *d; d = encoded_string; while ((c = *src++) != '\0') { // printf("c = %d = 0x%x\n", c, c); switch (c) { case '\0': ddd('0'); break; case '\a': ddd('a'); break; case '\b': ddd('b'); break; case '\f': ddd('f'); break; case '\n': ddd('n'); break; case '\r': ddd('r'); break; case '\t': ddd('t'); break; case '\v': ddd('v'); break; case '\\': ddd('\\'); break; case '\'': ddd('\''); break; case '\"': ddd('\"'); break; default: if ((' ' <= c) && (c <= '~')) *d++ = c; else { *d++ = '\\'; *d++ = 'x'; *d++ = "0123456789abcdef"[(c >> 4) & 0xf]; *d++ = "0123456789abcdef"[c & 0xf]; } break; } } *d = '\0'; return encoded_string; } // 2013/08/20 Iwasaki // rewrote not to produce S-expr format void print_bytecode(Bytecode bytecode[201][MAX_BYTECODE], int num, FILE *f) { int i, j; if (output_format == OUTPUT_SEXPR) fprintf(f, "(\n"); else fprintf(f, "funcLength %d\n", num); for(i = 0; i < num; i++) { #if DEBUG4 fprintf(f, "code_num[%d] = %d\n", i, code_num[i]); #endif if (output_format == OUTPUT_SEXPR) { fprintf(f, "("); if(i == 0) fprintf(f, "0 0 %d\n(", var_num[i]); else fprintf(f, "0 1 %d\n(",var_num[i]); } else { fprintf(f, "callentry 0\n"); fprintf(f, "sendentry %d\n", i == 0? 0: 1); fprintf(f, "numberOfLocals %d\n", var_num[i]); fprintf(f, "numberOfInstruction %d\n", code_num[i]); } for (j = 0; j < code_num[i]; j++) { if (bytecode[i][j].label != 0) { fprintf(f, "%d:\n", bytecode[i][j].label); } if (output_format == OUTPUT_SEXPR) fprintf(f, "("); switch (bytecode[i][j].nemonic) { case ADD: case SUB: case MUL: case DIV: case MOD: case BITAND: case BITOR: case LEFTSHIFT: case RIGHTSHIFT: case UNSIGNEDRIGHTSHIFT: fprintf(f, "%s %d %d %d", nemonic_to_str(bytecode[i][j].nemonic), bytecode[i][j].bc_u.trireg.r1, bytecode[i][j].bc_u.trireg.r2, bytecode[i][j].bc_u.trireg.r3); break; case FIXNUM: // fprintf(f, "%s %d %lld", nemonic_to_str(bytecode[i][j].nemonic), fprintf(f, "%s %d %"PRId64, nemonic_to_str(bytecode[i][j].nemonic), bytecode[i][j].bc_u.ival.dst, bytecode[i][j].bc_u.ival.val); break; case NUMBER: fprintf(f, "%s %d %g", nemonic_to_str(bytecode[i][j].nemonic), bytecode[i][j].bc_u.dval.dst, bytecode[i][j].bc_u.dval.val); break; case STRING: case ERROR: if (output_format == OUTPUT_SEXPR) fprintf(f, "%s %d \"%s\"", nemonic_to_str(bytecode[i][j].nemonic), bytecode[i][j].bc_u.str.dst, bytecode[i][j].bc_u.str.str); else fprintf(f, "%s %d \"%s\"", nemonic_to_str(bytecode[i][j].nemonic), bytecode[i][j].bc_u.str.dst, encode_str(bytecode[i][j].bc_u.str.str)); break; case REGEXP: if (output_format == OUTPUT_SEXPR) fprintf(f, "%s %d %d \"%s\"", nemonic_to_str(bytecode[i][j].nemonic), bytecode[i][j].bc_u.regexp.dst, bytecode[i][j].bc_u.regexp.flag, bytecode[i][j].bc_u.regexp.str); else fprintf(f, "%s %d %d \"%s\"", nemonic_to_str(bytecode[i][j].nemonic), bytecode[i][j].bc_u.regexp.dst, bytecode[i][j].bc_u.regexp.flag, encode_str(bytecode[i][j].bc_u.regexp.str)); break; case CONST: case SPECCONST: fprintf(f, "%s %d %s", nemonic_to_str(bytecode[i][j].nemonic), bytecode[i][j].bc_u.cons.dst, const_to_str(bytecode[i][j].bc_u.cons.cons)); break; case JUMPTRUE: case JUMPFALSE: if (bytecode[i][j].flag == 1) { fprintf(f, "%s %d L%d", nemonic_to_str(bytecode[i][j].nemonic), bytecode[i][j].bc_u.regnum.r1, bytecode[i][j].bc_u.regnum.n1); } else { fprintf(f, "%s %d %d", nemonic_to_str(bytecode[i][j].nemonic), bytecode[i][j].bc_u.regnum.r1, bytecode[i][j].bc_u.regnum.n1); } break; case JUMP: case TRY: if (bytecode[i][j].flag == 1) { fprintf(f, "%s L%d", nemonic_to_str(bytecode[i][j].nemonic), bytecode[i][j].bc_u.num.n1); } else { fprintf(f, "%s %d", nemonic_to_str(bytecode[i][j].nemonic), bytecode[i][j].bc_u.num.n1); } break; case LESSTHAN: case LESSTHANEQUAL: case EQ: case EQUAL: case GETPROP: case SETPROP: case SETARRAY: case INSTANCEOF: case NEXTPROPNAME: fprintf(f, "%s %d %d %d", nemonic_to_str(bytecode[i][j].nemonic), bytecode[i][j].bc_u.trireg.r1, bytecode[i][j].bc_u.trireg.r2, bytecode[i][j].bc_u.trireg.r3); break; case GETARG: case GETLOCAL: fprintf(f, "%s %d %d %d", nemonic_to_str(bytecode[i][j].nemonic), bytecode[i][j].bc_u.var.r1, bytecode[i][j].bc_u.var.n1, bytecode[i][j].bc_u.var.n2); break; case SETARG: case SETLOCAL: fprintf(f, "%s %d %d %d", nemonic_to_str(bytecode[i][j].nemonic), bytecode[i][j].bc_u.var.n1, bytecode[i][j].bc_u.var.n2, bytecode[i][j].bc_u.var.r1); break; case GETGLOBAL: case SETGLOBAL: case NEW: case TYPEOF: case ISUNDEF: case ISOBJECT: case NOT: case MAKEITERATOR: fprintf(f, "%s %d %d", nemonic_to_str(bytecode[i][j].nemonic), bytecode[i][j].bc_u.bireg.r1, bytecode[i][j].bc_u.bireg.r2); break; case GETA: case SETA: case GETERR: case GETGLOBALOBJ: case THROW: fprintf(f, "%s %d", nemonic_to_str(bytecode[i][j].nemonic), bytecode[i][j].bc_u.unireg.r1); break; case MOVE: if (bytecode[i][j].flag == 2) { fprintf(f, "%s (fl %d) %d", nemonic_to_str(bytecode[i][j].nemonic), bytecode[i][j].bc_u.bireg.r1, bytecode[i][j].bc_u.bireg.r2); } else { fprintf(f, "%s %d %d", nemonic_to_str(bytecode[i][j].nemonic), bytecode[i][j].bc_u.bireg.r1, bytecode[i][j].bc_u.bireg.r2); } break; case GETIDX: //2011/05/30追記 fprintf(f, "%s %d %d", nemonic_to_str(bytecode[i][j].nemonic), bytecode[i][j].bc_u.bireg.r1, bytecode[i][j].bc_u.bireg.r2); break; case CALL: case SEND: case TAILCALL: case TAILSEND: case MAKECLOSURE: case NEWSEND: fprintf(f, "%s %d %d", nemonic_to_str(bytecode[i][j].nemonic), bytecode[i][j].bc_u.regnum.r1, bytecode[i][j].bc_u.regnum.n1); break; case RET: case NEWARGS: case FINALLY: fprintf(f, "%s", nemonic_to_str(bytecode[i][j].nemonic)); break; case SETFL: case ADDSP: case SUBSP: fprintf(f, "%s %d", nemonic_to_str(bytecode[i][j].nemonic), bytecode[i][j].bc_u.num.n1); break; case UNKNOWN: break; } if (output_format == OUTPUT_SEXPR) fprintf(f, ")"); fprintf(f, "\n"); } if (output_format == OUTPUT_SEXPR) fprintf(f, "))\n"); } if (output_format == OUTPUT_SEXPR) fprintf(f, ")\n"); } void print_tree(JSParseNode * root, int indent) { if (root == NULL) { return; } printf("%*s", indent, ""); if (root->pn_type >= NUM_TOKENS) { printf("UNKNOWN"); } else { printf("%s starts at line %d, column %d, ends at line %d, column %d, pn_arity %d", TOKENS[root->pn_type], root->pn_pos.begin.lineno, root->pn_pos.begin.index, root->pn_pos.end.lineno, root->pn_pos.end.index,root->pn_arity); } printf("\n"); printf("%*s", indent, ""); printf("JSOP:%d\n",root->pn_op); switch (root->pn_arity) { case PN_UNARY: print_tree(root->pn_kid, indent + 2); break; case PN_BINARY: print_tree(root->pn_left, indent + 2); print_tree(root->pn_right, indent + 2); break; case PN_TERNARY: print_tree(root->pn_kid1, indent + 2); print_tree(root->pn_kid2, indent + 2); print_tree(root->pn_kid3, indent + 2); break; case PN_LIST: { JSParseNode * p; for (p = root->pn_head; p != NULL; p = p->pn_next) { print_tree(p, indent + 2); } } break; case PN_FUNC: printf("%*s\n", indent, ""); JSObject * object = ATOM_TO_OBJECT(root->pn_funAtom); // printf("test\n"); fflush(stdout); JSFunction * function = (JSFunction *) JS_GetPrivate(context, object); // printf("test\n"); fflush(stdout); /* function name */ if (function->atom) { JSAtom * atom = function->atom; printf("%p",atom); if (ATOM_IS_STRING(atom)) { JSString * strings = ATOM_TO_STRING(atom); int i; printf("%*s", indent, ""); for (i = 0;i < strings->length ;i++) { char c = strings->chars[i]; printf("%c",c); } printf("\n"); } } /* function parameters */ //printf("test\n"); //fflush(stdout); JSAtom ** params = malloc(function->nargs * sizeof(JSAtom *)); int i; //printf("test\n"); //fflush(stdout); for (i = 0; i < function->nargs; i++) { params[i] = NULL; } JSScope * scope = OBJ_SCOPE(object); JSScopeProperty * scope_property; for (scope_property = SCOPE_LAST_PROP(scope); scope_property != NULL; scope_property = scope_property->parent) { if (scope_property->getter != js_GetArgument) { continue; } // printf("test2\n"); // fflush(stdout); //params[(uint16) scope_property->shortid] = JSID_TO_ATOM(scope_property->id); } for (i = 0; i < function->nargs; i++) { } free(params); // printf("sclen=%d",root->pn_flags); print_tree(root->pn_body,indent+2); break; case PN_NAME: { JSAtom * atom = root->pn_atom; JSString * strings = ATOM_TO_STRING(atom); int i; printf("%*s", indent, ""); for (i = 0; i < strings->length; i++) { char c = strings->chars[i]; printf("%c",c); } printf("\n"); } if (root->pn_expr != NULL) { print_tree(root->pn_expr,indent+2); } break; case PN_NULLARY: if (root->pn_type == TOK_STRING) { JSAtom * atom = root->pn_atom; JSString * strings = ATOM_TO_STRING(atom); int i; printf("%*s", indent, ""); for (i=0;i < strings->length ;i++) { char c = strings->chars[i]; printf("%c",c); } printf("\n"); } else if(root->pn_type == TOK_NUMBER) { printf("%*s", indent, ""); printf("%lf\n",root->pn_dval); } else if(root->pn_type == TOK_OBJECT) { printf("%*s", indent, ""); printf("TOK_OBJECT:op=%d", root->pn_op); if (root->pn_op == JSOP_REGEXP) { JSAtom * atom = root->pn_atom; JSString * strings = ATOM_TO_STRING(atom); int i; printf("%*s", indent, ""); for (i = 0;i < strings->length ;i++) { char c = strings->chars[i]; printf("%c",c); } printf("\n"); } } break; default: fprintf(stderr, "Unknown node type\n"); exit(EXIT_FAILURE); break; } } char *make_filename(char *av, int rw) // rw == 0 ==> input, rw == 1 ==> output { int n, c; static char *dp; char *p; if ( rw == 1 ) goto L; dp = NULL; p = filename; n = 0; while ((c = *av++) != '\0') { *p = c; if (c == '/') dp = NULL; else if (c == '.') dp = p; p++; if ( ++n >= FLEN ) { /* too long file name */ return NULL; } } if ( p - filename + 5 >= FLEN ) { /* too long file name */ return NULL; } if (dp == NULL) { dp = p; strcat(p, ".js"); } return filename; L: *dp = '\0'; if (output_format == OUTPUT_SEXPR) strcat(dp, ".tbc"); else strcat(dp, ".sbc"); return filename; } //int main(void) { int main(int argc, char **argv) { JSRuntime * runtime; JSObject * global; JSTokenStream * token_stream; JSParseNode * node; Environment rho; int i; Register globalDst; int ac; FILE *fp; ac = 1; if (argc >= 2 && strcmp(argv[1], "-S") == 0) { output_format = OUTPUT_SEXPR; ac = 2; } if ( ac == argc ) { fp = stdin; // No filename is specified, use stdin } else if ( ac + 1 == argc ) { // filename is specfied, use it if ( (input_filename = make_filename(argv[ac], 0)) == NULL) { fprintf(stderr, "%s: %s: filename too long\n", argv[0], argv[ac]); exit(0); } //printf("input_filename = %s\n", input_filename); if ((fp = fopen(input_filename, "r")) == NULL) { fprintf(stderr, "%s: %s: ", argv[0], input_filename); perror(""); exit(0); } if ( (output_filename = make_filename(argv[ac], 1)) == NULL ) { fprintf(stderr, "%s: %s: bad filename\n", argv[0], argv[ac]); exit(0); } //printf("output_filename = %s\n", output_filename); } else { fprintf(stderr, "Usage: %s [-S] js-filename\n", argv[0]); exit(0); } rho = env_empty(); init_reg_tbl(0); memset(bytecode, 0, sizeof(bytecode)); fl_tbl[0]=100; max_func_fl=0; runtime = JS_NewRuntime(8L * 1024L * 1024L); if (runtime == NULL) { fprintf(stderr, "cannot create runtime"); exit(EXIT_FAILURE); } context = JS_NewContext(runtime, 8192); if (context == NULL) { fprintf(stderr, "cannot create context"); exit(EXIT_FAILURE); } global = JS_NewObject(context, NULL, NULL, NULL); if (global == NULL) { fprintf(stderr, "cannot create global object"); exit(EXIT_FAILURE); } if (! JS_InitStandardClasses(context, global)) { fprintf(stderr, "cannot initialize standard classes"); exit(EXIT_FAILURE); } token_stream = js_NewFileTokenStream(context, NULL, fp); if (token_stream == NULL) { fprintf(stderr, "cannot create token stream from file\n"); exit(EXIT_FAILURE); } node = js_ParseTokenStream(context, global, token_stream); if (node == NULL) { fprintf(stderr, "parse error in file\n"); exit(EXIT_FAILURE); } if (fp != stdin) { fclose(fp); } // print_tree(node, 0); // print_bytecode(node); set_bc_unireg(GETGLOBALOBJ, 0, 1); set_bc_num(SETFL, 2, 0); globalDst = search_unuse(); compile_bytecode(node,rho,globalDst, 0, 0); set_bc_unireg(SETA, 0, globalDst); set_bc_unireg(RET, 0, 0); // printf("touch_highest = %d, fl = %d\n", highest_touch_reg(), // fl_tbl[0] = calc_fl()); fl_tbl[0] = calc_fl(); //printf("touch_highest = %d, fl = %d\n", highest_touch_reg(), fl_tbl[0]); set_bc_fl(0); code_num[0] = curr_code_num; for (i = 1; i < curr_func; i++) { compile_function(func_tbl[i], i); code_num[i] = curr_code_num; fl_tbl[curr_code] = calc_fl(); set_bc_fl(curr_code); } if (output_filename != NULL) { if ((fp = fopen(output_filename, "w")) == NULL) { fprintf(stderr, "%s: %s: ", argv[0], output_filename); perror(""); exit(0); } } else fp = stdout; print_bytecode(bytecode, curr_func, fp); if (fp != stdout) fclose(fp); JS_DestroyContext(context); JS_DestroyRuntime(runtime); return 0; } <file_sep>/tjs-c/Makefile CC = gcc INCLUDE_PATH = /usr/local/include # CFLAGS = -O2 -I${INCLUDE_PATH} -DXP_UNIX CFLAGS = -Wall -O2 -I${INCLUDE_PATH} -DXP_UNIX # LIBJS_PATH = /usr/local/lib64 LIBJS_PATH = /usr/local/lib LDFLAGS = -L${LIBJS_PATH} ${LFLAGS} -lm -ljs tjscompiler: tjscompiler.o gcc -o $@ tjscompiler.o ${LDFLAGS} clean: -rm -f tjscompiler.o *~ tjscompiler <file_sep>/tjscompiler.js const fs = require('fs'); const esprima = require('esprima'); var TOKENLIST = [ "ArrayExpression", "ArrayPattern", "ArrowFunctionExpression", "AssignmentExpression", "AssignmentPattern", "BinaryExpression", "BlockStatement", "BreakStatement", "CallExpression", "CatchClause", "ClassBody", "ClassDeclaration", "ClassExpression", "ComputedMemberExpression", "ConditionalExpression", "ContinueStatement", "DebuggerStatement", "Directive", "DoWhileStatement", "EmptyStatement", "ExportAllDeclaration", "ExportDefaultDeclaration", "ExportNamedDeclaration", "ExportSpecifier", "ExpressionStatement", "ForInStatement", "ForOfStatement", "ForStatement", "FunctionDeclaration", "FunctionExpression", "Identifier", "IfStatement", "ImportDeclaration", "ImportDefaultSpecifier", "ImportNamespaceSpecifier", "ImportSpecifier", "LabeledStatement", "Literal", "MetaProperty", "MethodDefinition", "NewExpression", "ObjectExpression", "ObjectPattern", "Program", "Property", "RegexLiteral", "RestElement", "ReturnStatement", "SequenceExpression", "SpreadElement", "StaticMemberExpression", "Super", "SwitchCase", "SwitchStatement", "TaggedTemplateExpression", "TemplateElement", "TemplateLiteral", "ThisExpression", "ThrowStatement", "TryStatement", "UnaryExpression", "UpdateExpression", "VariableDeclaration", "VariableDeclarator", "WhileStatement", "WithStatement", "YieldExpression", "MemberExpression", "LogicalExpression" ]; Tokens = { PROGRAM : "Program", ARRAYEXPRESSION : "ArrayExpression", ARRAYPATTERN : "ArrayPattern", ARROWFUNCTIONEXPRESSION : "ArrowFunctionExpression", ASSIGNMENTEXPRESSION : "AssignmentExpression", ASSIGNMENTPATTERN : "AssignmentPattern", BINARYEXPRESSION : "BinaryExpression", BLOCKSTATEMENT : "BlockStatement", BREAKSTATEMENT : "BreakStatement", CALLEXPRESSION : "CallExpression", CATCHCLAUSE : "CatchClause", CLASSBODY : "ClassBody", CLASSDECLARATION : "ClassDeclaration", CLASSEXPRESSION : "ClassExpression", COMPUTEDMEMBEREXPRESSION : "ComputedMemberExpression", CONDITIONALEXPRESSION : "ConditionalExpression", CONTINUESTATEMENT : "ContinueStatement", DEBUGGERSTATEMENT : "DebuggerStatement", DIRECTIVE : "Directive", DOWHILESTATEMENT : "DoWhileStatement", EMPTYSTATEMENT : "EmptyStatement", EXPORTALLDECLARATION : "ExportAllDeclaration", EXPORTDEFAULTDECLARATION : "ExportDefaultDeclaration", EXPORTNAMEDDECLARATION : "ExportNamedDeclaration", EXPORTSPECIFIER : "ExportSpecifier", EXPRESSIONSTATEMENT : "ExpressionStatement", FORINSTATEMENT : "ForInStatement", FOROFSTATEMENT : "ForOfStatement", FORSTATEMENT : "ForStatement", FUNCTIONDECLARATION : "FunctionDeclaration", FUNCTIONEXPRESSION : "FunctionExpression", IDENTIFIER : "Identifier", IFSTATEMENT : "IfStatement", IMPORTDECLARATION : "ImportDeclaration", IMPORTDEFAULTSPECIFIER : "ImportDefaultSpecifier", IMPORTNAMESPACESPECIFIER : "ImportNamespaceSpecifier", IMPORTSPECIFIER : "ImportSpecifier", LABELEDSTATEMENT : "LabeledStatement", LITERAL : "Literal", METAPROPERTY : "MetaProperty", METHODDEFINITION : "MethodDefinition", NEWEXPRESSION : "NewExpression", OBJECTEXPRESSION : "ObjectExpression", OBJECTPATTERN : "ObjectPattern", PROGRAM : "Program", PROPERTY : "Property", REGEXLITERAL : "RegexLiteral", RESTELEMENT : "RestElement", RETURNSTATEMENT : "ReturnStatement", SEQUENCEEXPRESSION : "SequenceExpression", SPREADELEMENT : "SpreadElement", STATICMEMBEREXPRESSION : "StaticMemberExpression", SUPER : "Super", SWITCHCASE : "SwitchCase", SWITCHSTATEMENT : "SwitchStatement", TAGGEDTEMPLATEEXPRESSION : "TaggedTemplateExpression", TEMPLATEELEMENT : "TemplateElement", TEMPLATELITERAL : "TemplateLiteral", THISEXPRESSION : "ThisExpression", THROWSTATEMENT : "ThrowStatement", TRYSTATEMENT : "TryStatement", UNARYEXPRESSION : "UnaryExpression", UPDATEEXPRESSION : "UpdateExpression", VARIABLEDECLARATION : "VariableDeclaration", VARIABLEDECLARATOR : "VariableDeclarator", WHILESTATEMENT : "WhileStatement", WITHSTATEMENT : "WithStatement", YIELDEXPRESSION : "YieldExpression", MEMBEREXPRESSION : "MemberExpression", LOGICALEXPRESSION: "LogicalExpression" } //define constants Const = { TRUE : "true", FALSE : "false", UNDEFINED : "undefined", NULL : "null" } //Nemonics Nemonic = { NUMBER : "number", FIXNUM : "fixnum", STRING : "string", GETGLOBALOBJ : "getglobalobj", SETFL : "setfl", SETGLOBAL : "setglobal", GETGLOBAL : "getglobal", SETA : "seta", GETA : "geta", RET : "ret", ADD : "add", SUB : "sub", MUL : "mul", DIV : "div", MOD : "mod", BITAND : "bitand", BITOR : "bitor", LEFTSHIFT : "leftshift", RIGHTSHIFT : "rightshift", UNSIGNEDRIGHTSHIFT : "unsignedrightshift", SPECCONST : "specconst", CONST : "const", MOVE : "move", JUMP : "jump", JUMPTRUE : "jumptrue", JUMPFALSE : "jumpfalse", LESSTHAN : "lessthan", LESSTHANEQUAL : "lessthanequal", NEWARGS : "newargs", MAKECLOSURE : "makeclosure", GETARG : "getarg", GETLOCAL : "getlocal", CALL : "call", SETLOCAL : "setlocal", SETARG : "setarg", NEW : "new", NEWSEND : "newsend", SETARRAY: "setarray", GETIDX: "getidx", GETPROP: "getprop", SEND : "send", SETPROP: "setprop", INSTANCEOF: "instanceof", NOT: "not", TYPEOF: "typeof", ISOBJECT: "isobject", ISUNDEF: "isundef", ERROR: "error", EQUAL: "equal", TAILCALL: "tailcall", GETERR: "geterr", TRY: "try", FINALLY: "finally", THROW: "throw", EQ: "eq", TAILSEND: "tailsend", REGEXP: "regexp" } //Location Location = { LOC_ARGUMENTS : "LOC_ARGUMENTS", LOC_REGISTER : "LOC_REGISTER", LOC_CATCH : "LOC_CATCH", LOC_LOCAL : "LOC_LOCAL", LOC_ARG : "LOC_ARG", LOC_GLOBAL : "LOC_GLOBAL" } //Environment function Environment(name, location, level, offset, index, next){ this.name = name; this.location = location; this.level = level; this.offset = offset; this.index = index; this.next = next; } //function table function FunctionTable(node, rho, existClosure, level, callEntry, sendEntry){ this.node = node; this.rho = rho; this.existClosure = existClosure; this.level = level; this.callEntry = callEntry; this.sendEntry = sendEntry; } //Byte code function Bytecode(nemonic, label, flag, callEntry, sendEntry, bcType){ this.nemonic = nemonic; this.label = label; this.flag = flag; this.callEntry = callEntry; this.sendEntry = sendEntry; this.bcType = bcType; } //Byte code types follow function dval(dst, val){ this.dst = dst; this.val = val; } function ival(dst, val){ this.dst = dst; this.val = val; } function str(dst, theString){ this.dst = dst; this.theString = theString; } function regnum(r1, n1){ this.r1 = r1; this.n1 = n1; } function num(n1){ this.n1 = n1; } function unireg(r1){ this.r1 = r1; } function bireg(r1, r2){ this.r1 = r1; this.r2 = r2; } function trireg(r1, r2, r3){ this.r1 = r1; this.r2 = r2; this.r3 = r3; } function num(n){ this.n1 = n; } function constType(dst, cons){ this.dst = dst; this.cons = cons; } function variable(n1, n2, r1){ this.n1 = n1; this.n2 = n2; this.r1 = r1; } function regexp(dst, str, flag){ this.dst = dst; this.str = str; this.flag = flag; } var arithNemonic = function(operator){ switch (operator) { case "+": return Nemonic.ADD; case "-": return Nemonic.SUB; case "*": return Nemonic.MUL; case "/": return Nemonic.DIV; case "%": return Nemonic.MOD; case "&": return Nemonic.BITAND; case "|": return Nemonic.BITOR; case "<<": return Nemonic.LEFTSHIFT; case ">>": return Nemonic.RIGHTSHIFT; case ">>>": return Nemonic.UNSIGNEDRIGHTSHIFT; case "<": return Nemonic.LESSTHAN; case "<=": return Nemonic.LESSTHANEQUAL; default: return "UNKNOWN"; } } const FL_MAX = 1500; const MAX_BYTECODE = 10000; const FL_TABLE_MAX = 201; const gStringArray = "Array" const gStringObject = "Object" var frameLinkTable = new Array(FL_TABLE_MAX); var maxFuncFl = 0; var currentLabel = 1; var currentTable = 0; var variableNum = new Array(FL_TABLE_MAX); var codeNum = new Array(FL_TABLE_MAX); var currentFunction = 1; var usedRegTable = new Array(FL_MAX); var touchRegTable = new Array(FL_MAX); var currentCodeNum = 0; var currentCode = 0; var bytecode = new Array(FL_TABLE_MAX); var functionTable = new Array(FL_TABLE_MAX); //main code begins var inputFileName; var outputFileName; var sourceCode; var writeStream; var initBytecode = function(){ for(var i=0; i<FL_TABLE_MAX; i++){ bytecode[i] = new Array(MAX_BYTECODE) for(var j=0; j<MAX_BYTECODE; j++){ bytecode[i][j] = null; } } } var initVariableNumCodeNum = function(){ for(var i=0; i<variableNum.length; i++){ variableNum[i] = 0; codeNum[i] = 0; } } var initRegTbl = function(currentLevel){ for(var i=0; i<FL_MAX; i++){ usedRegTable[i] = 0; touchRegTable[i] = 0; } usedRegTable[0] = 1; touchRegTable[0] = 1; usedRegTable[1] = 1; touchRegTable[1] = 1; } var searchUnusedReg = function(){ var i = 0; for(i=0; usedRegTable[i] != 0 && i < FL_MAX; i++); usedRegTable[i] = 1; touchRegTable[i] = 1; return i; } var setBytecodeUniReg = function(nemonic, flag, r1){ var u = new unireg(r1); bytecode[currentCode][currentCodeNum++] = new Bytecode(nemonic, null, flag, null, null, u); } var setBytecodeBiReg = function(nemonic, flag, r1, r2){ var bi = new bireg(r1, r2); bytecode[currentCode][currentCodeNum++] = new Bytecode(nemonic, null, flag, null, null, bi); } var setBytecodeTriReg = function(nemonic, flag, r1, r2, r3){ var tri = new trireg(r1, r2, r3); bytecode[currentCode][currentCodeNum++] = new Bytecode(nemonic, null, flag, null, null, tri); } var setBytecodeVariable = function(nemonic, flag, n1, n2, r1){ var v = new variable(n1, n2, r1); bytecode[currentCode][currentCodeNum++] = new Bytecode(nemonic, null, flag, null, null, v); } var setBytecodeString = function(nemonic, flag, dst, theString){ var s = new str(dst, theString); bytecode[currentCode][currentCodeNum++] = new Bytecode(nemonic, null, flag, null, null, s); } var setBytecodeDVal = function(nemonic, flag, dst, doubleVal){ var d = new dval(dst, doubleVal); bytecode[currentCode][currentCodeNum++] = new Bytecode(nemonic, null, flag, null, null, d); } var setBytecodeIVal = function(nemonic, flag, dst, intVal){ var i = new ival(dst, intVal); bytecode[currentCode][currentCodeNum++] = new Bytecode(nemonic, null, flag, null, null, i); } var setBytecodeCons = function(nemonic, flag, dst, consVal){ var c = new constType(dst, consVal); bytecode[currentCode][currentCodeNum++] = new Bytecode(nemonic, null, flag, null, null, c); } var setBytecodeRegnum = function(nemonic, flag, r1, n1){ var rn = new regnum(r1, n1); bytecode[currentCode][currentCodeNum++] = new Bytecode(nemonic, null, flag, null, null, rn); } var setBytecodeNum = function(nemonic, flag, n1){ var n = new num(n1); bytecode[currentCode][currentCodeNum++] = new Bytecode(nemonic, null, flag, null, null, n); } function copyFunctionTable(tbl){ var copy = new FunctionTable(tbl.node, tbl.rho, tbl.existClosure, tbl.level, tbl.callEntry, tbl.sendEntry); return copy; } var setBytecodeFl = function(){ for(var i = 0; i < currentCodeNum; i++){ if(bytecode[currentCode][i].flag === 2){ switch (bytecode[currentCode][i].nemonic) { case Nemonic.SETFL: bytecode[currentCode][i].flag = 0; bytecode[currentCode][i].bcType.n1 += frameLinkTable[currentCode]; break; case Nemonic.MOVE: bytecode[currentCode][i].flag = 0; bytecode[currentCode][i].bcType.r1 += frameLinkTable[currentCode]; break; default: throw new Error("setBytecodeFl Unexpected expression: '" + bytecode[currentCode][i].nemonic + "'\n"); } } } } var setBytecodeRegExp = function(nemonic, flag, dst, str, regFlag){ var reg = new regexp(dst, str, regFlag); bytecode[currentCode][currentCodeNum++] = new Bytecode(nemonic, null, flag, null, null, reg); } var highestRegTouched = function(){ for(var i = 0; touchRegTable[i] != 0; i++); return i-1; } var dispatchLabel = function(jumpLine, labelLine){ switch(bytecode[currentCode][jumpLine].nemonic){ case Nemonic.JUMPTRUE: case Nemonic.JUMPFALSE: bytecode[currentCode][jumpLine].flag = 0; bytecode[currentCode][jumpLine].bcType.n1 = labelLine - jumpLine; break; case Nemonic.JUMP: case Nemonic.TRY: bytecode[currentCode][jumpLine].flag = 0; bytecode[currentCode][jumpLine].bcType.n1 = labelLine - jumpLine; break; default: throw new Error("Nemonic: '" + bytecode[currentCode][jumpLine].nemonic + "' NOT IMPLEMENTED YET." + "\n"); } } function environmentExpand(name, location, level, offset, index, rho){ var e = new Environment(name, location, level, offset, index, rho); return e; } var calculateFrameLink = function(){ return highestRegTouched() + maxFuncFl + 4; } var environmentLookup = function(rho, currentLevel, name){ while(rho != null){ if(name === rho.name){ return { level : currentLevel - rho.level, offset : rho.offset, index : rho.index, location : rho.location } } rho = rho.next; } return { level : 0, offset : 0, index : 0, location : Location.LOC_GLOBAL }; } function addFunctionTable(node, rho, level){ var existClosure = level > 1; var f = new FunctionTable(node, rho, existClosure, level, null, null); functionTable[currentFunction] = f; // currentFunction++; return currentFunction++ - 1; } function searchFunctionDefinition(root){ if(root == undefined || root == null){ return false; } if(TOKENLIST.indexOf(root.type) == undefined){ return false; } switch(root.type){ case Tokens.BINARYEXPRESSION: return searchFunctionDefinition(root.left) || searchFunctionDefinition(root.right); case Tokens.EXPRESSIONSTATEMENT: return searchFunctionDefinition(root.expression); case Tokens.ASSIGNMENTEXPRESSION: return searchFunctionDefinition(root.left || root.right); case Tokens.WHILESTATEMENT: case Tokens.DOWHILESTATEMENT: return searchFunctionDefinition(root.test || root.body); case Tokens.RETURNSTATEMENT: case Tokens.UNARYEXPRESSION: return searchFunctionDefinition(root.argument); case Tokens.LOGICALEXPRESSION: return searchFunctionDefinition(root.left) || searchFunctionDefinition(root.right); case Tokens.CONDITIONALEXPRESSION: case Tokens.IFSTATEMENT: return searchFunctionDefinition(root.test || root.consequent || root.alternate); case Tokens.FORSTATEMENT: return searchFunctionDefinition(root.init || root.test || root.update || root.body); case Tokens.VARIABLEDECLARATION: var f = false; for(var i=0; i<root.declarations.length && !f; i++){ f = searchFunctionDefinition(root.declarations[i]); } return f; case Tokens.CALLEXPRESSION: return searchFunctionDefinition(root.callee); case Tokens.NEWEXPRESSION: var f = false; for(var i=0; i<root.arguments.length && !f; i++){ f = searchFunctionDefinition(root.arguments[i]); } return f; case Tokens.FUNCTIONDECLARATION: return true; case Tokens.LITERAL: return false; case Tokens.VARIABLEDECLARATOR: return searchFunctionDefinition(root.id || root.init); case Tokens.MEMBEREXPRESSION: return searchUseArguments(root.object || root.property); case Tokens.BLOCKSTATEMENT: var f = false; for(var i=0; i<root.body.length && !f; i++){ f = searchFunctionDefinition(root.body[i]); } return f; case Tokens.LITERAL: case Tokens.IDENTIFIER: case Tokens.UPDATEEXPRESSION: case Tokens.TRYSTATEMENT: return false; default: return false; } } function searchUseArguments(root){ if(root == undefined || root == null){ return false; } if(TOKENLIST.indexOf(root.type) == undefined){ return false; } switch(root.type){ case Tokens.MEMBEREXPRESSION: return searchUseArguments(root.object || root.property); case Tokens.FUNCTIONDECLARATION: return false; case Tokens.LITERAL: return false; case Tokens.BINARYEXPRESSION: return searchUseArguments(root.left) || searchUseArguments(root.right) case Tokens.EXPRESSIONSTATEMENT: return searchUseArguments(root.expression); case Tokens.ASSIGNMENTEXPRESSION: return searchUseArguments(root.left || root.right); case Tokens.WHILESTATEMENT: case Tokens.DOWHILESTATEMENT: return searchUseArguments(root.test || root.body); case Tokens.RETURNSTATEMENT: return searchUseArguments(root.argument); case Tokens.IFSTATEMENT: return searchUseArguments(root.test || root.consequent || root.alternate); case Tokens.FORSTATEMENT: return searchUseArguments(root.init || root.test || root.update || root.body); case Tokens.VARIABLEDECLARATION: var f = false; for(var i=0; i<root.declarations.length && !f; i++){ f = searchUseArguments(root.declarations[i]); } return f; case Tokens.VARIABLEDECLARATOR: return searchUseArguments(root.id || root.init); case Tokens.MEMBEREXPRESSION: return searchUseArguments(root.object || root.property); case Tokens.IDENTIFIER: return root.name === "arguments"; case Tokens.THISEXPRESSION: case Tokens.LITERAL: return false; case Tokens.BLOCKSTATEMENT: var f = false; for(var i=0; i<root.body.length && !f; i++){ f = searchUseArguments(root.body[i]); } return f; case Tokens.TRYSTATEMENT: return false; default: return false; } } var printBytecode = function(bytecode, num, writeStream){ writeStream.write("funcLength " + num + "\n"); for(var i = 0; i < num; i++){ writeStream.write("callentry 0\n"); writeStream.write("sendentry " + (i==0?0:1) + "\n"); writeStream.write("numberOfLocals " + variableNum[i] + "\n"); writeStream.write("numberOfInstruction " + codeNum[i] + "\n"); for(var j = 0; j < codeNum[i]; j++){ if(bytecode[i][j].label != null && bytecode[i][j].label != 0){ writeStream.write(bytecode[i][j].label + ":\n"); } switch (bytecode[i][j].nemonic) { case Nemonic.NUMBER: writeStream.write(bytecode[i][j].nemonic + " " + bytecode[i][j].bcType.dst + " " + bytecode[i][j].bcType.val + "\n"); break; case Nemonic.FIXNUM: writeStream.write(bytecode[i][j].nemonic + " " + bytecode[i][j].bcType.dst + " " + bytecode[i][j].bcType.val + "\n"); break; case Nemonic.ERROR: case Nemonic.STRING: writeStream.write(bytecode[i][j].nemonic + " " + bytecode[i][j].bcType.dst + ' "' + bytecode[i][j].bcType.theString + '"' + "\n"); break; //TODO: Add MOD, BITAND, BITOR, LEFTSHIFT, RIGHTSHIFT, UNSIGNEDRIGHTSHIFT case Nemonic.ADD: case Nemonic.SUB: case Nemonic.MUL: case Nemonic.DIV: case Nemonic.MOD: case Nemonic.BITAND: case Nemonic.BITOR: case Nemonic.LEFTSHIFT: case Nemonic.RIGHTSHIFT: case Nemonic.UNSIGNEDRIGHTSHIFT: writeStream.write(bytecode[i][j].nemonic + " " + bytecode[i][j].bcType.r1 + " " + bytecode[i][j].bcType.r2 + " " + bytecode[i][j].bcType.r3 + "\n"); break; case Nemonic.TYPEOF: case Nemonic.NOT: case Nemonic.ISUNDEF: case Nemonic.ISOBJECT: case Nemonic.NEW: case Nemonic.GETGLOBAL: case Nemonic.SETGLOBAL: writeStream.write(bytecode[i][j].nemonic + " " + bytecode[i][j].bcType.r1 + " " + bytecode[i][j].bcType.r2 + "\n"); break; case Nemonic.GETERR: case Nemonic.THROW: case Nemonic.GETGLOBALOBJ: case Nemonic.GETA: case Nemonic.SETA: writeStream.write(bytecode[i][j].nemonic + " " + bytecode[i][j].bcType.r1 + "\n"); break; case Nemonic.RET: writeStream.write(bytecode[i][j].nemonic + "\n"); break; case Nemonic.SETFL: writeStream.write(bytecode[i][j].nemonic + " " + bytecode[i][j].bcType.n1 + "\n"); break; case Nemonic.CONST: case Nemonic.SPECCONST: writeStream.write(bytecode[i][j].nemonic + " " + bytecode[i][j].bcType.dst + " " + bytecode[i][j].bcType.cons + "\n"); break; case Nemonic.MOVE: if(bytecode[i][j].flag == 2){ throw new Error("Nemonic: '" + bytecode[i][j].nemonic + "' with flag '2' NOT IMPLEMENTED YET." + "\n"); } else { writeStream.write(bytecode[i][j].nemonic + " " + bytecode[i][j].bcType.r1 + " " + bytecode[i][j].bcType.r2 + "\n"); } break; case Nemonic.JUMPTRUE: case Nemonic.JUMPFALSE: if(bytecode[i][j].flag == 1){ writeStream.write(bytecode[i][j].nemonic + " " + bytecode[i][j].bcType.r1 + " L" + bytecode[i][j].bcType.n1 + "\n"); } else { writeStream.write(bytecode[i][j].nemonic + " " + bytecode[i][j].bcType.r1 + " " + bytecode[i][j].bcType.n1 + "\n"); } break; case Nemonic.TRY: case Nemonic.JUMP: if(bytecode[i][j].flag == 1){ writeStream.write(bytecode[i][j].nemonic + " L" + bytecode[i][j].bcType.n1 + "\n"); } else { writeStream.write(bytecode[i][j].nemonic + " " + bytecode[i][j].bcType.n1 + "\n"); } break; case Nemonic.SETARRAY: case Nemonic.GETPROP: case Nemonic.SETPROP: case Nemonic.LESSTHAN: case Nemonic.INSTANCEOF: case Nemonic.EQ: case Nemonic.EQUAL: case Nemonic.LESSTHANEQUAL: writeStream.write(bytecode[i][j].nemonic + " " + bytecode[i][j].bcType.r1 + " " + bytecode[i][j].bcType.r2 + " " + bytecode[i][j].bcType.r3 + "\n"); break; case Nemonic.MAKECLOSURE: writeStream.write(bytecode[i][j].nemonic + " " + bytecode[i][j].bcType.r1 + " " + bytecode[i][j].bcType.n1 + "\n"); break; case Nemonic.FINALLY: case Nemonic.NEWARGS: writeStream.write(bytecode[i][j].nemonic + "\n"); break; case Nemonic.GETARG: case Nemonic.GETLOCAL: writeStream.write(bytecode[i][j].nemonic + " " + bytecode[i][j].bcType.r1 + " " + bytecode[i][j].bcType.n1 + " " + bytecode[i][j].bcType.n2 + "\n"); break; case Nemonic.REGEXP: writeStream.write(bytecode[i][j].nemonic + " " + bytecode[i][j].bcType.dst + " " + bytecode[i][j].bcType.flag + ' "' + bytecode[i][j].bcType.str + '"\n'); break; case Nemonic.SEND: case Nemonic.NEWSEND: case Nemonic.TAILCALL: case Nemonic.CALL: writeStream.write(bytecode[i][j].nemonic + " " + bytecode[i][j].bcType.r1 + " " + bytecode[i][j].bcType.n1 + "\n"); break; case Nemonic.SETARG: case Nemonic.SETLOCAL: writeStream.write(bytecode[i][j].nemonic + " " + bytecode[i][j].bcType.n1 + " " + bytecode[i][j].bcType.n2 + " " + bytecode[i][j].bcType.r1 + "\n"); break; case Nemonic.GETIDX: writeStream.write(bytecode[i][j].nemonic + " " + bytecode[i][j].bcType.r1 + " " + bytecode[i][j].bcType.r2 + "\n"); break; default: throw new Error("Nemonic: '" + bytecode[i][j].nemonic + "' NOT IMPLEMENTED YET. i=" + "\n"); } } } } var compileAssignment = function(str, rho, src, currentLevel){ var level, offset, index, location; var obj = environmentLookup(rho, currentLevel, str); level = obj.level; offset = obj.offset; index = obj.index; location = obj.location; switch (location) { case Location.LOC_REGISTER: throw new Error(Location.LOC_REGISTER + ": NOT IMPLEMENTED YET."); break; case Location.LOC_GLOBAL: //tn is a register var tn = searchUnusedReg(); setBytecodeString(Nemonic.STRING, 0, tn, str); setBytecodeBiReg(Nemonic.SETGLOBAL, 0, tn, src); break; case Location.LOC_LOCAL: setBytecodeVariable(Nemonic.SETLOCAL, 0, level, offset, src); break; case Location.LOC_ARG: setBytecodeVariable(Nemonic.SETARG, 0, level, index, src); break; default: throw new Error(location + ": NOT IMPLEMENTED YET."); } } function compileFunction(functionTable, index){ var rho = functionTable.rho; currentCode = index; currentCodeNum = 0; maxFuncFl = 0; var retu; var existClosure, useArguments; existClosure = functionTable.existClosure || searchFunctionDefinition(functionTable.node.body); useArguments = searchUseArguments(functionTable.node.body); //TODO: figure out OPT_FRAME in .c file existClosure = true; setBytecodeUniReg(Nemonic.GETGLOBALOBJ, 0, 1); if(existClosure || useArguments){ setBytecodeUniReg(Nemonic.NEWARGS, 0, 0); functionTable.existClosure = true; } setBytecodeNum(Nemonic.SETFL, 2, 0); initRegTbl(functionTable.level); //register arguments in rho for(var i=0; i<functionTable.node.params.length; i++){ var name = functionTable.node.params[i].name; if(existClosure || useArguments){ rho = environmentExpand(name, Location.LOC_ARG, functionTable.level, 1, i, rho); } else { var r = searchUnusedReg(); rho = environmentExpand(name, Location.LOC_REGISTER, functionTable.level, 1, r, rho); } } var dst = 2; for(var i=0; i<functionTable.node.body.body.length; i++){ if(functionTable.node.body.body[i].type == Tokens.VARIABLEDECLARATION){ for(var j=0; j<functionTable.node.body.body[i].declarations.length; j++){ if(functionTable.node.body.body[i].declarations[j].type == Tokens.VARIABLEDECLARATOR){ var name = functionTable.node.body.body[i].declarations[j].id.name; if(existClosure || useArguments){ rho = environmentExpand(name, Location.LOC_LOCAL, functionTable.level, dst++, 1, rho); } else { var r = searchUnusedReg(); rho = environmentExpand(name, Location.LOC_REGISTER, functionTable.level, 1, r, rho); } } } } } variableNum[index] = dst; compileBytecode(functionTable.node.body, rho, searchUnusedReg(), 0, functionTable.level); retu = searchUnusedReg(); setBytecodeCons(Nemonic.SPECCONST, 1, retu, Const.UNDEFINED); setBytecodeUniReg(Nemonic.SETA, 0, retu); setBytecodeUniReg(Nemonic.RET, 0, 0); } var compileBytecode = function(root, rho, dst, tailFlag, currentLevel){ if(root == null){ return; } if(TOKENLIST.indexOf(root.type) == undefined){ throw new Error(root.type + ": NOT IMPLEMENTED YET."); } switch (root.type) { case Tokens.PROGRAM: for(var i = 0; i < root.body.length; i++){ compileBytecode(root.body[i], rho, dst, tailFlag, currentLevel); } break; case Tokens.BINARYEXPRESSION: var t1 = searchUnusedReg(); var t2 = searchUnusedReg(); compileBytecode(root.left, rho, t1, 0, currentLevel); compileBytecode(root.right, rho, t2, 0, currentLevel); switch (root.operator) { case "<": case "<=": setBytecodeTriReg(root.operator=="<"?Nemonic.LESSTHAN:Nemonic.LESSTHANEQUAL, 0, dst, t1, t2); break; case ">": case ">=": setBytecodeTriReg(root.operator==">"?Nemonic.LESSTHAN:Nemonic.LESSTHANEQUAL, 0, dst, t2, t1); break; case "==": var ffin1, ffin2, fconvb, fsecond; var tfin1, tfin2, tconvb, tsecond; var lfin1 = currentLabel++; var lfin2 = currentLabel++; var lconvb = currentLabel++; var lsecond = currentLabel++; var ts = searchUnusedReg(); var vs = searchUnusedReg(); var to = searchUnusedReg(); var fc = searchUnusedReg(); var ca = searchUnusedReg(); var cb = searchUnusedReg(); setBytecodeTriReg(Nemonic.EQUAL, 0, dst, t1, t2); setBytecodeBiReg(Nemonic.ISUNDEF, 0, ts, dst); ffin1 = currentCodeNum; setBytecodeRegnum(Nemonic.JUMPFALSE, 1, ts, lfin1); setBytecodeString(Nemonic.STRING, 0, vs, "valueOf"); setBytecodeBiReg(Nemonic.ISOBJECT, 0, to, t1); fconvb = currentCodeNum; setBytecodeBiReg(Nemonic.JUMPFALSE, 1, to, lconvb); setBytecodeTriReg(Nemonic.GETPROP, 0, fc, t1, vs); setBytecodeTriReg(Nemonic.MOVE, 2, 0, t1); setBytecodeRegnum(Nemonic.SEND, 0, fc, 0); setBytecodeUniReg(Nemonic.GETA, 0, ca); setBytecodeBiReg(Nemonic.MOVE, 0, cb, t2); fsecond = currentCodeNum; setBytecodeNum(Nemonic.JUMP, 1, lsecond); tconvb = currentCodeNum; setBytecodeTriReg(Nemonic.GETPROP, 0, fc, t2, vs); setBytecodeBiReg(Nemonic.MOVE, 2, 0, t2); setBytecodeRegnum(Nemonic.SEND, 0, fc, 0); setBytecodeUniReg(Nemonic.GETA, 0, cb); setBytecodeBiReg(Nemonic.MOVE, 0, ca, t1); tsecond = currentCodeNum; setBytecodeTriReg(Nemonic.EQUAL, 0, dst, ca, cb); setBytecodeBiReg(Nemonic.ISUNDEF, 0, ts, dst); ffin2 = currentCodeNum; setBytecodeRegnum(Nemonic.JUMPFALSE, 1, ts, lfin2); setBytecodeString(Nemonic.ERROR, 0, dst, "EQUAL_GETTOPRIMITIVE"); tfin1 = tfin2 = currentCodeNum; dispatchLabel(ffin1, tfin1); dispatchLabel(ffin2, tfin2); dispatchLabel(fconvb, tconvb); dispatchLabel(fsecond, tsecond); break; case "===": setBytecodeTriReg(Nemonic.EQ, 0, dst, t1, t2); break; default: setBytecodeTriReg(arithNemonic(root.operator), 0, dst, t1, t2); } break; case Tokens.ASSIGNMENTEXPRESSION: if(root.left.type == Tokens.IDENTIFIER){ var name = root.left.name; var t1 = searchUnusedReg(); var t2 = searchUnusedReg(); if(root.operator == "="){ compileBytecode(root.right, rho, dst, 0, currentLevel); compileAssignment(name, rho, dst, currentLevel); } else { compileBytecode(root.left, rho, t1, 0, currentLevel); compileBytecode(root.right, rho, t2, 0, currentLevel); setBytecodeTriReg(arithNemonic(root.operator.substring(0,1)), 0, dst, t1, t2); compileAssignment(name, rho, dst, currentLevel); } } else if(root.left.type == Tokens.MEMBEREXPRESSION){ if((root.left.computed === true) && ((root.left.property.type == Tokens.IDENTIFIER) || (typeof root.left.property.value == "number"))){ var t1 = searchUnusedReg(); var t2 = searchUnusedReg(); var t3 = searchUnusedReg(); var t4 = searchUnusedReg(); var t5 = searchUnusedReg(); var fGetIdX = searchUnusedReg(); if(root.operator == "="){ compileBytecode(root.left.object, rho, t1, 0, currentLevel); compileBytecode(root.left.property, rho, t3, 0, currentLevel); compileBytecode(root.right, rho, t2, 0, currentLevel); setBytecodeBiReg(Nemonic.GETIDX, 0, fGetIdX, t3); setBytecodeBiReg(Nemonic.MOVE, 2, 0, t3); setBytecodeRegnum(Nemonic.SEND, 0, fGetIdX, 0); setBytecodeNum(Nemonic.SETFL, 2, 0); setBytecodeUniReg(Nemonic.GETA, 0, t4); setBytecodeTriReg(Nemonic.SETPROP, 0, t1, t4, t2); } else { compileBytecode(root.left.object, rho, t1, 0, currentLevel); compileBytecode(root.left.property, rho, t3, 0, currentLevel); compileBytecode(root.right, rho, t2, 0, currentLevel); setBytecodeBiReg(Nemonic.GETIDX, 0, fGetIdX, t3); setBytecodeBiReg(Nemonic.MOVE, 2, 0, t3); setBytecodeRegnum(Nemonic.SEND, 0, fGetIdX, 0); setBytecodeNum(Nemonic.SETFL, 2, 0); setBytecodeUniReg(Nemonic.GETA, 0, t4); setBytecodeTriReg(Nemonic.GETPROP, 0, t5, t1, t4); setBytecodeTriReg(arithNemonic(root.operator.substring(0,1)), 0, t5, t5, t4); setBytecodeTriReg(Nemonic.SETPROP, 0, t1, t4, t5); } } else if(root.left.property.type == Tokens.LITERAL || root.left.computed === false){ var t1 = searchUnusedReg() var t2 = searchUnusedReg() var t3 = searchUnusedReg() var t4 = searchUnusedReg() var str if(root.left.property.type === Tokens.IDENTIFIER) str = root.left.property.name else var str = root.left.property.value if(root.operator === "="){ compileBytecode(root.left.object, rho, t1, 0, currentLevel) compileBytecode(root.right, rho, dst, 0, currentLevel) setBytecodeString(Nemonic.STRING, 0, t3, str) setBytecodeTriReg(Nemonic.SETPROP, 0, t1, t3, dst) } } } break; case Tokens.VARIABLEDECLARATION: for(var i = 0; i < root.declarations.length; i++){ compileBytecode(root.declarations[i], rho, dst, tailFlag, currentLevel); } break; case Tokens.VARIABLEDECLARATOR: if(root.init != null){ var name = root.id.name; compileBytecode(root.init, rho, dst, 0, currentLevel); compileAssignment(name, rho, dst, currentLevel); } break; case Tokens.LITERAL: if(root.value == null){ setBytecodeCons(Nemonic.SPECCONST, 0, dst, Const.NULL); break; } if(root.regex !== undefined){ var str = root.regex.pattern; var flags = root.regex.flags; var regExpFlag = 0; for(var i=0; i<flags.length; i++){ switch (flags.charAt(i)) { case 'g': regExpFlag |= 1; break; case 'i': regExpFlag |= 2; break; case 'm': regExpFlag |= 4; break; } } setBytecodeRegExp(Nemonic.REGEXP, 0, dst, str, regExpFlag); break; } switch (typeof root.value) { case "number": var val = root.value; if(Number.isSafeInteger(val)){ setBytecodeIVal(Nemonic.FIXNUM, 0, dst, val); } else{ setBytecodeDVal(Nemonic.NUMBER, 0, dst, val); } break; case "boolean": if(root.value){ setBytecodeCons(Nemonic.SPECCONST, 0, dst, Const.TRUE); } else { setBytecodeCons(Nemonic.SPECCONST, 0, dst, Const.FALSE); } break; case "string": var str = root.value; setBytecodeString(Nemonic.STRING, 0, dst, str); break; default: throw new Error("'" + typeof root.value + "' NOT IMPLEMENTED YET."); } break; case Tokens.THISEXPRESSION: setBytecodeBiReg(Nemonic.MOVE, 0, dst, 1); break; case Tokens.IDENTIFIER: var name = root.name; var tn = searchUnusedReg(); var level, offset, index, location; var obj = environmentLookup(rho, currentLevel, name); level = obj.level; offset = obj.offset; index = obj.index; location = obj.location; switch (location) { case Location.LOC_REGISTER: setBytecodeBiReg(Nemonic.MOVE, 0, dst, index); break; case Location.LOC_LOCAL: setBytecodeVariable(Nemonic.GETLOCAL, 0, level, offset, dst); break; case Location.LOC_ARG: setBytecodeVariable(Nemonic.GETARG, 0, level, index, dst); break; case Location.LOC_GLOBAL: setBytecodeString(Nemonic.STRING, 0, tn, name); setBytecodeBiReg(Nemonic.GETGLOBAL, 0, dst, tn); break; default: throw new Error("Unexpected case in case 'Identifier'"); } break; case Tokens.EXPRESSIONSTATEMENT: compileBytecode(root.expression, rho, dst, 0, currentLevel); break; case Tokens.SEQUENCEEXPRESSION: for(var i=0; i<root.expressions.length; i++){ compileBytecode(root.expressions[i], rho, dst, 0, currentLevel); } break; case Tokens.CONDITIONALEXPRESSION: var t = searchUnusedReg(); var label1 = currentLabel++; var label2 = currentLabel++; var j1, j2, l1, l2; compileBytecode(root.test, rho, t, 0, currentLevel); j1 = currentCodeNum; setBytecodeRegnum(Nemonic.JUMPFALSE, 1, t, label1); compileBytecode(root.consequent, rho, dst, tailFlag, currentLevel); j2 = currentCodeNum; setBytecodeNum(Nemonic.JUMP, 1, label2); l1 = currentCodeNum; compileBytecode(root.alternate, rho, dst, tailFlag, currentLevel); l2 = currentCodeNum; dispatchLabel(j1, l1); dispatchLabel(j2, l2); break; case Tokens.IFSTATEMENT: var elseExists = true; if(root.alternate === null) elseExists = false; var t = searchUnusedReg(); var l1 = currentLabel++; var l2 = currentLabel++; var j1, j2; compileBytecode(root.test, rho, t, 0, currentLevel); j1 = currentCodeNum; setBytecodeRegnum(Nemonic.JUMPFALSE, 1, t, l1); compileBytecode(root.consequent, rho, dst, 0, currentLevel); if(elseExists){ j2 = currentCodeNum; setBytecodeNum(Nemonic.JUMP, 1, l2); } l1 = currentCodeNum; if(elseExists){ compileBytecode(root.alternate, rho, dst, 0, currentLevel); l2 = currentCodeNum; } dispatchLabel(j1, l1); if(elseExists){ dispatchLabel(j2, l2); } break; case Tokens.BLOCKSTATEMENT: for(var i=0; i<root.body.length; i++){ compileBytecode(root.body[i], rho, dst, tailFlag, currentLevel); } break; case Tokens.WHILESTATEMENT: var t = searchUnusedReg(); var l1 = currentLabel++; var l2 = currentLabel++; var j1, j2; j1 = currentCodeNum; setBytecodeNum(Nemonic.JUMP, 1, l1); l2 = currentCodeNum; compileBytecode(root.body, rho, dst, 0, currentLevel); l1 = currentCodeNum; compileBytecode(root.test, rho, t, 0, currentLevel); j2 = currentCodeNum; setBytecodeRegnum(Nemonic.JUMPTRUE, 1, t, l2); dispatchLabel(j1, l1); dispatchLabel(j2, l2); break; case Tokens.DOWHILESTATEMENT: var t = searchUnusedReg(); var l1 = currentLabel++; var j1; l1 = currentCodeNum; compileBytecode(root.body, rho, dst, 0, currentLevel); compileBytecode(root.test, rho, t, 0, currentLevel); j1 = currentCodeNum; setBytecodeRegnum(Nemonic.JUMPTRUE, 1, t, l1); dispatchLabel(j1, l1); break; case Tokens.FORSTATEMENT: //TODO: add closure part var t = searchUnusedReg(); var l1 = currentLabel++; var l2 = currentLabel++; var j1, j2; compileBytecode(root.init, rho, t, 0, currentLevel); j1 = currentCodeNum; setBytecodeNum(Nemonic.JUMP, 1, l1); l2 = currentCodeNum; compileBytecode(root.body, rho, dst, 0, currentLevel); compileBytecode(root.update, rho, t, 0, currentLevel); l1 = currentCodeNum; compileBytecode(root.test, rho, t, 0, currentLevel); j2 = currentCodeNum; setBytecodeRegnum(Nemonic.JUMPTRUE, 1, t, l2); dispatchLabel(j1, l1); dispatchLabel(j2, l2); break; case Tokens.FUNCTIONEXPRESSION: case Tokens.FUNCTIONDECLARATION: var n = addFunctionTable(root, rho, currentLevel+1); setBytecodeRegnum(Nemonic.MAKECLOSURE, 0, dst, n); break; case Tokens.RETURNSTATEMENT: var t = searchUnusedReg(); compileBytecode(root.argument, rho, t, 1, currentLevel); setBytecodeUniReg(Nemonic.SETA, 0, t); setBytecodeUniReg(Nemonic.RET, 0, -1); break; case Tokens.CALLEXPRESSION: if(root.callee.type === Tokens.MEMBEREXPRESSION){ var tm = searchUnusedReg(); var ts = searchUnusedReg(); var tmp = []; var mName = root.callee.property.name; for(var i=0; i <= root.arguments.length; i++){ tmp[i] = searchUnusedReg(); } compileBytecode(root.callee.object, rho, tmp[0], 0, currentLevel); setBytecodeString(Nemonic.STRING, 0, ts, mName); setBytecodeTriReg(Nemonic.GETPROP, 0, tm, tmp[0], ts); for(i=0; i<root.arguments.length; i++){ compileBytecode(root.arguments[i], rho, tmp[i+1], 0, currentLevel); } if(tailFlag){ setBytecodeBiReg(Nemonic.MOVE, 0, 1, tmp[0]); for(i=0; i<root.arguments.length; i++){ setBytecodeBiReg(Nemonic.MOVE, 0, i+2, tmp[i+1]); } setBytecodeRegnum(Nemonic.TAILSEND, 0, tm, root.arguments.length); } else { setBytecodeBiReg(Nemonic.MOVE, 2, -root.arguments.length, tmp[0]); for(i=0; i<root.arguments.length; i++){ setBytecodeBiReg(Nemonic.MOVE, 2, -root.arguments.length+1+i, tmp[i+1]); } setBytecodeRegnum(Nemonic.SEND, 0, tm, root.arguments.length); setBytecodeNum(Nemonic.SETFL, 2, 0); setBytecodeUniReg(Nemonic.GETA, 0, dst); if(root.arguments.length+1 > maxFuncFl){ maxFuncFl = root.arguments.length+1; } } } else { var t = new Array(root.arguments.length + 1); for(var i=0; i<t.length; i++){ t[i] = searchUnusedReg(); } compileBytecode(root.callee, rho, t[0], 0, currentLevel); for(var i=1; i<t.length; i++){ compileBytecode(root.arguments[i-1], rho, t[i], 0, currentLevel); } if(tailFlag){ for(var i=0; i<root.arguments.length; i++){ setBytecodeBiReg(Nemonic.MOVE, 0, i+2, t[i+1]); } setBytecodeRegnum(Nemonic.TAILCALL, 0, t[0], root.arguments.length); } else { for(var i=1; i<t.length; i++){ setBytecodeBiReg(Nemonic.MOVE, 2, i - root.arguments.length, t[i]); } setBytecodeRegnum(Nemonic.CALL, 0, t[0], root.arguments.length); setBytecodeNum(Nemonic.SETFL, 2, 0); setBytecodeUniReg(Nemonic.GETA, 0, dst); if(root.arguments.length+1 > maxFuncFl){ maxFuncFl = root.arguments.length+1; } } } break; case Tokens.UNARYEXPRESSION: switch(root.operator){ case "!": var t1 = searchUnusedReg(); compileBytecode(root.argument, rho, t1, 0, currentLevel); setBytecodeBiReg(Nemonic.NOT, 0, dst, t1); break; case "-": var t1 = searchUnusedReg(); var tone = searchUnusedReg(); var mone = -1; compileBytecode(root.argument, rho, t1, 0, currentLevel); setBytecodeIVal(Nemonic.FIXNUM, 0, tone, mone); setBytecodeTriReg(Nemonic.MUL, 0, dst, t1, tone); break; case "typeof": compileBytecode(root.argument, rho, dst, 0, currentLevel); setBytecodeBiReg(Nemonic.TYPEOF, 0, dst, dst); break; case "void": compileBytecode(root.argument, rho, dst, 0, currentLevel); setBytecodeCons(Nemonic.SPECCONST, 0, dst, Const.UNDEFINED); break; default: compileBytecode(root.argument, rho, dst, 0, currentLevel); break; } break; case Tokens.LOGICALEXPRESSION: switch (root.operator) { case "&&": var l1, j1; var label = currentLabel++; compileBytecode(root.left, rho, dst, 0, currentLevel); j1 = currentCodeNum; setBytecodeRegnum(Nemonic.JUMPFALSE, 1, dst, label); compileBytecode(root.right, rho, dst, tailFlag, currentLevel); l1 = currentCodeNum; dispatchLabel(j1, l1); break; case "||": var l1, j1; var label = currentLabel++; compileBytecode(root.left, rho, dst, 0, currentLevel); j1 = currentCodeNum; setBytecodeRegnum(Nemonic.JUMPTRUE, 1, dst, label); compileBytecode(root.right, rho, dst, tailFlag, currentLevel); l1 = currentCodeNum; dispatchLabel(j1, l1); break; default: } break; case Tokens.ARRAYEXPRESSION: var objConsStr = searchUnusedReg(); var objCons = searchUnusedReg(); var propdst = searchUnusedReg(); var dlen = searchUnusedReg(); var count = root.elements.length; setBytecodeIVal(Nemonic.FIXNUM, 0, dlen, count); setBytecodeString(Nemonic.STRING, 0, objConsStr, gStringArray); setBytecodeBiReg(Nemonic.GETGLOBAL, 0, objCons, objConsStr); setBytecodeBiReg(Nemonic.NEW, 0, dst, objCons); setBytecodeBiReg(Nemonic.MOVE, 2, 0, dlen); setBytecodeBiReg(Nemonic.MOVE, 2, -1, dst); setBytecodeRegnum(Nemonic.NEWSEND, 0, objCons, 1); setBytecodeNum(Nemonic.SETFL, 2, 0); setBytecodeUniReg(Nemonic.GETA, 0, dst); for(var i=0; i<root.elements.length; i++){ compileBytecode(root.elements[i], rho, propdst, 0, currentLevel); setBytecodeTriReg(Nemonic.SETARRAY, 0, dst, i, propdst); } if(1 > maxFuncFl){ maxFuncFl = 1; } break; case Tokens.MEMBEREXPRESSION: if((root.computed === true) && typeof root.property.value !== "string"){ var r1 = searchUnusedReg(); var r2 = searchUnusedReg(); var fGetIdX = searchUnusedReg(); var r3 = searchUnusedReg(); compileBytecode(root.object, rho, r1, 0, currentLevel); compileBytecode(root.property, rho, r2, 0, currentLevel); setBytecodeBiReg(Nemonic.GETIDX, 0, fGetIdX, r2); setBytecodeBiReg(Nemonic.MOVE, 2, 0, r2); setBytecodeRegnum(Nemonic.SEND, 0, fGetIdX, 0); setBytecodeNum(Nemonic.SETFL, 2, 0); setBytecodeUniReg(Nemonic.GETA, 0, r3); setBytecodeTriReg(Nemonic.GETPROP, 0, dst, r1, r3); if(maxFuncFl === 0) maxFuncFl = 1; } else { var t1 = searchUnusedReg(); var t2 = searchUnusedReg(); var str; if(root.property.type === Tokens.IDENTIFIER) str = root.property.name; else str = root.property.value; compileBytecode(root.object, rho, t1, 0, currentLevel); setBytecodeString(Nemonic.STRING, 0, t2, str); setBytecodeTriReg(Nemonic.GETPROP, 0, dst, t1, t2); } break; case Tokens.OBJECTEXPRESSION: var objConsStr = searchUnusedReg(); var objCons = searchUnusedReg(); var propDst = searchUnusedReg(); var pstr = searchUnusedReg(); var fGetIdX = searchUnusedReg(); setBytecodeString(Nemonic.STRING, 0, objConsStr, gStringObject); setBytecodeBiReg(Nemonic.GETGLOBAL, 0, objCons, objConsStr); setBytecodeBiReg(Nemonic.NEW, 0, dst, objCons); setBytecodeBiReg(Nemonic.MOVE, 2, 0, dst); setBytecodeRegnum(Nemonic.NEWSEND, 0, objCons, 0); setBytecodeNum(Nemonic.SETFL, 2, 0); setBytecodeUniReg(Nemonic.GETA, 0, dst); for(var i=0; i<root.properties.length; i++){ if(typeof root.properties[i].key.value === "number"){ compileBytecode(root.properties[i].value, rho, propDst, 0, currentLevel); var val = root.properties[i].key.value; if(Number.isSafeInteger(val)){ setBytecodeIVal(Nemonic.FIXNUM, 0, pstr, val); } else{ setBytecodeDVal(Nemonic.NUMBER, 0, pstr, val); } setBytecodeBiReg(Nemonic.GETIDX, 0, fGetIdX, pstr); setBytecodeBiReg(Nemonic.MOVE, 2, 0, pstr); setBytecodeRegnum(Nemonic.SEND, 0, fGetIdX, 0); setBytecodeNum(Nemonic.SETFL, 2, 0); setBytecodeUniReg(Nemonic.GETA, 0, pstr); setBytecodeTriReg(Nemonic.SETPROP, 0, dst, pstr, propDst); } else { var name //TOK_NAME if(root.properties[i].key.type === Tokens.IDENTIFIER) name = root.properties[i].key.name //TOK_STRING else name = root.properties[i].key.value; compileBytecode(root.properties[i].value, rho, propDst, 0, currentLevel); setBytecodeString(Nemonic.STRING, 0, pstr, name); setBytecodeTriReg(Nemonic.SETPROP, 0, dst, pstr, propDst); } } if(root.properties.length > maxFuncFl){ maxFuncFl = root.properties.length; } break; case Tokens.NEWEXPRESSION: var tmp = [] var ts = searchUnusedReg() var tg = searchUnusedReg() var tins = searchUnusedReg() var retr = searchUnusedReg() var l1 = currentLabel++ var j1 for(var i=0; i<=root.arguments.length; i++){ tmp[i] = searchUnusedReg() } compileBytecode(root.callee, rho, tmp[0], 0, currentLevel) for(i=1; i<=root.arguments.length; i++){ compileBytecode(root.arguments[i-1], rho, tmp[i], 0, currentLevel) } for(i=0; i<root.arguments.length; i++){ setBytecodeBiReg(Nemonic.MOVE, 2, -root.arguments.length + i + 1, tmp[i+1]) } setBytecodeBiReg(Nemonic.NEW, 0, dst, tmp[0]) setBytecodeBiReg(Nemonic.MOVE, 2, -root.arguments.length, dst) setBytecodeRegnum(Nemonic.NEWSEND, 0, tmp[0], root.arguments.length) setBytecodeNum(Nemonic.SETFL, 2, 0) setBytecodeString(Nemonic.STRING, 0, ts, "Object") setBytecodeBiReg(Nemonic.GETGLOBAL, 0, tg, ts) setBytecodeUniReg(Nemonic.GETA, 0, retr) setBytecodeTriReg(Nemonic.INSTANCEOF, 0, tins, retr, tg) j1 = currentCodeNum setBytecodeRegnum(Nemonic.JUMPFALSE, 1, tins, l1) setBytecodeUniReg(Nemonic.GETA, 0, dst) l1 = currentCodeNum if(root.arguments.length+1 > maxFuncFl){ maxFuncFl = root.arguments.length + 1 } dispatchLabel(j1, l1) break; case Tokens.TRYSTATEMENT: var j1, j2; var l1 = currentLabel++; var l2 = currentLabel++; var level, offset, index; var str; var rho2; var err = searchUnusedReg(); var loc; j1 = currentCodeNum; setBytecodeNum(Nemonic.TRY, 1, l1); compileBytecode(root.block, rho, dst, 0, currentLevel); setBytecodeUniReg(Nemonic.FINALLY, 0, 0); j2 = currentCodeNum; setBytecodeNum(Nemonic.JUMP, 1, l2); str = root.handler.param.name; loc = currentCode == 0 ? Location.LOC_LOCAL : functionTable[currentCode].existClosure ? Location.LOC_LOCAL : Location.LOC_REGISTER; l1 = currentCodeNum; setBytecodeNum(Nemonic.SETFL, 2, 0); setBytecodeUniReg(Nemonic.GETERR, 0, err); if(loc === Location.LOC_LOCAL){ rho2 = environmentExpand(str, loc, currentLevel, ++variableNum[currentCode], 1, rho); var obj = environmentLookup(rho2, currentLevel, str); level = obj.level; offset = obj.offset; index = obj.index; setBytecodeVariable(Nemonic.SETLOCAL, 0, level, offset, err); } else { rho2 = environmentExpand(str, loc, currentLevel, 1, err, rho); } compileBytecode(root.handler.body, rho2, dst, 0, currentLevel); l2 = currentCodeNum; compileBytecode(root.finalizer, rho, dst, 0, currentLevel); dispatchLabel(j1, l1); dispatchLabel(j2, l2); break; case Tokens.THROWSTATEMENT: var th = searchUnusedReg(); compileBytecode(root.argument, rho, th, 0, currentLevel); setBytecodeUniReg(Nemonic.THROW, 0, th); break; case Tokens.UPDATEEXPRESSION: if(root.argument.type === Tokens.IDENTIFIER){ if(root.prefix){ var t1 = searchUnusedReg(); var tone = searchUnusedReg(); var str = root.argument.name; var one = 1; compileBytecode(root.argument, rho, t1, 0, currentLevel); setBytecodeIVal(Nemonic.FIXNUM, 0, tone, one) setBytecodeTriReg(arithNemonic(root.operator.substring(0,1)), 0, dst, t1, tone); compileAssignment(str, rho, dst, currentLevel); } else { var t1 = searchUnusedReg(); var tone = searchUnusedReg(); var str = root.argument.name; var one = 1; compileBytecode(root.argument, rho, dst, 0, currentLevel); setBytecodeIVal(Nemonic.FIXNUM, 0, tone, one); setBytecodeTriReg(arithNemonic(root.operator.substring(0,1)), 0, t1, dst, tone); compileAssignment(str, rho, t1, currentLevel); } } else if(root.argument.type === Tokens.MEMBEREXPRESSION){ if(root.prefix){ var t1 = searchUnusedReg(); var t2 = searchUnusedReg(); var tone = searchUnusedReg(); var tn = searchUnusedReg(); var str = root.argument.property.name; var one = 1; compileBytecode(root.argument.object, rho, t2, 0, currentLevel); setBytecodeString(Nemonic.STRING, 0, tn, str); setBytecodeTriReg(Nemonic.GETPROP, 0, t1, t2, tn); setBytecodeIVal(Nemonic.FIXNUM, 0, tone, one); setBytecodeTriReg(arithNemonic(root.operator.substring(0,1)), 0, dst, t1, tone); setBytecodeTriReg(Nemonic.SETPROP, 0, t2, tn, dst); } else { var t1 = searchUnusedReg(); var t2 = searchUnusedReg(); var tone = searchUnusedReg(); var tn = searchUnusedReg(); var str = root.argument.property.name; var one = 1; compileBytecode(root.argument.object, rho, t2, 0, currentLevel); setBytecodeString(Nemonic.STRING, 0, tn, str); setBytecodeTriReg(Nemonic.GETPROP, 0, dst, t2, tn); setBytecodeIVal(Nemonic.FIXNUM, 0, tone, one); setBytecodeTriReg(arithNemonic(root.operator.substring(0,1)), 0, t1, dst, tone); setBytecodeTriReg(Nemonic.SETPROP, 0, t2, tn, t1); } } break; default: throw new Error(root.type + ": NOT IMPLEMENTED YET."); } } //compile the source code var processSourceCode = function(){ var rho = new Environment(); var globalDst; initRegTbl(0); initBytecode(); initVariableNumCodeNum(); setBytecodeUniReg(Nemonic.GETGLOBALOBJ, 0, 1); setBytecodeNum(Nemonic.SETFL, 2, 0); globalDst = searchUnusedReg(); var ast = esprima.parse(sourceCode); compileBytecode(ast, rho, globalDst, 0, 0); setBytecodeUniReg(Nemonic.SETA, 0, globalDst); setBytecodeUniReg(Nemonic.RET, 0, 0); frameLinkTable[0] = calculateFrameLink(); setBytecodeFl(); codeNum[0] = currentCodeNum; for(var i=1; i<currentFunction; i++){ var tmp = copyFunctionTable(functionTable[i]); compileFunction(tmp, i); codeNum[i] = currentCodeNum; frameLinkTable[currentCode] = calculateFrameLink(); setBytecodeFl(currentCode); } printBytecode(bytecode, currentFunction, writeStream); writeStream.end(); } if(process.argv.length > 2){ //input file specified inputFileName = process.argv[2]; sourceCode = fs.readFileSync(inputFileName); outputFileName = inputFileName.substring(0, inputFileName.lastIndexOf('.')) + ".sbc"; writeStream = fs.createWriteStream(outputFileName); processSourceCode(); } else { //no input file specified, use stdin & stdout writeStream = fs.createWriteStream(outputFileName, {fd: 1}); //called on input from stdin process.stdin.on('readable',function() { var vText = process.stdin.read(); if (sourceCode == null && vText != null) sourceCode = vText; else if (vText != null) sourceCode = sourceCode + vText; }); //when input from stdin finishes process.stdin.on('end',function() { processSourceCode(); }); } <file_sep>/tokgen.js var TOKENS = [ "ArrayExpression", "ArrayPattern", "ArrowFunctionExpression", "AssignmentExpression", "AssignmentPattern", "BinaryExpression", "BlockStatement", "BreakStatement", "CallExpression", "CatchClause", "ClassBody", "ClassDeclaration", "ClassExpression", "ComputedMemberExpression", "ConditionalExpression", "ContinueStatement", "DebuggerStatement", "Directive", "DoWhileStatement", "EmptyStatement", "ExportAllDeclaration", "ExportDefaultDeclaration", "ExportNamedDeclaration", "ExportSpecifier", "ExpressionStatement", "ForInStatement", "ForOfStatement", "ForStatement", "FunctionDeclaration", "FunctionExpression", "Identifier", "IfStatement", "ImportDeclaration", "ImportDefaultSpecifier", "ImportNamespaceSpecifier", "ImportSpecifier", "LabeledStatement", "Literal", "MetaProperty", "MethodDefinition", "NewExpression", "ObjectExpression", "ObjectPattern", "Program", "Property", "RegexLiteral", "RestElement", "ReturnStatement", "SequenceExpression", "SpreadElement", "StaticMemberExpression", "Super", "SwitchCase", "SwitchStatement", "TaggedTemplateExpression", "TemplateElement", "TemplateLiteral", "ThisExpression", "ThrowStatement", "TryStatement", "UnaryExpression", "UpdateExpression", "VariableDeclaration", "VariableDeclarator", "WhileStatement", "WithStatement", "YieldExpression" ]; var str = ""; for(var i=0; i<TOKENS.length; i++){ var s = TOKENS[i].toUpperCase() + ' : "' + TOKENS[i] + '",\n'; str = str + s; } console.log(str); <file_sep>/demo4.js var fact, result; fact = function(n,r) { if (n < 2){ return r; }else return fact(n-1, r*n); }; result = fact(100, 1);
38265c9689e9eaeeb07a309a2fb7cbb207a18665
[ "JavaScript", "C", "Makefile", "Shell" ]
7
JavaScript
amogh-git09/TinyJSCompiler
5ed33ae0b00d95dcdb0e67605399ab75c51a8ea6
93c7de26bf16ebe47e9761736397712087914f17
refs/heads/master
<repo_name>LauraRussels/MP-Core<file_sep>/src/com/mpcore/main/util/enforcer_util/Alternate_Account.java package com.mpcore.main.util.enforcer_util; import com.mpcore.main.MPCore; import org.bukkit.entity.Player; public class Alternate_Account { private MPCore core; public Alternate_Account(MPCore core) { this.core = core; } public boolean isAlt(Player player) { for(String users : core.getAccountEnforcer().getConfig().getConfigurationSection("ALT-ACCOUNT.").getKeys(true)) { for(String IP : core.getAccountEnforcer().getConfig().getConfigurationSection("ALT-ACCOUNT." + users + ".IP").getKeys(true)) { if(IP.equals(player.getAddress().getHostString()) && !users.equals(player.getUniqueId().toString())) return true; return false; } } return false; } } <file_sep>/src/com/mpcore/main/commands/group_commands/Group_Prefix.java package com.mpcore.main.commands.group_commands; import com.mpcore.main.MPCore; import com.mpcore.main.commands.CommandCentre; import com.mpcore.main.util.M; import org.bukkit.Bukkit; import org.bukkit.command.Command; import org.bukkit.command.CommandSender; import org.bukkit.entity.Player; import ru.tehkode.permissions.PermissionGroup; import ru.tehkode.permissions.bukkit.PermissionsEx; import java.util.Collection; public class Group_Prefix extends CommandCentre { public Group_Prefix(MPCore core) { super(core); } @Override public String getName() { return "group-prefix"; } @Override public boolean onCommand(CommandSender commandSender, Command command, String s, String[] args) { if(isPlayer(commandSender)) { Player sender = (Player) commandSender; if(hasPermission(sender, "meraki.public-group.prefix")) { if(args.length <= 1) { M.m(sender, M.G.WARNING, "Group", "Too few arguments.\n§7(Usage): /group-prefix <group> <prefix>"); } else { Collection groups = PermissionsEx.getPermissionManager().getGroupNames(); if(groups.contains(args[0])) { String prefix = ""; for(int i = 1; i < args.length; i++) { String newprefix = args[i] + " "; prefix = prefix + newprefix; } PermissionsEx.getPermissionManager().getGroup(args[0]).setPrefix(prefix, null); M.log(sender, M.G.LOG, "Group", "Successfully updated " + args[0] + "'s prefix. (Changes should take effect immediately)."); for(Player online : Bukkit.getOnlinePlayers()) { if(online.hasPermission("meraki.public.notify")) { M.log(online, M.G.LOG, "Group", sender.getName() + " updated group prefix of " + args[0].toUpperCase() + " to " + prefix); } } } else { M.m(sender, M.G.WARNING, "Group", "Could not find group '" + args[0] + "' in our database."); } } } } return true; } }<file_sep>/src/com/mpcore/main/commands/util_commands/TP_Player.java package com.mpcore.main.commands.util_commands; import com.mpcore.main.MPCore; import com.mpcore.main.commands.CommandCentre; import com.mpcore.main.util.M; import com.mpcore.main.util.events_util.Teleport_Util; import org.bukkit.Bukkit; import org.bukkit.command.Command; import org.bukkit.command.CommandSender; import org.bukkit.entity.Player; import org.bukkit.event.player.PlayerTeleportEvent; public class TP_Player extends CommandCentre { public TP_Player(MPCore core) { super(core); } @Override public String getName() { return "tp"; } private Teleport_Util teleportUtil; @Override public boolean onCommand(CommandSender commandSender, Command command, String s, String[] args) { if(isPlayer(commandSender)) { Player sender = (Player) commandSender; if(hasPermission(sender, "meraki.public.teleport-player")) { if(args.length > 0) { Player target = Bukkit.getPlayer(args[0]); if(target == null) { M.m(sender, M.G.WARNING, "Teleport", "Player '" + args[0] + "' is offline.\n§7(Tip): Use /list to view who is online."); } else { double X = sender.getLocation().getX(); double Y = sender.getLocation().getY(); double Z = sender.getLocation().getZ(); core.getLocations().getConfig().set("USER-LOCATIONS." + sender.getUniqueId() + ".X", X); core.getLocations().getConfig().set("USER-LOCATIONS." + sender.getUniqueId() + ".Y", Y); core.getLocations().getConfig().set("USER-LOCATIONS." + sender.getUniqueId() + ".Z", Z); core.getLocations().getConfig().set("USER-LOCATIONS." + sender.getUniqueId() + ".world", sender.getWorld().getName()); core.getLocations().saveConfig(); Bukkit.getScheduler().scheduleSyncDelayedTask(core, new Runnable() { @Override public void run() { sender.teleport(target.getLocation(), PlayerTeleportEvent.TeleportCause.COMMAND); M.m(sender, M.G.PRIMARY, "Teleport", "Teleporting to '" + args[0] + "'."); } }, 10); } } else { M.m(sender, M.G.WARNING, "Teleport", "Too few arguments.\n§7(Usage): /teleport <player>"); } } } return true; } } <file_sep>/src/com/mpcore/main/commands/CommandsHandler.java package com.mpcore.main.commands; import com.mpcore.main.MPCore; import com.mpcore.main.commands.group_commands.Group_Prefix; import com.mpcore.main.commands.user_commands.*; import com.mpcore.main.commands.util_commands.*; import com.mpcore.main.console_commands.Console_Commands; import java.util.ArrayList; import java.util.List; public class CommandsHandler { private MPCore core; private static List<CommandCentre> commands; public CommandsHandler(MPCore core) { this.core = core; commands = new ArrayList<CommandCentre>(); register(new TP_Player(core)); register(new TP_Pos(core)); register(new Gamemode_Player(core)); register(new Gamemode_Other(core)); register(new Back_Player(core)); register(new User_Information(core)); register(new User_Rank(core)); register(new Group_Prefix(core)); register(new com.mpcore.main.commands.util_commands.List(core)); register(new Console_Commands(core)); } public void register(CommandCentre cmd){ if(!commands.isEmpty()){ boolean co = true; for (CommandCentre command : commands) { if (command.getName().equalsIgnoreCase(cmd.getName())){ co = false; break; } } if(!co) return; } commands.add(cmd); System.out.println("[INFO] Registered command " + cmd.getName()); core.getCommand(cmd.getName()).setExecutor(cmd); } public void disableCommand(String cmd){ for (CommandCentre command : commands) { if(command.isEnabled() && command.getName().equalsIgnoreCase(cmd)) { command.setEnabled(false); } } } }
b8fdd4351c7808e27bffa737012ad62a74fd7c6c
[ "Java" ]
4
Java
LauraRussels/MP-Core
0f9d7242c76a5e27bbc1de735e6793605a0c682f
c6ca9d01f85f49ce2b55e51eda4023802d67e7ef
refs/heads/master
<repo_name>pcwitz/hannalandscaping<file_sep>/expertise.html <!DOCTYPE html> <html lang=en> <head> <title>Cincinnati Landscape Designer | Hanna Landscaping and Design | Expertise</title> <meta charset=utf-8> <meta name="viewport" content="width=device-width, user-scalable=no"> <meta name="description" content="Hanna Landscaping and Design serves Cincinnati and its suburbs in complete yard and lawn landscape installation, maintenance, and replacement." /> <meta property="og:locale" content="en_US" /> <meta property="og:type" content="website" /> <meta property="og:title" content="Cincinnati Landscape Designer | Hanna Landscaping and Design | Expertise" /> <meta property="og:description" content="Hanna Landscaping and Design serves Cincinnati and its suburbs in complete yard and lawn landscape installation, maintenance, and replacement." /> <meta property="og:url" content="http://hannalandscaping.com/" /> <meta property="og:site_name" content="Hanna Landscaping and Design" /> <link rel="stylesheet" type="text/css" href="style.css"> <!-- Add Google analytics --> <script src="js/google-analytics.js"></script> </head> <body> <div id="page-wrap"> <div class="row0"> <div class="col-2-3"> <a href="index.html" id="hlink"> <img id="trowel" src="./images/trowel.gif" alt="trowel"> <header> <h1 title="Hanna Landscaping and Design">Hanna Landscaping and Design</h1> <small id="in">"ain't nothing to it, but to do it"</small> </header> </a> </div> <div class="col-1-3"> <header> <h2 id="right" itemprop="telephone">513.708.7765 <img id="phone" src="./images/mobile.svg" alt="telephone"> <a href="//plus.google.com/u/0/106449370396466738752?prsrc=3" rel="publisher" target="_blank"><img id="newreview" src="./images/g+29.png" alt="Google+"/> </a> </h2> <small><EMAIL></small> </header> </div> </div> <div class="row_nav"> <nav> <ul> <div class="col-1-8"> <li class="hov"><a href="about.html">about</a></li> </div> <div class="col-1-8"> <li class="hov"><a href="expertise.html">expertise</a></li> </div> <div class="col-1-8"> <li class="hov"><a href="ideas.html">ideas</a></li> </div> <div class="col-1-8"> <li class="hov"><a href="contact.php">contact</a></li> </div> </ul> </nav> <div class="col-1-2"> <div id="mod0"> <div id="address" itemscope itemtype="http://schema.org/LocalBusiness"> <span itemprop="address" itemscope itemtype="http://schema.org/PostalAddress"> <span itemprop="streetAddress">9330 Arnold Lane</span> &middot; <span itemprop="addressLocality">Loveland,</span> <span itemprop="addressRegion">Ohio</span> &middot; <span itemprop="postalCode">45140</span> </span> </div> <!-- end address --> </div> <!-- end mod0 --> </div> <!-- end col-1-2 --> </div> <!-- end row_nav --> <div class="row1"> <div class="col-1-3"> <div class="mod4_expertise"> <h2>consult and design<img class="arrow" src="./images/arrow-right.svg" alt="right arrow"></h2> </div> </div> <div class="col-2-3"> <div class="mod3_expertise"> <p> We love to dabble in ideas. We have experience to know what works and where, and enough experience to know you're the boss. We encourage talking and planning before digging. </p> </div> </div> </div> <!--end row--> <div class="row1"> <div class="col-1-3"> <div class="mod4_expertise"> <h2>maintenance<img class="arrow" src="./images/arrow-right.svg" alt="right arrow"></h2> </div> </div> <div class="col-2-3"> <div class="mod3_expertise"> <p> If you own property and need ongoing care, we can help on a regular basis. We can offer a set schedule that leaves you care free. </p> </div> </div> </div> <!--end row--> <div class="row1"> <div class="col-1-3"> <div class="mod4_expertise"> <h2>build and plant<img class="arrow" src="./images/arrow-right.svg" alt="right arrow"></h2> </div> </div> <div class="col-2-3"> <div class="mod3_expertise"> <p> We specialize in retaining or decorative walls using natural stone or block. Our repertoire also includes over 100 varieties of trees and shrubs selected based on site requirements and plant hardiness of the <span itemprop="addressLocality">Cincinnati</span> region. We also install sustainable water features. </p> </div> </div> </div> <!--end row--> <div class="row1"> <div class="col-1-3"> <div class="mod4_expertise"> <h2>showcase<img class="arrow" src="./images/arrow-right.svg" alt="right arrow"></h2> </div> </div> <div class="col-2-3"> <div class="mod3_expertise"> <p> When the project is complete, it's time to showcase. People will appreciate your beautifying the neighborhood so have some drinks ready to go. </p> </div> </div> </div> <!--end row--> </div> <!--end page_wrap--> <div class="row_footer"> <div class="col-whole"> <footer> &copy;2015 &middot; <span itemprop="name"><NAME> and Design</span> &middot; <EMAIL> &middot; <span itemprop="telephone">513.708.7765</span> </footer> </div> </div> <!--end row_footer--> </body> </html> <file_sep>/README.md hannalandscaping ==================== [prod](http://www.hannalandscaping.com) OBJECTIVE -------------------- advertise USERS AND AUDIENCE -------------------- homeowners FEATURES -------------------- * php contact form REQUIREMENTS -------------------- * almost entirely static <file_sep>/contact.php <!DOCTYPE html> <html lang="en"> <head> <title>Cincinnati Landscape Designer | Hanna Landscaping and Design | Contact</title> <meta charset=utf-8> <meta name="viewport" content="width=device-width, user-scalable=no"> <meta name="description" content="Hanna Landscaping and Design serves Cincinnati and its suburbs in complete yard and lawn landscape installation, maintenance, and replacement." /> <meta property="og:locale" content="en_US" /> <meta property="og:type" content="website" /> <meta property="og:title" content="Cincinnati Landscape Designer | Hanna Landscaping and Design | Contact" /> <meta property="og:description" content="Hanna Landscaping and Design serves Cincinnati and its suburbs in complete yard and lawn landscape installation, maintenance, and replacement." /> <meta property="og:url" content="http://hannalandscaping.com/" /> <meta property="og:site_name" content="Hanna Landscaping and Design" /> <link rel="stylesheet" type="text/css" href="style.css"> <!-- Add Google analytics --> <script src="js/google-analytics.js"></script> </head> <body> <!-- @begin contact --> <div id="page-wrap"> <div class="row0"> <div class="col-2-3"> <a href="index.html" id="hlink"> <img id="trowel" src="./images/trowel.gif" alt="trowel"> <header> <h1 title="Hanna Landscaping and Design">Hanna Landscaping and Design</h1> <small id="in">"ain't nothing to it, but to do it"</small> </header> </a> </div> <div class="col-1-3"> <header> <h2 id="right" itemprop="telephone">513.708.7765 <img id="phone" src="./images/mobile.svg" alt="telephone"> <a href="//plus.google.com/u/0/106449370396466738752?prsrc=3" rel="publisher" target="_blank"><img id="newreview" src="./images/g+29.png" alt="Google+"/> </a> </h2> <small><EMAIL></small> </header> </div> </div> <div class="row_nav"> <nav> <ul> <div class="col-1-8"> <li class="hov"><a href="about.html">about</a></li> </div> <div class="col-1-8"> <li class="hov"><a href="expertise.html">expertise</a></li> </div> <div class="col-1-8"> <li class="hov"><a href="ideas.html">ideas</a></li> </div> <div class="col-1-8"> <li class="hov"><a href="contact.php">contact</a></li> </div> </ul> </nav> <div class="col-1-2"> <div id="mod0"> <div id="address" itemscope itemtype="http://schema.org/LocalBusiness"> <span itemprop="address" itemscope itemtype="http://schema.org/PostalAddress"> <span itemprop="streetAddress">9330 Arnold Lane</span> &middot; <span itemprop="addressLocality">Loveland,</span> <span itemprop="addressRegion">Ohio</span> &middot; <span itemprop="postalCode">45140</span> </span> </div> <!-- end address --> </div> <!-- end mod0 --> </div> <!-- end col-1-2 --> </div> <!-- end row_nav --> <h2 id="contact">Contact Us</h2> <p id="left"> Please use the contact form below to send us any information we may need. </p> <?php if (isset($_POST['submit']) && $_POST['submit'] == "submit") { $contactName = $_POST["contactName"]; $email = $_POST["email"]; $message = $_POST["comments"]; if (empty($contactName) || empty($email) || empty($message)) { echo '<p id="warn">Please complete the form.</p>'; } else { $to = "<EMAIL>"; $subject = "hannalandscaping.com"; $header = "From: $email" . "\r\n" . "Bcc: <EMAIL>"; mail ($to, $subject, $message, $header); $re = "Hanna Landscaping and Design"; $reply = "Thank you for contacting Adam at Hanna Landscaping and Design. We will be in touch.\n\n" . "Best regards,\n\n" . "<NAME>\n" . "Landscape Design Professional\n" . "<EMAIL>\n" . "ph: 513.708.7765"; $headers = "From: <EMAIL>" . "\r\n" . "Bcc: <EMAIL>"; mail ($email, $re, $reply, $headers); echo "<p class='left'>Thank you for contacting Adam at Hanna Landscaping and Design. We will be in touch.</p>"; } } ?> <div class="row1"> <div class="col-1-2"> <div class="mod2_contact"> <form action="contact.php" method="post"> <input type="text" name="contactName" id="contactName" value="" placeholder="Name" /> <input type="text" name="email" id="email" value="" placeholder="Email" /> <br> <div id="message"> <label>Message:</label> <textarea rows="10" cols="50" name="comments" id="commentsText"></textarea> <br> <button id="subbutton" type="submit" name="submit" value = "submit">Send!</button> </div> </form> </div> </div> <div class="col-1-2"> <div class="mod2_contact"> <img id="plant" src="./images/cutplant.jpg" alt="young plant in soil"> </div> </div> </div><!--end row1--> </div> <!--end page_wrap--> <div class="row_footer"> <div class="col-whole"> <footer> &copy;2015 &middot; <span itemprop="name"><NAME> and Design</span> &middot; <EMAIL> &middot; <span itemprop="telephone">513.708.7765</span> </footer> </div> </div> <!--end row_footer--> </body> </html>
70a3295d786b780aa8760b538e025f4467cb2558
[ "Markdown", "HTML", "PHP" ]
3
HTML
pcwitz/hannalandscaping
89a4148d25ecea3f44651180daa90da5b86929c6
197f09e344c1c36ad7bb72bcfd05b0fcb19e790e